idx
int64 1
56k
| question
stringlengths 15
155
| answer
stringlengths 2
29.2k
⌀ | question_cut
stringlengths 15
100
| answer_cut
stringlengths 2
200
⌀ | conversation
stringlengths 47
29.3k
| conversation_cut
stringlengths 47
301
|
|---|---|---|---|---|---|---|
45,901
|
Time series modeling with dynamic regressors in SAS vs R
|
While it is not built in, it is easy enough to do:
library(forecast)
fity <- auto.arima(y, xreg=x)
fitx <- auto.arima(x)
forecast(fity,h=10,xreg=forecast(fitx,h=10)$mean)
However, the prediction intervals obtained do not account for the variance in the forecasts of x. I doubt that SAS handles this either.
|
Time series modeling with dynamic regressors in SAS vs R
|
While it is not built in, it is easy enough to do:
library(forecast)
fity <- auto.arima(y, xreg=x)
fitx <- auto.arima(x)
forecast(fity,h=10,xreg=forecast(fitx,h=10)$mean)
However, the prediction inte
|
Time series modeling with dynamic regressors in SAS vs R
While it is not built in, it is easy enough to do:
library(forecast)
fity <- auto.arima(y, xreg=x)
fitx <- auto.arima(x)
forecast(fity,h=10,xreg=forecast(fitx,h=10)$mean)
However, the prediction intervals obtained do not account for the variance in the forecasts of x. I doubt that SAS handles this either.
|
Time series modeling with dynamic regressors in SAS vs R
While it is not built in, it is easy enough to do:
library(forecast)
fity <- auto.arima(y, xreg=x)
fitx <- auto.arima(x)
forecast(fity,h=10,xreg=forecast(fitx,h=10)$mean)
However, the prediction inte
|
45,902
|
Is left-of-mean cdf of exponential distribution greater than that of a gamma distribution?
|
The answer to your monotonicity conjecture is affirmative. It admits a somewhat sneaky proof and allows us to conclude something about the Poisson distribution in the
process. This is what we explore below.
The picture
The question asks whether the cdfs decrease pointwise as $n$ increases
for each $x$ to the left of the vertical line $x=1$.
The math
Let's start with a restatement of the question. First, if $\renewcommand{\Pr}{\mathbb P}\newcommand{\d}{\mathrm d}T \sim
\mathrm{Exp}(1)$, then it's easy to see that $T/n \sim
\mathrm{Exp}(n)$. So, we can rewrite a $\Gamma(n,n)$ random variable
$S_n$ as $S_n = (T_1 + \cdots + T_n)/n$ where $T_i$ is a sequence of
iid $\mathrm{Exp}(1)$ random variables. Instead of asking whether the
cdf decreases pointwise as a function of $n$ for each $0 < x < 1$, we
can ask whether the survival distribution increases
pointwise. Hence, we have the following equivalent question.
Equivalent question: Let $T_1, T_2,\ldots$ be an iid sequence of $\mathrm{Exp}(1)$ random variables and let $S_n = T_1 + \dots + T_n$. Then, is it true that, for all fixed $x \in (0,1)$, $$ \Pr( S_{n+1} > (n+1) x ) \geq \Pr(S_n > n x) \,? $$
Proof. The key idea here is to divide and conquer. We need to somehow compare the events $\{S_{n+1} > (n+1)x\}$ and $\{S_n > nx\}$. To that end, notice that
$$
\Pr(S_{n+1} > (n+1)x) = \Pr(S_{n+1} > n x) - \Pr(nx \leq S_{n+1} \leq (n+1)x) \>.
$$
We are halfway there. To deal with the remaining part, observe that
$$
\{S_{n+1} > n x\} = \{S_n > n x\} \cup \{S_n \leq n x, T_{n+1} > nx - S_n \} \>,
$$
and the two events on the right-hand size are disjoint. So,
$$
\Pr(S_{n+1} > (n+1)x) = \Pr(S_n > n x) + \Pr(S_n \leq nx, T_{n+1} > nx - S_n) - \Pr(nx \leq S_{n+1} \leq (n+1)x) \>.
$$
If we can show the second probability is greater than the third, we are done. To do this, we'll first find an explicit value for the second probability and then find an upper bound for the third.
(Second term.) $S_n$ and $T_{n+1}$ are independent, so to find $\Pr(S_n \leq nx, T_{n+1} > nx - S_n)$, we need only integrate over the
region of interest. This is
$$
\Pr(S_n \leq nx, T_{n+1} > nx - S_n) = \int_0^{nx} \int_{nx-s}^\infty
e^{-t} \frac{s^{n-1}e^{-s}}{(n-1)!} \, \d t \, \d s =
\frac{e^{-nx}(nx)^n}{n!} \>.
$$
(Third term.) This step is more involved, but still employs only elementary tools. Using the density of $S_{n+1}$, we have
$$\newcommand{\d}{\mathrm d}
\Pr(nx \leq S_{n+1} \leq (n+1)x )= \int_{nx}^{(n+1)x} \frac{u^n
e^{-u}}{n!} \,d u = \frac{e^{-nx} (nx)^n}{n!} x \int_0^1 (1+v/n)^n
e^{-xv} \d v
$$
where we've obtained the integral on the far right by using the substitution $v =
(u-nx)/x$. Now $(1+v/n)^n < e^v$ for all $n$ and so
$$
\int_0^1 (1+v/n)^n e^{-xv} \d v < \int_0^1 e^{(1-x) v} \d v =
\frac{e^{1-x} - 1}{1-x} \leq \frac{1}{x} \>,
$$
where the last step follows from the fact that $e^{1-x} < x^{-1}$ for
all $x \in (0,1)$. So,
$$
\Pr(nx \leq S_{n+1} \leq (n+1)x ) < \frac{e^{-nx}(nx)^n}{n!} \>.
$$
But, this last quantity is the same as the second term! Putting the three pieces together, we get
$$
\Pr(S_{n+1} > (n+1)x ) > \Pr(S_n > n x) \>,
$$
for each $x \in (0,1)$, which is what we set out to prove.
A consequence
The appearance of the term $\frac{e^{-nx}(nx)^n}{n!}$ strongly hints
that there is a relation to the Poisson hiding in here. Indeed, the
proof implies the following.
Proposition: Let $X_{n\lambda} \sim \mathrm{Poisson}(n\lambda)$ for $\lambda \in (0,1)$. Then $$ \Pr(X_{n\lambda} < n) \geq e^{-\lambda} \>. $$
Indeed, this was the original context in which I recently gave an equivalent
proof in this MathOverflow answer.
|
Is left-of-mean cdf of exponential distribution greater than that of a gamma distribution?
|
The answer to your monotonicity conjecture is affirmative. It admits a somewhat sneaky proof and allows us to conclude something about the Poisson distribution in the
process. This is what we explore
|
Is left-of-mean cdf of exponential distribution greater than that of a gamma distribution?
The answer to your monotonicity conjecture is affirmative. It admits a somewhat sneaky proof and allows us to conclude something about the Poisson distribution in the
process. This is what we explore below.
The picture
The question asks whether the cdfs decrease pointwise as $n$ increases
for each $x$ to the left of the vertical line $x=1$.
The math
Let's start with a restatement of the question. First, if $\renewcommand{\Pr}{\mathbb P}\newcommand{\d}{\mathrm d}T \sim
\mathrm{Exp}(1)$, then it's easy to see that $T/n \sim
\mathrm{Exp}(n)$. So, we can rewrite a $\Gamma(n,n)$ random variable
$S_n$ as $S_n = (T_1 + \cdots + T_n)/n$ where $T_i$ is a sequence of
iid $\mathrm{Exp}(1)$ random variables. Instead of asking whether the
cdf decreases pointwise as a function of $n$ for each $0 < x < 1$, we
can ask whether the survival distribution increases
pointwise. Hence, we have the following equivalent question.
Equivalent question: Let $T_1, T_2,\ldots$ be an iid sequence of $\mathrm{Exp}(1)$ random variables and let $S_n = T_1 + \dots + T_n$. Then, is it true that, for all fixed $x \in (0,1)$, $$ \Pr( S_{n+1} > (n+1) x ) \geq \Pr(S_n > n x) \,? $$
Proof. The key idea here is to divide and conquer. We need to somehow compare the events $\{S_{n+1} > (n+1)x\}$ and $\{S_n > nx\}$. To that end, notice that
$$
\Pr(S_{n+1} > (n+1)x) = \Pr(S_{n+1} > n x) - \Pr(nx \leq S_{n+1} \leq (n+1)x) \>.
$$
We are halfway there. To deal with the remaining part, observe that
$$
\{S_{n+1} > n x\} = \{S_n > n x\} \cup \{S_n \leq n x, T_{n+1} > nx - S_n \} \>,
$$
and the two events on the right-hand size are disjoint. So,
$$
\Pr(S_{n+1} > (n+1)x) = \Pr(S_n > n x) + \Pr(S_n \leq nx, T_{n+1} > nx - S_n) - \Pr(nx \leq S_{n+1} \leq (n+1)x) \>.
$$
If we can show the second probability is greater than the third, we are done. To do this, we'll first find an explicit value for the second probability and then find an upper bound for the third.
(Second term.) $S_n$ and $T_{n+1}$ are independent, so to find $\Pr(S_n \leq nx, T_{n+1} > nx - S_n)$, we need only integrate over the
region of interest. This is
$$
\Pr(S_n \leq nx, T_{n+1} > nx - S_n) = \int_0^{nx} \int_{nx-s}^\infty
e^{-t} \frac{s^{n-1}e^{-s}}{(n-1)!} \, \d t \, \d s =
\frac{e^{-nx}(nx)^n}{n!} \>.
$$
(Third term.) This step is more involved, but still employs only elementary tools. Using the density of $S_{n+1}$, we have
$$\newcommand{\d}{\mathrm d}
\Pr(nx \leq S_{n+1} \leq (n+1)x )= \int_{nx}^{(n+1)x} \frac{u^n
e^{-u}}{n!} \,d u = \frac{e^{-nx} (nx)^n}{n!} x \int_0^1 (1+v/n)^n
e^{-xv} \d v
$$
where we've obtained the integral on the far right by using the substitution $v =
(u-nx)/x$. Now $(1+v/n)^n < e^v$ for all $n$ and so
$$
\int_0^1 (1+v/n)^n e^{-xv} \d v < \int_0^1 e^{(1-x) v} \d v =
\frac{e^{1-x} - 1}{1-x} \leq \frac{1}{x} \>,
$$
where the last step follows from the fact that $e^{1-x} < x^{-1}$ for
all $x \in (0,1)$. So,
$$
\Pr(nx \leq S_{n+1} \leq (n+1)x ) < \frac{e^{-nx}(nx)^n}{n!} \>.
$$
But, this last quantity is the same as the second term! Putting the three pieces together, we get
$$
\Pr(S_{n+1} > (n+1)x ) > \Pr(S_n > n x) \>,
$$
for each $x \in (0,1)$, which is what we set out to prove.
A consequence
The appearance of the term $\frac{e^{-nx}(nx)^n}{n!}$ strongly hints
that there is a relation to the Poisson hiding in here. Indeed, the
proof implies the following.
Proposition: Let $X_{n\lambda} \sim \mathrm{Poisson}(n\lambda)$ for $\lambda \in (0,1)$. Then $$ \Pr(X_{n\lambda} < n) \geq e^{-\lambda} \>. $$
Indeed, this was the original context in which I recently gave an equivalent
proof in this MathOverflow answer.
|
Is left-of-mean cdf of exponential distribution greater than that of a gamma distribution?
The answer to your monotonicity conjecture is affirmative. It admits a somewhat sneaky proof and allows us to conclude something about the Poisson distribution in the
process. This is what we explore
|
45,903
|
Is left-of-mean cdf of exponential distribution greater than that of a gamma distribution?
|
An analytical proof might be quite difficult to obtain. The CDF of a gamma distribution fixed to have mean 1 is $P(k,kx) = \frac{\gamma\left(k,kx\right)}{\Gamma\left(k\right)}$ and you want to show for $0 \le x \le 1$ and $k > 0$ that
$$
\frac{dP\left(k,kx\right)}{dk} \ge 0
$$
But this works out as being fairly horrible:
$$
\frac{dP\left(k,kx\right)}{dk} = - \frac{x \operatorname{\gamma}\left(k, k x\right) \operatorname{\psi}\left(k x\right)}{\operatorname{\Gamma}\left(k x\right)} + \frac{\frac{x \left(k x\right)^{k -1}}{e^{k x}} - \operatorname{log}\left(k x\right) \operatorname{\Gamma}\left(k, k x\right) + \operatorname{\Gamma}\left(k\right) \operatorname{\psi}\left(k\right) + {G_{2, 3}^{3, 0}\left.\left(\begin{matrix} 1, 1 \\0, 0, k \end{matrix} \right| {k x} \right)}}{\operatorname{\Gamma}\left(k x\right)}
$$
where $\psi(x)$ is the digamma function and $G_{p,q}^{m,n}\left.\left(\begin{matrix} a_1,\ldots,a_p \\ b_1,\ldots, b_q \end{matrix} \right| z \right)$ is the Meijer G-function.
I'm not saying it's impossible to prove the inequality but it looks like an awful lot of work!
FYI the differential was calculated using Python 2.7 and the SymPy library.
PS there may be other ways to prove this, for example you could try expanding $P(k,kx)$ into its integral form and working from there
|
Is left-of-mean cdf of exponential distribution greater than that of a gamma distribution?
|
An analytical proof might be quite difficult to obtain. The CDF of a gamma distribution fixed to have mean 1 is $P(k,kx) = \frac{\gamma\left(k,kx\right)}{\Gamma\left(k\right)}$ and you want to show fo
|
Is left-of-mean cdf of exponential distribution greater than that of a gamma distribution?
An analytical proof might be quite difficult to obtain. The CDF of a gamma distribution fixed to have mean 1 is $P(k,kx) = \frac{\gamma\left(k,kx\right)}{\Gamma\left(k\right)}$ and you want to show for $0 \le x \le 1$ and $k > 0$ that
$$
\frac{dP\left(k,kx\right)}{dk} \ge 0
$$
But this works out as being fairly horrible:
$$
\frac{dP\left(k,kx\right)}{dk} = - \frac{x \operatorname{\gamma}\left(k, k x\right) \operatorname{\psi}\left(k x\right)}{\operatorname{\Gamma}\left(k x\right)} + \frac{\frac{x \left(k x\right)^{k -1}}{e^{k x}} - \operatorname{log}\left(k x\right) \operatorname{\Gamma}\left(k, k x\right) + \operatorname{\Gamma}\left(k\right) \operatorname{\psi}\left(k\right) + {G_{2, 3}^{3, 0}\left.\left(\begin{matrix} 1, 1 \\0, 0, k \end{matrix} \right| {k x} \right)}}{\operatorname{\Gamma}\left(k x\right)}
$$
where $\psi(x)$ is the digamma function and $G_{p,q}^{m,n}\left.\left(\begin{matrix} a_1,\ldots,a_p \\ b_1,\ldots, b_q \end{matrix} \right| z \right)$ is the Meijer G-function.
I'm not saying it's impossible to prove the inequality but it looks like an awful lot of work!
FYI the differential was calculated using Python 2.7 and the SymPy library.
PS there may be other ways to prove this, for example you could try expanding $P(k,kx)$ into its integral form and working from there
|
Is left-of-mean cdf of exponential distribution greater than that of a gamma distribution?
An analytical proof might be quite difficult to obtain. The CDF of a gamma distribution fixed to have mean 1 is $P(k,kx) = \frac{\gamma\left(k,kx\right)}{\Gamma\left(k\right)}$ and you want to show fo
|
45,904
|
Interpreting odds ratios
|
The fact that these are coefficients are represented entirely by factors in R means that the Intercept is the log-odds for the event, i.e log(the proportion with event / proportion without) for subjects who all have their factor values at the lowest level. We know that of the 1615 in level 1 of the factor under scrutiny, 1088 survived, although 1088/(1615-1088) (= odds of survival given factor =1) is not necessarily going to match up with exp(Intercept) since not all of those people also had the other factors at the lowest level. In fact the odds of survival (or it could be death, since it's not really been made clear what the coding for the events was) was quite different. At the best case of all factors being = 1 the odds of survival were:
exp( 4.2284770 )
[1] 68.61266
That's actually a pretty low odds for newborn survival, so this must have been a NICU study or something happening in a third world county. But its way higher than the odds for all children who had that value and any other values for the other predictors. (When looking at the single line of data it was neither ... it was on a different species.) In R the way to get a quick estimate of survival probability would be:
(pred1s <- predict(mod, newdata=as.data.frame( with( lesna,
list( seas = 1 ,
btw=1 , prectem5 =1 ,
pcscore =1 , pindx5 =1 ,
presp2= 1 , ppscore= 1,
mtone2 = , fos = ,
psex = 1 , pscolor = 1,
pshiv =1 , backfat5= 1 ,
srect2 =levels(srect2)[1] , gest3 =1 ,
int3= 1 , agit= 1 , tacc =1 ) )
),
type="response" )
) # the outer parens are to get a value to print when the assignment is made
You can the compare exp(Intercept) to that ( atypical ) prediction divided by (1-prediction) ... since that what odds are. So I hope it's becoming clear. You need to specify all of the factor level values at once to get a prediction. Or you need to create a synthetic cohort with a specific composition of all factor levels. You cannot take a single factor distribution and create a prediction from such a complex model unless you specify some sort of average value for all the other factors.
Edit after looking at the single line of data:
Some (most in fact) of those variable were not factors, (and I guess I should have recognized that), which means they do not have any levels in your dataframe, but do have levels in the model matrix. I had assumed that the levels would be attributes of the factor variable, but I was wrong. It's going to be easier to work on this model if the structure of your 'newdata' arguments given to predict have the same structure as the original dataframe and I would seriously consider making a copy and turning all those items into factors. But with the exception of "srect2" we can change all of those items to 1. at least under the assumption that that is the minimum value for each of those variables. If it's not, ... then you need to use the minimum value. Code edited.
response value calculated:
1.4418 is the log-odds ( the Intercept in the linear predictor fpr the baseline category)
odds = Pr(X=1)/(1-Pr(X=1)) :: definition
log(odds) = log(Pr(X=1)/(1-Pr(X=1)) ) = 1.4418 :: starting point
Solve for Pr(X=1) ... should be = the calculated "response" value.
exp(1.4418)*(1- Pr(X=1) ) = Pr(X=1)
exp(1.4418) = (1+exp(1.4418))* Pr(X=1)
Pr(X=1) = exp(1.4418) / (1+exp(1.4418))
> exp(1.4418) / (1+exp(1.4418))
[1] 0.8087332
All of the other levels need to have the Intercept added to get their correct linear predictors. The difference in log-odds, i.e. the coefficients, is directly equivalent to the ratio on the odds scale, hence the exp(coef) is a bunch of odds ratios.
{ log(x-y) = c } <=> { x/y = exp(c) }
--
|
Interpreting odds ratios
|
The fact that these are coefficients are represented entirely by factors in R means that the Intercept is the log-odds for the event, i.e log(the proportion with event / proportion without) for subjec
|
Interpreting odds ratios
The fact that these are coefficients are represented entirely by factors in R means that the Intercept is the log-odds for the event, i.e log(the proportion with event / proportion without) for subjects who all have their factor values at the lowest level. We know that of the 1615 in level 1 of the factor under scrutiny, 1088 survived, although 1088/(1615-1088) (= odds of survival given factor =1) is not necessarily going to match up with exp(Intercept) since not all of those people also had the other factors at the lowest level. In fact the odds of survival (or it could be death, since it's not really been made clear what the coding for the events was) was quite different. At the best case of all factors being = 1 the odds of survival were:
exp( 4.2284770 )
[1] 68.61266
That's actually a pretty low odds for newborn survival, so this must have been a NICU study or something happening in a third world county. But its way higher than the odds for all children who had that value and any other values for the other predictors. (When looking at the single line of data it was neither ... it was on a different species.) In R the way to get a quick estimate of survival probability would be:
(pred1s <- predict(mod, newdata=as.data.frame( with( lesna,
list( seas = 1 ,
btw=1 , prectem5 =1 ,
pcscore =1 , pindx5 =1 ,
presp2= 1 , ppscore= 1,
mtone2 = , fos = ,
psex = 1 , pscolor = 1,
pshiv =1 , backfat5= 1 ,
srect2 =levels(srect2)[1] , gest3 =1 ,
int3= 1 , agit= 1 , tacc =1 ) )
),
type="response" )
) # the outer parens are to get a value to print when the assignment is made
You can the compare exp(Intercept) to that ( atypical ) prediction divided by (1-prediction) ... since that what odds are. So I hope it's becoming clear. You need to specify all of the factor level values at once to get a prediction. Or you need to create a synthetic cohort with a specific composition of all factor levels. You cannot take a single factor distribution and create a prediction from such a complex model unless you specify some sort of average value for all the other factors.
Edit after looking at the single line of data:
Some (most in fact) of those variable were not factors, (and I guess I should have recognized that), which means they do not have any levels in your dataframe, but do have levels in the model matrix. I had assumed that the levels would be attributes of the factor variable, but I was wrong. It's going to be easier to work on this model if the structure of your 'newdata' arguments given to predict have the same structure as the original dataframe and I would seriously consider making a copy and turning all those items into factors. But with the exception of "srect2" we can change all of those items to 1. at least under the assumption that that is the minimum value for each of those variables. If it's not, ... then you need to use the minimum value. Code edited.
response value calculated:
1.4418 is the log-odds ( the Intercept in the linear predictor fpr the baseline category)
odds = Pr(X=1)/(1-Pr(X=1)) :: definition
log(odds) = log(Pr(X=1)/(1-Pr(X=1)) ) = 1.4418 :: starting point
Solve for Pr(X=1) ... should be = the calculated "response" value.
exp(1.4418)*(1- Pr(X=1) ) = Pr(X=1)
exp(1.4418) = (1+exp(1.4418))* Pr(X=1)
Pr(X=1) = exp(1.4418) / (1+exp(1.4418))
> exp(1.4418) / (1+exp(1.4418))
[1] 0.8087332
All of the other levels need to have the Intercept added to get their correct linear predictors. The difference in log-odds, i.e. the coefficients, is directly equivalent to the ratio on the odds scale, hence the exp(coef) is a bunch of odds ratios.
{ log(x-y) = c } <=> { x/y = exp(c) }
--
|
Interpreting odds ratios
The fact that these are coefficients are represented entirely by factors in R means that the Intercept is the log-odds for the event, i.e log(the proportion with event / proportion without) for subjec
|
45,905
|
Interpreting odds ratios
|
Odds ratios are a measure of difference in rate between two groups. So, it doesn't make sense to talk about just the "odds ratio" for a single group, you have to say what you're comparing that group with.
You might find it easier to start with more fundamental quantity, odds - actually this is just another way of expressing probability. The odds of an event is the probability it happens divided by the probability it does not happen. So, if the probability of an event happening is 0.8 (i.e. 80%) then its odds are 0.8/0.2=4.
In your example, I'm not totally certain what "Number" means - is is the number of infants, or the number of infants who survived? From your first table, to calculate what you want, you'll need the Odds in (at least) one group, not just Odds Ratios.
Finally, if this is homework, could you add a homework tag?
|
Interpreting odds ratios
|
Odds ratios are a measure of difference in rate between two groups. So, it doesn't make sense to talk about just the "odds ratio" for a single group, you have to say what you're comparing that group w
|
Interpreting odds ratios
Odds ratios are a measure of difference in rate between two groups. So, it doesn't make sense to talk about just the "odds ratio" for a single group, you have to say what you're comparing that group with.
You might find it easier to start with more fundamental quantity, odds - actually this is just another way of expressing probability. The odds of an event is the probability it happens divided by the probability it does not happen. So, if the probability of an event happening is 0.8 (i.e. 80%) then its odds are 0.8/0.2=4.
In your example, I'm not totally certain what "Number" means - is is the number of infants, or the number of infants who survived? From your first table, to calculate what you want, you'll need the Odds in (at least) one group, not just Odds Ratios.
Finally, if this is homework, could you add a homework tag?
|
Interpreting odds ratios
Odds ratios are a measure of difference in rate between two groups. So, it doesn't make sense to talk about just the "odds ratio" for a single group, you have to say what you're comparing that group w
|
45,906
|
Interpreting odds ratios
|
You can get the predicted probability of survival from a logistic regression program. In R, fitted() gives you fitted probabilities for each person. Your code would be something like:
model1 <- glm(survival~birthweight, family = binomial)
fitted(model1)
And you can extract from that the value for different birthweights.
Alternatively, you can get the coefficients of the model (use coef() in R) and then use the formula
$\pi(x) = \frac{e^{(\beta_0 + \beta_1 X_1 + e)}} {e^{(\beta_0 + \beta1 X_1 + e)} + 1} = \frac {1} {e^{-(\beta_0 + \beta_1 X_1 + e)} + 1}$
where the $\beta$ are the coefficients and the $X$ are the variables (you will need to adjust it if you have more than one independent variable)
|
Interpreting odds ratios
|
You can get the predicted probability of survival from a logistic regression program. In R, fitted() gives you fitted probabilities for each person. Your code would be something like:
model1 <- glm(su
|
Interpreting odds ratios
You can get the predicted probability of survival from a logistic regression program. In R, fitted() gives you fitted probabilities for each person. Your code would be something like:
model1 <- glm(survival~birthweight, family = binomial)
fitted(model1)
And you can extract from that the value for different birthweights.
Alternatively, you can get the coefficients of the model (use coef() in R) and then use the formula
$\pi(x) = \frac{e^{(\beta_0 + \beta_1 X_1 + e)}} {e^{(\beta_0 + \beta1 X_1 + e)} + 1} = \frac {1} {e^{-(\beta_0 + \beta_1 X_1 + e)} + 1}$
where the $\beta$ are the coefficients and the $X$ are the variables (you will need to adjust it if you have more than one independent variable)
|
Interpreting odds ratios
You can get the predicted probability of survival from a logistic regression program. In R, fitted() gives you fitted probabilities for each person. Your code would be something like:
model1 <- glm(su
|
45,907
|
Kurtosis/4th central moment in terms of mean and variance
|
What you think about here is something like a philosopher's stone of statistics.
The strict answer is:
No, it is impossible to express skewness or kurtosis via the mean and variance.
@Macro gave a counterexample of distributions with different skewness and kurtosis. A question of coming up with distributions for the given set of moments has entertained statisticians since the very early ages, and Pearson's system of frequency curves is one of the examples of how one could come up with a continuous distribution for the numeric values of the first four moments. You could also look at the moment generating function $m(t)={\rm E}[\exp(Xt)]$, a characteristic function $\phi(t)={\rm E}[\exp(iXt)]$, or a cumulant generating function $\psi(t) = \ln \phi(t)$. With some luck, you can try putting your four moments into them and invert these functions to obtain explicit expression of the densities. Finally, you can always find a distribution with discrete support on five points to satisfy the five equations for the moments of order 0 through 4 by solving a corresponding system of nonlinear equations.
To express the higher order moments via the lower order moments, you need to know the shape of the distribution and its parameters. For one-parameter (Poisson, exponential, geometric) or two-parameter (normal, gamma, binomial) distributions, you can express the higher order moments via the natural parameters of these distributions; e.g., for a Poisson with rate $\lambda$, skewness is $\lambda^{-1/2}$, and kurtosis is $\lambda^{-1}$ (sanity check: both going to zero as $\lambda \to \infty$, providing a normal approximation for Poisson for large $\lambda$). But these exceptions should not fool you; for more interesting distributions, including anything from the real world, you can just forget about doing anything meaningful with the kurtosis.
|
Kurtosis/4th central moment in terms of mean and variance
|
What you think about here is something like a philosopher's stone of statistics.
The strict answer is:
No, it is impossible to express skewness or kurtosis via the mean and variance.
@Macro gave a
|
Kurtosis/4th central moment in terms of mean and variance
What you think about here is something like a philosopher's stone of statistics.
The strict answer is:
No, it is impossible to express skewness or kurtosis via the mean and variance.
@Macro gave a counterexample of distributions with different skewness and kurtosis. A question of coming up with distributions for the given set of moments has entertained statisticians since the very early ages, and Pearson's system of frequency curves is one of the examples of how one could come up with a continuous distribution for the numeric values of the first four moments. You could also look at the moment generating function $m(t)={\rm E}[\exp(Xt)]$, a characteristic function $\phi(t)={\rm E}[\exp(iXt)]$, or a cumulant generating function $\psi(t) = \ln \phi(t)$. With some luck, you can try putting your four moments into them and invert these functions to obtain explicit expression of the densities. Finally, you can always find a distribution with discrete support on five points to satisfy the five equations for the moments of order 0 through 4 by solving a corresponding system of nonlinear equations.
To express the higher order moments via the lower order moments, you need to know the shape of the distribution and its parameters. For one-parameter (Poisson, exponential, geometric) or two-parameter (normal, gamma, binomial) distributions, you can express the higher order moments via the natural parameters of these distributions; e.g., for a Poisson with rate $\lambda$, skewness is $\lambda^{-1/2}$, and kurtosis is $\lambda^{-1}$ (sanity check: both going to zero as $\lambda \to \infty$, providing a normal approximation for Poisson for large $\lambda$). But these exceptions should not fool you; for more interesting distributions, including anything from the real world, you can just forget about doing anything meaningful with the kurtosis.
|
Kurtosis/4th central moment in terms of mean and variance
What you think about here is something like a philosopher's stone of statistics.
The strict answer is:
No, it is impossible to express skewness or kurtosis via the mean and variance.
@Macro gave a
|
45,908
|
Differentiating correlation and causation using conditional probablity
|
Conditional Probability and Causality
The idea that you can define causation in terms of conditional probability was the 'probabilistic causality' programme in philosophy associated with e.g. Cartwright and Eels. Arguably, it failed (See Pearl for the argument). A good introductory read on the topic is here. Several counterexamples to the probability raising relationship you suggest are in section 2.10.
As a result, it is unlikely that you will fully understand or otherwise reconstruct the difference between correlation and causation using only the machinery of conditional probability because it is insufficient. Explicitly causal i.e. non-probability assumptions are needed in addition.
Correlation
Correlation is, as @Michael Chernick and other commenters point out, closely related to conditional probability. In a narrow technical sense it is a standardised undirected measure of linear or at least monotonic association between two variables. In a wider informal sense it is as Michael describes it: a departure from statistical independence. In either sense it may appear as a result of an underlying causal relationship. Or not, e.g. it instantiates one of the counterexamples above or exhibits Simpson's Paradox. Hence the difficulty/impossibility of reconstructing the one with the other.
|
Differentiating correlation and causation using conditional probablity
|
Conditional Probability and Causality
The idea that you can define causation in terms of conditional probability was the 'probabilistic causality' programme in philosophy associated with e.g. Cartwrig
|
Differentiating correlation and causation using conditional probablity
Conditional Probability and Causality
The idea that you can define causation in terms of conditional probability was the 'probabilistic causality' programme in philosophy associated with e.g. Cartwright and Eels. Arguably, it failed (See Pearl for the argument). A good introductory read on the topic is here. Several counterexamples to the probability raising relationship you suggest are in section 2.10.
As a result, it is unlikely that you will fully understand or otherwise reconstruct the difference between correlation and causation using only the machinery of conditional probability because it is insufficient. Explicitly causal i.e. non-probability assumptions are needed in addition.
Correlation
Correlation is, as @Michael Chernick and other commenters point out, closely related to conditional probability. In a narrow technical sense it is a standardised undirected measure of linear or at least monotonic association between two variables. In a wider informal sense it is as Michael describes it: a departure from statistical independence. In either sense it may appear as a result of an underlying causal relationship. Or not, e.g. it instantiates one of the counterexamples above or exhibits Simpson's Paradox. Hence the difficulty/impossibility of reconstructing the one with the other.
|
Differentiating correlation and causation using conditional probablity
Conditional Probability and Causality
The idea that you can define causation in terms of conditional probability was the 'probabilistic causality' programme in philosophy associated with e.g. Cartwrig
|
45,909
|
Differentiating correlation and causation using conditional probablity
|
Showing that $E_2$ increases the likelihood of $E_1$ is just another way of saying that there is a relationship and hence a nonzero correlation between the events. It does not show causation. There are no probability relationships that "show" causation. Correlation means $P(E_1 E_2)$ not equal $P(E_1) P(E_2)$ which can be written in terms of conditional probabilities as $P(E_1|E_2) \neq P(E_1)$.
|
Differentiating correlation and causation using conditional probablity
|
Showing that $E_2$ increases the likelihood of $E_1$ is just another way of saying that there is a relationship and hence a nonzero correlation between the events. It does not show causation. There
|
Differentiating correlation and causation using conditional probablity
Showing that $E_2$ increases the likelihood of $E_1$ is just another way of saying that there is a relationship and hence a nonzero correlation between the events. It does not show causation. There are no probability relationships that "show" causation. Correlation means $P(E_1 E_2)$ not equal $P(E_1) P(E_2)$ which can be written in terms of conditional probabilities as $P(E_1|E_2) \neq P(E_1)$.
|
Differentiating correlation and causation using conditional probablity
Showing that $E_2$ increases the likelihood of $E_1$ is just another way of saying that there is a relationship and hence a nonzero correlation between the events. It does not show causation. There
|
45,910
|
How to measure usage data across cohorts/segments?
|
Statistically, this question seems reducible to: how can you compare two distributions to see which one is bigger? You are right to question the naive use of the mean as a blind summary of the distribution. However, there are still very many ways you could approach this. Here are a couple of options:
1) The two-sample Kolgomorov-Smirnov test. You can think of this as a way to plot the two empirical cumulative distributions and then search for the point with the largest maximum vertical deviation between the distributions. This has the advantage of being agnostic about precisely where in the distribution you look for the differences. I actually think this page is better than the Wikipedia page at explaining it, because it has better graphics.
2) A Bayesian comparison between the case that both samples are drawn from the same distribution and the case that both are drawn from different distributions. Here you will likely want to bin the distributions into histograms. This paper discusses and demonstrates a nice way of performing this. It models each histogram as coming from a Poisson distribution, and then infers whether they share the same rate parameter or whether the rate parameters differ. This is captured by a parameter $\pi$, whose probability mass is near one in the case that the histograms are the same,
and is near zero in the case that the histograms are different,
(The code is available online. You'll need ROOT installed.)
This method is likely to give better answers, but will take more time to implement. Whether you should use it or something like it depends on how crucial it is to you to get an extremely accurate answer rather than a good enough one.
Q-Q plots
This might be a nice way to visualize the differences between the two usage distributions. From what I can tell, Q-Q plots are more often used to compare one empirical distribution to a theoretical one, e.g. to a normal distribution, to justify its use. If you want to do a Q-Q plot with two empirical distributions you will first need to estimate the quantiles.
Q-Q plots may be worth investing some time into, but as a descriptive plot (i.e., you can't easily get a summary statistic out of them), you will either have to convert what you learn from them into a form that is easier to interpret, or make sure that whoever you are presenting the data to can interpret them. And they are not that easy to interpret. So, bottom line: yes, they could work, but unless you are already good at them I think it'd be easier to use another option.
|
How to measure usage data across cohorts/segments?
|
Statistically, this question seems reducible to: how can you compare two distributions to see which one is bigger? You are right to question the naive use of the mean as a blind summary of the distrib
|
How to measure usage data across cohorts/segments?
Statistically, this question seems reducible to: how can you compare two distributions to see which one is bigger? You are right to question the naive use of the mean as a blind summary of the distribution. However, there are still very many ways you could approach this. Here are a couple of options:
1) The two-sample Kolgomorov-Smirnov test. You can think of this as a way to plot the two empirical cumulative distributions and then search for the point with the largest maximum vertical deviation between the distributions. This has the advantage of being agnostic about precisely where in the distribution you look for the differences. I actually think this page is better than the Wikipedia page at explaining it, because it has better graphics.
2) A Bayesian comparison between the case that both samples are drawn from the same distribution and the case that both are drawn from different distributions. Here you will likely want to bin the distributions into histograms. This paper discusses and demonstrates a nice way of performing this. It models each histogram as coming from a Poisson distribution, and then infers whether they share the same rate parameter or whether the rate parameters differ. This is captured by a parameter $\pi$, whose probability mass is near one in the case that the histograms are the same,
and is near zero in the case that the histograms are different,
(The code is available online. You'll need ROOT installed.)
This method is likely to give better answers, but will take more time to implement. Whether you should use it or something like it depends on how crucial it is to you to get an extremely accurate answer rather than a good enough one.
Q-Q plots
This might be a nice way to visualize the differences between the two usage distributions. From what I can tell, Q-Q plots are more often used to compare one empirical distribution to a theoretical one, e.g. to a normal distribution, to justify its use. If you want to do a Q-Q plot with two empirical distributions you will first need to estimate the quantiles.
Q-Q plots may be worth investing some time into, but as a descriptive plot (i.e., you can't easily get a summary statistic out of them), you will either have to convert what you learn from them into a form that is easier to interpret, or make sure that whoever you are presenting the data to can interpret them. And they are not that easy to interpret. So, bottom line: yes, they could work, but unless you are already good at them I think it'd be easier to use another option.
|
How to measure usage data across cohorts/segments?
Statistically, this question seems reducible to: how can you compare two distributions to see which one is bigger? You are right to question the naive use of the mean as a blind summary of the distrib
|
45,911
|
How to measure usage data across cohorts/segments?
|
Quick answer
Compare medians instead of means, which will be more robust to the effects of extreme values.
More details
The best way to compare the distributions of usage between your customer groups depends on what you are trying to achieve by comparing them. For example, say you have the following groups:
A: 4, 5, 6
B: 0, 0, 0, 0, 50
There is no one answer to which group is has higher usage, but here are a few scenarios:
Mean
Comparing the mean of B (10) to the mean of A (5) would be appropriate if you want to know, for example, whether the increase in total usage would be greater if you were to add 5 new customers that would fall into group A (expected increase of 25) versus 5 new customers from group B (expected increase of 50). The extreme values will only contribute to larger variance on these expectations.
Median
Comparing the median of A (5) to the median of B (0) would be appropriate if you just want a quick way of saying whether a "typical" customer from group A would have higher usage than a "typical" customer from group B. Calculating the median is easy and gives good results, and in most cases will provide nearly the same results as the following more rigorous approach.
Mann-Whitney U / Wilcoxon rank-sum / AUC... a.k.a "test statistic of many names"
Calculating the U statistic is my personal favorite (although the proliferation of names is confusing). The U statistic is the probability that the usage of a uniform randomly chosen customer from group A is greater than the usage of a randomly chosen customer from group B. It's useful in a wide variety of situations. In addition to having an intuitive meaning, it's easy to test if the value of this U statistic is significant. It generalizes well to more than two groups, under the name Multiclass AUC*.
Significance
You will probably also want to check that any differences between groups are significant. The Mann-Whitney U works for this, as does the Kolgomorov-Smirnov (KS) test. The way-too-common T test makes assumptions about the distributions that don't sound justified with your data.
If, like me, you can't stand the proliferation of tests named "{Dead statistician} {Letter of alphabet} Test", (and you are interested in really understanding the concept of statistical significance), you can choose your software and simulate the process many times and see how unlikely the observed value of the test statistic is (bootstrapping*).
For example, if you want to see if the measured value of your U statistic is unlikely to occur if the groups are not different at all, try this:
Combine the data from group A and group B into one group, 4, 5, 6, 0, 0, 0, 0, 50
Randomly pick values from the combined list, with replacement, to form two groups with the same sizes as A and B, for example A': 0, 4, 4 and B': 50, 0, 0, 6, 5. Since you know that these A' and B' were just chosen randomly from the same population, this is an instance of a "null model" that the groups are not different.
Measure the "test statistic" for these two groups (this could be the difference in means, the difference in medians, the AUC, the KS value, or anything else you dream up) and write it down.
Repeat 2 and 3 many times.
Measure the "test statistic" for your actual groups, and compare it to the distribution of test statistics that you just generated. If it it falls outside the range, then the actual value of your test statistic was unlikely to occur in your null model, and the value is statistically significant.
NOTE: I couldn't put more than two links in here, because I don't have enough street cred on Cross Validated yet. I'll edit when I do.
|
How to measure usage data across cohorts/segments?
|
Quick answer
Compare medians instead of means, which will be more robust to the effects of extreme values.
More details
The best way to compare the distributions of usage between your customer groups
|
How to measure usage data across cohorts/segments?
Quick answer
Compare medians instead of means, which will be more robust to the effects of extreme values.
More details
The best way to compare the distributions of usage between your customer groups depends on what you are trying to achieve by comparing them. For example, say you have the following groups:
A: 4, 5, 6
B: 0, 0, 0, 0, 50
There is no one answer to which group is has higher usage, but here are a few scenarios:
Mean
Comparing the mean of B (10) to the mean of A (5) would be appropriate if you want to know, for example, whether the increase in total usage would be greater if you were to add 5 new customers that would fall into group A (expected increase of 25) versus 5 new customers from group B (expected increase of 50). The extreme values will only contribute to larger variance on these expectations.
Median
Comparing the median of A (5) to the median of B (0) would be appropriate if you just want a quick way of saying whether a "typical" customer from group A would have higher usage than a "typical" customer from group B. Calculating the median is easy and gives good results, and in most cases will provide nearly the same results as the following more rigorous approach.
Mann-Whitney U / Wilcoxon rank-sum / AUC... a.k.a "test statistic of many names"
Calculating the U statistic is my personal favorite (although the proliferation of names is confusing). The U statistic is the probability that the usage of a uniform randomly chosen customer from group A is greater than the usage of a randomly chosen customer from group B. It's useful in a wide variety of situations. In addition to having an intuitive meaning, it's easy to test if the value of this U statistic is significant. It generalizes well to more than two groups, under the name Multiclass AUC*.
Significance
You will probably also want to check that any differences between groups are significant. The Mann-Whitney U works for this, as does the Kolgomorov-Smirnov (KS) test. The way-too-common T test makes assumptions about the distributions that don't sound justified with your data.
If, like me, you can't stand the proliferation of tests named "{Dead statistician} {Letter of alphabet} Test", (and you are interested in really understanding the concept of statistical significance), you can choose your software and simulate the process many times and see how unlikely the observed value of the test statistic is (bootstrapping*).
For example, if you want to see if the measured value of your U statistic is unlikely to occur if the groups are not different at all, try this:
Combine the data from group A and group B into one group, 4, 5, 6, 0, 0, 0, 0, 50
Randomly pick values from the combined list, with replacement, to form two groups with the same sizes as A and B, for example A': 0, 4, 4 and B': 50, 0, 0, 6, 5. Since you know that these A' and B' were just chosen randomly from the same population, this is an instance of a "null model" that the groups are not different.
Measure the "test statistic" for these two groups (this could be the difference in means, the difference in medians, the AUC, the KS value, or anything else you dream up) and write it down.
Repeat 2 and 3 many times.
Measure the "test statistic" for your actual groups, and compare it to the distribution of test statistics that you just generated. If it it falls outside the range, then the actual value of your test statistic was unlikely to occur in your null model, and the value is statistically significant.
NOTE: I couldn't put more than two links in here, because I don't have enough street cred on Cross Validated yet. I'll edit when I do.
|
How to measure usage data across cohorts/segments?
Quick answer
Compare medians instead of means, which will be more robust to the effects of extreme values.
More details
The best way to compare the distributions of usage between your customer groups
|
45,912
|
How to measure usage data across cohorts/segments?
|
It sounds like you are looking for a robust test of the difference between two measures of location. You are right that using the mean poses all sorts of problems, not least of them extreme outliers. Research in recent decades has shown that comparison of means, relying on large sample properties, is much more problematic in many real-life situations than had been appreciated.
A good alternative is a comparison of 20% trimmed means. A percentile bootstrap around a mean with at least 0.2 trimming is "one of the most effective methods for obtaining accurate probability coverage and achieving relatively high power" (p.336 of Wilcox 2012, Modern Statistics for the Social and Behavioral Sciences, CRC Press, thoroughly recommended). There are straightforward implementations available in R.
For example, consider the mixed log-normal distributions in the R code below. x1 is generally much bigger than x2, but x2 is contaminated with 20 very large values that blow the mean out of the water. Either the median or the trimemd mean give a much better sense of the general centre of location.
> x1 <- exp(rnorm(1000,10,1))
> x2 <- exp(rnorm(1000,8,2))
> x2[sample(1:1000,20)] <- exp(rnorm(20,12,5))
> combined <- melt(data.frame(x1,x2))
Using as id variables
> tmp <- round(rbind(with(combined, tapply(value, variable, mean)),
+ with(combined, tapply(value, variable, mean, tr=.2)),
+ with(combined, tapply(value, variable, median))))
> row.names(tmp) <- c("Mean", "TrimmedMean", "Median")
> tmp
x1 x2
Mean 35229 1282017
TrimmedMean 25077 5992
Median 22454 3896
> qplot(value, data=combined, log="x") + facet_wrap(~variable)
|
How to measure usage data across cohorts/segments?
|
It sounds like you are looking for a robust test of the difference between two measures of location. You are right that using the mean poses all sorts of problems, not least of them extreme outliers.
|
How to measure usage data across cohorts/segments?
It sounds like you are looking for a robust test of the difference between two measures of location. You are right that using the mean poses all sorts of problems, not least of them extreme outliers. Research in recent decades has shown that comparison of means, relying on large sample properties, is much more problematic in many real-life situations than had been appreciated.
A good alternative is a comparison of 20% trimmed means. A percentile bootstrap around a mean with at least 0.2 trimming is "one of the most effective methods for obtaining accurate probability coverage and achieving relatively high power" (p.336 of Wilcox 2012, Modern Statistics for the Social and Behavioral Sciences, CRC Press, thoroughly recommended). There are straightforward implementations available in R.
For example, consider the mixed log-normal distributions in the R code below. x1 is generally much bigger than x2, but x2 is contaminated with 20 very large values that blow the mean out of the water. Either the median or the trimemd mean give a much better sense of the general centre of location.
> x1 <- exp(rnorm(1000,10,1))
> x2 <- exp(rnorm(1000,8,2))
> x2[sample(1:1000,20)] <- exp(rnorm(20,12,5))
> combined <- melt(data.frame(x1,x2))
Using as id variables
> tmp <- round(rbind(with(combined, tapply(value, variable, mean)),
+ with(combined, tapply(value, variable, mean, tr=.2)),
+ with(combined, tapply(value, variable, median))))
> row.names(tmp) <- c("Mean", "TrimmedMean", "Median")
> tmp
x1 x2
Mean 35229 1282017
TrimmedMean 25077 5992
Median 22454 3896
> qplot(value, data=combined, log="x") + facet_wrap(~variable)
|
How to measure usage data across cohorts/segments?
It sounds like you are looking for a robust test of the difference between two measures of location. You are right that using the mean poses all sorts of problems, not least of them extreme outliers.
|
45,913
|
Difference between CI of ANOVA level coefficients vs t-test CI - which one is "correct"?
|
There is a difference between the CIs because in case of ANOVA, the estimate of the error variance is based on all observations from all groups, whereas in the separate one-sample $t$-test CI for each group, each CI uses its own error estimate based on the observations from just that single group.
Edit: Using a pooled error estimate is appropriate when the true error variance in each group is the same (variance homogeneity assumption). In that case, using the residuals from, e.g., group C to estimate the error variance in group A makes sense. The pooled error estimate is based on more observations than in each one-sample $t$-test CI, and therefore is more reliable (when assumptions are met). This increase in reliability is reflected in a lower $t_{\alpha/2}$ quantile value that influences the width of the CI. It is lower because the $t$-distribution has more df.
In sum, both methods give you CIs for the true means of each group. The CIs based on the pooled error estimate are typically (but not necessarily for each group) narrower because more observations are used for the error estimate. You buy this advantage by assuming equality of true error variances in each group.
set.seed(1.234) # generate some reproducible data
P <- 3 # number of groups
Nj <- c(41, 37, 42) # group sizes
N <- sum(Nj) # total number of observations
DV <- rnorm(N, rep(c(-1, 0, 1), Nj), 4) # simulated data for all groups
IV <- factor(rep(LETTERS[1:P], Nj)) # grouping factor
Now fit a cell means model such that the theoretical model coefficients are the cell expected values, and their estimates are the cell means.
> fit <- lm(DV ~ IV - 1) # ANOVA with cell means model (no intercept)
> (bJ <- coef(fit)) # estimated coefficients
IVA IVB IVC
-0.6569245 0.5935542 1.3960387
> (Mj <- tapply(DV, IV, mean)) # ... are just the cell means
A B C
-0.6569245 0.5935542 1.3960387
Test the coefficients individually (null hypothesis: coefficient is 0, with cell means model: same hypothesis as in corresponding one-sample $t$-test) as well as the whole model. Also get the confidence intervals for the coefficients. No need to do this manually, there's confint().
> summary(fit) # some output lines deleted
Coefficients:
Estimate Std. Error t value Pr(>|t|)
IVA -0.6569 0.5551 -1.183 0.2390
IVB 0.5936 0.5843 1.016 0.3118
IVC 1.3960 0.5485 2.545 0.0122 *
---
Residual standard error: 3.554 on 117 degrees of freedom
Multiple R-squared: 0.07077, Adjusted R-squared: 0.04695
F-statistic: 2.97 on 3 and 117 DF, p-value: 0.03472
> confint(fit) # confidence intervals for coefficients
2.5 % 97.5 %
IVA -1.7562828 0.4424337
IVB -0.5637040 1.7508125
IVC 0.3098469 2.4822305
The standard errors of the coefficient estimates are the diagonal of the matrix $\hat{\sigma} (\bf{X}'\bf{X})^{-1}$ where $\hat{\sigma}^{2} = ||e||^{2} / (N-P)$ is the estimate of the error variance ($||e||^{2}$ is the sum of squared residuals, $N$ the total number of obervations, and $P$ the number of groups), and $\bf{X}$ is the design matrix. With these standard errors and the $t_{\alpha/2; N-P}$ value, we get the confidence intervals.
> sigHatSq <- sum(residuals(fit)^2) / (N-P)
> X <- model.matrix(fit) # design matrix
> (StdErr <- sqrt(diag(sigHatSq * solve(t(X) %*% X))))
IVA IVB IVC
0.5551059 0.5843418 0.5484577
> bJ - qt(0.025, N-P)*StdErr # confidence interval upper bound
IVA IVB IVC
0.4424337 1.7508125 2.4822305
> bJ + qt(0.025, N-P)*StdErr # confidence interval lower bound
IVA IVB IVC
-1.7562828 -0.5637040 0.3098469
In the corresponding one-sample $t$-tests, the CIs are based on each single cell standard deviation and the $t_{\alpha/2; n_{j}-1}$ values (note different df that reflect that error estimate is based on fewer observations).
> t.test(DV[IV == "A"])$conf.int
[1] -1.763466 0.449617
> t.test(DV[IV == "B"])$conf.int
[1] -0.679711 1.866819
> t.test(DV[IV == "C"])$conf.int
[1] 0.3504876 2.4415898
> sdJ <- tapply(DV, IV, sd) # group standard deviations
> Mj - qt(0.025, Nj-1)*(sdJ / sqrt(Nj)) # confidence interval upper bound
A B C
0.449617 1.866819 2.441590
> Mj + qt(0.025, Nj-1)*(sdJ / sqrt(Nj)) # confidence interval lower bound
A B C
-1.7634661 -0.6797110 0.3504876
|
Difference between CI of ANOVA level coefficients vs t-test CI - which one is "correct"?
|
There is a difference between the CIs because in case of ANOVA, the estimate of the error variance is based on all observations from all groups, whereas in the separate one-sample $t$-test CI for each
|
Difference between CI of ANOVA level coefficients vs t-test CI - which one is "correct"?
There is a difference between the CIs because in case of ANOVA, the estimate of the error variance is based on all observations from all groups, whereas in the separate one-sample $t$-test CI for each group, each CI uses its own error estimate based on the observations from just that single group.
Edit: Using a pooled error estimate is appropriate when the true error variance in each group is the same (variance homogeneity assumption). In that case, using the residuals from, e.g., group C to estimate the error variance in group A makes sense. The pooled error estimate is based on more observations than in each one-sample $t$-test CI, and therefore is more reliable (when assumptions are met). This increase in reliability is reflected in a lower $t_{\alpha/2}$ quantile value that influences the width of the CI. It is lower because the $t$-distribution has more df.
In sum, both methods give you CIs for the true means of each group. The CIs based on the pooled error estimate are typically (but not necessarily for each group) narrower because more observations are used for the error estimate. You buy this advantage by assuming equality of true error variances in each group.
set.seed(1.234) # generate some reproducible data
P <- 3 # number of groups
Nj <- c(41, 37, 42) # group sizes
N <- sum(Nj) # total number of observations
DV <- rnorm(N, rep(c(-1, 0, 1), Nj), 4) # simulated data for all groups
IV <- factor(rep(LETTERS[1:P], Nj)) # grouping factor
Now fit a cell means model such that the theoretical model coefficients are the cell expected values, and their estimates are the cell means.
> fit <- lm(DV ~ IV - 1) # ANOVA with cell means model (no intercept)
> (bJ <- coef(fit)) # estimated coefficients
IVA IVB IVC
-0.6569245 0.5935542 1.3960387
> (Mj <- tapply(DV, IV, mean)) # ... are just the cell means
A B C
-0.6569245 0.5935542 1.3960387
Test the coefficients individually (null hypothesis: coefficient is 0, with cell means model: same hypothesis as in corresponding one-sample $t$-test) as well as the whole model. Also get the confidence intervals for the coefficients. No need to do this manually, there's confint().
> summary(fit) # some output lines deleted
Coefficients:
Estimate Std. Error t value Pr(>|t|)
IVA -0.6569 0.5551 -1.183 0.2390
IVB 0.5936 0.5843 1.016 0.3118
IVC 1.3960 0.5485 2.545 0.0122 *
---
Residual standard error: 3.554 on 117 degrees of freedom
Multiple R-squared: 0.07077, Adjusted R-squared: 0.04695
F-statistic: 2.97 on 3 and 117 DF, p-value: 0.03472
> confint(fit) # confidence intervals for coefficients
2.5 % 97.5 %
IVA -1.7562828 0.4424337
IVB -0.5637040 1.7508125
IVC 0.3098469 2.4822305
The standard errors of the coefficient estimates are the diagonal of the matrix $\hat{\sigma} (\bf{X}'\bf{X})^{-1}$ where $\hat{\sigma}^{2} = ||e||^{2} / (N-P)$ is the estimate of the error variance ($||e||^{2}$ is the sum of squared residuals, $N$ the total number of obervations, and $P$ the number of groups), and $\bf{X}$ is the design matrix. With these standard errors and the $t_{\alpha/2; N-P}$ value, we get the confidence intervals.
> sigHatSq <- sum(residuals(fit)^2) / (N-P)
> X <- model.matrix(fit) # design matrix
> (StdErr <- sqrt(diag(sigHatSq * solve(t(X) %*% X))))
IVA IVB IVC
0.5551059 0.5843418 0.5484577
> bJ - qt(0.025, N-P)*StdErr # confidence interval upper bound
IVA IVB IVC
0.4424337 1.7508125 2.4822305
> bJ + qt(0.025, N-P)*StdErr # confidence interval lower bound
IVA IVB IVC
-1.7562828 -0.5637040 0.3098469
In the corresponding one-sample $t$-tests, the CIs are based on each single cell standard deviation and the $t_{\alpha/2; n_{j}-1}$ values (note different df that reflect that error estimate is based on fewer observations).
> t.test(DV[IV == "A"])$conf.int
[1] -1.763466 0.449617
> t.test(DV[IV == "B"])$conf.int
[1] -0.679711 1.866819
> t.test(DV[IV == "C"])$conf.int
[1] 0.3504876 2.4415898
> sdJ <- tapply(DV, IV, sd) # group standard deviations
> Mj - qt(0.025, Nj-1)*(sdJ / sqrt(Nj)) # confidence interval upper bound
A B C
0.449617 1.866819 2.441590
> Mj + qt(0.025, Nj-1)*(sdJ / sqrt(Nj)) # confidence interval lower bound
A B C
-1.7634661 -0.6797110 0.3504876
|
Difference between CI of ANOVA level coefficients vs t-test CI - which one is "correct"?
There is a difference between the CIs because in case of ANOVA, the estimate of the error variance is based on all observations from all groups, whereas in the separate one-sample $t$-test CI for each
|
45,914
|
List of likelihood-based classification techniques
|
It think this has potential to become an interesting list. Maybe we should all either explain or reference how the methods use a likelihood approach.
A list of additional likelihood classification procedures:
GLMs for binomial or multinomial data (Logistic Regression, Probit Regression, other Link Functions) McCullagh & Nelder and their regularized extensions Hastie et al.
The equivalent GAMs Hastie & Tibshirani
Certain classification and model trees can also be seen as likelihood-based models (Su et al, Loh et al's work , Zeileis et al , Rusch & Zeileis, etc.)
Certain types of Boosting may also be seen as likelihood-based Lebanon & Lafferty, Friedman et al.
From what I know, Bayesian approaches nearly always use the likelihood as part of the model, hence they are always likelihood based.
If a negative (log)-likelihood for a classification problem is used as the loss function that is minimized to train the model and then predictions from this model are made, I suppose any classification approach following this counts as likelihood-based.
|
List of likelihood-based classification techniques
|
It think this has potential to become an interesting list. Maybe we should all either explain or reference how the methods use a likelihood approach.
A list of additional likelihood classification
|
List of likelihood-based classification techniques
It think this has potential to become an interesting list. Maybe we should all either explain or reference how the methods use a likelihood approach.
A list of additional likelihood classification procedures:
GLMs for binomial or multinomial data (Logistic Regression, Probit Regression, other Link Functions) McCullagh & Nelder and their regularized extensions Hastie et al.
The equivalent GAMs Hastie & Tibshirani
Certain classification and model trees can also be seen as likelihood-based models (Su et al, Loh et al's work , Zeileis et al , Rusch & Zeileis, etc.)
Certain types of Boosting may also be seen as likelihood-based Lebanon & Lafferty, Friedman et al.
From what I know, Bayesian approaches nearly always use the likelihood as part of the model, hence they are always likelihood based.
If a negative (log)-likelihood for a classification problem is used as the loss function that is minimized to train the model and then predictions from this model are made, I suppose any classification approach following this counts as likelihood-based.
|
List of likelihood-based classification techniques
It think this has potential to become an interesting list. Maybe we should all either explain or reference how the methods use a likelihood approach.
A list of additional likelihood classification
|
45,915
|
List of likelihood-based classification techniques
|
LDA and QDA are likelihood based approaches based on respectively both class-conditional densities are multivariate normal with the same covariance matrix and both class-conditional densities are multivariate normal with different covariance matrices. In a broad sense kernel discrimination can be considered likelihood based. because if you assumed that the estimated densities were the actual class conditional densities the decision boundary could be considered based on likelihood ratios. If you put a prior distribution on the class associated with a given feature vector you can get a Bayes rule by any of these approaches under the respective model assumptions. I like the 1972 book "Pattern Classification and Scene Analysis" by Duda and Hart for a clear description of this. There is a new addition of this book that came out a few years ago with a third author (Stork, I think).
|
List of likelihood-based classification techniques
|
LDA and QDA are likelihood based approaches based on respectively both class-conditional densities are multivariate normal with the same covariance matrix and both class-conditional densities are mult
|
List of likelihood-based classification techniques
LDA and QDA are likelihood based approaches based on respectively both class-conditional densities are multivariate normal with the same covariance matrix and both class-conditional densities are multivariate normal with different covariance matrices. In a broad sense kernel discrimination can be considered likelihood based. because if you assumed that the estimated densities were the actual class conditional densities the decision boundary could be considered based on likelihood ratios. If you put a prior distribution on the class associated with a given feature vector you can get a Bayes rule by any of these approaches under the respective model assumptions. I like the 1972 book "Pattern Classification and Scene Analysis" by Duda and Hart for a clear description of this. There is a new addition of this book that came out a few years ago with a third author (Stork, I think).
|
List of likelihood-based classification techniques
LDA and QDA are likelihood based approaches based on respectively both class-conditional densities are multivariate normal with the same covariance matrix and both class-conditional densities are mult
|
45,916
|
Increase training performance of a neural network with low learning rate?
|
If time is a limiting factor, you could try reducing the number of hidden units substantially. In my experience, it's very rare to need this many hidden units. I would start with a small number (less than ten) of hidden units, and see if this gives adequate performance.
If you're more worried about local minima, perhaps it's worth trying adding a stochastic component to your algorithm, based on simulated annealing or stochastic gradient descent. This may slow things down a bit, but will prevent local minima from being such a problem.
|
Increase training performance of a neural network with low learning rate?
|
If time is a limiting factor, you could try reducing the number of hidden units substantially. In my experience, it's very rare to need this many hidden units. I would start with a small number (less
|
Increase training performance of a neural network with low learning rate?
If time is a limiting factor, you could try reducing the number of hidden units substantially. In my experience, it's very rare to need this many hidden units. I would start with a small number (less than ten) of hidden units, and see if this gives adequate performance.
If you're more worried about local minima, perhaps it's worth trying adding a stochastic component to your algorithm, based on simulated annealing or stochastic gradient descent. This may slow things down a bit, but will prevent local minima from being such a problem.
|
Increase training performance of a neural network with low learning rate?
If time is a limiting factor, you could try reducing the number of hidden units substantially. In my experience, it's very rare to need this many hidden units. I would start with a small number (less
|
45,917
|
Increase training performance of a neural network with low learning rate?
|
Gradient descent is usually a bad optimization algorithm. Try one of the following:
stochastic gradient descent
Levenberg-Marquardt
conjugate gradient
These algorithms are usually
faster and
achieve better results
E. g. the "two spirals" problem can be solved by gradient descent in >10,000 iterations and by Levenberg-Marquardt in < 300 iterations.
I think there is an advice about the training set size in the neural network FAQ but I can't find it at the moment. Usually it should be number of inputs * n, where n sufficiently large (OK, this probably won't help you).
|
Increase training performance of a neural network with low learning rate?
|
Gradient descent is usually a bad optimization algorithm. Try one of the following:
stochastic gradient descent
Levenberg-Marquardt
conjugate gradient
These algorithms are usually
faster and
achiev
|
Increase training performance of a neural network with low learning rate?
Gradient descent is usually a bad optimization algorithm. Try one of the following:
stochastic gradient descent
Levenberg-Marquardt
conjugate gradient
These algorithms are usually
faster and
achieve better results
E. g. the "two spirals" problem can be solved by gradient descent in >10,000 iterations and by Levenberg-Marquardt in < 300 iterations.
I think there is an advice about the training set size in the neural network FAQ but I can't find it at the moment. Usually it should be number of inputs * n, where n sufficiently large (OK, this probably won't help you).
|
Increase training performance of a neural network with low learning rate?
Gradient descent is usually a bad optimization algorithm. Try one of the following:
stochastic gradient descent
Levenberg-Marquardt
conjugate gradient
These algorithms are usually
faster and
achiev
|
45,918
|
CCA/KCCA for more than two views
|
If by more than two 'views' you actually mean extending the CCA framework to k-blocks data structure, then you might be interested in
Tenenhaus, A. and Tenenhaus, M. (2011). Regularized Generalized
Canonical Correlation Analysis. Psychometrika, 76(2), 257-284.
The corresponding R package is called RGCCA.
|
CCA/KCCA for more than two views
|
If by more than two 'views' you actually mean extending the CCA framework to k-blocks data structure, then you might be interested in
Tenenhaus, A. and Tenenhaus, M. (2011). Regularized Generalized
|
CCA/KCCA for more than two views
If by more than two 'views' you actually mean extending the CCA framework to k-blocks data structure, then you might be interested in
Tenenhaus, A. and Tenenhaus, M. (2011). Regularized Generalized
Canonical Correlation Analysis. Psychometrika, 76(2), 257-284.
The corresponding R package is called RGCCA.
|
CCA/KCCA for more than two views
If by more than two 'views' you actually mean extending the CCA framework to k-blocks data structure, then you might be interested in
Tenenhaus, A. and Tenenhaus, M. (2011). Regularized Generalized
|
45,919
|
CCA/KCCA for more than two views
|
This is just a guess. Is it not that CCA can be interpreted as a probabilistic model of the following form?
X | Z ~ N(A*Z,Psi)
Y | Z ~ N(B*Z,Phi)
where X is vector in first view, Y is vector in second view, and Z is latent variable which captures the relation between X and Y. Psi and Phi are covariance matrices which soak up all the rest of the variations not captured by Z. Generalization to >2 views is now straightforward.
Learning in this framework would presumably be EM but that is not very efficient. It is likely that the typical generalized eigenvalue computations for CCA is a more efficient method to get at the maximum likelihood solution in 2 view case, and there might be a generalization to >2 view2 setting?
|
CCA/KCCA for more than two views
|
This is just a guess. Is it not that CCA can be interpreted as a probabilistic model of the following form?
X | Z ~ N(A*Z,Psi)
Y | Z ~ N(B*Z,Phi)
where X is vector in first view, Y is vector in second
|
CCA/KCCA for more than two views
This is just a guess. Is it not that CCA can be interpreted as a probabilistic model of the following form?
X | Z ~ N(A*Z,Psi)
Y | Z ~ N(B*Z,Phi)
where X is vector in first view, Y is vector in second view, and Z is latent variable which captures the relation between X and Y. Psi and Phi are covariance matrices which soak up all the rest of the variations not captured by Z. Generalization to >2 views is now straightforward.
Learning in this framework would presumably be EM but that is not very efficient. It is likely that the typical generalized eigenvalue computations for CCA is a more efficient method to get at the maximum likelihood solution in 2 view case, and there might be a generalization to >2 view2 setting?
|
CCA/KCCA for more than two views
This is just a guess. Is it not that CCA can be interpreted as a probabilistic model of the following form?
X | Z ~ N(A*Z,Psi)
Y | Z ~ N(B*Z,Phi)
where X is vector in first view, Y is vector in second
|
45,920
|
Effect size for Fisher's exact test?
|
Fisher's exact test is usually used for 2x2 tables. In such a table, you have a few choices for effect size.
One is the odds ratio, which can be calculated by hand pretty easily. If the four cells are $A_{11} A_{12} A_{21} $ and $A_{22}$ then the OR is $A_{11}*A_{22}/A_{21}*A_{12}$.
Another is the difference in proportions in the two rows or two columns: $A_{22}/(A_{12}+A_{22}) -A_{21}/(A_{21}+A_{11})$ or vice versa.
There are others; see any good book on categorical data analysis, such as Agresti's Categorical Data Analysis.
If you have a table that is bigger than 2 x 2, things get more complex, and it depends on whether either row or column is ordinal and on what you are interested in, as well.
|
Effect size for Fisher's exact test?
|
Fisher's exact test is usually used for 2x2 tables. In such a table, you have a few choices for effect size.
One is the odds ratio, which can be calculated by hand pretty easily. If the four cells ar
|
Effect size for Fisher's exact test?
Fisher's exact test is usually used for 2x2 tables. In such a table, you have a few choices for effect size.
One is the odds ratio, which can be calculated by hand pretty easily. If the four cells are $A_{11} A_{12} A_{21} $ and $A_{22}$ then the OR is $A_{11}*A_{22}/A_{21}*A_{12}$.
Another is the difference in proportions in the two rows or two columns: $A_{22}/(A_{12}+A_{22}) -A_{21}/(A_{21}+A_{11})$ or vice versa.
There are others; see any good book on categorical data analysis, such as Agresti's Categorical Data Analysis.
If you have a table that is bigger than 2 x 2, things get more complex, and it depends on whether either row or column is ordinal and on what you are interested in, as well.
|
Effect size for Fisher's exact test?
Fisher's exact test is usually used for 2x2 tables. In such a table, you have a few choices for effect size.
One is the odds ratio, which can be calculated by hand pretty easily. If the four cells ar
|
45,921
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
|
You seem to be slightly misunderstanding the purpose of the weights in IPTW. You are right it would not make sense to have a fractional value for a binary outcome, but the goal of weighting here is not to get a "corrected" outcome value for each individual.
Instead, you are creating a pseudo-population the composition of which is the individuals in the original population weighted by the inverse of their probability of treatment, given some covariates. In the pseudo-population, there is no longer any association between those covariates and treatment (and therefore no confounding). The goal of weighting, therefore, is to get a contribution to the average outcome value that each individual makes. You can now have fractional values, because these are fractional contributions, not fractional outcome values.
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
|
You seem to be slightly misunderstanding the purpose of the weights in IPTW. You are right it would not make sense to have a fractional value for a binary outcome, but the goal of weighting here is no
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
You seem to be slightly misunderstanding the purpose of the weights in IPTW. You are right it would not make sense to have a fractional value for a binary outcome, but the goal of weighting here is not to get a "corrected" outcome value for each individual.
Instead, you are creating a pseudo-population the composition of which is the individuals in the original population weighted by the inverse of their probability of treatment, given some covariates. In the pseudo-population, there is no longer any association between those covariates and treatment (and therefore no confounding). The goal of weighting, therefore, is to get a contribution to the average outcome value that each individual makes. You can now have fractional values, because these are fractional contributions, not fractional outcome values.
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
You seem to be slightly misunderstanding the purpose of the weights in IPTW. You are right it would not make sense to have a fractional value for a binary outcome, but the goal of weighting here is no
|
45,922
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
|
$\hat e_i$ is I believe the propensity score; i.e., the probability of $Z_i = 1 | X_i$, so treatment patients are weighted by the inverse of the propensity score, while control patients are weighted by (1- propensity score).
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
|
$\hat e_i$ is I believe the propensity score; i.e., the probability of $Z_i = 1 | X_i$, so treatment patients are weighted by the inverse of the propensity score, while control patients are weighted b
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
$\hat e_i$ is I believe the propensity score; i.e., the probability of $Z_i = 1 | X_i$, so treatment patients are weighted by the inverse of the propensity score, while control patients are weighted by (1- propensity score).
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
$\hat e_i$ is I believe the propensity score; i.e., the probability of $Z_i = 1 | X_i$, so treatment patients are weighted by the inverse of the propensity score, while control patients are weighted b
|
45,923
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
|
To expand on what Ellie said, the "inverse" part of the weighting means that if a subject has a low probability of receiving the treatment given the other covariates, they receive more representation in the IPTW "population." If your propensity model is correct (spoiler: it isn't), then the IPTW estimator is the naive treatment effect estimate (just the average difference between the treatment and control group) where the samples have been weighted to be representative of the population.
As a sanity check, if the treatment is truly randomly assigned, then the modeled propensity to be treated will be roughly the proportion of treated units in the sample (regardless of the covariates, which are independent of the treatment by hypothesis). Then the treatment variables and propensities will cancel out, leaving the simple mean difference in the outcome.
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
|
To expand on what Ellie said, the "inverse" part of the weighting means that if a subject has a low probability of receiving the treatment given the other covariates, they receive more representation
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
To expand on what Ellie said, the "inverse" part of the weighting means that if a subject has a low probability of receiving the treatment given the other covariates, they receive more representation in the IPTW "population." If your propensity model is correct (spoiler: it isn't), then the IPTW estimator is the naive treatment effect estimate (just the average difference between the treatment and control group) where the samples have been weighted to be representative of the population.
As a sanity check, if the treatment is truly randomly assigned, then the modeled propensity to be treated will be roughly the proportion of treated units in the sample (regardless of the covariates, which are independent of the treatment by hypothesis). Then the treatment variables and propensities will cancel out, leaving the simple mean difference in the outcome.
|
Inverse probability of treatment weighted (IPTW) estimator for a binary outcome
To expand on what Ellie said, the "inverse" part of the weighting means that if a subject has a low probability of receiving the treatment given the other covariates, they receive more representation
|
45,924
|
Testing two-tailed p-values using Stouffer's approach
|
1) If two-sided p-values are being analyzed, you use the two-sided p-value in the calculation of the $Z_i$. The two-sided p-value is $\tilde{p}_i = p_i/2$.
2) If left-tailed p-values are used, you use $1-p_i$ instead of $p_i$ in the calculation of the $Z_i$.
|
Testing two-tailed p-values using Stouffer's approach
|
1) If two-sided p-values are being analyzed, you use the two-sided p-value in the calculation of the $Z_i$. The two-sided p-value is $\tilde{p}_i = p_i/2$.
2) If left-tailed p-values are used, you us
|
Testing two-tailed p-values using Stouffer's approach
1) If two-sided p-values are being analyzed, you use the two-sided p-value in the calculation of the $Z_i$. The two-sided p-value is $\tilde{p}_i = p_i/2$.
2) If left-tailed p-values are used, you use $1-p_i$ instead of $p_i$ in the calculation of the $Z_i$.
|
Testing two-tailed p-values using Stouffer's approach
1) If two-sided p-values are being analyzed, you use the two-sided p-value in the calculation of the $Z_i$. The two-sided p-value is $\tilde{p}_i = p_i/2$.
2) If left-tailed p-values are used, you us
|
45,925
|
Calculating mutual Information
|
To be a little more explicit, what you are really doing is performing a double sum where you are iterating over all possible states of feature $X_i$ as well as all possible states of $C$. In your particular instance $C$ happens to be binary; that is, it has only two states (spam and ham).
As for $X_i$, it's a little unclear but I'm guessing that is also a binary feature that indicates either the presence or absence of word $i$. So there are really 4 terms in your summation: word $i$ is present in spam, word $i$ is absent in spam, word $i$ is present in ham, and word $i$ is absent in ham.
So the $P(X_i)$ parts are really:
P(word $i$ is present)
P(word $i$ is absent)
The $P(C)$ parts are really:
P(class is spam)
P(class is ham)
Then the $P(X_i, C)$ bits are really:
P(word $i$ is present and class is spam)
P(word $i$ is absent and class is spam)
P(word $i$ is present and class is ham)
P(word $i$ is absent and class is ham)
You can then plug these values into the summation accordingly.
|
Calculating mutual Information
|
To be a little more explicit, what you are really doing is performing a double sum where you are iterating over all possible states of feature $X_i$ as well as all possible states of $C$. In your par
|
Calculating mutual Information
To be a little more explicit, what you are really doing is performing a double sum where you are iterating over all possible states of feature $X_i$ as well as all possible states of $C$. In your particular instance $C$ happens to be binary; that is, it has only two states (spam and ham).
As for $X_i$, it's a little unclear but I'm guessing that is also a binary feature that indicates either the presence or absence of word $i$. So there are really 4 terms in your summation: word $i$ is present in spam, word $i$ is absent in spam, word $i$ is present in ham, and word $i$ is absent in ham.
So the $P(X_i)$ parts are really:
P(word $i$ is present)
P(word $i$ is absent)
The $P(C)$ parts are really:
P(class is spam)
P(class is ham)
Then the $P(X_i, C)$ bits are really:
P(word $i$ is present and class is spam)
P(word $i$ is absent and class is spam)
P(word $i$ is present and class is ham)
P(word $i$ is absent and class is ham)
You can then plug these values into the summation accordingly.
|
Calculating mutual Information
To be a little more explicit, what you are really doing is performing a double sum where you are iterating over all possible states of feature $X_i$ as well as all possible states of $C$. In your par
|
45,926
|
What causes loss of power in hypothesis testing?
|
There is an enormous literature on this subject; I'll just give you a quick thumbnail sketch. Let's say you're testing groups' mean differences, as in T-tests. Power will be reduced if...
...variables are measured unreliably. This will in essence "fuzz over" the differences.
...variability within groups is high. This will render between-group differences less noteworthy.
...your criterion for statistical significance is strict, e.g., .001 as opposed to the more common .05.
...you are using a one-tailed test, hypothesizing that if there is a difference, a certain group will have the higher mean. This cuts down on opportunistically significant findings that occur with two-tailed tests.
...you are dealing with (or expecting) very slim mean differences in the first place. Small effect sizes decrease power.
If you google "power calculator" you'll find some nifty sites that demonstrate the way these factors interact, depending on values you input. And if you download the free Gpower3 program you'll have a nice tool for calculating power and considering the effects of different conditions--for a wide variety of statistical procedures.
|
What causes loss of power in hypothesis testing?
|
There is an enormous literature on this subject; I'll just give you a quick thumbnail sketch. Let's say you're testing groups' mean differences, as in T-tests. Power will be reduced if...
...variab
|
What causes loss of power in hypothesis testing?
There is an enormous literature on this subject; I'll just give you a quick thumbnail sketch. Let's say you're testing groups' mean differences, as in T-tests. Power will be reduced if...
...variables are measured unreliably. This will in essence "fuzz over" the differences.
...variability within groups is high. This will render between-group differences less noteworthy.
...your criterion for statistical significance is strict, e.g., .001 as opposed to the more common .05.
...you are using a one-tailed test, hypothesizing that if there is a difference, a certain group will have the higher mean. This cuts down on opportunistically significant findings that occur with two-tailed tests.
...you are dealing with (or expecting) very slim mean differences in the first place. Small effect sizes decrease power.
If you google "power calculator" you'll find some nifty sites that demonstrate the way these factors interact, depending on values you input. And if you download the free Gpower3 program you'll have a nice tool for calculating power and considering the effects of different conditions--for a wide variety of statistical procedures.
|
What causes loss of power in hypothesis testing?
There is an enormous literature on this subject; I'll just give you a quick thumbnail sketch. Let's say you're testing groups' mean differences, as in T-tests. Power will be reduced if...
...variab
|
45,927
|
What causes loss of power in hypothesis testing?
|
Think of power as your ability to recognize the truthfulness of one of two competing data generating processes. It will obviously be easier when:
The data have much signal with little noise (good SNR).
The competing processes are very different one from the other (null and alternative are separated).
You have ample amounts of data.
You are not too concerned with mistakes (large type I error rate).
If the above do not hold, it will be harder to choose the "true" process. I.e., you will lose power.
|
What causes loss of power in hypothesis testing?
|
Think of power as your ability to recognize the truthfulness of one of two competing data generating processes. It will obviously be easier when:
The data have much signal with little noise (good SNR
|
What causes loss of power in hypothesis testing?
Think of power as your ability to recognize the truthfulness of one of two competing data generating processes. It will obviously be easier when:
The data have much signal with little noise (good SNR).
The competing processes are very different one from the other (null and alternative are separated).
You have ample amounts of data.
You are not too concerned with mistakes (large type I error rate).
If the above do not hold, it will be harder to choose the "true" process. I.e., you will lose power.
|
What causes loss of power in hypothesis testing?
Think of power as your ability to recognize the truthfulness of one of two competing data generating processes. It will obviously be easier when:
The data have much signal with little noise (good SNR
|
45,928
|
How to interpret 95%CI's in conjunction with significance tests for differences between group means?
|
The main message
Your hypothesis pertains to differences between two group means. The confidence intervals you mention pertain to the actual group means themselves.
You probably want to estimate and report the confidence interval of the difference between group means rather than confidence intervals of the group means.
When the 95% confidence interval of the difference between group means does not include zero, then your p-value should also be less than .05 (although exceptions could occur if you used a standard t-test for the significance test and bootstrapping for the confidence intervals). Thus, the tension you discuss between overlapping confidence intervals of individual group means and the significance test will be resolved.
R Example
Here's a little R simulation to demonstrate the idea.
First let us create some data for two groups, n=100 per group, drawn from a population with mean difference between groups of d=.35
> set.seed(4444)
> n <- 100
> g1 <- rnorm(n, mean = 0, sd = 1)
> g2 <- rnorm(n, mean = 0.35, sd = 1)
We can have a quick look at the group means and the difference between group means.
> # Group means
> round(mean(g1), 2)
[1] 0.11
> round(mean(g2), 2)
[1] 0.46
> round(mean(g2) - mean(g1), 2)
[1] 0.35
We can then have a look at the confidence intervals for the individual group means.
> round(as.numeric(t.test(g1, conf.level=.95)$conf.int), 2)
[1] -0.10 0.31
> round(as.numeric(t.test(g2, conf.level=.95)$conf.int), 2)
[1] 0.26 0.66
See how the group means have overlapping confidence intervals (i.e., .31 is larger than .26).
However we can look at the confidence interval of interest; i.e., the confidence interval of the difference between group means.
> round(as.numeric(t.test(g2, g1, conf.level=.95)$conf.int), 2)
[1] 0.07 0.64
It does not include zero.
We can now perform at t-test looking at differences between group means and see that the p-value is less than .05 consistent with the confidence interval of the difference between group means.
> t.test(g2, g1)
Welch Two Sample t-test
data: g2 and g1
t = 2.4506, df = 197.308, p-value = 0.01513
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
0.06897783 0.63745786
sample estimates:
mean of x mean of y
0.4588689 0.1056511
|
How to interpret 95%CI's in conjunction with significance tests for differences between group means?
|
The main message
Your hypothesis pertains to differences between two group means. The confidence intervals you mention pertain to the actual group means themselves.
You probably want to estimate and
|
How to interpret 95%CI's in conjunction with significance tests for differences between group means?
The main message
Your hypothesis pertains to differences between two group means. The confidence intervals you mention pertain to the actual group means themselves.
You probably want to estimate and report the confidence interval of the difference between group means rather than confidence intervals of the group means.
When the 95% confidence interval of the difference between group means does not include zero, then your p-value should also be less than .05 (although exceptions could occur if you used a standard t-test for the significance test and bootstrapping for the confidence intervals). Thus, the tension you discuss between overlapping confidence intervals of individual group means and the significance test will be resolved.
R Example
Here's a little R simulation to demonstrate the idea.
First let us create some data for two groups, n=100 per group, drawn from a population with mean difference between groups of d=.35
> set.seed(4444)
> n <- 100
> g1 <- rnorm(n, mean = 0, sd = 1)
> g2 <- rnorm(n, mean = 0.35, sd = 1)
We can have a quick look at the group means and the difference between group means.
> # Group means
> round(mean(g1), 2)
[1] 0.11
> round(mean(g2), 2)
[1] 0.46
> round(mean(g2) - mean(g1), 2)
[1] 0.35
We can then have a look at the confidence intervals for the individual group means.
> round(as.numeric(t.test(g1, conf.level=.95)$conf.int), 2)
[1] -0.10 0.31
> round(as.numeric(t.test(g2, conf.level=.95)$conf.int), 2)
[1] 0.26 0.66
See how the group means have overlapping confidence intervals (i.e., .31 is larger than .26).
However we can look at the confidence interval of interest; i.e., the confidence interval of the difference between group means.
> round(as.numeric(t.test(g2, g1, conf.level=.95)$conf.int), 2)
[1] 0.07 0.64
It does not include zero.
We can now perform at t-test looking at differences between group means and see that the p-value is less than .05 consistent with the confidence interval of the difference between group means.
> t.test(g2, g1)
Welch Two Sample t-test
data: g2 and g1
t = 2.4506, df = 197.308, p-value = 0.01513
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
0.06897783 0.63745786
sample estimates:
mean of x mean of y
0.4588689 0.1056511
|
How to interpret 95%CI's in conjunction with significance tests for differences between group means?
The main message
Your hypothesis pertains to differences between two group means. The confidence intervals you mention pertain to the actual group means themselves.
You probably want to estimate and
|
45,929
|
How to interpret 95%CI's in conjunction with significance tests for differences between group means?
|
95%CI's around your individual group means (I'm assuming it's an independent group design) will overlap when the t-test is significant at 0.05 (they typically don't separate until p<0.01). The minimum distance required between the means is the size of 1 CI bar x sqrt(2). What you'll find if you calculate the CI of the difference between the means (which many t-tests report) is that's it's approximately your original CI x sqrt(2). This is a known method of interpreting those CIs and something you could include in your figure caption if you wish.
To understand this you might recall that the denominator of a t-test has a 2x multiplier for the MSE. That's because the variance of the difference between means is double the variance of the means. The standard deviation is the sqrt of the variance. The standard error used in testing the difference is a standard deviation of the distribution of sampling means. Therefore, the factor differing between individual mean standard errors, and effect standard errors is sqrt(2).
So, that's the way to understand why they can overlap and still be significantly different. For goodness sake though, don't move to standard errors if you find this confusing because they have an even less consistent inferential interpretation that's dependent upon N.
The best way to present your data is with confidence intervals of your means and of your effect. This makes your data easy to interpret for the unitiated and you could even leave the t-test out then. Each of these confidence intervals should be interpreted in your text as including what you believe are likely values for the means and effects. Values outside of these you believe to be unlikely. If 0 is outside your effect CI then you would conclude you had a significant effect. But the CI is much more meaningful than just concluding significance because you are also making a statement about the likely location of the true magnitude of the effect.
|
How to interpret 95%CI's in conjunction with significance tests for differences between group means?
|
95%CI's around your individual group means (I'm assuming it's an independent group design) will overlap when the t-test is significant at 0.05 (they typically don't separate until p<0.01). The minimu
|
How to interpret 95%CI's in conjunction with significance tests for differences between group means?
95%CI's around your individual group means (I'm assuming it's an independent group design) will overlap when the t-test is significant at 0.05 (they typically don't separate until p<0.01). The minimum distance required between the means is the size of 1 CI bar x sqrt(2). What you'll find if you calculate the CI of the difference between the means (which many t-tests report) is that's it's approximately your original CI x sqrt(2). This is a known method of interpreting those CIs and something you could include in your figure caption if you wish.
To understand this you might recall that the denominator of a t-test has a 2x multiplier for the MSE. That's because the variance of the difference between means is double the variance of the means. The standard deviation is the sqrt of the variance. The standard error used in testing the difference is a standard deviation of the distribution of sampling means. Therefore, the factor differing between individual mean standard errors, and effect standard errors is sqrt(2).
So, that's the way to understand why they can overlap and still be significantly different. For goodness sake though, don't move to standard errors if you find this confusing because they have an even less consistent inferential interpretation that's dependent upon N.
The best way to present your data is with confidence intervals of your means and of your effect. This makes your data easy to interpret for the unitiated and you could even leave the t-test out then. Each of these confidence intervals should be interpreted in your text as including what you believe are likely values for the means and effects. Values outside of these you believe to be unlikely. If 0 is outside your effect CI then you would conclude you had a significant effect. But the CI is much more meaningful than just concluding significance because you are also making a statement about the likely location of the true magnitude of the effect.
|
How to interpret 95%CI's in conjunction with significance tests for differences between group means?
95%CI's around your individual group means (I'm assuming it's an independent group design) will overlap when the t-test is significant at 0.05 (they typically don't separate until p<0.01). The minimu
|
45,930
|
How to forecast CPU demand from a time series?
|
Start with the forecast package in R. Both auto.arima and ets have predict and forecast methods that are useful.
Here is an example:
#Make a periodic dataset
set.seed(1)
data <- c(3,2,1,5,7,8,9,1,3,12,4,5)
data <- rep(data,5)
data <- data+seq(1,length(data)) #Add trend
data <- data+rnorm(length(data))*5 #Add noise
data <- ts(data,frequency=12)
plot(data)
#Build models
library(forecast)
model1 <- StructTS(data)
model2 <- ets(data)
model3 <- auto.arima(data)
model4 <- stl(data,s.window='periodic')
#Test accuracy (on training data)
round(accuracy(model1),4)
round(accuracy(model2),4)
round(accuracy(model3),4)
p4 <- model4$time.series
p4 <- p4[,'seasonal']+p4[,'trend']+p4[,'remainder']
round(accuracy(data,p4),4) #This model needs to be tested OUT of sample
#Forecast 1 period
f1 <- forecast(model1,h=12) #this fails for some reason
f2 <- forecast(model2,h=12)
f3 <- forecast(model3,h=12)
f4 <- forecast(model4,h=12)
par(mfrow = c(2,2))
plot(f1)
plot(f2)
plot(f3)
plot(f4)
|
How to forecast CPU demand from a time series?
|
Start with the forecast package in R. Both auto.arima and ets have predict and forecast methods that are useful.
Here is an example:
#Make a periodic dataset
set.seed(1)
data <- c(3,2,1,5,7,8,9,1,3,1
|
How to forecast CPU demand from a time series?
Start with the forecast package in R. Both auto.arima and ets have predict and forecast methods that are useful.
Here is an example:
#Make a periodic dataset
set.seed(1)
data <- c(3,2,1,5,7,8,9,1,3,12,4,5)
data <- rep(data,5)
data <- data+seq(1,length(data)) #Add trend
data <- data+rnorm(length(data))*5 #Add noise
data <- ts(data,frequency=12)
plot(data)
#Build models
library(forecast)
model1 <- StructTS(data)
model2 <- ets(data)
model3 <- auto.arima(data)
model4 <- stl(data,s.window='periodic')
#Test accuracy (on training data)
round(accuracy(model1),4)
round(accuracy(model2),4)
round(accuracy(model3),4)
p4 <- model4$time.series
p4 <- p4[,'seasonal']+p4[,'trend']+p4[,'remainder']
round(accuracy(data,p4),4) #This model needs to be tested OUT of sample
#Forecast 1 period
f1 <- forecast(model1,h=12) #this fails for some reason
f2 <- forecast(model2,h=12)
f3 <- forecast(model3,h=12)
f4 <- forecast(model4,h=12)
par(mfrow = c(2,2))
plot(f1)
plot(f2)
plot(f3)
plot(f4)
|
How to forecast CPU demand from a time series?
Start with the forecast package in R. Both auto.arima and ets have predict and forecast methods that are useful.
Here is an example:
#Make a periodic dataset
set.seed(1)
data <- c(3,2,1,5,7,8,9,1,3,1
|
45,931
|
How to forecast CPU demand from a time series?
|
What you are doing is time series analysis, and there are many packages for that. Take a look at the Task View to get you started.
Probably the simplest analysis to do (and you should always start simple) is to decompose the series into a daily effect, a trend and irregular components. Take a look at the stl function.
|
How to forecast CPU demand from a time series?
|
What you are doing is time series analysis, and there are many packages for that. Take a look at the Task View to get you started.
Probably the simplest analysis to do (and you should always start si
|
How to forecast CPU demand from a time series?
What you are doing is time series analysis, and there are many packages for that. Take a look at the Task View to get you started.
Probably the simplest analysis to do (and you should always start simple) is to decompose the series into a daily effect, a trend and irregular components. Take a look at the stl function.
|
How to forecast CPU demand from a time series?
What you are doing is time series analysis, and there are many packages for that. Take a look at the Task View to get you started.
Probably the simplest analysis to do (and you should always start si
|
45,932
|
How to forecast CPU demand from a time series?
|
If you have reliable historical data, you can use an MCMC approach
check the following articles out,
http://lpenz.github.com/articles/df0pred-2/index.html
http://lpenz.github.com/articles/df0pred-3/index.html
He does prediction of hard drive space requirements using MCMC.
|
How to forecast CPU demand from a time series?
|
If you have reliable historical data, you can use an MCMC approach
check the following articles out,
http://lpenz.github.com/articles/df0pred-2/index.html
http://lpenz.github.com/articles/df0pred-3/i
|
How to forecast CPU demand from a time series?
If you have reliable historical data, you can use an MCMC approach
check the following articles out,
http://lpenz.github.com/articles/df0pred-2/index.html
http://lpenz.github.com/articles/df0pred-3/index.html
He does prediction of hard drive space requirements using MCMC.
|
How to forecast CPU demand from a time series?
If you have reliable historical data, you can use an MCMC approach
check the following articles out,
http://lpenz.github.com/articles/df0pred-2/index.html
http://lpenz.github.com/articles/df0pred-3/i
|
45,933
|
How to forecast CPU demand from a time series?
|
"I have 120 values showing the demand of 10 days of 12 hours each." . This is a mixed frequency problem where you might have an integrated model containing an ARIMA component describing the within day structure and a Transfer Function component ( generalization of regression ) to deal with the daily effects. These "daily effects" might be impacted by heretofore unknown ( but statistically identifiable via Intervention Detection ) Pulses, Level Shifts and Local Time Trends. Furthermore there may be day-of-the-week; day-of-the-month ; week/month of-the-year effects. There might also be patterns before ,on and after known events. Additionally there may be evidented non-constant error variance suggesting GLS/GARCH or even changes in parameters over time.
After forming such a model with proven Gaussian errors it seems to me a straightforward application using the confidence limits of the forecast vis-a-vis the last value to assess the probability that you are seeking.
|
How to forecast CPU demand from a time series?
|
"I have 120 values showing the demand of 10 days of 12 hours each." . This is a mixed frequency problem where you might have an integrated model containing an ARIMA component describing the within day
|
How to forecast CPU demand from a time series?
"I have 120 values showing the demand of 10 days of 12 hours each." . This is a mixed frequency problem where you might have an integrated model containing an ARIMA component describing the within day structure and a Transfer Function component ( generalization of regression ) to deal with the daily effects. These "daily effects" might be impacted by heretofore unknown ( but statistically identifiable via Intervention Detection ) Pulses, Level Shifts and Local Time Trends. Furthermore there may be day-of-the-week; day-of-the-month ; week/month of-the-year effects. There might also be patterns before ,on and after known events. Additionally there may be evidented non-constant error variance suggesting GLS/GARCH or even changes in parameters over time.
After forming such a model with proven Gaussian errors it seems to me a straightforward application using the confidence limits of the forecast vis-a-vis the last value to assess the probability that you are seeking.
|
How to forecast CPU demand from a time series?
"I have 120 values showing the demand of 10 days of 12 hours each." . This is a mixed frequency problem where you might have an integrated model containing an ARIMA component describing the within day
|
45,934
|
How to forecast CPU demand from a time series?
|
From a math aspect. They finding the distribution of your data (Poisson, exponential, uniform, etc). Calculate the average to get an approximate mean. Then apply the Central Limit Theorem to find the normal distribution of samples of averages. This will let you find a good confidence interval for your estimate of that mean.
|
How to forecast CPU demand from a time series?
|
From a math aspect. They finding the distribution of your data (Poisson, exponential, uniform, etc). Calculate the average to get an approximate mean. Then apply the Central Limit Theorem to find the
|
How to forecast CPU demand from a time series?
From a math aspect. They finding the distribution of your data (Poisson, exponential, uniform, etc). Calculate the average to get an approximate mean. Then apply the Central Limit Theorem to find the normal distribution of samples of averages. This will let you find a good confidence interval for your estimate of that mean.
|
How to forecast CPU demand from a time series?
From a math aspect. They finding the distribution of your data (Poisson, exponential, uniform, etc). Calculate the average to get an approximate mean. Then apply the Central Limit Theorem to find the
|
45,935
|
How to calculate skewness of data from histogram in R?
|
Sounds like you're looking at a published histogram and don't have the actual data?
If that is the case you could calculate a rough skewness figure by doing something like pub_his <- c(rep(10,16),rep(15,18),rep(20,27)...), picking the mid point of each bar and reading the frequency off the graph, then you'd have the data and could use the skewness function.
|
How to calculate skewness of data from histogram in R?
|
Sounds like you're looking at a published histogram and don't have the actual data?
If that is the case you could calculate a rough skewness figure by doing something like pub_his <- c(rep(10,16),rep(
|
How to calculate skewness of data from histogram in R?
Sounds like you're looking at a published histogram and don't have the actual data?
If that is the case you could calculate a rough skewness figure by doing something like pub_his <- c(rep(10,16),rep(15,18),rep(20,27)...), picking the mid point of each bar and reading the frequency off the graph, then you'd have the data and could use the skewness function.
|
How to calculate skewness of data from histogram in R?
Sounds like you're looking at a published histogram and don't have the actual data?
If that is the case you could calculate a rough skewness figure by doing something like pub_his <- c(rep(10,16),rep(
|
45,936
|
How to calculate skewness of data from histogram in R?
|
In the case of variance (and indeed for the fourth central moment), the "taking the bin center" approach carries a bias.
Such bias can be corrected, via what are known as Sheppard's correction e.g. see here, which in the case of variance would subtract $\frac{1}{12}$ of the square of the bin-width from the binned estimate of the second moment. However, in the case of the third moment, no such adjustment is needed.
On the other hand, the third-moment-skewness, if just calculated directly by dividing the binned third-moment by the unadjusted binned-variance to the power $\frac{3}{2}$ will yield too large a denominator, and so the skewness will be on average slightly underestimated.
This suggests that the binned variance be adjusted by Sheppard's correction before computing the skewness. So:
1) calculate the binned moments (first, second, third) as needed (i.e. by taking every observation at its bin center and if possible using the weighted/grouped-data formulas)
2) correct the variance for the grouping bias
3) compute the skewness by dividing the grouped third moment by the corrected grouped second moment.
However, you may want to ponder the circumstances under which the corrections apply. For example, you might see the discussion of the corrections in Kendall and Stuart, or maybe consult
M. G. Kendall (1938),
The Conditions under which Sheppard's Corrections are Valid
Journal of the Royal Statistical Society,
Vol. 101, No. 3, p592-605
[Even so, dividing an unbiased numerator by an unbiased denominator doesn't itself lead to an unbiased ratio, even when they're independent, so if an actually unbiased ratio is of interest, further analysis would be needed -- but we don't generally concern ourselves with that when dealing with ordinary sample skewness either.]
|
How to calculate skewness of data from histogram in R?
|
In the case of variance (and indeed for the fourth central moment), the "taking the bin center" approach carries a bias.
Such bias can be corrected, via what are known as Sheppard's correction e.g. se
|
How to calculate skewness of data from histogram in R?
In the case of variance (and indeed for the fourth central moment), the "taking the bin center" approach carries a bias.
Such bias can be corrected, via what are known as Sheppard's correction e.g. see here, which in the case of variance would subtract $\frac{1}{12}$ of the square of the bin-width from the binned estimate of the second moment. However, in the case of the third moment, no such adjustment is needed.
On the other hand, the third-moment-skewness, if just calculated directly by dividing the binned third-moment by the unadjusted binned-variance to the power $\frac{3}{2}$ will yield too large a denominator, and so the skewness will be on average slightly underestimated.
This suggests that the binned variance be adjusted by Sheppard's correction before computing the skewness. So:
1) calculate the binned moments (first, second, third) as needed (i.e. by taking every observation at its bin center and if possible using the weighted/grouped-data formulas)
2) correct the variance for the grouping bias
3) compute the skewness by dividing the grouped third moment by the corrected grouped second moment.
However, you may want to ponder the circumstances under which the corrections apply. For example, you might see the discussion of the corrections in Kendall and Stuart, or maybe consult
M. G. Kendall (1938),
The Conditions under which Sheppard's Corrections are Valid
Journal of the Royal Statistical Society,
Vol. 101, No. 3, p592-605
[Even so, dividing an unbiased numerator by an unbiased denominator doesn't itself lead to an unbiased ratio, even when they're independent, so if an actually unbiased ratio is of interest, further analysis would be needed -- but we don't generally concern ourselves with that when dealing with ordinary sample skewness either.]
|
How to calculate skewness of data from histogram in R?
In the case of variance (and indeed for the fourth central moment), the "taking the bin center" approach carries a bias.
Such bias can be corrected, via what are known as Sheppard's correction e.g. se
|
45,937
|
What are some applications of Chinese restaurant processes?
|
Here are some important papers that have applied nonparametric Bayes to topic modeling for example:
Blei et al., Hierarchical Topic Models and the Nested Chinese Restaurant Process, NIPS 2003.
Teh et al., Hierarchical Dirichlet Processes, JASA 2006.
You can find tons of other papers at aclweb.org.
|
What are some applications of Chinese restaurant processes?
|
Here are some important papers that have applied nonparametric Bayes to topic modeling for example:
Blei et al., Hierarchical Topic Models and the Nested Chinese Restaurant Process, NIPS 2003.
Teh et
|
What are some applications of Chinese restaurant processes?
Here are some important papers that have applied nonparametric Bayes to topic modeling for example:
Blei et al., Hierarchical Topic Models and the Nested Chinese Restaurant Process, NIPS 2003.
Teh et al., Hierarchical Dirichlet Processes, JASA 2006.
You can find tons of other papers at aclweb.org.
|
What are some applications of Chinese restaurant processes?
Here are some important papers that have applied nonparametric Bayes to topic modeling for example:
Blei et al., Hierarchical Topic Models and the Nested Chinese Restaurant Process, NIPS 2003.
Teh et
|
45,938
|
What are some applications of Chinese restaurant processes?
|
Kevin Knight's Bayesian Inference With Tears describes applications of the Chinese Restaurant Process (which he calls a "cache model") to tree substitution grammars, Chinese word segmentation, and part-of-speech tagging.
(If anyone knows the original sources for these applications, that'd be great as well.)
|
What are some applications of Chinese restaurant processes?
|
Kevin Knight's Bayesian Inference With Tears describes applications of the Chinese Restaurant Process (which he calls a "cache model") to tree substitution grammars, Chinese word segmentation, and par
|
What are some applications of Chinese restaurant processes?
Kevin Knight's Bayesian Inference With Tears describes applications of the Chinese Restaurant Process (which he calls a "cache model") to tree substitution grammars, Chinese word segmentation, and part-of-speech tagging.
(If anyone knows the original sources for these applications, that'd be great as well.)
|
What are some applications of Chinese restaurant processes?
Kevin Knight's Bayesian Inference With Tears describes applications of the Chinese Restaurant Process (which he calls a "cache model") to tree substitution grammars, Chinese word segmentation, and par
|
45,939
|
Critical values for Anderson-Darling test
|
Using Marsaglia & Marsaglia's code, and a bisection search, one can find that the 0.001 critical value is around 5.9694. This would be for 'Case 1' in the wikipedia article quoted. I am not sure how to convert to 'Case 4'.
|
Critical values for Anderson-Darling test
|
Using Marsaglia & Marsaglia's code, and a bisection search, one can find that the 0.001 critical value is around 5.9694. This would be for 'Case 1' in the wikipedia article quoted. I am not sure how t
|
Critical values for Anderson-Darling test
Using Marsaglia & Marsaglia's code, and a bisection search, one can find that the 0.001 critical value is around 5.9694. This would be for 'Case 1' in the wikipedia article quoted. I am not sure how to convert to 'Case 4'.
|
Critical values for Anderson-Darling test
Using Marsaglia & Marsaglia's code, and a bisection search, one can find that the 0.001 critical value is around 5.9694. This would be for 'Case 1' in the wikipedia article quoted. I am not sure how t
|
45,940
|
Critical values for Anderson-Darling test
|
You can use simulation (this is not a new idea, it is how Gosset/Student derived the original t table (but we have faster tools than he did)).
Generate a psuedo random sample from a normal distribution (or at least as close as the computer can come) of the sample size of interest and compute the Anderson Darling Statistic for that sample. Now repeate this process a few million times (or maybe more than a few depending on how precise you want to be). The 0.1% critical value will be the 0.1% or 99.9% percentile.
However, I have a hard time imagining a useful question that would be answered by an Anderson-Darling test at 0.1% significance. What is the question that you are trying to answer?
|
Critical values for Anderson-Darling test
|
You can use simulation (this is not a new idea, it is how Gosset/Student derived the original t table (but we have faster tools than he did)).
Generate a psuedo random sample from a normal distributio
|
Critical values for Anderson-Darling test
You can use simulation (this is not a new idea, it is how Gosset/Student derived the original t table (but we have faster tools than he did)).
Generate a psuedo random sample from a normal distribution (or at least as close as the computer can come) of the sample size of interest and compute the Anderson Darling Statistic for that sample. Now repeate this process a few million times (or maybe more than a few depending on how precise you want to be). The 0.1% critical value will be the 0.1% or 99.9% percentile.
However, I have a hard time imagining a useful question that would be answered by an Anderson-Darling test at 0.1% significance. What is the question that you are trying to answer?
|
Critical values for Anderson-Darling test
You can use simulation (this is not a new idea, it is how Gosset/Student derived the original t table (but we have faster tools than he did)).
Generate a psuedo random sample from a normal distributio
|
45,941
|
Stambaugh bias definition
|
I'm not sure you can explain this term without using some technical terms, unfortunately. I'll give it my best shot.
Some definitions first:
Bias: the difference between the expectation of an estimator and the true value of the parameter you're estimating.
OLS: Ordinary Least Squares; a method for solving a regression problem.
Autoregressive process (AR): (via Wikipedia)
Stambaugh bias occurs when you perform regression on a lagged stochastic input. Essentially, when you do this, you have to use an estimate for the input (regressor), which requires estimating autocorrelation coefficients. The bias in the autocorrelation coefficients is then proportional to the bias in the slope coefficient's estimate from the OLS. You can correct for this if you know that your method for computing autocorrelation coefficients is biased.
The original paper really isn't too complicated, so long as you know both what an AR process is and how OLS regression works: Paper.
|
Stambaugh bias definition
|
I'm not sure you can explain this term without using some technical terms, unfortunately. I'll give it my best shot.
Some definitions first:
Bias: the difference between the expectation of an estimat
|
Stambaugh bias definition
I'm not sure you can explain this term without using some technical terms, unfortunately. I'll give it my best shot.
Some definitions first:
Bias: the difference between the expectation of an estimator and the true value of the parameter you're estimating.
OLS: Ordinary Least Squares; a method for solving a regression problem.
Autoregressive process (AR): (via Wikipedia)
Stambaugh bias occurs when you perform regression on a lagged stochastic input. Essentially, when you do this, you have to use an estimate for the input (regressor), which requires estimating autocorrelation coefficients. The bias in the autocorrelation coefficients is then proportional to the bias in the slope coefficient's estimate from the OLS. You can correct for this if you know that your method for computing autocorrelation coefficients is biased.
The original paper really isn't too complicated, so long as you know both what an AR process is and how OLS regression works: Paper.
|
Stambaugh bias definition
I'm not sure you can explain this term without using some technical terms, unfortunately. I'll give it my best shot.
Some definitions first:
Bias: the difference between the expectation of an estimat
|
45,942
|
Stambaugh bias definition
|
This is the original paper that explains the Stambaugh bias: Stambaugh (JFE1999). It examines the bias in the slope coefficient in the predictive regression of returns on past dividend yields, when the dividend yield process is highly persistent.
Let $y_t$ denote the date $t$ return and $x_t=D_t/P_t$ the date $t$ dividend yield. Consider the following regression equations:
\begin{align*}
y_t &= \alpha+\beta\,x_{t-1}+u_t\\
x_t &= \theta+\rho\,x_{t-1}+v_t
\end{align*}
for $t=1,\ldots,T$ with
$\begin{bmatrix}u_t\\v_t\end{bmatrix}=\mathcal{N}\left(0,\Sigma=
\begin{bmatrix}
\sigma_u^2&\sigma_{uv}\\
\sigma_{uv}&\sigma_v^2
\end{bmatrix}\right)$.
The paper shows that the bias in $\beta$ is
$$\mathbb{E}\left[\hat{\beta}-\beta\right]=\frac{\sigma_{uv}}{\sigma^2_v}\mathbb{E}\left[\hat{\rho}-\rho\right],$$ where $\hat{\rho}$ is the OLS estimator of $\rho$.
The paper shows that $\hat{\rho}$ has a downward bias and $\sigma_{uv}$ is negative leading to an upward bias in $\hat{\beta}$.
|
Stambaugh bias definition
|
This is the original paper that explains the Stambaugh bias: Stambaugh (JFE1999). It examines the bias in the slope coefficient in the predictive regression of returns on past dividend yields, when th
|
Stambaugh bias definition
This is the original paper that explains the Stambaugh bias: Stambaugh (JFE1999). It examines the bias in the slope coefficient in the predictive regression of returns on past dividend yields, when the dividend yield process is highly persistent.
Let $y_t$ denote the date $t$ return and $x_t=D_t/P_t$ the date $t$ dividend yield. Consider the following regression equations:
\begin{align*}
y_t &= \alpha+\beta\,x_{t-1}+u_t\\
x_t &= \theta+\rho\,x_{t-1}+v_t
\end{align*}
for $t=1,\ldots,T$ with
$\begin{bmatrix}u_t\\v_t\end{bmatrix}=\mathcal{N}\left(0,\Sigma=
\begin{bmatrix}
\sigma_u^2&\sigma_{uv}\\
\sigma_{uv}&\sigma_v^2
\end{bmatrix}\right)$.
The paper shows that the bias in $\beta$ is
$$\mathbb{E}\left[\hat{\beta}-\beta\right]=\frac{\sigma_{uv}}{\sigma^2_v}\mathbb{E}\left[\hat{\rho}-\rho\right],$$ where $\hat{\rho}$ is the OLS estimator of $\rho$.
The paper shows that $\hat{\rho}$ has a downward bias and $\sigma_{uv}$ is negative leading to an upward bias in $\hat{\beta}$.
|
Stambaugh bias definition
This is the original paper that explains the Stambaugh bias: Stambaugh (JFE1999). It examines the bias in the slope coefficient in the predictive regression of returns on past dividend yields, when th
|
45,943
|
Can anyone explain why I have obtained an anti-predictive Support Vector Machine?
|
It is very probably the settings for the hyper-parameters that are the issue, leading to severe over-fitting of the data. Without proper tuning of the hyper-parameters, and SVM can perform arbitrarily badly, especially for high dimensional data (it is the tuning of the regularisation parameter that gives robustness against over-fitting in high dimensional spaces). I would suggest nested cross-validation, with the outer (leave-oue-out) cross-validation used form performance estimation and the hyper-parameters tuned independently in each fold by minimising a cross-validation based model selection criterion (I use Nelder-Mead simplex method rather than grid search).
The short answer, is never use default hyper-parameter values, always tune them afresh for each new (partition of the) dataset.
|
Can anyone explain why I have obtained an anti-predictive Support Vector Machine?
|
It is very probably the settings for the hyper-parameters that are the issue, leading to severe over-fitting of the data. Without proper tuning of the hyper-parameters, and SVM can perform arbitraril
|
Can anyone explain why I have obtained an anti-predictive Support Vector Machine?
It is very probably the settings for the hyper-parameters that are the issue, leading to severe over-fitting of the data. Without proper tuning of the hyper-parameters, and SVM can perform arbitrarily badly, especially for high dimensional data (it is the tuning of the regularisation parameter that gives robustness against over-fitting in high dimensional spaces). I would suggest nested cross-validation, with the outer (leave-oue-out) cross-validation used form performance estimation and the hyper-parameters tuned independently in each fold by minimising a cross-validation based model selection criterion (I use Nelder-Mead simplex method rather than grid search).
The short answer, is never use default hyper-parameter values, always tune them afresh for each new (partition of the) dataset.
|
Can anyone explain why I have obtained an anti-predictive Support Vector Machine?
It is very probably the settings for the hyper-parameters that are the issue, leading to severe over-fitting of the data. Without proper tuning of the hyper-parameters, and SVM can perform arbitraril
|
45,944
|
How to estimate a critical value of Spearman's correlation for n=100?
|
For values over thirty the approximation (for a two-tailed test) is
$$\frac{\Phi^{-1}\left(1-\tfrac{\alpha}{2}\right)}{\sqrt{n-1}}$$
so for example with $\alpha = 0.05$ and $n=100$ the numerator is about 1.96 and the denominator about 9.95, giving a critical value of about 0.197.
This comes from $\rho$ having approximately a normal distribution for large $n$, with mean $0$ and variance $1/(n − 1)$, assuming independence of the observations.
|
How to estimate a critical value of Spearman's correlation for n=100?
|
For values over thirty the approximation (for a two-tailed test) is
$$\frac{\Phi^{-1}\left(1-\tfrac{\alpha}{2}\right)}{\sqrt{n-1}}$$
so for example with $\alpha = 0.05$ and $n=100$ the numerator is a
|
How to estimate a critical value of Spearman's correlation for n=100?
For values over thirty the approximation (for a two-tailed test) is
$$\frac{\Phi^{-1}\left(1-\tfrac{\alpha}{2}\right)}{\sqrt{n-1}}$$
so for example with $\alpha = 0.05$ and $n=100$ the numerator is about 1.96 and the denominator about 9.95, giving a critical value of about 0.197.
This comes from $\rho$ having approximately a normal distribution for large $n$, with mean $0$ and variance $1/(n − 1)$, assuming independence of the observations.
|
How to estimate a critical value of Spearman's correlation for n=100?
For values over thirty the approximation (for a two-tailed test) is
$$\frac{\Phi^{-1}\left(1-\tfrac{\alpha}{2}\right)}{\sqrt{n-1}}$$
so for example with $\alpha = 0.05$ and $n=100$ the numerator is a
|
45,945
|
How to estimate a critical value of Spearman's correlation for n=100?
|
See Wikipedia: Spearman's rank correlation coefficient#Determining significance:
"One can test for significance using
$$t = r \sqrt{\frac{n-2}{1-r^2}},$$
which is distributed approximately as Student's $t$ distribution with $n − 2$ degrees of freedom under the null hypothesis."
Here $r$ is the sample estimate of Spearman's rank correlation coefficient. The reason critical values often aren't tabulated for $n > 30$ is that this approximation gets better as $n$ gets larger, and is very good for $n > 30$. The Stata statistical software package uses this formula to calculate $p$-values for all values of $n$.
|
How to estimate a critical value of Spearman's correlation for n=100?
|
See Wikipedia: Spearman's rank correlation coefficient#Determining significance:
"One can test for significance using
$$t = r \sqrt{\frac{n-2}{1-r^2}},$$
which is distributed approximately as Student'
|
How to estimate a critical value of Spearman's correlation for n=100?
See Wikipedia: Spearman's rank correlation coefficient#Determining significance:
"One can test for significance using
$$t = r \sqrt{\frac{n-2}{1-r^2}},$$
which is distributed approximately as Student's $t$ distribution with $n − 2$ degrees of freedom under the null hypothesis."
Here $r$ is the sample estimate of Spearman's rank correlation coefficient. The reason critical values often aren't tabulated for $n > 30$ is that this approximation gets better as $n$ gets larger, and is very good for $n > 30$. The Stata statistical software package uses this formula to calculate $p$-values for all values of $n$.
|
How to estimate a critical value of Spearman's correlation for n=100?
See Wikipedia: Spearman's rank correlation coefficient#Determining significance:
"One can test for significance using
$$t = r \sqrt{\frac{n-2}{1-r^2}},$$
which is distributed approximately as Student'
|
45,946
|
Number of trials required from a binomial distribution to get the desired odds
|
I wonder what it means to be "99% sure."
The code seems to equate "dumb luck" with $p$ = 52.8% probability of wins. Let's imagine conducting $N$ trials, during which we observe $k$ wins. Suppose, for instance, $N$ = 1000 and you observe $k$ = 530 wins. That's greater than the expected number $p N$ = 528, but it's so close that a sceptic would argue it could be due to chance: "dumb luck." So, you need a test. The best test uses a threshold $t$ (which depends, obviously, on $N$ and $p$ and will be a bit greater than $N p$). The chance--still assuming $p$ = 52.8%--of having more than $t$ wins needs to be so low that if you do observe more than $t$ wins, both you and a reasonable sceptic will allow that $p$ is probably greater than 52.8%. This chance is usually called $\alpha$, the "false positive rate." Your first task is to set this threshold. How will you do it? That is, what value of $\alpha$ do you want to use? Does "99% sure" mean that $1 - \alpha$ should equal 99%?
The second task is to consider your chances of beating the threshold if in fact $p$ equals 55% (or whatever you choose). Does "99% sure" mean you want to have a 99% chance of having more than $t$ wins in $N$ trials when $p$ = 55%?
So, it seems to me there are two chances involved here: one in determining the test to distinguish "dumb luck" and another one that will subsequently determine how many trials you need. If this analysis correctly reflects the situation, the problem is easily solved. Note a few things:
There are plenty of uncertainties about this procedure and some of them are not captured by the statistical model. Therefore we shouldn't aim for too much precision. There's really no difference between, say, 2742 and 2749 trials.
In case it turns out hundreds or thousands of trials are needed, the (usual) Normal approximation to the Binomial distribution will be highly accurate. Point #1 justifies using an approximation.
Consequently, there is a simple formula to compute the number of trials directly: no need to explore hundreds of possibilities!
The formula alluded to in #3 is this: in $N$ trials with probability $p$ of winning, the standard error of the proportion of wins is
$$s = \sqrt{p(1-p)/N}.$$
The threshold therefore should be
$$t(N) = N(p + z_\alpha s)$$
where $z_\alpha$ is the upper $100 - 100\alpha$ percentile of the standard normal distribution. If the true probability of a win actually is $q$ (such as $q$ = 55%), the chance of exceeding $t(N)$ in $N$ trials equals
$$\Phi\left(\frac{(q-t(N)/N)\sqrt{N}}{\sqrt{q(1-q)}}\right)
= \Phi\left(\frac{(q-p)\sqrt{N} - z_\alpha \sqrt{p(1-p)}}{\sqrt{q(1-q)}}\right)
$$
where $\Phi$ denotes the standard normal cumulative distribution function. Equating this with your desired degree of certainty (such as $\beta$ = 99%) and solving this equation for $N$ (rounding up to the nearest integer) gives the solution
$$N = \left(\frac{z_\alpha \sqrt{p(1-p)} + z_\beta \sqrt{q(1-q)}}{q-p}\right)^2$$
(assuming $q \gt p$).
Example
For $p$ = 52.8%, $q$ = 55%, $\alpha$ = 1%, and $\beta$ = 99%, which give $z_\alpha$ = $z_\beta$ = 2.32635, I obtain $N$ = 11109 with this formula. In 11109 trials you would expect to win about 5866 times by "dumb luck" and maybe as many as $t$ = 5988 times due to chance variation. If the true winning percentage is 55%, you expect to win about 6110 times, but there's a 1% chance you will win 5988 or fewer times, and thereby (due to "bad luck") not succeed in showing (with 99% confidence) that "dumb luck" isn't operating.
R code for the example
#
# Specify inputs.
#
p <- 52.8/100 # Null hypothesis
q <- 55/100 # Alternative
alpha <- 1/100 # Test size
beta <- 99/100 # Chance of confirming the alternative
#
# Compute number of trials.
#
s.p <- sqrt(p*(1-p))
s.q <- sqrt(q*(1-q))
z.alpha <- qnorm(1 - alpha)
z.beta <- qnorm(beta)
delta <- q - p
N <- ceiling(((z.alpha * s.p + z.beta * s.q)/delta)^2)
#
# Explain.
#
t <- floor(N*(p + z.alpha*se.p)) # Threshold
m <- round(N*p) # Expectation (null)
k <- round(N*q) # Expectation (alternate)
size <- pnorm((t + 1/2 - N*p)/(s.p * sqrt(N))) # Actual test size
sureness <- 1 - pnorm((N*q - (t + 1/2))/(s.q * sqrt(N)))
print(list(N=N, threshold=t, expectation=m, alternate=k,
size=size, sureness=sureness))
|
Number of trials required from a binomial distribution to get the desired odds
|
I wonder what it means to be "99% sure."
The code seems to equate "dumb luck" with $p$ = 52.8% probability of wins. Let's imagine conducting $N$ trials, during which we observe $k$ wins. Suppose, fo
|
Number of trials required from a binomial distribution to get the desired odds
I wonder what it means to be "99% sure."
The code seems to equate "dumb luck" with $p$ = 52.8% probability of wins. Let's imagine conducting $N$ trials, during which we observe $k$ wins. Suppose, for instance, $N$ = 1000 and you observe $k$ = 530 wins. That's greater than the expected number $p N$ = 528, but it's so close that a sceptic would argue it could be due to chance: "dumb luck." So, you need a test. The best test uses a threshold $t$ (which depends, obviously, on $N$ and $p$ and will be a bit greater than $N p$). The chance--still assuming $p$ = 52.8%--of having more than $t$ wins needs to be so low that if you do observe more than $t$ wins, both you and a reasonable sceptic will allow that $p$ is probably greater than 52.8%. This chance is usually called $\alpha$, the "false positive rate." Your first task is to set this threshold. How will you do it? That is, what value of $\alpha$ do you want to use? Does "99% sure" mean that $1 - \alpha$ should equal 99%?
The second task is to consider your chances of beating the threshold if in fact $p$ equals 55% (or whatever you choose). Does "99% sure" mean you want to have a 99% chance of having more than $t$ wins in $N$ trials when $p$ = 55%?
So, it seems to me there are two chances involved here: one in determining the test to distinguish "dumb luck" and another one that will subsequently determine how many trials you need. If this analysis correctly reflects the situation, the problem is easily solved. Note a few things:
There are plenty of uncertainties about this procedure and some of them are not captured by the statistical model. Therefore we shouldn't aim for too much precision. There's really no difference between, say, 2742 and 2749 trials.
In case it turns out hundreds or thousands of trials are needed, the (usual) Normal approximation to the Binomial distribution will be highly accurate. Point #1 justifies using an approximation.
Consequently, there is a simple formula to compute the number of trials directly: no need to explore hundreds of possibilities!
The formula alluded to in #3 is this: in $N$ trials with probability $p$ of winning, the standard error of the proportion of wins is
$$s = \sqrt{p(1-p)/N}.$$
The threshold therefore should be
$$t(N) = N(p + z_\alpha s)$$
where $z_\alpha$ is the upper $100 - 100\alpha$ percentile of the standard normal distribution. If the true probability of a win actually is $q$ (such as $q$ = 55%), the chance of exceeding $t(N)$ in $N$ trials equals
$$\Phi\left(\frac{(q-t(N)/N)\sqrt{N}}{\sqrt{q(1-q)}}\right)
= \Phi\left(\frac{(q-p)\sqrt{N} - z_\alpha \sqrt{p(1-p)}}{\sqrt{q(1-q)}}\right)
$$
where $\Phi$ denotes the standard normal cumulative distribution function. Equating this with your desired degree of certainty (such as $\beta$ = 99%) and solving this equation for $N$ (rounding up to the nearest integer) gives the solution
$$N = \left(\frac{z_\alpha \sqrt{p(1-p)} + z_\beta \sqrt{q(1-q)}}{q-p}\right)^2$$
(assuming $q \gt p$).
Example
For $p$ = 52.8%, $q$ = 55%, $\alpha$ = 1%, and $\beta$ = 99%, which give $z_\alpha$ = $z_\beta$ = 2.32635, I obtain $N$ = 11109 with this formula. In 11109 trials you would expect to win about 5866 times by "dumb luck" and maybe as many as $t$ = 5988 times due to chance variation. If the true winning percentage is 55%, you expect to win about 6110 times, but there's a 1% chance you will win 5988 or fewer times, and thereby (due to "bad luck") not succeed in showing (with 99% confidence) that "dumb luck" isn't operating.
R code for the example
#
# Specify inputs.
#
p <- 52.8/100 # Null hypothesis
q <- 55/100 # Alternative
alpha <- 1/100 # Test size
beta <- 99/100 # Chance of confirming the alternative
#
# Compute number of trials.
#
s.p <- sqrt(p*(1-p))
s.q <- sqrt(q*(1-q))
z.alpha <- qnorm(1 - alpha)
z.beta <- qnorm(beta)
delta <- q - p
N <- ceiling(((z.alpha * s.p + z.beta * s.q)/delta)^2)
#
# Explain.
#
t <- floor(N*(p + z.alpha*se.p)) # Threshold
m <- round(N*p) # Expectation (null)
k <- round(N*q) # Expectation (alternate)
size <- pnorm((t + 1/2 - N*p)/(s.p * sqrt(N))) # Actual test size
sureness <- 1 - pnorm((N*q - (t + 1/2))/(s.q * sqrt(N)))
print(list(N=N, threshold=t, expectation=m, alternate=k,
size=size, sureness=sureness))
|
Number of trials required from a binomial distribution to get the desired odds
I wonder what it means to be "99% sure."
The code seems to equate "dumb luck" with $p$ = 52.8% probability of wins. Let's imagine conducting $N$ trials, during which we observe $k$ wins. Suppose, fo
|
45,947
|
Number of trials required from a binomial distribution to get the desired odds
|
numtri[c(min(which(perwin <= 0.55)),max(which(perwin >= 0.55)))]
|
Number of trials required from a binomial distribution to get the desired odds
|
numtri[c(min(which(perwin <= 0.55)),max(which(perwin >= 0.55)))]
|
Number of trials required from a binomial distribution to get the desired odds
numtri[c(min(which(perwin <= 0.55)),max(which(perwin >= 0.55)))]
|
Number of trials required from a binomial distribution to get the desired odds
numtri[c(min(which(perwin <= 0.55)),max(which(perwin >= 0.55)))]
|
45,948
|
Minimization of a function by Metropolis-Hastings algorithms
|
You are rather looking for a simulated annealing, which is easier to understand when formulated in the original, physics way:
Having
$x$ is a state of the system
$f(x)$ is an energy of the system; energy is defined up to addition of a constant, so there is no problem with it being negative or positive -- the only constraint is the-lower-the-better
$T$ is a temperature of the system, and $kT$ is this temperature expressed in energy units
the MH algorithm, formulated as
$x'=x+\text{random change}$
if $\big\{\exp{\frac{f(x)-f(x')}{kT}}>R(0;1)\big\}$ than $x=x'$
goto 1
recreates the same occupancy of particular states (values of $x$) as for a system placed in temperature $T$, as shown by Metropolis in his pioneer work.
Physical systems tend to spontaneously go into the lowest energy state and stay there, so after initial relaxation $x$ should generally oscillate around minimum. Those oscillations' amplitude depends on temperature, so simulated annealing reduces $T$ during run to reduce them and make more accurate localisation of minimum. Initially high temperature is required to prevent the system from landing and staying stuck for a very long time in some local minimum.
EDIT: If you were told that you should use just Metropolis-Hastings, it most probably means you should do this this way, only with constant temperature (constantly deceasing temperature is the only thing that simulated annealing adds to MH). Then you will need to make few experiments to figure out a good temperature, so that there will be quite good accuracy no stucking in the local minima.
|
Minimization of a function by Metropolis-Hastings algorithms
|
You are rather looking for a simulated annealing, which is easier to understand when formulated in the original, physics way:
Having
$x$ is a state of the system
$f(x)$ is an energy of the system; en
|
Minimization of a function by Metropolis-Hastings algorithms
You are rather looking for a simulated annealing, which is easier to understand when formulated in the original, physics way:
Having
$x$ is a state of the system
$f(x)$ is an energy of the system; energy is defined up to addition of a constant, so there is no problem with it being negative or positive -- the only constraint is the-lower-the-better
$T$ is a temperature of the system, and $kT$ is this temperature expressed in energy units
the MH algorithm, formulated as
$x'=x+\text{random change}$
if $\big\{\exp{\frac{f(x)-f(x')}{kT}}>R(0;1)\big\}$ than $x=x'$
goto 1
recreates the same occupancy of particular states (values of $x$) as for a system placed in temperature $T$, as shown by Metropolis in his pioneer work.
Physical systems tend to spontaneously go into the lowest energy state and stay there, so after initial relaxation $x$ should generally oscillate around minimum. Those oscillations' amplitude depends on temperature, so simulated annealing reduces $T$ during run to reduce them and make more accurate localisation of minimum. Initially high temperature is required to prevent the system from landing and staying stuck for a very long time in some local minimum.
EDIT: If you were told that you should use just Metropolis-Hastings, it most probably means you should do this this way, only with constant temperature (constantly deceasing temperature is the only thing that simulated annealing adds to MH). Then you will need to make few experiments to figure out a good temperature, so that there will be quite good accuracy no stucking in the local minima.
|
Minimization of a function by Metropolis-Hastings algorithms
You are rather looking for a simulated annealing, which is easier to understand when formulated in the original, physics way:
Having
$x$ is a state of the system
$f(x)$ is an energy of the system; en
|
45,949
|
Minimization of a function by Metropolis-Hastings algorithms
|
If you want to find the global minimum of a function, simulated annealing would be the algorithm to look at, in which case there is no need to view the function as an unnormalised density of any kind and no need to transform the function.
|
Minimization of a function by Metropolis-Hastings algorithms
|
If you want to find the global minimum of a function, simulated annealing would be the algorithm to look at, in which case there is no need to view the function as an unnormalised density of any kind
|
Minimization of a function by Metropolis-Hastings algorithms
If you want to find the global minimum of a function, simulated annealing would be the algorithm to look at, in which case there is no need to view the function as an unnormalised density of any kind and no need to transform the function.
|
Minimization of a function by Metropolis-Hastings algorithms
If you want to find the global minimum of a function, simulated annealing would be the algorithm to look at, in which case there is no need to view the function as an unnormalised density of any kind
|
45,950
|
Minimization of a function by Metropolis-Hastings algorithms
|
Yes, simulated annealing is also an instance of Metropolis Hasting sampling.
Just set the unnormalized density function as $e^{-f(x)/T}$ and use symmetric proposal distribution (which also makes Metropolis Hasting sampling as Metropolis sampling).
So, the acceptance probability is $min(1, \dfrac{e^{-f(x')/T}}{e^{-f(x)/T}})=min(1,e^{-(f(x')-f(x))/T})$. Yeah! simulated annealing!
|
Minimization of a function by Metropolis-Hastings algorithms
|
Yes, simulated annealing is also an instance of Metropolis Hasting sampling.
Just set the unnormalized density function as $e^{-f(x)/T}$ and use symmetric proposal distribution (which also makes Metro
|
Minimization of a function by Metropolis-Hastings algorithms
Yes, simulated annealing is also an instance of Metropolis Hasting sampling.
Just set the unnormalized density function as $e^{-f(x)/T}$ and use symmetric proposal distribution (which also makes Metropolis Hasting sampling as Metropolis sampling).
So, the acceptance probability is $min(1, \dfrac{e^{-f(x')/T}}{e^{-f(x)/T}})=min(1,e^{-(f(x')-f(x))/T})$. Yeah! simulated annealing!
|
Minimization of a function by Metropolis-Hastings algorithms
Yes, simulated annealing is also an instance of Metropolis Hasting sampling.
Just set the unnormalized density function as $e^{-f(x)/T}$ and use symmetric proposal distribution (which also makes Metro
|
45,951
|
Inter-rater reliability using Intra-class correlation with ratings for multiple objects on multiple properties
|
These are distinct ways of accounting for raters or items variance in overall variance, following Shrout and Fleiss (1979) (cases 1 to 3 in Table 1):
One-way random effects model: raters are considered as sampled from a larger pool of potential raters, hence they are treated as random effects; the ICC is then interpreted as the % of total variance accounted for by subjects/items variance. This is called the consistency ICC.
Two-way random effects model: both factors -- raters and items/subjects -- are viewed as random effects, and we have two variance components (or mean squares) in addition to the residual variance; we further assume that raters assess all items/subjects; the ICC gives in this case the % of variance attributable to raters + items/subjects.
Two-way mixed model: contrary to the one-way approach, here raters are considered as fixed effects (no generalization beyond the sample at hand) but items/subjects are treated as random effects; the unit of analysis may be the individual or the average ratings.
I would say raters have to be entered as columns, although I'm not a specialist of SPSS.
Dave Garson's dedicated website is worth looking at for those working with SPSS. There is also a complete on-line tutorial on reliability analysis (Robert A. Yaffee) [archived version].
For theoretical consideration about the mixed-effect approach, please consider reading my answer to this related question: Reliability in Elicitation Exercise.
|
Inter-rater reliability using Intra-class correlation with ratings for multiple objects on multiple
|
These are distinct ways of accounting for raters or items variance in overall variance, following Shrout and Fleiss (1979) (cases 1 to 3 in Table 1):
One-way random effects model: raters are consider
|
Inter-rater reliability using Intra-class correlation with ratings for multiple objects on multiple properties
These are distinct ways of accounting for raters or items variance in overall variance, following Shrout and Fleiss (1979) (cases 1 to 3 in Table 1):
One-way random effects model: raters are considered as sampled from a larger pool of potential raters, hence they are treated as random effects; the ICC is then interpreted as the % of total variance accounted for by subjects/items variance. This is called the consistency ICC.
Two-way random effects model: both factors -- raters and items/subjects -- are viewed as random effects, and we have two variance components (or mean squares) in addition to the residual variance; we further assume that raters assess all items/subjects; the ICC gives in this case the % of variance attributable to raters + items/subjects.
Two-way mixed model: contrary to the one-way approach, here raters are considered as fixed effects (no generalization beyond the sample at hand) but items/subjects are treated as random effects; the unit of analysis may be the individual or the average ratings.
I would say raters have to be entered as columns, although I'm not a specialist of SPSS.
Dave Garson's dedicated website is worth looking at for those working with SPSS. There is also a complete on-line tutorial on reliability analysis (Robert A. Yaffee) [archived version].
For theoretical consideration about the mixed-effect approach, please consider reading my answer to this related question: Reliability in Elicitation Exercise.
|
Inter-rater reliability using Intra-class correlation with ratings for multiple objects on multiple
These are distinct ways of accounting for raters or items variance in overall variance, following Shrout and Fleiss (1979) (cases 1 to 3 in Table 1):
One-way random effects model: raters are consider
|
45,952
|
Algorithm for choosing the number of clusters when using pam in R?
|
You may find an answer to a similar question useful. I have also used clValid but, as I recall, it was rather slow (at least for relatively large datasets).
|
Algorithm for choosing the number of clusters when using pam in R?
|
You may find an answer to a similar question useful. I have also used clValid but, as I recall, it was rather slow (at least for relatively large datasets).
|
Algorithm for choosing the number of clusters when using pam in R?
You may find an answer to a similar question useful. I have also used clValid but, as I recall, it was rather slow (at least for relatively large datasets).
|
Algorithm for choosing the number of clusters when using pam in R?
You may find an answer to a similar question useful. I have also used clValid but, as I recall, it was rather slow (at least for relatively large datasets).
|
45,953
|
Algorithm for choosing the number of clusters when using pam in R?
|
The fpc package provides a few clustering statistics. If you're looking for information criteria in particular, the cluster.stats method provides an information based distance. For mixture models based on clustering, the BIC is available.
|
Algorithm for choosing the number of clusters when using pam in R?
|
The fpc package provides a few clustering statistics. If you're looking for information criteria in particular, the cluster.stats method provides an information based distance. For mixture models ba
|
Algorithm for choosing the number of clusters when using pam in R?
The fpc package provides a few clustering statistics. If you're looking for information criteria in particular, the cluster.stats method provides an information based distance. For mixture models based on clustering, the BIC is available.
|
Algorithm for choosing the number of clusters when using pam in R?
The fpc package provides a few clustering statistics. If you're looking for information criteria in particular, the cluster.stats method provides an information based distance. For mixture models ba
|
45,954
|
Algorithm for choosing the number of clusters when using pam in R?
|
What about silhouette?
|
Algorithm for choosing the number of clusters when using pam in R?
|
What about silhouette?
|
Algorithm for choosing the number of clusters when using pam in R?
What about silhouette?
|
Algorithm for choosing the number of clusters when using pam in R?
What about silhouette?
|
45,955
|
Export/format output from pairwise.t.test to LaTeX [closed]
|
Does this help?
> library(xtable)
> attach(airquality)
> res <- pairwise.t.test(Ozone, Month)
> xtable(res$p.value, caption=res$method)
% latex table generated in R 2.9.2 by xtable 1.5-6 package
% Mon Aug 16 04:24:21 2010
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrrrr}
\hline
& 5 & 6 & 7 & 8 \\
\hline
6 & 1.00 & & & \\
7 & 0.00 & 0.05 & & \\
8 & 0.00 & 0.05 & 1.00 & \\
9 & 1.00 & 1.00 & 0.00 & 0.00 \\
\hline
\end{tabular}
\caption{t tests with pooled SD}
\end{center}
\end{table}
|
Export/format output from pairwise.t.test to LaTeX [closed]
|
Does this help?
> library(xtable)
> attach(airquality)
> res <- pairwise.t.test(Ozone, Month)
> xtable(res$p.value, caption=res$method)
% latex table generated in R 2.9.2 by xtable 1.5-6 package
% Mon
|
Export/format output from pairwise.t.test to LaTeX [closed]
Does this help?
> library(xtable)
> attach(airquality)
> res <- pairwise.t.test(Ozone, Month)
> xtable(res$p.value, caption=res$method)
% latex table generated in R 2.9.2 by xtable 1.5-6 package
% Mon Aug 16 04:24:21 2010
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrrrr}
\hline
& 5 & 6 & 7 & 8 \\
\hline
6 & 1.00 & & & \\
7 & 0.00 & 0.05 & & \\
8 & 0.00 & 0.05 & 1.00 & \\
9 & 1.00 & 1.00 & 0.00 & 0.00 \\
\hline
\end{tabular}
\caption{t tests with pooled SD}
\end{center}
\end{table}
|
Export/format output from pairwise.t.test to LaTeX [closed]
Does this help?
> library(xtable)
> attach(airquality)
> res <- pairwise.t.test(Ozone, Month)
> xtable(res$p.value, caption=res$method)
% latex table generated in R 2.9.2 by xtable 1.5-6 package
% Mon
|
45,956
|
Export/format output from pairwise.t.test to LaTeX [closed]
|
One way that you can do the above task without using Sweave is as follows:
Write a custom export function from R that takes the pairwise.t.test object and outputs latex code.
Use \input{...} in your LaTeX document to input this file into your LaTeX document.
With regards to step 1, there are many functions that are useful. Here are a few:
paste() is useful for concatenating elements including latex elements with R objects
formatC() is useful for formatting numbers
write() is useful for exporting the combined LaTeX/R character vector from R to a text file
There are also a variety of LaTeX table generating functions (e.g., see the xtable package)
|
Export/format output from pairwise.t.test to LaTeX [closed]
|
One way that you can do the above task without using Sweave is as follows:
Write a custom export function from R that takes the pairwise.t.test object and outputs latex code.
Use \input{...} in your
|
Export/format output from pairwise.t.test to LaTeX [closed]
One way that you can do the above task without using Sweave is as follows:
Write a custom export function from R that takes the pairwise.t.test object and outputs latex code.
Use \input{...} in your LaTeX document to input this file into your LaTeX document.
With regards to step 1, there are many functions that are useful. Here are a few:
paste() is useful for concatenating elements including latex elements with R objects
formatC() is useful for formatting numbers
write() is useful for exporting the combined LaTeX/R character vector from R to a text file
There are also a variety of LaTeX table generating functions (e.g., see the xtable package)
|
Export/format output from pairwise.t.test to LaTeX [closed]
One way that you can do the above task without using Sweave is as follows:
Write a custom export function from R that takes the pairwise.t.test object and outputs latex code.
Use \input{...} in your
|
45,957
|
Piece-wise proportional hazards model as equivalent Poisson model
|
It doesn't have a Poisson distribution, only a Poisson likelihood. That is, for any observed values $y$ of $Y$ the likelihood ratios $P(Y=y;\theta_1)/P(Y=y;\theta_0)$ are the same as they would be for a Poisson distribution (which is all you need for estimation and other parameter inference). The probabilities of values of $Y$ that you don't observe don't enter into the likelihood ratios, so they need not match.
The reason you have a Poisson likelihood is that you can model the data as produced by a stopped non-homogeneous Poisson process. The process for any individual stops when that individual first dies (or when they are censored). This sort of early stopping alters the sampling distribution of the data but doesn't alter the likelihood ratios.
A simpler example is binomial vs negative binomial: the likelihood ratios for a given set of data are the same even though the sampling distributions over sets of data are different. Here we have 5 successes and 2 failures in 7 seven trials, as binomial and negative binomial
> dbinom(5,7,.5)/dbinom(5,7,.3)
[1] 6.561266
> dnbinom(2,5,.5)/dnbinom(2,5,.3)
[1] 6.561266
|
Piece-wise proportional hazards model as equivalent Poisson model
|
It doesn't have a Poisson distribution, only a Poisson likelihood. That is, for any observed values $y$ of $Y$ the likelihood ratios $P(Y=y;\theta_1)/P(Y=y;\theta_0)$ are the same as they would be fo
|
Piece-wise proportional hazards model as equivalent Poisson model
It doesn't have a Poisson distribution, only a Poisson likelihood. That is, for any observed values $y$ of $Y$ the likelihood ratios $P(Y=y;\theta_1)/P(Y=y;\theta_0)$ are the same as they would be for a Poisson distribution (which is all you need for estimation and other parameter inference). The probabilities of values of $Y$ that you don't observe don't enter into the likelihood ratios, so they need not match.
The reason you have a Poisson likelihood is that you can model the data as produced by a stopped non-homogeneous Poisson process. The process for any individual stops when that individual first dies (or when they are censored). This sort of early stopping alters the sampling distribution of the data but doesn't alter the likelihood ratios.
A simpler example is binomial vs negative binomial: the likelihood ratios for a given set of data are the same even though the sampling distributions over sets of data are different. Here we have 5 successes and 2 failures in 7 seven trials, as binomial and negative binomial
> dbinom(5,7,.5)/dbinom(5,7,.3)
[1] 6.561266
> dnbinom(2,5,.5)/dnbinom(2,5,.3)
[1] 6.561266
|
Piece-wise proportional hazards model as equivalent Poisson model
It doesn't have a Poisson distribution, only a Poisson likelihood. That is, for any observed values $y$ of $Y$ the likelihood ratios $P(Y=y;\theta_1)/P(Y=y;\theta_0)$ are the same as they would be fo
|
45,958
|
Piece-wise proportional hazards model as equivalent Poisson model
|
One way to think about this is that, within each time interval $j$, you are modeling the Poisson parameter $\mu_{ij}$ based on the time $t_{ij}$ to the first event within interval $j$ for individual $i$, where interval $j$ starts at time $\tau_{j-1}$ and ends at $\tau_j$.
Similarly to how individuals with censored event times don't contribute information beyond the last follow-up time, individual $i$ provides no information after the observed event time $(\tau_{j-1}+t_{ij})$--even if more than one event might be possible in principle. Put slightly differently, the derivation on that page shows that the likelihood of the data you have is equivalent to that of a Poisson model, except for a parameter-independent constant.
The extension of this approach to multiple independent individuals having the same baseline hazard then leads to a Poisson model for the total number of deaths during a shared time interval.
|
Piece-wise proportional hazards model as equivalent Poisson model
|
One way to think about this is that, within each time interval $j$, you are modeling the Poisson parameter $\mu_{ij}$ based on the time $t_{ij}$ to the first event within interval $j$ for individual $
|
Piece-wise proportional hazards model as equivalent Poisson model
One way to think about this is that, within each time interval $j$, you are modeling the Poisson parameter $\mu_{ij}$ based on the time $t_{ij}$ to the first event within interval $j$ for individual $i$, where interval $j$ starts at time $\tau_{j-1}$ and ends at $\tau_j$.
Similarly to how individuals with censored event times don't contribute information beyond the last follow-up time, individual $i$ provides no information after the observed event time $(\tau_{j-1}+t_{ij})$--even if more than one event might be possible in principle. Put slightly differently, the derivation on that page shows that the likelihood of the data you have is equivalent to that of a Poisson model, except for a parameter-independent constant.
The extension of this approach to multiple independent individuals having the same baseline hazard then leads to a Poisson model for the total number of deaths during a shared time interval.
|
Piece-wise proportional hazards model as equivalent Poisson model
One way to think about this is that, within each time interval $j$, you are modeling the Poisson parameter $\mu_{ij}$ based on the time $t_{ij}$ to the first event within interval $j$ for individual $
|
45,959
|
Applying Leibniz's integral rule to the Gaussian distribution's normalization condition
|
Nice question!
option 1
Derivatives are limits (of fractions), and moving limits inside an expectation often triggers an invocation of a theorem such as the monotone convergence theorem, Lebesgue's dominated convergence theorem, the uniformly integrable convergnce theorem or maybe even Fatou's lemma. The theorem @jbowman seems to be referring to is this one from Jeffrey Rosenthal's book that provides a condition that allows you to exchange the order of differentiation and integration. In the book it's numbered Proposition 9.2.1.
Let $\{F_t\}_{a<t<b}$ be a collection of random variables with finite expectations on a probability triple $(\Omega, \mathcal{F}, \mathbf{P})$. Suppose further that for each $\omega$ and $t\in (a,b)$, the derivative $F'_t(\omega)=\frac{\partial}{\partial t} F_t(\omega)$ exists. Furthermore, if there is a random variable $Y$ on the same probability triple so that $E(Y)<\infty$ and $|F'_t| \leq Y$ for all $t\in (a,b)$. Then:
$F'_t$ is a random variable with finite expectation;
$\phi(t)$ is differentiable with finite derivative $\phi'(t)=E(F'_t)$ for all $t\in (a,b)$, where $\phi(t)=E(F_t)$.
Note: $E$ refers to Lebesgue expectations, and this notation differs with your $E$.
Here's the proof. You'll notice that it does indeed use DCT, as @jbowman mentioned, as well as the mean value theorem.
Write
$$F'_t=\lim_{h\rightarrow 0} \frac{F_{t+h}-F_t}{h}$$
and notice $F'_t$ is a random variable (i.e. it's measurable) as it is the limit of random variables.
Furthermore, we have $E(|F'_t|)\leq E(Y)<\infty$.
By the mean value theorem, there is always a $t^*$ between $t+h$ and $t$, so that $\frac{F_{t+h}-F_t}{h}=F'_{t^*}$.
Then $|\frac{F_{t+h}-F_t}{h}|\leq Y$. By the dominated convergence theorem:
\begin{align*}
\phi'(t)
& =\lim_{h\rightarrow 0} \frac{\phi(t+h)-\phi(t) }{h}\\
&=\lim_{h\rightarrow 0} E \big ( \frac{F_{t+h}-F_t}{h} \big ) \\
&=E \big (\lim_{h\rightarrow 0} \frac{F_{t+h}-F_t}{h} \big )\\
&=E(F'_t).
\end{align*}
Most of the $\LaTeX$ below is taken from some some slides from one of my courses.
To be honest, I'm not sure this is legitimate. The thing that tripped me up is that I always thought this theorem was for expectations with respect to finite measures (e.g. probability measures), not sigma-finite measures (e.g. integrating with respect to $dx$). In this option, you're not taking derivatives of densities. I'm hoping that it still works for that situation too, but I've never directly constructed Lebesgue integrals with respect to sigma-finite measures. The construction goes simple random variables, then nonnegative r.v.s, then general ones, and all the while you're dealing with finite probability measures that put mass of $1$ on the whole space. I guess it works for that situation, too? I was also getting tripped up with the theorem being unclear about whether $t$ can be a parameter for the random variable (it can't be).
option 2
A second option would be to fight the hint. It is straightforward to integrate directly to find $E[(X-\mu)^2]$ or to use Stein's Lemma, whose proof just uses integration by parts. The justification does not involve moving a limit inside the integral, but if you look at how it's written it appears to have a derivative on the inside of an integral. This derivative is not with respect to $\sigma^2$, though...
option 3: @whuber's approach
Option 3 is to use a Taylor approximation. Out of the three approaches it most directly answers your question, and it doesn't even assume normality. Fix $x \in \mathbb{R}$ and write the 1-d dimensional, second-order Taylor approximation
$$
f(x; \sigma_0^2+h) = f(x; \sigma_0^2) + \frac{d}{d\sigma^2}f(x; \sigma_0^2) h + \frac{h^2}{2} \frac{d^2}{d(\sigma^2)^2}f(x; \sigma_0^2) + R(x,\sigma^2)
$$
where the remainder term is such that $R(x,\sigma^2)/h^2 \to 0$ as $h \to 0$. We're ignoring $\mu$ for the moment by supposing it's fixed, and technically we have a different approximation for each value of $x$.
Plugging it in
\begin{align*}
&\frac{d}{d\sigma^2}\int f(x;\sigma^2)dx \\
&= \lim_{h \to 0}\frac{\int f(x;\sigma^2+h)dx - \int f(x;\sigma^2)dx}{h} \\
&= \int \frac{d}{d\sigma^2}f(x; \sigma^2)dx
+ \underbrace{\lim_{h \to 0} \frac{h}{2} \int \frac{d^2}{d(\sigma^2)^2}f(x; \sigma^2)dx
+ \lim_{h \to 0} \int \frac{R(x, \sigma^2)}{h} dx}_{\text{hopefully zero!}} \\
\end{align*}
There are a lot of ways you can assume things to get the last two integrals to vanish. @whuber suggests the following: suppose
$$
\left|\frac{d^2}{d(\sigma^2)^2}f(x; \sigma^2)\right| \le G(x)
$$
where $G(x)$ is free of $\sigma^2$ and $\int G(x) dx < \infty$, then
$$
\left|\frac{h}{2} \int \frac{d^2}{d(\sigma^2)^2}f(x; \sigma^2)dx\right| \le \frac{h}{2} \int |\frac{d^2}{d(\sigma^2)^2}f(x; \sigma^2)dx| \le
\frac{h}{2} \int G(x) dx \to 0.
$$
For the last integral, you might assume higher-order derivatives so you can write out the remainder term explicitly. This will allow you to take a similar approach.
|
Applying Leibniz's integral rule to the Gaussian distribution's normalization condition
|
Nice question!
option 1
Derivatives are limits (of fractions), and moving limits inside an expectation often triggers an invocation of a theorem such as the monotone convergence theorem, Lebesgue's do
|
Applying Leibniz's integral rule to the Gaussian distribution's normalization condition
Nice question!
option 1
Derivatives are limits (of fractions), and moving limits inside an expectation often triggers an invocation of a theorem such as the monotone convergence theorem, Lebesgue's dominated convergence theorem, the uniformly integrable convergnce theorem or maybe even Fatou's lemma. The theorem @jbowman seems to be referring to is this one from Jeffrey Rosenthal's book that provides a condition that allows you to exchange the order of differentiation and integration. In the book it's numbered Proposition 9.2.1.
Let $\{F_t\}_{a<t<b}$ be a collection of random variables with finite expectations on a probability triple $(\Omega, \mathcal{F}, \mathbf{P})$. Suppose further that for each $\omega$ and $t\in (a,b)$, the derivative $F'_t(\omega)=\frac{\partial}{\partial t} F_t(\omega)$ exists. Furthermore, if there is a random variable $Y$ on the same probability triple so that $E(Y)<\infty$ and $|F'_t| \leq Y$ for all $t\in (a,b)$. Then:
$F'_t$ is a random variable with finite expectation;
$\phi(t)$ is differentiable with finite derivative $\phi'(t)=E(F'_t)$ for all $t\in (a,b)$, where $\phi(t)=E(F_t)$.
Note: $E$ refers to Lebesgue expectations, and this notation differs with your $E$.
Here's the proof. You'll notice that it does indeed use DCT, as @jbowman mentioned, as well as the mean value theorem.
Write
$$F'_t=\lim_{h\rightarrow 0} \frac{F_{t+h}-F_t}{h}$$
and notice $F'_t$ is a random variable (i.e. it's measurable) as it is the limit of random variables.
Furthermore, we have $E(|F'_t|)\leq E(Y)<\infty$.
By the mean value theorem, there is always a $t^*$ between $t+h$ and $t$, so that $\frac{F_{t+h}-F_t}{h}=F'_{t^*}$.
Then $|\frac{F_{t+h}-F_t}{h}|\leq Y$. By the dominated convergence theorem:
\begin{align*}
\phi'(t)
& =\lim_{h\rightarrow 0} \frac{\phi(t+h)-\phi(t) }{h}\\
&=\lim_{h\rightarrow 0} E \big ( \frac{F_{t+h}-F_t}{h} \big ) \\
&=E \big (\lim_{h\rightarrow 0} \frac{F_{t+h}-F_t}{h} \big )\\
&=E(F'_t).
\end{align*}
Most of the $\LaTeX$ below is taken from some some slides from one of my courses.
To be honest, I'm not sure this is legitimate. The thing that tripped me up is that I always thought this theorem was for expectations with respect to finite measures (e.g. probability measures), not sigma-finite measures (e.g. integrating with respect to $dx$). In this option, you're not taking derivatives of densities. I'm hoping that it still works for that situation too, but I've never directly constructed Lebesgue integrals with respect to sigma-finite measures. The construction goes simple random variables, then nonnegative r.v.s, then general ones, and all the while you're dealing with finite probability measures that put mass of $1$ on the whole space. I guess it works for that situation, too? I was also getting tripped up with the theorem being unclear about whether $t$ can be a parameter for the random variable (it can't be).
option 2
A second option would be to fight the hint. It is straightforward to integrate directly to find $E[(X-\mu)^2]$ or to use Stein's Lemma, whose proof just uses integration by parts. The justification does not involve moving a limit inside the integral, but if you look at how it's written it appears to have a derivative on the inside of an integral. This derivative is not with respect to $\sigma^2$, though...
option 3: @whuber's approach
Option 3 is to use a Taylor approximation. Out of the three approaches it most directly answers your question, and it doesn't even assume normality. Fix $x \in \mathbb{R}$ and write the 1-d dimensional, second-order Taylor approximation
$$
f(x; \sigma_0^2+h) = f(x; \sigma_0^2) + \frac{d}{d\sigma^2}f(x; \sigma_0^2) h + \frac{h^2}{2} \frac{d^2}{d(\sigma^2)^2}f(x; \sigma_0^2) + R(x,\sigma^2)
$$
where the remainder term is such that $R(x,\sigma^2)/h^2 \to 0$ as $h \to 0$. We're ignoring $\mu$ for the moment by supposing it's fixed, and technically we have a different approximation for each value of $x$.
Plugging it in
\begin{align*}
&\frac{d}{d\sigma^2}\int f(x;\sigma^2)dx \\
&= \lim_{h \to 0}\frac{\int f(x;\sigma^2+h)dx - \int f(x;\sigma^2)dx}{h} \\
&= \int \frac{d}{d\sigma^2}f(x; \sigma^2)dx
+ \underbrace{\lim_{h \to 0} \frac{h}{2} \int \frac{d^2}{d(\sigma^2)^2}f(x; \sigma^2)dx
+ \lim_{h \to 0} \int \frac{R(x, \sigma^2)}{h} dx}_{\text{hopefully zero!}} \\
\end{align*}
There are a lot of ways you can assume things to get the last two integrals to vanish. @whuber suggests the following: suppose
$$
\left|\frac{d^2}{d(\sigma^2)^2}f(x; \sigma^2)\right| \le G(x)
$$
where $G(x)$ is free of $\sigma^2$ and $\int G(x) dx < \infty$, then
$$
\left|\frac{h}{2} \int \frac{d^2}{d(\sigma^2)^2}f(x; \sigma^2)dx\right| \le \frac{h}{2} \int |\frac{d^2}{d(\sigma^2)^2}f(x; \sigma^2)dx| \le
\frac{h}{2} \int G(x) dx \to 0.
$$
For the last integral, you might assume higher-order derivatives so you can write out the remainder term explicitly. This will allow you to take a similar approach.
|
Applying Leibniz's integral rule to the Gaussian distribution's normalization condition
Nice question!
option 1
Derivatives are limits (of fractions), and moving limits inside an expectation often triggers an invocation of a theorem such as the monotone convergence theorem, Lebesgue's do
|
45,960
|
Applying Leibniz's integral rule to the Gaussian distribution's normalization condition
|
Leibniz' rule can be extended to infinite regions of integration with an extra condition on the function being integrated. Let's write out the basic form:
$${d \over dy}\int_a^b f(x,y)dx = \int_a^b {df(x,y)\over dy}dx $$
To extend the bounds of integration to the infinite case, we need to have $df(x,y) / dy$ behave "well" as $x \to \infty$. The condition defining "behave well" is that there exists a function $g(x,y)$ that is integrable w.r.t. $x$ over the relevant range (e.g., $[0, \infty)$ or whatever) such that:
$$|df(x,y)/dy| \leq g(x,y) \;\forall x,y$$
This result is due to the Lebesgue Dominated Convergence Theorem.
|
Applying Leibniz's integral rule to the Gaussian distribution's normalization condition
|
Leibniz' rule can be extended to infinite regions of integration with an extra condition on the function being integrated. Let's write out the basic form:
$${d \over dy}\int_a^b f(x,y)dx = \int_a^b {
|
Applying Leibniz's integral rule to the Gaussian distribution's normalization condition
Leibniz' rule can be extended to infinite regions of integration with an extra condition on the function being integrated. Let's write out the basic form:
$${d \over dy}\int_a^b f(x,y)dx = \int_a^b {df(x,y)\over dy}dx $$
To extend the bounds of integration to the infinite case, we need to have $df(x,y) / dy$ behave "well" as $x \to \infty$. The condition defining "behave well" is that there exists a function $g(x,y)$ that is integrable w.r.t. $x$ over the relevant range (e.g., $[0, \infty)$ or whatever) such that:
$$|df(x,y)/dy| \leq g(x,y) \;\forall x,y$$
This result is due to the Lebesgue Dominated Convergence Theorem.
|
Applying Leibniz's integral rule to the Gaussian distribution's normalization condition
Leibniz' rule can be extended to infinite regions of integration with an extra condition on the function being integrated. Let's write out the basic form:
$${d \over dy}\int_a^b f(x,y)dx = \int_a^b {
|
45,961
|
Can I use logistic regression when all of the regressors sum to 1?
|
Variables representing parts of a total, like your proportion of cell type, are called compositional-data, for more information you can peruse that tag.
But in your case the solution is simple. Your design matrix will be rank-deficient, since the sum P1 + P2 + P3 + P4 + P5 will equal the intercept. That way the intercept is included in the design matrix in two different ways. The most practical (that is, interpretable) solution is to omit the intercept from the model. In R that would be something like
glm(X ~ 0 + P1 + P2 + P3 + P4 + P5, family=binomial,
data=your_data_frame)
The ~ 0 + part of the formula means omit the intercept.
User whuber points to another sort of analysis, using logratio transformation. See How to perform isometric log-ratio transformation
|
Can I use logistic regression when all of the regressors sum to 1?
|
Variables representing parts of a total, like your proportion of cell type, are called compositional-data, for more information you can peruse that tag.
But in your case the solution is simple. Your d
|
Can I use logistic regression when all of the regressors sum to 1?
Variables representing parts of a total, like your proportion of cell type, are called compositional-data, for more information you can peruse that tag.
But in your case the solution is simple. Your design matrix will be rank-deficient, since the sum P1 + P2 + P3 + P4 + P5 will equal the intercept. That way the intercept is included in the design matrix in two different ways. The most practical (that is, interpretable) solution is to omit the intercept from the model. In R that would be something like
glm(X ~ 0 + P1 + P2 + P3 + P4 + P5, family=binomial,
data=your_data_frame)
The ~ 0 + part of the formula means omit the intercept.
User whuber points to another sort of analysis, using logratio transformation. See How to perform isometric log-ratio transformation
|
Can I use logistic regression when all of the regressors sum to 1?
Variables representing parts of a total, like your proportion of cell type, are called compositional-data, for more information you can peruse that tag.
But in your case the solution is simple. Your d
|
45,962
|
Who estimated war casualties from tightly-controlled government news sources?
|
You may be referring to Hugo Steinhaus. He was a Polish-Jewish mathematician, which resorted to the ingenious method you sketch to estimate the casualties of the Nazis, while in hiding during WWII. What source I got this information from, I cannot remember. It was a book, which I may have given away to someone long ago; but I checked the information from
https://hmong.es/wiki/Hugo_Steinhaus (in Spanish) a moment ago, and you will surely find sources in English if you google for Hugo Steinhaus.
|
Who estimated war casualties from tightly-controlled government news sources?
|
You may be referring to Hugo Steinhaus. He was a Polish-Jewish mathematician, which resorted to the ingenious method you sketch to estimate the casualties of the Nazis, while in hiding during WWII. Wh
|
Who estimated war casualties from tightly-controlled government news sources?
You may be referring to Hugo Steinhaus. He was a Polish-Jewish mathematician, which resorted to the ingenious method you sketch to estimate the casualties of the Nazis, while in hiding during WWII. What source I got this information from, I cannot remember. It was a book, which I may have given away to someone long ago; but I checked the information from
https://hmong.es/wiki/Hugo_Steinhaus (in Spanish) a moment ago, and you will surely find sources in English if you google for Hugo Steinhaus.
|
Who estimated war casualties from tightly-controlled government news sources?
You may be referring to Hugo Steinhaus. He was a Polish-Jewish mathematician, which resorted to the ingenious method you sketch to estimate the casualties of the Nazis, while in hiding during WWII. Wh
|
45,963
|
Who estimated war casualties from tightly-controlled government news sources?
|
Adding to the answer by @F.Tusell: The english wikipedia article on Hugo Steinhaus contains
Also while in hiding, and cut off from reliable news on the course of the war, Steinhaus devised a statistical means of estimating for himself the German casualties at the front based on sporadic obituaries published in the local press. The method relied on the relative frequency with which the obituaries stated that the soldier who died was someone's son, someone's "second son", someone's "third son" and so on.
It also links to: Kac, Mark (1974). "Hugo Steinhaus--A Reminiscence and a Tribute" which contains
I cannot resist giving one more example of Steinhaus’ quick mathematical
intelligence. It has to do with his estimate of the casualties of the German army in 1944, and it should be borne in mind that he was then in hiding and completely cut off from any source of reliable news.
He noticed that some of the obituaries of German soldiers which were published in the rigidly controlled local newssheet mentioned that the dead was the second or even third member of his family to have fallen in the war, and this was information enough!
For by dividing the percentage of obituaries of second, third, etc. sons by the
(conditional) probability that a family with at least one son will have more than one,
an estimate of casualty percentage can be obtained. Disregarding the age factor (some
sons may be too young to be drafted), all one needs is the average number of sons in a
family (easily estimable) and the knowledge that the number of sons obeys the
Poisson distribution.
|
Who estimated war casualties from tightly-controlled government news sources?
|
Adding to the answer by @F.Tusell: The english wikipedia article on Hugo Steinhaus contains
Also while in hiding, and cut off from reliable news on the course of the war, Steinhaus devised a statisti
|
Who estimated war casualties from tightly-controlled government news sources?
Adding to the answer by @F.Tusell: The english wikipedia article on Hugo Steinhaus contains
Also while in hiding, and cut off from reliable news on the course of the war, Steinhaus devised a statistical means of estimating for himself the German casualties at the front based on sporadic obituaries published in the local press. The method relied on the relative frequency with which the obituaries stated that the soldier who died was someone's son, someone's "second son", someone's "third son" and so on.
It also links to: Kac, Mark (1974). "Hugo Steinhaus--A Reminiscence and a Tribute" which contains
I cannot resist giving one more example of Steinhaus’ quick mathematical
intelligence. It has to do with his estimate of the casualties of the German army in 1944, and it should be borne in mind that he was then in hiding and completely cut off from any source of reliable news.
He noticed that some of the obituaries of German soldiers which were published in the rigidly controlled local newssheet mentioned that the dead was the second or even third member of his family to have fallen in the war, and this was information enough!
For by dividing the percentage of obituaries of second, third, etc. sons by the
(conditional) probability that a family with at least one son will have more than one,
an estimate of casualty percentage can be obtained. Disregarding the age factor (some
sons may be too young to be drafted), all one needs is the average number of sons in a
family (easily estimable) and the knowledge that the number of sons obeys the
Poisson distribution.
|
Who estimated war casualties from tightly-controlled government news sources?
Adding to the answer by @F.Tusell: The english wikipedia article on Hugo Steinhaus contains
Also while in hiding, and cut off from reliable news on the course of the war, Steinhaus devised a statisti
|
45,964
|
Coefficient of an Interaction Term when Regressors are Independent
|
Next to Dave's +1 numerical example, consider an applied one, explaining wages as a function of covariates like ability, gender etc.
It is well-documented that ability and gender both have an influence on wages (i.e., $\beta_1,\beta_2$ both are nonzero), because being more able is good for your earnings and there is such a thing as wage discrinimation. Also, we may assume that gender and ability are independent - women are no more/less able than men in general/on average.
That, however, does not rule out that there is an interaction with ability ($\beta_3\neq0$). For example, there might be more wage discrimination for high-skilled women than for low-skilled women, where wages for the latter group may involve less individual negotiation due to wage-setting negotiated via unions and smaller glass-ceilings effects etc.
|
Coefficient of an Interaction Term when Regressors are Independent
|
Next to Dave's +1 numerical example, consider an applied one, explaining wages as a function of covariates like ability, gender etc.
It is well-documented that ability and gender both have an influenc
|
Coefficient of an Interaction Term when Regressors are Independent
Next to Dave's +1 numerical example, consider an applied one, explaining wages as a function of covariates like ability, gender etc.
It is well-documented that ability and gender both have an influence on wages (i.e., $\beta_1,\beta_2$ both are nonzero), because being more able is good for your earnings and there is such a thing as wage discrinimation. Also, we may assume that gender and ability are independent - women are no more/less able than men in general/on average.
That, however, does not rule out that there is an interaction with ability ($\beta_3\neq0$). For example, there might be more wage discrimination for high-skilled women than for low-skilled women, where wages for the latter group may involve less individual negotiation due to wage-setting negotiated via unions and smaller glass-ceilings effects etc.
|
Coefficient of an Interaction Term when Regressors are Independent
Next to Dave's +1 numerical example, consider an applied one, explaining wages as a function of covariates like ability, gender etc.
It is well-documented that ability and gender both have an influenc
|
45,965
|
Coefficient of an Interaction Term when Regressors are Independent
|
This is not correct, and it is possible to simulate a counterexample, such as with R code.
set.seed(2022)
x1 <- c(0,1,0,1,0,1,0,1)
x2 <- c(0,0,0,0,1,1,1,1)
y <- x1 + x2 + x1*x2 + rnorm(length(x1))
summary(lm(y ~ x1*x2))
This has independent $x_1$ and $x_2$ but also results in a nonzero coefficient on their interaction.
|
Coefficient of an Interaction Term when Regressors are Independent
|
This is not correct, and it is possible to simulate a counterexample, such as with R code.
set.seed(2022)
x1 <- c(0,1,0,1,0,1,0,1)
x2 <- c(0,0,0,0,1,1,1,1)
y <- x1 + x2 + x1*x2 + rnorm(length(x1))
sum
|
Coefficient of an Interaction Term when Regressors are Independent
This is not correct, and it is possible to simulate a counterexample, such as with R code.
set.seed(2022)
x1 <- c(0,1,0,1,0,1,0,1)
x2 <- c(0,0,0,0,1,1,1,1)
y <- x1 + x2 + x1*x2 + rnorm(length(x1))
summary(lm(y ~ x1*x2))
This has independent $x_1$ and $x_2$ but also results in a nonzero coefficient on their interaction.
|
Coefficient of an Interaction Term when Regressors are Independent
This is not correct, and it is possible to simulate a counterexample, such as with R code.
set.seed(2022)
x1 <- c(0,1,0,1,0,1,0,1)
x2 <- c(0,0,0,0,1,1,1,1)
y <- x1 + x2 + x1*x2 + rnorm(length(x1))
sum
|
45,966
|
conceptual understanding of quadratic regression
|
The individual associations of your hours and hours2 with happiness are extremely weak in your example, and nothing completely "non-mathematical" can explain this. Maybe the following plot can help illustrate how multiple regression allows the predictor hours2 to improve on predictions based solely on hours.
The values are circles. The dashed black line shows the linear association of happiness with hours alone. Not very good, not even "statistically significant" (p = 0.53 for the hours coefficient).
The solid black line shows the full model. You might think of this as starting with a linear extrapolation of the values near hours = 0, shown in the blue line. You might then think of the (squared) hours2 term as providing a non-linear correction to that extrapolation. Subtract the red curve from the blue line and you get the full model.
Code in R:
plot(happiness~hours,data,bty="n",xlim=c(0,60),ylim=c(0,300))
abline(lm(happiness~hours,data),lty=2)
abline(-18.2536,6.7444,col="blue") # "extrapolation" from 'hours' near 0
curve(.1012*x^2,from=0,to=60,add=TRUE,col="red") # non-linear "correction"
curve(-18.2536+6.7444*x-0.1012*x^2,from=0,to=60,add=TRUE) # full model
legend("topleft",bty="n",
legend="black dashed, linear 'hours' alone
\nblack solid, full model
\nblue, 'hours' component, full model
\nred, negative of 'hours2' component, full model")
|
conceptual understanding of quadratic regression
|
The individual associations of your hours and hours2 with happiness are extremely weak in your example, and nothing completely "non-mathematical" can explain this. Maybe the following plot can help il
|
conceptual understanding of quadratic regression
The individual associations of your hours and hours2 with happiness are extremely weak in your example, and nothing completely "non-mathematical" can explain this. Maybe the following plot can help illustrate how multiple regression allows the predictor hours2 to improve on predictions based solely on hours.
The values are circles. The dashed black line shows the linear association of happiness with hours alone. Not very good, not even "statistically significant" (p = 0.53 for the hours coefficient).
The solid black line shows the full model. You might think of this as starting with a linear extrapolation of the values near hours = 0, shown in the blue line. You might then think of the (squared) hours2 term as providing a non-linear correction to that extrapolation. Subtract the red curve from the blue line and you get the full model.
Code in R:
plot(happiness~hours,data,bty="n",xlim=c(0,60),ylim=c(0,300))
abline(lm(happiness~hours,data),lty=2)
abline(-18.2536,6.7444,col="blue") # "extrapolation" from 'hours' near 0
curve(.1012*x^2,from=0,to=60,add=TRUE,col="red") # non-linear "correction"
curve(-18.2536+6.7444*x-0.1012*x^2,from=0,to=60,add=TRUE) # full model
legend("topleft",bty="n",
legend="black dashed, linear 'hours' alone
\nblack solid, full model
\nblue, 'hours' component, full model
\nred, negative of 'hours2' component, full model")
|
conceptual understanding of quadratic regression
The individual associations of your hours and hours2 with happiness are extremely weak in your example, and nothing completely "non-mathematical" can explain this. Maybe the following plot can help il
|
45,967
|
MLE for a modified German tank problem
|
Given your specified distributions, the marginal density of $X$ is:
$$\begin{align}
f_X(x)
&= \int \limits_0^a \text{N}(x |\mu,\sigma^2) \cdot \text{U}(\mu|0,a) \ d \mu \\[6pt]
&= \frac{1}{a} \int \limits_0^a \frac{1}{\sigma \sqrt{2 \pi}}
\exp \bigg( -\frac{1}{2} \bigg( \frac{x-\mu}{\sigma} \bigg)^2 \bigg) \ d \mu \\[6pt]
&= -\frac{1}{a} \int \limits_{x/\sigma}^{(x-a)/\sigma} \frac{1}{\sqrt{2 \pi}}
\exp \bigg( -\frac{1}{2} \bigg( \frac{x-\mu}{\sigma} \bigg)^2 \bigg) \ d ((x-\mu)/\sigma) \\[6pt]
&= \frac{1}{a} \bigg[ \Phi \Big( \frac{x}{\sigma} \Big) - \Phi \Big( \frac{x-a}{\sigma} \Big) \bigg]. \\[6pt]
\end{align}$$
So your log-likelihood function should be:
$$\ell_{\mathbf{x}}(a)
= - n \log(a) + \sum_{i=1}^n \log \bigg[ \Phi \Big( \frac{x_i}{\sigma_i} \Big) - \Phi \Big( \frac{x_i-a}{\sigma_i} \Big) \bigg].$$
Note that there is no upper bound on $a$ in this problem because the $x_i$ values all have support over the whole real line irrespective of the value of $a$. To find the MLE, your score function and information function are:
$$\begin{align}
s_{\mathbf{x}}(a)
\equiv \frac{d \ell_{\mathbf{x}}}{da} (a)
&= - \frac{n}{a} + \sum_{i=1}^n \frac{\phi((x_i-a)/\sigma_i)}{\sigma_i H_\mathbf{x}(a)}, \\[12pt]
I_{\mathbf{x}}(a)
\equiv -\frac{d^2 \ell_{\mathbf{x}}}{da^2} (a)
&= - \frac{n}{a^2} - \sum_{i=1}^n (x_i-a) \cdot \frac{\phi((x_i-a)/\sigma_i)}{\sigma_i^3 H_\mathbf{x}(a)} + \sum_{i=1}^n \frac{\phi((x_i-a)/\sigma_i)^2}{\sigma_i^2 H_\mathbf{x}(a)^2}, \\[12pt]
\end{align}$$
where $H_\mathbf{x}(a) \equiv \Phi(x_i/\sigma_i) - \Phi((x_i-a)/\sigma_i)$. Taking $s_{\mathbf{x}}(\hat{a}) = 0$ and solving numerically for $\hat{a}$ will yield the MLE for $a$. You should bear in mind that the MLE tends to be a biased estimator for problems involving estimating a maximum-bound parameter, but it is a common form of estimation in general.
Using the laws of iterated expectation and variance, it is simple to show that $\mathbb{E}(X) = \tfrac{1}{2}a$ and $\mathbb{V}(X) = \tfrac{1}{12} a^2 + \sigma^2$. Consequently, under some relatively weak conditions on the values $\sigma_i$ (ensuring that we don't have a finite subset of values that "dominate" in the limit) we have $2\bar{x}_n \rightarrow a$ as $n \rightarrow \infty$. Consequently, for large $n$ we ought to have $\hat{a} \approx 2\bar{x}_n$. (But be careful with this approximation; in some cases we may have $\bar{x}_n \leqslant 0$.)
Implementation in R: We can implement the numeric solution to the MLE for this problem using the following R function. This function takes in the vectors $\mathbf{x}$ and $\boldsymbol{\sigma}$ and returns the MLE $\hat{a}$ and the mean-maximum-log-likelihood $\ell_{\mathbf{x}}(\hat{a})/n$. (Optimisation is done here using the nlm function rather than using a root-finding algorithm on the score function.) The function also has an option to return the convergence code from the optimisation to check that the numerical maximisation worked properly.
MLE.modified.tank <- function(x, sigma = rep(1, length(x)), nlm.code = FALSE) {
#Check inputs
if (!is.numeric(x)) stop('Error: Input x should be numeric')
if (!is.numeric(sigma)) stop('Error: Input sigma should be numeric')
if (length(x) != length(sigma)) stop('Error: Inputs x and sigma should be the same length')
if (min(sigma) <= 0) stop('Error: Input sigma should only have positive values')
#Set objective function using parameterisation p = log(a)
NEGLOGLIKE <- function(p) {
n <- length(x)
LOG1 <- pnorm(x/sigma, log = TRUE)
LOG2 <- pnorm((x-exp(p))/sigma, log = TRUE)
LOGDIFF <- LOG1 + VGAM::log1mexp(LOG1 - LOG2)
n*p - sum(LOGDIFF) }
#Find the MLE
P0 <- log(max(2*mean(x), 1e-6))
NLM <- nlm(f = NEGLOGLIKE, p = P0)
MLE.a <- exp(NLM$estimate)
MMAX <- -NLM$minimum/n
CODE <- NLM$code
#Create the output
OUT <- data.frame(MLE.a = MLE.a, mean.max.loglike = MMAX)
if (nlm.code) { OUT$nlm.code <- CODE }
rownames(OUT) <- ''
#Return the output
OUT }
We can implement this function to see if it estimates well. In the code below we take a set of mock data generated from your model (with known parameter) and we estimate via MLE. With $n=200$ data points this gives a good estimate of the true parameter.
#Set parameters
a <- 20
n <- 200
sigma <- rgamma(n, shape = 6, scale = 0.4)
#Generate some mock data
set.seed(1)
m <- runif(n, min = 0, max = a)
x <- m + sigma*rnorm(n)
#Compute the MLE of a
MLE <- MLE.modified.tank(x, sigma, nlm.code = TRUE)
#Plot the data and MLE
plot(sigma, x,
main = '(Blue line shows true parameter - Red line shows MLE)',
xlab = 'SDs of observed values',
ylab = 'Observed values')
abline(h = a, lty = 2, col = 'blue')
abline(h = MLE$MLE.a, col = 'red')
#Display the MLE
MLE
MLE.a mean.max.loglike nlm.code
19.7711 -3.178023 1
|
MLE for a modified German tank problem
|
Given your specified distributions, the marginal density of $X$ is:
$$\begin{align}
f_X(x)
&= \int \limits_0^a \text{N}(x |\mu,\sigma^2) \cdot \text{U}(\mu|0,a) \ d \mu \\[6pt]
&= \frac{1}{a} \int \l
|
MLE for a modified German tank problem
Given your specified distributions, the marginal density of $X$ is:
$$\begin{align}
f_X(x)
&= \int \limits_0^a \text{N}(x |\mu,\sigma^2) \cdot \text{U}(\mu|0,a) \ d \mu \\[6pt]
&= \frac{1}{a} \int \limits_0^a \frac{1}{\sigma \sqrt{2 \pi}}
\exp \bigg( -\frac{1}{2} \bigg( \frac{x-\mu}{\sigma} \bigg)^2 \bigg) \ d \mu \\[6pt]
&= -\frac{1}{a} \int \limits_{x/\sigma}^{(x-a)/\sigma} \frac{1}{\sqrt{2 \pi}}
\exp \bigg( -\frac{1}{2} \bigg( \frac{x-\mu}{\sigma} \bigg)^2 \bigg) \ d ((x-\mu)/\sigma) \\[6pt]
&= \frac{1}{a} \bigg[ \Phi \Big( \frac{x}{\sigma} \Big) - \Phi \Big( \frac{x-a}{\sigma} \Big) \bigg]. \\[6pt]
\end{align}$$
So your log-likelihood function should be:
$$\ell_{\mathbf{x}}(a)
= - n \log(a) + \sum_{i=1}^n \log \bigg[ \Phi \Big( \frac{x_i}{\sigma_i} \Big) - \Phi \Big( \frac{x_i-a}{\sigma_i} \Big) \bigg].$$
Note that there is no upper bound on $a$ in this problem because the $x_i$ values all have support over the whole real line irrespective of the value of $a$. To find the MLE, your score function and information function are:
$$\begin{align}
s_{\mathbf{x}}(a)
\equiv \frac{d \ell_{\mathbf{x}}}{da} (a)
&= - \frac{n}{a} + \sum_{i=1}^n \frac{\phi((x_i-a)/\sigma_i)}{\sigma_i H_\mathbf{x}(a)}, \\[12pt]
I_{\mathbf{x}}(a)
\equiv -\frac{d^2 \ell_{\mathbf{x}}}{da^2} (a)
&= - \frac{n}{a^2} - \sum_{i=1}^n (x_i-a) \cdot \frac{\phi((x_i-a)/\sigma_i)}{\sigma_i^3 H_\mathbf{x}(a)} + \sum_{i=1}^n \frac{\phi((x_i-a)/\sigma_i)^2}{\sigma_i^2 H_\mathbf{x}(a)^2}, \\[12pt]
\end{align}$$
where $H_\mathbf{x}(a) \equiv \Phi(x_i/\sigma_i) - \Phi((x_i-a)/\sigma_i)$. Taking $s_{\mathbf{x}}(\hat{a}) = 0$ and solving numerically for $\hat{a}$ will yield the MLE for $a$. You should bear in mind that the MLE tends to be a biased estimator for problems involving estimating a maximum-bound parameter, but it is a common form of estimation in general.
Using the laws of iterated expectation and variance, it is simple to show that $\mathbb{E}(X) = \tfrac{1}{2}a$ and $\mathbb{V}(X) = \tfrac{1}{12} a^2 + \sigma^2$. Consequently, under some relatively weak conditions on the values $\sigma_i$ (ensuring that we don't have a finite subset of values that "dominate" in the limit) we have $2\bar{x}_n \rightarrow a$ as $n \rightarrow \infty$. Consequently, for large $n$ we ought to have $\hat{a} \approx 2\bar{x}_n$. (But be careful with this approximation; in some cases we may have $\bar{x}_n \leqslant 0$.)
Implementation in R: We can implement the numeric solution to the MLE for this problem using the following R function. This function takes in the vectors $\mathbf{x}$ and $\boldsymbol{\sigma}$ and returns the MLE $\hat{a}$ and the mean-maximum-log-likelihood $\ell_{\mathbf{x}}(\hat{a})/n$. (Optimisation is done here using the nlm function rather than using a root-finding algorithm on the score function.) The function also has an option to return the convergence code from the optimisation to check that the numerical maximisation worked properly.
MLE.modified.tank <- function(x, sigma = rep(1, length(x)), nlm.code = FALSE) {
#Check inputs
if (!is.numeric(x)) stop('Error: Input x should be numeric')
if (!is.numeric(sigma)) stop('Error: Input sigma should be numeric')
if (length(x) != length(sigma)) stop('Error: Inputs x and sigma should be the same length')
if (min(sigma) <= 0) stop('Error: Input sigma should only have positive values')
#Set objective function using parameterisation p = log(a)
NEGLOGLIKE <- function(p) {
n <- length(x)
LOG1 <- pnorm(x/sigma, log = TRUE)
LOG2 <- pnorm((x-exp(p))/sigma, log = TRUE)
LOGDIFF <- LOG1 + VGAM::log1mexp(LOG1 - LOG2)
n*p - sum(LOGDIFF) }
#Find the MLE
P0 <- log(max(2*mean(x), 1e-6))
NLM <- nlm(f = NEGLOGLIKE, p = P0)
MLE.a <- exp(NLM$estimate)
MMAX <- -NLM$minimum/n
CODE <- NLM$code
#Create the output
OUT <- data.frame(MLE.a = MLE.a, mean.max.loglike = MMAX)
if (nlm.code) { OUT$nlm.code <- CODE }
rownames(OUT) <- ''
#Return the output
OUT }
We can implement this function to see if it estimates well. In the code below we take a set of mock data generated from your model (with known parameter) and we estimate via MLE. With $n=200$ data points this gives a good estimate of the true parameter.
#Set parameters
a <- 20
n <- 200
sigma <- rgamma(n, shape = 6, scale = 0.4)
#Generate some mock data
set.seed(1)
m <- runif(n, min = 0, max = a)
x <- m + sigma*rnorm(n)
#Compute the MLE of a
MLE <- MLE.modified.tank(x, sigma, nlm.code = TRUE)
#Plot the data and MLE
plot(sigma, x,
main = '(Blue line shows true parameter - Red line shows MLE)',
xlab = 'SDs of observed values',
ylab = 'Observed values')
abline(h = a, lty = 2, col = 'blue')
abline(h = MLE$MLE.a, col = 'red')
#Display the MLE
MLE
MLE.a mean.max.loglike nlm.code
19.7711 -3.178023 1
|
MLE for a modified German tank problem
Given your specified distributions, the marginal density of $X$ is:
$$\begin{align}
f_X(x)
&= \int \limits_0^a \text{N}(x |\mu,\sigma^2) \cdot \text{U}(\mu|0,a) \ d \mu \\[6pt]
&= \frac{1}{a} \int \l
|
45,968
|
In nonlinear regression, when is MLE equivalent to least squares regression?
|
By definition, the least squares estimator minimises the sum of the squared distances between the actual and predicted responses. With a set of simple steps, you can show that this estimator is equivalent to the solution of a certain maximisation problem. If we let $f$ denote the nonlinear regression function and let $\boldsymbol{\beta}$ denote the parameter of this function (and let $\sigma>0$ be an arbitrary scaling parameter), we then have:
$$\begin{align}
\hat{\boldsymbol{\beta}}_\text{OLS}(\mathbf{y}, \mathbf{x})
&\equiv \underset{\boldsymbol{\beta}}{\text{arg min}} \sum_{i=1}^n (y_i - f(\mathbf{x}_i, \boldsymbol{\beta}))^2 \\[6pt]
&= \underset{\boldsymbol{\beta}}{\text{arg max}} \bigg( - \sum_{i=1}^n (y_i - f(\mathbf{x}_i, \boldsymbol{\beta}))^2 \bigg) \\[6pt]
&= \underset{\boldsymbol{\beta}}{\text{arg max}} \bigg( - \frac{1}{2 \sigma^2} \sum_{i=1}^n (y_i - f(\mathbf{x}_i, \boldsymbol{\beta}))^2 \bigg) \\[6pt]
&= \underset{\boldsymbol{\beta}}{\text{arg max}} \ \exp \bigg( - \frac{1}{2 \sigma^2} \sum_{i=1}^n (y_i - f(\mathbf{x}_i, \boldsymbol{\beta}))^2 \bigg) \\[6pt]
&= \underset{\boldsymbol{\beta}}{\text{arg max}} \ \prod_{i=1}^n \exp \bigg( - \frac{1}{2 \sigma^2} (y_i - f(\mathbf{x}_i, \boldsymbol{\beta}))^2 \bigg) \\[6pt]
&= \underset{\boldsymbol{\beta}}{\text{arg max}} \ \prod_{i=1}^n \text{N} (y_i | f(\mathbf{x}_i, \boldsymbol{\beta}), \sigma^2). \\[6pt]
\end{align}$$
(These steps use the fact that the $\text{arg min}$ and $\text{arg max}$ are invariant/anti-variant to strictly monotonic transformations. Look through the steps to ensure you understand why the minimising/maximising point is preserved under the steps.) The latter estimator is an MLE for a certain nonlinear regression model form --- can you see what model form this is?
Update: Per the suggestion from Dave in comments below, now that this question is a year old we can give a full solution. From the above equation we see that the MLE matches the least squares estimator when the regression model uses IID normal (Gaussian) error terms.
|
In nonlinear regression, when is MLE equivalent to least squares regression?
|
By definition, the least squares estimator minimises the sum of the squared distances between the actual and predicted responses. With a set of simple steps, you can show that this estimator is equiv
|
In nonlinear regression, when is MLE equivalent to least squares regression?
By definition, the least squares estimator minimises the sum of the squared distances between the actual and predicted responses. With a set of simple steps, you can show that this estimator is equivalent to the solution of a certain maximisation problem. If we let $f$ denote the nonlinear regression function and let $\boldsymbol{\beta}$ denote the parameter of this function (and let $\sigma>0$ be an arbitrary scaling parameter), we then have:
$$\begin{align}
\hat{\boldsymbol{\beta}}_\text{OLS}(\mathbf{y}, \mathbf{x})
&\equiv \underset{\boldsymbol{\beta}}{\text{arg min}} \sum_{i=1}^n (y_i - f(\mathbf{x}_i, \boldsymbol{\beta}))^2 \\[6pt]
&= \underset{\boldsymbol{\beta}}{\text{arg max}} \bigg( - \sum_{i=1}^n (y_i - f(\mathbf{x}_i, \boldsymbol{\beta}))^2 \bigg) \\[6pt]
&= \underset{\boldsymbol{\beta}}{\text{arg max}} \bigg( - \frac{1}{2 \sigma^2} \sum_{i=1}^n (y_i - f(\mathbf{x}_i, \boldsymbol{\beta}))^2 \bigg) \\[6pt]
&= \underset{\boldsymbol{\beta}}{\text{arg max}} \ \exp \bigg( - \frac{1}{2 \sigma^2} \sum_{i=1}^n (y_i - f(\mathbf{x}_i, \boldsymbol{\beta}))^2 \bigg) \\[6pt]
&= \underset{\boldsymbol{\beta}}{\text{arg max}} \ \prod_{i=1}^n \exp \bigg( - \frac{1}{2 \sigma^2} (y_i - f(\mathbf{x}_i, \boldsymbol{\beta}))^2 \bigg) \\[6pt]
&= \underset{\boldsymbol{\beta}}{\text{arg max}} \ \prod_{i=1}^n \text{N} (y_i | f(\mathbf{x}_i, \boldsymbol{\beta}), \sigma^2). \\[6pt]
\end{align}$$
(These steps use the fact that the $\text{arg min}$ and $\text{arg max}$ are invariant/anti-variant to strictly monotonic transformations. Look through the steps to ensure you understand why the minimising/maximising point is preserved under the steps.) The latter estimator is an MLE for a certain nonlinear regression model form --- can you see what model form this is?
Update: Per the suggestion from Dave in comments below, now that this question is a year old we can give a full solution. From the above equation we see that the MLE matches the least squares estimator when the regression model uses IID normal (Gaussian) error terms.
|
In nonlinear regression, when is MLE equivalent to least squares regression?
By definition, the least squares estimator minimises the sum of the squared distances between the actual and predicted responses. With a set of simple steps, you can show that this estimator is equiv
|
45,969
|
Potential outcomes selection bias
|
It's really important to distinguish the observed outome, $Y_i$, and the potential outcomes, $(Y_i(1), Y_i(0))$.
The observed outcomes are, well, simply the outcome you observed for each subject.
The potential outcomes are the outcomes that you would observe if a patient was given a certain treatment.
If you have two versions of a treatment (say $0$ and $1$ for control and experimental treatment) then each subject has two potential outcomes $Y_i(1)$ and $Y_i(0)$ but only one observed outcome. These potential outcomes are interesting to derive causal interpretation of the treatment effect.
The consistency implies that the observed outcome of a subject is the potential outcome associated with the treatment the subject effectively received. That is,
If the subject $i$ received treatment $1$ then $Y_i = Y_i(1)$
If the subject $i$ received treatment $0$ then $Y_i = Y_i(0)$
Or, said differently, if $D_i$ is the treatment indicator then by consistency $D_i = 1 \Rightarrow Y_i = Y_i(1)$ which gives
$$
E(Y_i \mid D_i = 1) = E(Y_i(1) \mid D_i = 1)
$$
Idem for $D_i = 0$ we have
$$
E(Y_i \mid D_i = 0) = E(Y_i(0) \mid D_i = 0)
$$
The consistency is invoked here because the first line uses the observed outcome while the second uses the potential outcomes (which carry a "causal" interpretation).
The consistency may seem "obvious" but I think they are experiments for which it may not hold.
The step 2 is simply the step 1 plus the term $E(Y_i(0) \mid D_i = 1) - E_(Y_i(0) \mid D_i = 1)$ which is $0$. Introducing this term allows to decompose the difference of observed outcomes between the two treatment arm
$$
A = E(Y_i \mid D_i= 1) - E(Y_i \mid D_i = 0)
$$
as
$$
B = E(Y_i(1) - Y_i(0) \mid D_i = 1)
$$
plus
$$
C = E(Y_i(0) \mid D_i = 1) - E(Y_i(0) \mid D_i = 0)
$$
The term "B" is "the average treatment effect on the treated" (ATT).
It's an average because of the expectation, of the treatment effect because of $Y_i(1) - Y_i(0)$ and "on the treated" because we take this expectation conditional on $D_i =1$ that is for the subjects on the experimental arm.
The term "C" is labelled as "selection bias" which means that subjects on the experimental arm and on the control arm may be different due to selection.
If there was no selection bias (as in a randomized treatment) both groups would be, on average, alike.
You could have given the experimental treatment to one or the other group that this would have not changed (again, on average) the results: both groups are said to be exchangeable.
This translates as "the potential outcomes are the same on average for between the two groups":
\begin{gather*}
E(Y_i(1) \mid D_i = 1) = E(Y_i(1) \mid D_i = 0) \\
E(Y_i(0) \mid D_i = 1) = E(Y_i(0) \mid D_i = 0)
\end{gather*}
If there is no selection then $E(Y_i(0) \mid D_i = 1) - E(Y_i(0) \mid D_i = 0) = 0$ and the observed difference between both groups (A) is equal to the ATT (B).
|
Potential outcomes selection bias
|
It's really important to distinguish the observed outome, $Y_i$, and the potential outcomes, $(Y_i(1), Y_i(0))$.
The observed outcomes are, well, simply the outcome you observed for each subject.
The
|
Potential outcomes selection bias
It's really important to distinguish the observed outome, $Y_i$, and the potential outcomes, $(Y_i(1), Y_i(0))$.
The observed outcomes are, well, simply the outcome you observed for each subject.
The potential outcomes are the outcomes that you would observe if a patient was given a certain treatment.
If you have two versions of a treatment (say $0$ and $1$ for control and experimental treatment) then each subject has two potential outcomes $Y_i(1)$ and $Y_i(0)$ but only one observed outcome. These potential outcomes are interesting to derive causal interpretation of the treatment effect.
The consistency implies that the observed outcome of a subject is the potential outcome associated with the treatment the subject effectively received. That is,
If the subject $i$ received treatment $1$ then $Y_i = Y_i(1)$
If the subject $i$ received treatment $0$ then $Y_i = Y_i(0)$
Or, said differently, if $D_i$ is the treatment indicator then by consistency $D_i = 1 \Rightarrow Y_i = Y_i(1)$ which gives
$$
E(Y_i \mid D_i = 1) = E(Y_i(1) \mid D_i = 1)
$$
Idem for $D_i = 0$ we have
$$
E(Y_i \mid D_i = 0) = E(Y_i(0) \mid D_i = 0)
$$
The consistency is invoked here because the first line uses the observed outcome while the second uses the potential outcomes (which carry a "causal" interpretation).
The consistency may seem "obvious" but I think they are experiments for which it may not hold.
The step 2 is simply the step 1 plus the term $E(Y_i(0) \mid D_i = 1) - E_(Y_i(0) \mid D_i = 1)$ which is $0$. Introducing this term allows to decompose the difference of observed outcomes between the two treatment arm
$$
A = E(Y_i \mid D_i= 1) - E(Y_i \mid D_i = 0)
$$
as
$$
B = E(Y_i(1) - Y_i(0) \mid D_i = 1)
$$
plus
$$
C = E(Y_i(0) \mid D_i = 1) - E(Y_i(0) \mid D_i = 0)
$$
The term "B" is "the average treatment effect on the treated" (ATT).
It's an average because of the expectation, of the treatment effect because of $Y_i(1) - Y_i(0)$ and "on the treated" because we take this expectation conditional on $D_i =1$ that is for the subjects on the experimental arm.
The term "C" is labelled as "selection bias" which means that subjects on the experimental arm and on the control arm may be different due to selection.
If there was no selection bias (as in a randomized treatment) both groups would be, on average, alike.
You could have given the experimental treatment to one or the other group that this would have not changed (again, on average) the results: both groups are said to be exchangeable.
This translates as "the potential outcomes are the same on average for between the two groups":
\begin{gather*}
E(Y_i(1) \mid D_i = 1) = E(Y_i(1) \mid D_i = 0) \\
E(Y_i(0) \mid D_i = 1) = E(Y_i(0) \mid D_i = 0)
\end{gather*}
If there is no selection then $E(Y_i(0) \mid D_i = 1) - E(Y_i(0) \mid D_i = 0) = 0$ and the observed difference between both groups (A) is equal to the ATT (B).
|
Potential outcomes selection bias
It's really important to distinguish the observed outome, $Y_i$, and the potential outcomes, $(Y_i(1), Y_i(0))$.
The observed outcomes are, well, simply the outcome you observed for each subject.
The
|
45,970
|
Potential outcomes selection bias
|
Just to build on @periwinkle answer, I want to emphasise that this equation is solved by an algebraic trick by adding $E[Y(0) | D = 1]$ twice. Professors do not make this clear enough. You see that often in math actually, the use of "tricks" to solve equations (for instance adding $\cdot1$ can help solve equations).
What is remarkable and not often talked about is how the Rubin framework has allowed this "discovery" (naive group average = ATT + selection).
Rubin framework is only one framework among others (like Pearl's framework) for understanding causality. But the genius of Rubin is to have used Neyman's notation $Y(1), Y(0)$ and the idea of potential outcomes to be able to derive this result.
Is it amazing that by conceiving causality formally with this notation, like $Y(1) | D = 1$, you are able to derive such an insight.
As said in the comment the trick can be used the other way around by adding $E[Y(0) | D = 1]$ twice.
\begin{equation}
\begin{split}
&= E[Y(1) \mid D = 1] - E[Y(0) \mid D = 0] \\
&= E[Y(1) \mid D = 1] + \color{red}{E[Y(1) \mid D = 0] - E[Y(1) \mid D = 0]} - E[Y(0) \mid D = 0] \\
&= E[Y(1) \mid D = 1] + \color{red}{E[Y(1) \mid D = 0]} - E[\color{red}{Y(1)} - Y(0) \mid D = 0] \\
&= ATC + \text{baseline bias}
\end{split}
\end{equation}
It worth appreciate this theoretical result with a simulation. I made a simple one with R.
library(tidyverse)
# U affects both treatment and outcome (Y).
# simulation #
set.seed(123)
n = 1000
u = rnorm(n, 1, 1) # generate latent variable affecting treatment selection
d = rbinom(n, 1, prob = plogis(u)) # treatment
e = rnorm(n, 0, 1)
# homogenous causal effect #
causal_effect = 2
# Y(0)
y0 = u + e
# Y(1)
y1 = causal_effect + u + e
# Observed Y
yobs = d*causal_effect + u + e
#
df = data.frame(u, d, y0, y1, yobs)
#
# individual causal effect #
df$y1y0 = df$y1 - df$y0
# grand mean #
mean(df$y1y0)
# ATT / ATC #
df %>% group_by(d) %>% summarise(mean(y1 - y0))
# naive group comparison #
naive_group_comparison = df %>% group_by(d) %>% summarise(m = mean(yobs)) %>% summarise(m[d == 1] - m[d == 0])
naive_group_comparison
# ATT
`Y(1) Y(0) | D =1` = df[df$d==1,] %>% summarise(mean(y1 - y0))
# ATC
`Y(1) Y(0) | D =0` = df[df$d==0,] %>% summarise(mean(y1 - y0))
# unobserved quantities #
`Y(0) | D =1` = df[df$d==1,] %>% summarise(mean(y0))
`Y(1) | D =0` = df[df$d==0,] %>% summarise(mean(y1))
# observed
`Y(1) | D =1` = df[df$d==1,] %>% summarise(mean(y1))
`Y(0) | D =0` = df[df$d==0,] %>% summarise(mean(y0))
# ATT
selection_bias_1 = `Y(0) | D =1` - `Y(0) | D =0`
# ATT + selection bias 1 #
`Y(1) Y(0) | D =1` + selection_bias_1
# We get the correct result as
# naive_group_comparison
# ATC
selection_bias_2 = `Y(1) | D =0` - `Y(1) | D =1`
# ATC + selection bias 1 #
`Y(1) Y(0) | D =1` + selection_bias_2
|
Potential outcomes selection bias
|
Just to build on @periwinkle answer, I want to emphasise that this equation is solved by an algebraic trick by adding $E[Y(0) | D = 1]$ twice. Professors do not make this clear enough. You see that of
|
Potential outcomes selection bias
Just to build on @periwinkle answer, I want to emphasise that this equation is solved by an algebraic trick by adding $E[Y(0) | D = 1]$ twice. Professors do not make this clear enough. You see that often in math actually, the use of "tricks" to solve equations (for instance adding $\cdot1$ can help solve equations).
What is remarkable and not often talked about is how the Rubin framework has allowed this "discovery" (naive group average = ATT + selection).
Rubin framework is only one framework among others (like Pearl's framework) for understanding causality. But the genius of Rubin is to have used Neyman's notation $Y(1), Y(0)$ and the idea of potential outcomes to be able to derive this result.
Is it amazing that by conceiving causality formally with this notation, like $Y(1) | D = 1$, you are able to derive such an insight.
As said in the comment the trick can be used the other way around by adding $E[Y(0) | D = 1]$ twice.
\begin{equation}
\begin{split}
&= E[Y(1) \mid D = 1] - E[Y(0) \mid D = 0] \\
&= E[Y(1) \mid D = 1] + \color{red}{E[Y(1) \mid D = 0] - E[Y(1) \mid D = 0]} - E[Y(0) \mid D = 0] \\
&= E[Y(1) \mid D = 1] + \color{red}{E[Y(1) \mid D = 0]} - E[\color{red}{Y(1)} - Y(0) \mid D = 0] \\
&= ATC + \text{baseline bias}
\end{split}
\end{equation}
It worth appreciate this theoretical result with a simulation. I made a simple one with R.
library(tidyverse)
# U affects both treatment and outcome (Y).
# simulation #
set.seed(123)
n = 1000
u = rnorm(n, 1, 1) # generate latent variable affecting treatment selection
d = rbinom(n, 1, prob = plogis(u)) # treatment
e = rnorm(n, 0, 1)
# homogenous causal effect #
causal_effect = 2
# Y(0)
y0 = u + e
# Y(1)
y1 = causal_effect + u + e
# Observed Y
yobs = d*causal_effect + u + e
#
df = data.frame(u, d, y0, y1, yobs)
#
# individual causal effect #
df$y1y0 = df$y1 - df$y0
# grand mean #
mean(df$y1y0)
# ATT / ATC #
df %>% group_by(d) %>% summarise(mean(y1 - y0))
# naive group comparison #
naive_group_comparison = df %>% group_by(d) %>% summarise(m = mean(yobs)) %>% summarise(m[d == 1] - m[d == 0])
naive_group_comparison
# ATT
`Y(1) Y(0) | D =1` = df[df$d==1,] %>% summarise(mean(y1 - y0))
# ATC
`Y(1) Y(0) | D =0` = df[df$d==0,] %>% summarise(mean(y1 - y0))
# unobserved quantities #
`Y(0) | D =1` = df[df$d==1,] %>% summarise(mean(y0))
`Y(1) | D =0` = df[df$d==0,] %>% summarise(mean(y1))
# observed
`Y(1) | D =1` = df[df$d==1,] %>% summarise(mean(y1))
`Y(0) | D =0` = df[df$d==0,] %>% summarise(mean(y0))
# ATT
selection_bias_1 = `Y(0) | D =1` - `Y(0) | D =0`
# ATT + selection bias 1 #
`Y(1) Y(0) | D =1` + selection_bias_1
# We get the correct result as
# naive_group_comparison
# ATC
selection_bias_2 = `Y(1) | D =0` - `Y(1) | D =1`
# ATC + selection bias 1 #
`Y(1) Y(0) | D =1` + selection_bias_2
|
Potential outcomes selection bias
Just to build on @periwinkle answer, I want to emphasise that this equation is solved by an algebraic trick by adding $E[Y(0) | D = 1]$ twice. Professors do not make this clear enough. You see that of
|
45,971
|
Stuck on Penney's game question
|
Appropriate diagrams make these results intuitive -- and they can even lead to exact calculations with little effort.
Probability flows like water (or any other conserved substance). After observing a sequence $\omega$ of coin tosses, its probability is split into two "flow channels" according to the chance of heads, $p,$ and the chance of tails (which must be $1-p$ to conserve probability).
In technical notation, this picture describes two conditional probabilities $p = \Pr(\omega H\mid \omega)$ and $1-p = \Pr(\omega T\mid \omega).$
Because all examples in the question involve sequences of three flips, nothing interesting happens until after the first three flips. At this point there are $2^3=8$ possible states, such as THH (tails, then heads, then heads), and because the coin is fair, all states have a chance of $1/8.$
From then on, by focusing on the most recent run of three outcomes, each flip induces a transition from the current state to another state. For instance, a THH followed by a tails transitions to HHH.
The initial state probabilities are like pools of water, with a volume of $1/8$ in each pool. The transitions make the water flow out of each pool into two pools.
Here is the full diagram of all transitions. Solid red arrows are the transitions occurring when a head is observed; dashed blue arrows are the transitions occurring when a tail is observed.
By means of examples, I will show how to compute with this graph.
Example 1: THH vs. HHT
The game ends upon encountering either THH or HHT. We can model this by removing all outflows from these pools. Having done this, the water eventually will reach one of them and collect there.
The chance that THH is reached first equals the amount of water (probability) that accumulates in the THH basin.
Here is the preceding transition diagram with (i) the outflows from THH and HHT removed and (ii) THH outlined in black, HHT outlined in green.
Removing the outflows has disconnected the flow system. It is visually obvious that all water (probability) originally at HHH or HHT eventually ends in HHT. Therefore the chance HHT is reached before THH is $(2)\times(1/8) = 1/4.$ This is the first example of the question.
Example 2: THH vs. THT
Not all analyses are so simple. Here is the pruned graph for THH vs. THT.
Some pools flow eventually into both the terminal basins. However, there are obvious groups of pools: HHH eventually flows only into HHT. We might as well think of this as a pool with $1/8+1/8=1/4$ of the water (probability). HTT and TTT eventually flow into TTH. We might as well merge them into a pool with $3/8$ of the water. In doing these merges, we must retain all inflows and outflows. Here is the resulting "reduced graph."
A neat way to compute how much water (probability) ends in the THH basin is to create a "flow fractions" graph. It begins by assigning 100% of the water in THH to the THH basin and 0% of the water in THT to the THH basin. Then it works backwards through the graph. For instance, HTH splits its outflows between THH and THT. Thus, only 50% (1/2) of the water in HTH winds up in THH. The same is true for the combined HTT/TTT/TTH pool: half its water (probability) ends up in THH. Finally, the outflow from the HHH/HHT pool is split between HTH and the HTT/TTT/TTH pools. Since each of the latter contribute half their water to THH, the same must be true for HHH/HHT.
Here is the resulting flow fractions graph, drawn to parallel the reduced graph:
Finally, recall how much water begins in each pool: $1/8$ in THH, $1/8$ in HTH, $1/8$ in THT, $3/8$ in HTT/TTT/TTH, and $2/8$ in HHH/HHT. Multiplying these amounts by the flow fractions gives
$$\frac{1}{8} \times 1 + \frac{1}{8} \times \frac{1}{2} + \frac{1}{8}\times 0 + \frac{3}{8}\times \frac{1}{2} + \frac{2}{8} \times \frac{1}{2} = \frac{1}{2}.$$
Thus, the chance THH is encountered first is $1/2.$
Example 3: THH vs. TTH
This is the second example of the question.
Again begin by pruning the graph to remove all outfalls from the target basins:
Collect groups of interconnected pools into the reduced graph.
It is already obvious that TTH has the advantage, because most of the pools drain wholly or partly into it.
The challenge this time is to compute the flow fractions: the water can swirl endlessly between HTH and THT. However, half is lost forever to THH when flowing out of HTH and half is lost forever to TTH when flowing out of THT (because eventually it flows only into TTH). This HTH-THT loop, though, seems to make it impossible to backtrack through the graph.
The solution is to leave one of the fractions as an unknown $x.$ Here, I have arbitrarily chosen to let $x$ be the flow fraction for THT.
The flow fraction for HTH is $1/2\times 1$ because of the flow into THH plus $1/2\times x$ because of the flow into THT.
Upon visiting all the nodes, we obtain two expressions for the THT flow fraction. This yields the equation
$$x = \frac{1}{2}\times \frac{1+x}{2} + \frac{1}{2}\times 0,$$
whose (unique) solution is $x=1/3.$ Now we can just read off the remaining flow fractions: $(1+x)/2 = 2/3$ for HTH and $1/3$ for the HHH/HHT pool. The chance of reaching THH first therefore is
$$\frac{1}{8}\times 1 + \frac{1}{8}\times \frac{2}{3} + \frac{1}{8}\times \frac{1}{3} + \frac{3}{8}\times 0 + \frac{2}{8} \times \frac{1}{3} = \frac{1}{3}.$$
Comments
These graph calculations generalize. It is clear how they can be applied to comparing any two terminal states in this game. But no change needs to be made when terminating the game at multiple states. For instance, suppose you play this game against an opponent who wins if either TTH or THT is reached and you win if THH is first reached. What are your chances of winning?
Here are the pruned graph, the reduced graph, and the flow fractions. You can do the arithmetic.
|
Stuck on Penney's game question
|
Appropriate diagrams make these results intuitive -- and they can even lead to exact calculations with little effort.
Probability flows like water (or any other conserved substance). After observing
|
Stuck on Penney's game question
Appropriate diagrams make these results intuitive -- and they can even lead to exact calculations with little effort.
Probability flows like water (or any other conserved substance). After observing a sequence $\omega$ of coin tosses, its probability is split into two "flow channels" according to the chance of heads, $p,$ and the chance of tails (which must be $1-p$ to conserve probability).
In technical notation, this picture describes two conditional probabilities $p = \Pr(\omega H\mid \omega)$ and $1-p = \Pr(\omega T\mid \omega).$
Because all examples in the question involve sequences of three flips, nothing interesting happens until after the first three flips. At this point there are $2^3=8$ possible states, such as THH (tails, then heads, then heads), and because the coin is fair, all states have a chance of $1/8.$
From then on, by focusing on the most recent run of three outcomes, each flip induces a transition from the current state to another state. For instance, a THH followed by a tails transitions to HHH.
The initial state probabilities are like pools of water, with a volume of $1/8$ in each pool. The transitions make the water flow out of each pool into two pools.
Here is the full diagram of all transitions. Solid red arrows are the transitions occurring when a head is observed; dashed blue arrows are the transitions occurring when a tail is observed.
By means of examples, I will show how to compute with this graph.
Example 1: THH vs. HHT
The game ends upon encountering either THH or HHT. We can model this by removing all outflows from these pools. Having done this, the water eventually will reach one of them and collect there.
The chance that THH is reached first equals the amount of water (probability) that accumulates in the THH basin.
Here is the preceding transition diagram with (i) the outflows from THH and HHT removed and (ii) THH outlined in black, HHT outlined in green.
Removing the outflows has disconnected the flow system. It is visually obvious that all water (probability) originally at HHH or HHT eventually ends in HHT. Therefore the chance HHT is reached before THH is $(2)\times(1/8) = 1/4.$ This is the first example of the question.
Example 2: THH vs. THT
Not all analyses are so simple. Here is the pruned graph for THH vs. THT.
Some pools flow eventually into both the terminal basins. However, there are obvious groups of pools: HHH eventually flows only into HHT. We might as well think of this as a pool with $1/8+1/8=1/4$ of the water (probability). HTT and TTT eventually flow into TTH. We might as well merge them into a pool with $3/8$ of the water. In doing these merges, we must retain all inflows and outflows. Here is the resulting "reduced graph."
A neat way to compute how much water (probability) ends in the THH basin is to create a "flow fractions" graph. It begins by assigning 100% of the water in THH to the THH basin and 0% of the water in THT to the THH basin. Then it works backwards through the graph. For instance, HTH splits its outflows between THH and THT. Thus, only 50% (1/2) of the water in HTH winds up in THH. The same is true for the combined HTT/TTT/TTH pool: half its water (probability) ends up in THH. Finally, the outflow from the HHH/HHT pool is split between HTH and the HTT/TTT/TTH pools. Since each of the latter contribute half their water to THH, the same must be true for HHH/HHT.
Here is the resulting flow fractions graph, drawn to parallel the reduced graph:
Finally, recall how much water begins in each pool: $1/8$ in THH, $1/8$ in HTH, $1/8$ in THT, $3/8$ in HTT/TTT/TTH, and $2/8$ in HHH/HHT. Multiplying these amounts by the flow fractions gives
$$\frac{1}{8} \times 1 + \frac{1}{8} \times \frac{1}{2} + \frac{1}{8}\times 0 + \frac{3}{8}\times \frac{1}{2} + \frac{2}{8} \times \frac{1}{2} = \frac{1}{2}.$$
Thus, the chance THH is encountered first is $1/2.$
Example 3: THH vs. TTH
This is the second example of the question.
Again begin by pruning the graph to remove all outfalls from the target basins:
Collect groups of interconnected pools into the reduced graph.
It is already obvious that TTH has the advantage, because most of the pools drain wholly or partly into it.
The challenge this time is to compute the flow fractions: the water can swirl endlessly between HTH and THT. However, half is lost forever to THH when flowing out of HTH and half is lost forever to TTH when flowing out of THT (because eventually it flows only into TTH). This HTH-THT loop, though, seems to make it impossible to backtrack through the graph.
The solution is to leave one of the fractions as an unknown $x.$ Here, I have arbitrarily chosen to let $x$ be the flow fraction for THT.
The flow fraction for HTH is $1/2\times 1$ because of the flow into THH plus $1/2\times x$ because of the flow into THT.
Upon visiting all the nodes, we obtain two expressions for the THT flow fraction. This yields the equation
$$x = \frac{1}{2}\times \frac{1+x}{2} + \frac{1}{2}\times 0,$$
whose (unique) solution is $x=1/3.$ Now we can just read off the remaining flow fractions: $(1+x)/2 = 2/3$ for HTH and $1/3$ for the HHH/HHT pool. The chance of reaching THH first therefore is
$$\frac{1}{8}\times 1 + \frac{1}{8}\times \frac{2}{3} + \frac{1}{8}\times \frac{1}{3} + \frac{3}{8}\times 0 + \frac{2}{8} \times \frac{1}{3} = \frac{1}{3}.$$
Comments
These graph calculations generalize. It is clear how they can be applied to comparing any two terminal states in this game. But no change needs to be made when terminating the game at multiple states. For instance, suppose you play this game against an opponent who wins if either TTH or THT is reached and you win if THH is first reached. What are your chances of winning?
Here are the pruned graph, the reduced graph, and the flow fractions. You can do the arithmetic.
|
Stuck on Penney's game question
Appropriate diagrams make these results intuitive -- and they can even lead to exact calculations with little effort.
Probability flows like water (or any other conserved substance). After observing
|
45,972
|
Stuck on Penney's game question
|
This type of problem relates to "string-counts", which in turn relate to deterministic finite automata (DFAs) for strings (see this related question). The simplest way to understand these problems is to construct a DFA for the "language" of interest in the problem (i.e., the set of strings being counted). In the figure below I show the minimised DFA for your first case, with heads represented by the blue arrows and tails represented by the red arrows. There are seven different states in the minimised DFA, and the final states of interest are at the bottom of the figure. As you can see from the picture, the transitions in the DFA are not symmetric with respect to these final states.
As you can see from the figure, there are a substantial number of transitions into the state T in this DFA, and this is the main reason why the the state THH tends to occur before the state HHT. The first string is a more "forgiving" string on the first run (i.e., starting from the null state); once you are in the state T you are guaranteed to reach the state THH before the state HHT. If you would like some more insight into this, consider the number of transitions into these two states from the NULL state, noting that each transition of head/tails is equiprobable under your model.
Implementation in R: Below I implement the first of these string-count problems in my own custom DFA function in R (to be released at a later date). This output shows the transition table for the DFA (matching the arrows in the figure) and shows the transition probability matrix and steady state for the DFA. As you can see, the two outcomes of interest to you will occur with equal probability in the steady state, and will therefore tend to occur in roughly the same proportions in the long run. However, the state THH tends to occur before the state HHT due to the large number of transitions into the early components of that string.
Deterministic Finite Automaton (DFA)
DFA for a language containing 2 strings
---------------------Transitions and final states----------------------
| H T | F[1] F[2]
State[0] | 2 1 | 0 0
State[1] | 3 1 | 0 0
State[2] | 4 1 | 0 0
State[3] | 5 1 | 0 0
State[4] | 4 6 | 0 0
State[5] | 4 6 | 0 1
State[6] | 3 1 | 1 0
-------------------------Symbol probabilities--------------------------
H T
Probability 0.5 0.5
--------------------Stationary state probabilities---------------------
State[0] State[1] State[2] State[3] State[4] State[5] State[6]
Stationary 0 0.375 0 0.25 0.125 0.125 0.125
---------------------Transition probability matrix---------------------
State[0] State[1] State[2] State[3] State[4] State[5] State[6]
State[0] 0 0.5 0.5 0.0 0.0 0.0 0.0
State[1] 0 0.5 0.0 0.5 0.0 0.0 0.0
State[2] 0 0.5 0.0 0.0 0.5 0.0 0.0
State[3] 0 0.5 0.0 0.0 0.0 0.5 0.0
State[4] 0 0.0 0.0 0.0 0.5 0.0 0.5
State[5] 0 0.0 0.0 0.0 0.5 0.0 0.5
State[6] 0 0.5 0.0 0.5 0.0 0.0 0.0
-------------------Alphabet and language information-------------------
The alphabet contains 2 symbols
H T
String[1] contains 3 symbols
H H T
String[2] contains 3 symbols
T H H
-----------------------------------------------------------------------
|
Stuck on Penney's game question
|
This type of problem relates to "string-counts", which in turn relate to deterministic finite automata (DFAs) for strings (see this related question). The simplest way to understand these problems is
|
Stuck on Penney's game question
This type of problem relates to "string-counts", which in turn relate to deterministic finite automata (DFAs) for strings (see this related question). The simplest way to understand these problems is to construct a DFA for the "language" of interest in the problem (i.e., the set of strings being counted). In the figure below I show the minimised DFA for your first case, with heads represented by the blue arrows and tails represented by the red arrows. There are seven different states in the minimised DFA, and the final states of interest are at the bottom of the figure. As you can see from the picture, the transitions in the DFA are not symmetric with respect to these final states.
As you can see from the figure, there are a substantial number of transitions into the state T in this DFA, and this is the main reason why the the state THH tends to occur before the state HHT. The first string is a more "forgiving" string on the first run (i.e., starting from the null state); once you are in the state T you are guaranteed to reach the state THH before the state HHT. If you would like some more insight into this, consider the number of transitions into these two states from the NULL state, noting that each transition of head/tails is equiprobable under your model.
Implementation in R: Below I implement the first of these string-count problems in my own custom DFA function in R (to be released at a later date). This output shows the transition table for the DFA (matching the arrows in the figure) and shows the transition probability matrix and steady state for the DFA. As you can see, the two outcomes of interest to you will occur with equal probability in the steady state, and will therefore tend to occur in roughly the same proportions in the long run. However, the state THH tends to occur before the state HHT due to the large number of transitions into the early components of that string.
Deterministic Finite Automaton (DFA)
DFA for a language containing 2 strings
---------------------Transitions and final states----------------------
| H T | F[1] F[2]
State[0] | 2 1 | 0 0
State[1] | 3 1 | 0 0
State[2] | 4 1 | 0 0
State[3] | 5 1 | 0 0
State[4] | 4 6 | 0 0
State[5] | 4 6 | 0 1
State[6] | 3 1 | 1 0
-------------------------Symbol probabilities--------------------------
H T
Probability 0.5 0.5
--------------------Stationary state probabilities---------------------
State[0] State[1] State[2] State[3] State[4] State[5] State[6]
Stationary 0 0.375 0 0.25 0.125 0.125 0.125
---------------------Transition probability matrix---------------------
State[0] State[1] State[2] State[3] State[4] State[5] State[6]
State[0] 0 0.5 0.5 0.0 0.0 0.0 0.0
State[1] 0 0.5 0.0 0.5 0.0 0.0 0.0
State[2] 0 0.5 0.0 0.0 0.5 0.0 0.0
State[3] 0 0.5 0.0 0.0 0.0 0.5 0.0
State[4] 0 0.0 0.0 0.0 0.5 0.0 0.5
State[5] 0 0.0 0.0 0.0 0.5 0.0 0.5
State[6] 0 0.5 0.0 0.5 0.0 0.0 0.0
-------------------Alphabet and language information-------------------
The alphabet contains 2 symbols
H T
String[1] contains 3 symbols
H H T
String[2] contains 3 symbols
T H H
-----------------------------------------------------------------------
|
Stuck on Penney's game question
This type of problem relates to "string-counts", which in turn relate to deterministic finite automata (DFAs) for strings (see this related question). The simplest way to understand these problems is
|
45,973
|
How to sample $n$ observations from a multinomial distribution using binomial (or poisson) sampling?
|
You can do it by progressing conditionally through the categories. I'm going to work from the last category backward (for a particular reason) but it can be done in any order as long as you're consistent in how you go about it.
Equal probability case:
Sample the count in the $n$-th category, $X_n\sim\text{bin}(n,\frac{1}{n})$.
Sample the count in the $n-1$-th category conditionally on $X_n=x_n$, i.e. $X_{n-1}\sim\text{bin}(n-x_n,\frac{1}{n-1})$.
Sample the count in the $n-2$-th category conditionally on $X_{n-1}+X_n=s_{n-1:n}$, i.e. $X_{n-2}\sim\text{bin}(n-s_{n-1:n},\frac{1}{n-2})$,
... and so on. Naturally, if $s_{i:n}$ hits $n$, all lower $X$'s are $0$ for that sample.
Unequal probability case:
Sample the count in the $n$-th category, $X_n\sim\text{bin}(n,p_n)$.
Sample the count in the $n-1$-th category conditionally on $X_n=x_n$, i.e. compute $p_{n-1:n} = \frac{p_{n-1}}{{1-p_n}}$ (i.e. scaling up the remaining probabilities since we no longer have the last category) and draw $X_{n-1}\sim\text{bin}(n-x_n,p_{n-1:n})$.
Sample the count in the $n-2$-th category conditionally on $X_{n-1}+X_n=s_{n-1:n}$, i.e. compute $p_{n-2:n} = \frac{p_{n-2}}{{1-p_{n-1}-p_n}}$ and draw $X_{n-2}\sim\text{bin}(n-s_{n-1:n},p_{n-2:n})$,
... and so on. Naturally, if $s_{i:n}$ hits $n$, all lower $X$'s are $0$ for that sample.
So you progress through, adjusting both the "n" and "p" to account for the conditioning on what categories are already drawn and what's left to draw from.
If there are a very large number of categories and so typically very small values of $p_i$ you may need to pay attention to numerical error in the scaling of those $p$ values as you progress.
|
How to sample $n$ observations from a multinomial distribution using binomial (or poisson) sampling?
|
You can do it by progressing conditionally through the categories. I'm going to work from the last category backward (for a particular reason) but it can be done in any order as long as you're consist
|
How to sample $n$ observations from a multinomial distribution using binomial (or poisson) sampling?
You can do it by progressing conditionally through the categories. I'm going to work from the last category backward (for a particular reason) but it can be done in any order as long as you're consistent in how you go about it.
Equal probability case:
Sample the count in the $n$-th category, $X_n\sim\text{bin}(n,\frac{1}{n})$.
Sample the count in the $n-1$-th category conditionally on $X_n=x_n$, i.e. $X_{n-1}\sim\text{bin}(n-x_n,\frac{1}{n-1})$.
Sample the count in the $n-2$-th category conditionally on $X_{n-1}+X_n=s_{n-1:n}$, i.e. $X_{n-2}\sim\text{bin}(n-s_{n-1:n},\frac{1}{n-2})$,
... and so on. Naturally, if $s_{i:n}$ hits $n$, all lower $X$'s are $0$ for that sample.
Unequal probability case:
Sample the count in the $n$-th category, $X_n\sim\text{bin}(n,p_n)$.
Sample the count in the $n-1$-th category conditionally on $X_n=x_n$, i.e. compute $p_{n-1:n} = \frac{p_{n-1}}{{1-p_n}}$ (i.e. scaling up the remaining probabilities since we no longer have the last category) and draw $X_{n-1}\sim\text{bin}(n-x_n,p_{n-1:n})$.
Sample the count in the $n-2$-th category conditionally on $X_{n-1}+X_n=s_{n-1:n}$, i.e. compute $p_{n-2:n} = \frac{p_{n-2}}{{1-p_{n-1}-p_n}}$ and draw $X_{n-2}\sim\text{bin}(n-s_{n-1:n},p_{n-2:n})$,
... and so on. Naturally, if $s_{i:n}$ hits $n$, all lower $X$'s are $0$ for that sample.
So you progress through, adjusting both the "n" and "p" to account for the conditioning on what categories are already drawn and what's left to draw from.
If there are a very large number of categories and so typically very small values of $p_i$ you may need to pay attention to numerical error in the scaling of those $p$ values as you progress.
|
How to sample $n$ observations from a multinomial distribution using binomial (or poisson) sampling?
You can do it by progressing conditionally through the categories. I'm going to work from the last category backward (for a particular reason) but it can be done in any order as long as you're consist
|
45,974
|
Which class to define as positive in unbalanced classification
|
It does not matter. It is done that way because it would be something like disease detection where most people don’t have the disease, but that’s what you want to catch. However, all of the math works out fine either way. If you made the heathy class the $1$s, your model would be outputting the probability of being healthy instead of the probability of having the disease. The English phrasing of those two might carry different connotations, but the mathematical logic is the same.
|
Which class to define as positive in unbalanced classification
|
It does not matter. It is done that way because it would be something like disease detection where most people don’t have the disease, but that’s what you want to catch. However, all of the math works
|
Which class to define as positive in unbalanced classification
It does not matter. It is done that way because it would be something like disease detection where most people don’t have the disease, but that’s what you want to catch. However, all of the math works out fine either way. If you made the heathy class the $1$s, your model would be outputting the probability of being healthy instead of the probability of having the disease. The English phrasing of those two might carry different connotations, but the mathematical logic is the same.
|
Which class to define as positive in unbalanced classification
It does not matter. It is done that way because it would be something like disease detection where most people don’t have the disease, but that’s what you want to catch. However, all of the math works
|
45,975
|
Which class to define as positive in unbalanced classification
|
@Dave's answer is that all classification algorithms are symmetrical in regard to which class is called positive and which is called negative, or which is assigned to 0 and which to 1. This is probably true in almost all cases, but maybe one. It is true for decision trees and ensembles of decision trees since the classes are treated as categorical variables, as is for KNN, naive Bayes and so on. The two families of classifier algorithms that threat the classes as numbers, and therefore may be non-symmetrical in relation to the values 0 and 1 are logistic regression and SVM, but one can verify that the formulas are symmetrical, and thus no problem there.
But there is one case which I think may not be symmetrical regarding 2nd order aspects. I am not 100% sure and would appreciate if more knowledgeable people would chip in this discussion. Consider a neural network (MLP for example) optimizing log loss.
$$ log loss = \sum [y_i \log p_i + (1-y_i) \log (1-p_i)] $$
$y_i$ is the correct output, $p_i$ is the predicted probability.
The formula is symmetric by exchanging the y_i from 0 to 1 and vice versa, BUT the optimization being computed by the neural network is not (this is the 2nd order aspect). Output with $y_i = 0$ do not contribute to the log loss and thus do not contribute to the gradient and this it is not used in the gradient descent of the neural network. Therefore, by using the majority class 0 one is not using most of the data to optimize the MLP! The minimum is the same but a) if the gradient descent will reach that minimum, b) if it will the convergence rate to that minimum and c) the solution the MLP will settle given that it does not reach the global minimum are not the same whether one uses 0 or 1 for the majority class.
Am I right here?
|
Which class to define as positive in unbalanced classification
|
@Dave's answer is that all classification algorithms are symmetrical in regard to which class is called positive and which is called negative, or which is assigned to 0 and which to 1. This is probabl
|
Which class to define as positive in unbalanced classification
@Dave's answer is that all classification algorithms are symmetrical in regard to which class is called positive and which is called negative, or which is assigned to 0 and which to 1. This is probably true in almost all cases, but maybe one. It is true for decision trees and ensembles of decision trees since the classes are treated as categorical variables, as is for KNN, naive Bayes and so on. The two families of classifier algorithms that threat the classes as numbers, and therefore may be non-symmetrical in relation to the values 0 and 1 are logistic regression and SVM, but one can verify that the formulas are symmetrical, and thus no problem there.
But there is one case which I think may not be symmetrical regarding 2nd order aspects. I am not 100% sure and would appreciate if more knowledgeable people would chip in this discussion. Consider a neural network (MLP for example) optimizing log loss.
$$ log loss = \sum [y_i \log p_i + (1-y_i) \log (1-p_i)] $$
$y_i$ is the correct output, $p_i$ is the predicted probability.
The formula is symmetric by exchanging the y_i from 0 to 1 and vice versa, BUT the optimization being computed by the neural network is not (this is the 2nd order aspect). Output with $y_i = 0$ do not contribute to the log loss and thus do not contribute to the gradient and this it is not used in the gradient descent of the neural network. Therefore, by using the majority class 0 one is not using most of the data to optimize the MLP! The minimum is the same but a) if the gradient descent will reach that minimum, b) if it will the convergence rate to that minimum and c) the solution the MLP will settle given that it does not reach the global minimum are not the same whether one uses 0 or 1 for the majority class.
Am I right here?
|
Which class to define as positive in unbalanced classification
@Dave's answer is that all classification algorithms are symmetrical in regard to which class is called positive and which is called negative, or which is assigned to 0 and which to 1. This is probabl
|
45,976
|
Robust Variance Estimation in Bayesian Meta-analysis
|
The reviewer is correct in the sense that this model does not properly account for correlated sampling errors (when multiple effects are computed based on the same sample of subjects, then the sampling errors of the estimates are typically correlated). By adding random effects to your model, you are modeling potential correlation/dependencies in the underlying true effects, but not the sampling errors. Just like you are specifying the standard errors of the estimates (sei), one would have to specify the covariances of the estimates (i.e., an entire variance-covariance matrix of the sampling errors) to properly account for the latter. This is an example where this is done:
https://www.metafor-project.org/doku.php/analyses:berkey1998
In practice, constructing this var-cov matrix ($V$) is difficult. One can construct an approximate var-cov matrix based on a 'guestimate' of the correlation among the sampling errors and then treat this as the 'working model'. Even if the $V$ matrix is somewhat misspecified, the estimates of the fixed effects should be approximately unbiased. But the standard errors might be off. Hence, for inferences, we can use cluster robust standard errors.
This aside, just adding a random effect at the study level implicitly assumes that the true effects within studies are homogeneous. That is not an assumption I would recommend to make a priori.
Here is an example illustrating the different approaches (note: esid is an 'effect size id', not the study id).
library(metafor)
library(brms)
library(clubSandwich)
dat <- dat.assink2016
dat$sei <- sqrt(dat$vi)
head(dat, 10)
# study esid id yi vi pubstatus year deltype sei
# 1 1 1 1 0.9066 0.0740 1 4.5 general 0.27202941
# 2 1 2 2 0.4295 0.0398 1 4.5 general 0.19949937
# 3 1 3 3 0.2679 0.0481 1 4.5 general 0.21931712
# 4 1 4 4 0.2078 0.0239 1 4.5 general 0.15459625
# 5 1 5 5 0.0526 0.0331 1 4.5 general 0.18193405
# 6 1 6 6 -0.0507 0.0886 1 4.5 general 0.29765752
# 7 2 1 7 0.5117 0.0115 1 1.5 general 0.10723805
# 8 2 2 8 0.4738 0.0076 1 1.5 general 0.08717798
# 9 2 3 9 0.3544 0.0065 1 1.5 general 0.08062258
# 10 3 1 10 2.2844 0.3325 1 -8.5 general 0.57662813
# fit multilevel model (assuming no covariance among the sampling errors)
res1 <- rma.mv(yi, vi, random = ~ 1 | study/esid, data=dat)
res1
# analogous brm() model
res2 <- brm(yi|se(sei) ~ 1 + (1 | study/esid), data = dat)
summary(res2, priors=TRUE)
# construct approx V matrix assuming r=0.6 for the sampling errors
V <- impute_covariance_matrix(dat$vi, cluster=dat$study, r=0.6)
# fit multilevel model with the approximate V matrix
res3 <- rma.mv(yi, V, random = ~ 1 | study/esid, data=dat)
res3
# use cluster robust inference methods
robust(res3, cluster=dat$study)
# or use coef_test() from clubSandwich
coef_test(res3, vcov="CR2", cluster=dat$study)
You will find that the results in res1 and res2 are quite similar.$^1$ The results in res3 differ more by having specified the approximate $V$ matrix. Using cluster robust methods barely changes the results in this case, but could do so more in other cases.
Some relevant papers on the use of robust variance estimation (also known as the 'sandwich method') in the context of Bayesian analyses are https://doi.org/10.1214/10-AOAS362 and https://doi.org/10.3982/ECTA9097 but these are not focused on meta-analysis and I am not aware of any papers that do so.
If you want to stick with brms, then I would recommend to at least specify the random effects as above. There is some evidence that ignoring the sampling error covariances can also work (the study-level variance component then gets inflated to compensate for essentially assuming that the covariances are equal to zero, which we also see happening in this example). See https://doi.org/10.3758/s13428-012-0261-6 and https://doi.org/10.3758/s13428-014-0527-2 and https://doi.org/10.1080/13645579.2016.1252189 (none of these discuss Bayesian approaches though).
$^1$ The mean of the posterior for the study-level standard deviation is a tad higher in res2 than the REML estimate in res1, presumably because with 17 studies, the prior (a half student-t with df=3 and scale parameter 2.5) pulls the mean of the posterior up a bit.
|
Robust Variance Estimation in Bayesian Meta-analysis
|
The reviewer is correct in the sense that this model does not properly account for correlated sampling errors (when multiple effects are computed based on the same sample of subjects, then the samplin
|
Robust Variance Estimation in Bayesian Meta-analysis
The reviewer is correct in the sense that this model does not properly account for correlated sampling errors (when multiple effects are computed based on the same sample of subjects, then the sampling errors of the estimates are typically correlated). By adding random effects to your model, you are modeling potential correlation/dependencies in the underlying true effects, but not the sampling errors. Just like you are specifying the standard errors of the estimates (sei), one would have to specify the covariances of the estimates (i.e., an entire variance-covariance matrix of the sampling errors) to properly account for the latter. This is an example where this is done:
https://www.metafor-project.org/doku.php/analyses:berkey1998
In practice, constructing this var-cov matrix ($V$) is difficult. One can construct an approximate var-cov matrix based on a 'guestimate' of the correlation among the sampling errors and then treat this as the 'working model'. Even if the $V$ matrix is somewhat misspecified, the estimates of the fixed effects should be approximately unbiased. But the standard errors might be off. Hence, for inferences, we can use cluster robust standard errors.
This aside, just adding a random effect at the study level implicitly assumes that the true effects within studies are homogeneous. That is not an assumption I would recommend to make a priori.
Here is an example illustrating the different approaches (note: esid is an 'effect size id', not the study id).
library(metafor)
library(brms)
library(clubSandwich)
dat <- dat.assink2016
dat$sei <- sqrt(dat$vi)
head(dat, 10)
# study esid id yi vi pubstatus year deltype sei
# 1 1 1 1 0.9066 0.0740 1 4.5 general 0.27202941
# 2 1 2 2 0.4295 0.0398 1 4.5 general 0.19949937
# 3 1 3 3 0.2679 0.0481 1 4.5 general 0.21931712
# 4 1 4 4 0.2078 0.0239 1 4.5 general 0.15459625
# 5 1 5 5 0.0526 0.0331 1 4.5 general 0.18193405
# 6 1 6 6 -0.0507 0.0886 1 4.5 general 0.29765752
# 7 2 1 7 0.5117 0.0115 1 1.5 general 0.10723805
# 8 2 2 8 0.4738 0.0076 1 1.5 general 0.08717798
# 9 2 3 9 0.3544 0.0065 1 1.5 general 0.08062258
# 10 3 1 10 2.2844 0.3325 1 -8.5 general 0.57662813
# fit multilevel model (assuming no covariance among the sampling errors)
res1 <- rma.mv(yi, vi, random = ~ 1 | study/esid, data=dat)
res1
# analogous brm() model
res2 <- brm(yi|se(sei) ~ 1 + (1 | study/esid), data = dat)
summary(res2, priors=TRUE)
# construct approx V matrix assuming r=0.6 for the sampling errors
V <- impute_covariance_matrix(dat$vi, cluster=dat$study, r=0.6)
# fit multilevel model with the approximate V matrix
res3 <- rma.mv(yi, V, random = ~ 1 | study/esid, data=dat)
res3
# use cluster robust inference methods
robust(res3, cluster=dat$study)
# or use coef_test() from clubSandwich
coef_test(res3, vcov="CR2", cluster=dat$study)
You will find that the results in res1 and res2 are quite similar.$^1$ The results in res3 differ more by having specified the approximate $V$ matrix. Using cluster robust methods barely changes the results in this case, but could do so more in other cases.
Some relevant papers on the use of robust variance estimation (also known as the 'sandwich method') in the context of Bayesian analyses are https://doi.org/10.1214/10-AOAS362 and https://doi.org/10.3982/ECTA9097 but these are not focused on meta-analysis and I am not aware of any papers that do so.
If you want to stick with brms, then I would recommend to at least specify the random effects as above. There is some evidence that ignoring the sampling error covariances can also work (the study-level variance component then gets inflated to compensate for essentially assuming that the covariances are equal to zero, which we also see happening in this example). See https://doi.org/10.3758/s13428-012-0261-6 and https://doi.org/10.3758/s13428-014-0527-2 and https://doi.org/10.1080/13645579.2016.1252189 (none of these discuss Bayesian approaches though).
$^1$ The mean of the posterior for the study-level standard deviation is a tad higher in res2 than the REML estimate in res1, presumably because with 17 studies, the prior (a half student-t with df=3 and scale parameter 2.5) pulls the mean of the posterior up a bit.
|
Robust Variance Estimation in Bayesian Meta-analysis
The reviewer is correct in the sense that this model does not properly account for correlated sampling errors (when multiple effects are computed based on the same sample of subjects, then the samplin
|
45,977
|
Robust Variance Estimation in Bayesian Meta-analysis
|
Please check this article by brms' author: https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0173660, where they say: "...outcomes reported by the same study were explicitly modeled as correlated. In the absence of any reported correlations in the primary studies, correlations were set to r = 0.7. To investigate the influence of this decision on the obtained results, a sensitivity analysis was conducted where correlations were varied between r = 0.1 and r = 0.9."
Fortunately, they used brms to run the meta-analysis and the code is available here: https://osf.io/gs6hk/
|
Robust Variance Estimation in Bayesian Meta-analysis
|
Please check this article by brms' author: https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0173660, where they say: "...outcomes reported by the same study were explicitly modeled as
|
Robust Variance Estimation in Bayesian Meta-analysis
Please check this article by brms' author: https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0173660, where they say: "...outcomes reported by the same study were explicitly modeled as correlated. In the absence of any reported correlations in the primary studies, correlations were set to r = 0.7. To investigate the influence of this decision on the obtained results, a sensitivity analysis was conducted where correlations were varied between r = 0.1 and r = 0.9."
Fortunately, they used brms to run the meta-analysis and the code is available here: https://osf.io/gs6hk/
|
Robust Variance Estimation in Bayesian Meta-analysis
Please check this article by brms' author: https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0173660, where they say: "...outcomes reported by the same study were explicitly modeled as
|
45,978
|
Converting a confidence interval into a credible interval
|
For so called location models, such as your linear regression, anovas etc., basically for models where the outcome depends linearly on the estimated parameters, the confidence interval will be the same as the credible interval with flat prior.
If you want to know how would that credible interval look like with a different prior, then you add that prior information to your results as you would do normally as a Bayesian.
This is not the case for models where the outcome depends non-linearly on parameters, such as for logistic regression. I think this is because likelihood is invariant to reparametrizations, but priors are not, so you cannot really have a non-informative prior in this case. There are also invariant priors, and probability matching priors, but unfortunately I don't know how they fit into the picture. Sorry
How much will confidence and credible intervals differ, depends on the data. The more data you have, the less will they differ. With a lot of data (infinite) they will be the same again. If they are different, credible intervals won't have the proper coverage, which might not be something you want.
If you want a more mathy treatment of this topic look at
Fraser, D. A. S. “Is Bayes Posterior Just Quick and Dirty Confidence?” Statistical Science, vol. 26, no. 3, 2011, pp. 299–316. JSTOR, www.jstor.org/stable/23059129. Accessed 3 June 2021. (there is also an arxiv version https://arxiv.org/abs/1112.5582)
There you will also find a formula to how much will they differ and also how to get from a confidence quantile to Bayesian quantile. The math in the paper should be good, but the sentiment of the paper is not something that is generally accepted.
|
Converting a confidence interval into a credible interval
|
For so called location models, such as your linear regression, anovas etc., basically for models where the outcome depends linearly on the estimated parameters, the confidence interval will be the sam
|
Converting a confidence interval into a credible interval
For so called location models, such as your linear regression, anovas etc., basically for models where the outcome depends linearly on the estimated parameters, the confidence interval will be the same as the credible interval with flat prior.
If you want to know how would that credible interval look like with a different prior, then you add that prior information to your results as you would do normally as a Bayesian.
This is not the case for models where the outcome depends non-linearly on parameters, such as for logistic regression. I think this is because likelihood is invariant to reparametrizations, but priors are not, so you cannot really have a non-informative prior in this case. There are also invariant priors, and probability matching priors, but unfortunately I don't know how they fit into the picture. Sorry
How much will confidence and credible intervals differ, depends on the data. The more data you have, the less will they differ. With a lot of data (infinite) they will be the same again. If they are different, credible intervals won't have the proper coverage, which might not be something you want.
If you want a more mathy treatment of this topic look at
Fraser, D. A. S. “Is Bayes Posterior Just Quick and Dirty Confidence?” Statistical Science, vol. 26, no. 3, 2011, pp. 299–316. JSTOR, www.jstor.org/stable/23059129. Accessed 3 June 2021. (there is also an arxiv version https://arxiv.org/abs/1112.5582)
There you will also find a formula to how much will they differ and also how to get from a confidence quantile to Bayesian quantile. The math in the paper should be good, but the sentiment of the paper is not something that is generally accepted.
|
Converting a confidence interval into a credible interval
For so called location models, such as your linear regression, anovas etc., basically for models where the outcome depends linearly on the estimated parameters, the confidence interval will be the sam
|
45,979
|
Converting a confidence interval into a credible interval
|
"But what if someone were to switch from a frequentist to a Bayesian viewpoint after constructing the CI and ask themselves the question: "How confident am I (i. e. at what rate would I - given that there is someone who knows μ and will reveal it at some point - be willing to bet) that this given CI contains μ knowing that it was constructed using A95?""
Yes, that is often exactly what people do interpret confidence intervals without realising they are silently moving from one probabilistic framework to another, without stating the assumption that bridges the two.
It is often fairly benign as there may be a reasonable (i.e. non-contrived) Baysian prior for which the frequentist confidence interval and credible interval are numerically the same. From a subjectivist perspective, there is nothing wrong with viewing the long history of benign interpretations of confidence intervals as credible intervals as justifying that Bayesian confidence in credible intervals.
However the point is that they are answers to different questions so we should not expect the answer to be the same. Bayesians can also form confidence intervals if they choose to do so, I suspect they rarely do because it generally isn't the question you want to ask, and frequentists only use them because they can't give a direct probabilistic answer to the question you actually do want to ask.
|
Converting a confidence interval into a credible interval
|
"But what if someone were to switch from a frequentist to a Bayesian viewpoint after constructing the CI and ask themselves the question: "How confident am I (i. e. at what rate would I - given that t
|
Converting a confidence interval into a credible interval
"But what if someone were to switch from a frequentist to a Bayesian viewpoint after constructing the CI and ask themselves the question: "How confident am I (i. e. at what rate would I - given that there is someone who knows μ and will reveal it at some point - be willing to bet) that this given CI contains μ knowing that it was constructed using A95?""
Yes, that is often exactly what people do interpret confidence intervals without realising they are silently moving from one probabilistic framework to another, without stating the assumption that bridges the two.
It is often fairly benign as there may be a reasonable (i.e. non-contrived) Baysian prior for which the frequentist confidence interval and credible interval are numerically the same. From a subjectivist perspective, there is nothing wrong with viewing the long history of benign interpretations of confidence intervals as credible intervals as justifying that Bayesian confidence in credible intervals.
However the point is that they are answers to different questions so we should not expect the answer to be the same. Bayesians can also form confidence intervals if they choose to do so, I suspect they rarely do because it generally isn't the question you want to ask, and frequentists only use them because they can't give a direct probabilistic answer to the question you actually do want to ask.
|
Converting a confidence interval into a credible interval
"But what if someone were to switch from a frequentist to a Bayesian viewpoint after constructing the CI and ask themselves the question: "How confident am I (i. e. at what rate would I - given that t
|
45,980
|
When there are more variables than observations do shrinkage methods (such as Ridge and Lasso) always find a solution?
|
Yes, $p>n, \lambda=0$ case is rank-deficient. Since you already know that OLS for $p>n$ is rank-deficient, then we can see that substituting $\lambda = 0$ in your equation gives the same objective as OLS, and the proof is complete.
Yes, ridge regression works for any $\lambda >0$. The immediate demonstration is that the $\lambda I$ is positive definite, so $\lambda I + X^T X$ must be positive definite. You can alternatively show this by applying SVD, and showing that the singular values in the ridge case are all positive. The proof of shrinking coefficients using ridge regression through "spectral decomposition" However, as a matter of doing computation on a computer (not mathematics), choosing $\lambda$ too small may not work because floating point arithmetic is not exact.
This is essentially a question of bias-variance-tradeoff. If we choose $\lambda$ too large, then there is too steep a penalty on the coefficients and our predictions may be too far from reality to be useful. If we choose $\lambda$ too small, then the variance of the model may be too high -- estimates will be strongly influenced by our specific data set. In the extreme, excluding or including a single datum could radically change the coefficient estimates.
|
When there are more variables than observations do shrinkage methods (such as Ridge and Lasso) alway
|
Yes, $p>n, \lambda=0$ case is rank-deficient. Since you already know that OLS for $p>n$ is rank-deficient, then we can see that substituting $\lambda = 0$ in your equation gives the same objective as
|
When there are more variables than observations do shrinkage methods (such as Ridge and Lasso) always find a solution?
Yes, $p>n, \lambda=0$ case is rank-deficient. Since you already know that OLS for $p>n$ is rank-deficient, then we can see that substituting $\lambda = 0$ in your equation gives the same objective as OLS, and the proof is complete.
Yes, ridge regression works for any $\lambda >0$. The immediate demonstration is that the $\lambda I$ is positive definite, so $\lambda I + X^T X$ must be positive definite. You can alternatively show this by applying SVD, and showing that the singular values in the ridge case are all positive. The proof of shrinking coefficients using ridge regression through "spectral decomposition" However, as a matter of doing computation on a computer (not mathematics), choosing $\lambda$ too small may not work because floating point arithmetic is not exact.
This is essentially a question of bias-variance-tradeoff. If we choose $\lambda$ too large, then there is too steep a penalty on the coefficients and our predictions may be too far from reality to be useful. If we choose $\lambda$ too small, then the variance of the model may be too high -- estimates will be strongly influenced by our specific data set. In the extreme, excluding or including a single datum could radically change the coefficient estimates.
|
When there are more variables than observations do shrinkage methods (such as Ridge and Lasso) alway
Yes, $p>n, \lambda=0$ case is rank-deficient. Since you already know that OLS for $p>n$ is rank-deficient, then we can see that substituting $\lambda = 0$ in your equation gives the same objective as
|
45,981
|
How to propagate measurement uncertainty in predictors *and* responses for multidimensional, non-parametric regression (and software to do it)?
|
One of the more interesting choices in R is rstan, where you could code this up yourself in the Stan modeling language (which tends to be amazing in that it can produce inference for models that we used to be unable to do for a long time). However, getting started can be a little challenging and it sounds like you'd like a higher level interface.
That could be the brms package, that uses the R model syntax and in the background generates Stan code. Via that detour (generate the Stan code via brms in R and then use the generated Stan code with pystan - or any of the other Stan-tie-ins in other languages such as MathematicaStan or MatlabStan - you can then also use it in Stan). In brms there's the me() function for predictors with measurement errors and a quite nice range of modeling options for non-linear models (it depends a bit of what exactly you are thinking about whether that's covered) and it also supports Gaussian processes, but I'm not sure from what you described to what extent you can fit it all together the way you want (if not you may be best off looking at the - usually quite well-chosen / efficient - Stan code that brms generates and having to fit it together exactly the way you want manually in Stan).
|
How to propagate measurement uncertainty in predictors *and* responses for multidimensional, non-par
|
One of the more interesting choices in R is rstan, where you could code this up yourself in the Stan modeling language (which tends to be amazing in that it can produce inference for models that we us
|
How to propagate measurement uncertainty in predictors *and* responses for multidimensional, non-parametric regression (and software to do it)?
One of the more interesting choices in R is rstan, where you could code this up yourself in the Stan modeling language (which tends to be amazing in that it can produce inference for models that we used to be unable to do for a long time). However, getting started can be a little challenging and it sounds like you'd like a higher level interface.
That could be the brms package, that uses the R model syntax and in the background generates Stan code. Via that detour (generate the Stan code via brms in R and then use the generated Stan code with pystan - or any of the other Stan-tie-ins in other languages such as MathematicaStan or MatlabStan - you can then also use it in Stan). In brms there's the me() function for predictors with measurement errors and a quite nice range of modeling options for non-linear models (it depends a bit of what exactly you are thinking about whether that's covered) and it also supports Gaussian processes, but I'm not sure from what you described to what extent you can fit it all together the way you want (if not you may be best off looking at the - usually quite well-chosen / efficient - Stan code that brms generates and having to fit it together exactly the way you want manually in Stan).
|
How to propagate measurement uncertainty in predictors *and* responses for multidimensional, non-par
One of the more interesting choices in R is rstan, where you could code this up yourself in the Stan modeling language (which tends to be amazing in that it can produce inference for models that we us
|
45,982
|
What is the purpose of having multiple neurons in each layer?
|
Or is each neuron learning something else entirely?
This is the purpose, although I wouldn't say they learn entirely different things since they might have some correlation. Each neuron will have its own view of the data and produces outputs according to it. It's like multiple people from different perspectives looking at the same thing, sharing their opinions, and these opinions are aggregated over and over again in the subsequent layers.
|
What is the purpose of having multiple neurons in each layer?
|
Or is each neuron learning something else entirely?
This is the purpose, although I wouldn't say they learn entirely different things since they might have some correlation. Each neuron will have its
|
What is the purpose of having multiple neurons in each layer?
Or is each neuron learning something else entirely?
This is the purpose, although I wouldn't say they learn entirely different things since they might have some correlation. Each neuron will have its own view of the data and produces outputs according to it. It's like multiple people from different perspectives looking at the same thing, sharing their opinions, and these opinions are aggregated over and over again in the subsequent layers.
|
What is the purpose of having multiple neurons in each layer?
Or is each neuron learning something else entirely?
This is the purpose, although I wouldn't say they learn entirely different things since they might have some correlation. Each neuron will have its
|
45,983
|
What is the purpose of having multiple neurons in each layer?
|
Neural network is basically a tensor function (tensors = scalars, vectors, matrices etc.). It takes stuff in (e.g. vector of some features), compoundly apply some operations like matrix multipication or activation functions, and produces stuff out (e.g. vector of probability distribution over some classes).
The term neuron basically refers to a particular element of a tensor. Having 1 neuron in a layer = the layer would consist of a scalar value (or equivalently vector of size 1, matrix of size 1x1 etc.). Usually, it's good idea to have more dimensional tensors in a network.
Example: You have network that takes an input of 10-dimensional vector, apply matrix multiplication (the matrix is a learnable parameter) to get a vector of 64-dimension, then apply elementwise activation function (e.g. RELU), then apply e.g. softmax classification to get probability distribution over 7 classes.
The hidden layer have 64 neurons, which means that the vector have a dimensionality of 64. If it would have only a dimensionality of 1, the capacity (complexity) of the network would be much lower.
|
What is the purpose of having multiple neurons in each layer?
|
Neural network is basically a tensor function (tensors = scalars, vectors, matrices etc.). It takes stuff in (e.g. vector of some features), compoundly apply some operations like matrix multipication
|
What is the purpose of having multiple neurons in each layer?
Neural network is basically a tensor function (tensors = scalars, vectors, matrices etc.). It takes stuff in (e.g. vector of some features), compoundly apply some operations like matrix multipication or activation functions, and produces stuff out (e.g. vector of probability distribution over some classes).
The term neuron basically refers to a particular element of a tensor. Having 1 neuron in a layer = the layer would consist of a scalar value (or equivalently vector of size 1, matrix of size 1x1 etc.). Usually, it's good idea to have more dimensional tensors in a network.
Example: You have network that takes an input of 10-dimensional vector, apply matrix multiplication (the matrix is a learnable parameter) to get a vector of 64-dimension, then apply elementwise activation function (e.g. RELU), then apply e.g. softmax classification to get probability distribution over 7 classes.
The hidden layer have 64 neurons, which means that the vector have a dimensionality of 64. If it would have only a dimensionality of 1, the capacity (complexity) of the network would be much lower.
|
What is the purpose of having multiple neurons in each layer?
Neural network is basically a tensor function (tensors = scalars, vectors, matrices etc.). It takes stuff in (e.g. vector of some features), compoundly apply some operations like matrix multipication
|
45,984
|
What is the purpose of having multiple neurons in each layer?
|
I think I have the answer having taken some time out.
When we run a neuron, it is a glorified $z=W.T*x +b$ followed by $sigmoid(z)$
As a result, the output is just a single value in a certain range. If a layer has 100 neurons, it has 100 such features.
When we cascade and add multiple layers, the output of $L1$ is the input to $L2$. As a result, if $L1$ has only a single neuron, the next layer has only one feature to learn from. So adding more layers just allows us to get more features and better represent our data.
|
What is the purpose of having multiple neurons in each layer?
|
I think I have the answer having taken some time out.
When we run a neuron, it is a glorified $z=W.T*x +b$ followed by $sigmoid(z)$
As a result, the output is just a single value in a certain range. I
|
What is the purpose of having multiple neurons in each layer?
I think I have the answer having taken some time out.
When we run a neuron, it is a glorified $z=W.T*x +b$ followed by $sigmoid(z)$
As a result, the output is just a single value in a certain range. If a layer has 100 neurons, it has 100 such features.
When we cascade and add multiple layers, the output of $L1$ is the input to $L2$. As a result, if $L1$ has only a single neuron, the next layer has only one feature to learn from. So adding more layers just allows us to get more features and better represent our data.
|
What is the purpose of having multiple neurons in each layer?
I think I have the answer having taken some time out.
When we run a neuron, it is a glorified $z=W.T*x +b$ followed by $sigmoid(z)$
As a result, the output is just a single value in a certain range. I
|
45,985
|
What is the purpose of having multiple neurons in each layer?
|
Expanding upon what @gunes said, if you take a shallow network and explicitly trace out what the network's forward pass is. You can see the adding of additional nodes (within a layer) allows the network to minimise its prediction error.
Let's assume we have some Feed-Forward Neural Network (FFNN) that takes in a single input and a single output and has a single hidden layer of N hidden nodes, and a non-linear activation function denoted, $\sigma$, and the entire forward pass of the network can be described as $\hat{y} = f(x)$, where $\hat{y}$ is the prediction of the true output $y$.
For N = 1, the network can be written as,
$$ \hat{y} = w^{(2)}\sigma(w^{(1)}x_j + b^{(1)})$$
for a given number of hidden nodes, N, it's written as a sum of single neurons, i.e.,
$$ \hat{y} = \sum_i w^{(2)}_{i}\sigma(w^{(1)}_ix_j + b^{(1)}_i) $$
If we look at this from a linear regression standpoint we would minimise a loss function, for example the Mean Absolute Error (MAE), in order to tune the weights and biases such that our network accurately predicts our training data.
Let's apply the Universal Approximation Theorem to see what adding more neurons does. Let's say we have a single hidden node in our network and we give our network a single example pair $(x_j, y_j)$, this would give a prediction $\hat{y_j}$ which would have an error of $\vert y_j - \hat{y}_j \vert$. We would then use some optimization algorithm (SGD, RMSprop, Adam etc...) to minimise this error. However, a single hidden node can only 'learn' so much and will eventually hit a local minimum where it'll learn no more.
This would be written out like,
$$\hat{y}_j = w^{(2)}_1\sigma(w^{(1)}_1 x_j + b^{(1)}_1)$$
and let's say (for the sake of argument) the lowest error we can get is 10. This error of 10 can be minimising by adding a new neuron. Let's say the target $y_j$ is 20 and our model predicts $\hat{y}_j$ = 10 (giving the error of 10 from above). We can add a new neuron to try and reduce this error by getting the new neuron to output a contribution to the total sum which minimising our error. And, let's say the best the 2nd neuron can do is an output of 5 - which would bring out total MAE to 5.
$$\hat{y}_j = \underbrace{w^{(2)}_1\sigma(w^{(1)}_1 x_j + b^{(1)}_1)}_{\text{first neuron outputs 10}} + \underbrace{w^{(2)}_2\sigma(w^{(1)}_2 x_j + b^{(1)}_2)}_{\text{second neuron outputs 5}} $$
In this two neuron case, the best the model can do is 15 and in principle, we can keep adding neurons to the layer to reduce this error. Leading to the Univeral Approximation Theorem stating that a neural network can approximate any continuous function if given enough nodes to do so.
In short, the neurons for a given layer allow the network to transform the input in a certain manner and having fewer neurons restricts the ability of the layer to transform the data in the 'correct' way. Which in the case of deeper networks this restricts the ability of higher layers in transforming the data because the initial transformation they get are 'further' away (in terms of a loss metric) from the exact transformation!
|
What is the purpose of having multiple neurons in each layer?
|
Expanding upon what @gunes said, if you take a shallow network and explicitly trace out what the network's forward pass is. You can see the adding of additional nodes (within a layer) allows the netwo
|
What is the purpose of having multiple neurons in each layer?
Expanding upon what @gunes said, if you take a shallow network and explicitly trace out what the network's forward pass is. You can see the adding of additional nodes (within a layer) allows the network to minimise its prediction error.
Let's assume we have some Feed-Forward Neural Network (FFNN) that takes in a single input and a single output and has a single hidden layer of N hidden nodes, and a non-linear activation function denoted, $\sigma$, and the entire forward pass of the network can be described as $\hat{y} = f(x)$, where $\hat{y}$ is the prediction of the true output $y$.
For N = 1, the network can be written as,
$$ \hat{y} = w^{(2)}\sigma(w^{(1)}x_j + b^{(1)})$$
for a given number of hidden nodes, N, it's written as a sum of single neurons, i.e.,
$$ \hat{y} = \sum_i w^{(2)}_{i}\sigma(w^{(1)}_ix_j + b^{(1)}_i) $$
If we look at this from a linear regression standpoint we would minimise a loss function, for example the Mean Absolute Error (MAE), in order to tune the weights and biases such that our network accurately predicts our training data.
Let's apply the Universal Approximation Theorem to see what adding more neurons does. Let's say we have a single hidden node in our network and we give our network a single example pair $(x_j, y_j)$, this would give a prediction $\hat{y_j}$ which would have an error of $\vert y_j - \hat{y}_j \vert$. We would then use some optimization algorithm (SGD, RMSprop, Adam etc...) to minimise this error. However, a single hidden node can only 'learn' so much and will eventually hit a local minimum where it'll learn no more.
This would be written out like,
$$\hat{y}_j = w^{(2)}_1\sigma(w^{(1)}_1 x_j + b^{(1)}_1)$$
and let's say (for the sake of argument) the lowest error we can get is 10. This error of 10 can be minimising by adding a new neuron. Let's say the target $y_j$ is 20 and our model predicts $\hat{y}_j$ = 10 (giving the error of 10 from above). We can add a new neuron to try and reduce this error by getting the new neuron to output a contribution to the total sum which minimising our error. And, let's say the best the 2nd neuron can do is an output of 5 - which would bring out total MAE to 5.
$$\hat{y}_j = \underbrace{w^{(2)}_1\sigma(w^{(1)}_1 x_j + b^{(1)}_1)}_{\text{first neuron outputs 10}} + \underbrace{w^{(2)}_2\sigma(w^{(1)}_2 x_j + b^{(1)}_2)}_{\text{second neuron outputs 5}} $$
In this two neuron case, the best the model can do is 15 and in principle, we can keep adding neurons to the layer to reduce this error. Leading to the Univeral Approximation Theorem stating that a neural network can approximate any continuous function if given enough nodes to do so.
In short, the neurons for a given layer allow the network to transform the input in a certain manner and having fewer neurons restricts the ability of the layer to transform the data in the 'correct' way. Which in the case of deeper networks this restricts the ability of higher layers in transforming the data because the initial transformation they get are 'further' away (in terms of a loss metric) from the exact transformation!
|
What is the purpose of having multiple neurons in each layer?
Expanding upon what @gunes said, if you take a shallow network and explicitly trace out what the network's forward pass is. You can see the adding of additional nodes (within a layer) allows the netwo
|
45,986
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
|
What can be simulated is the power of the Shapiro-Wilk test for detecting specific non-normal distributions. This depends strongly on the exact distribution you want to detect. For this reason a plethora of results can be considered, and you can find examples for the test working well and not so well. (This means that data from a certain non-normal distribution with a certain sample size is simulated, and by this you can determine, at least approximately, the probability for the S-W test to reject normality; the higher the better.)
Here is some work that simulates the power of the Shapiro-Wilk test:
Hadi Alizadeh, N. R. Arghami (2011) Monte Carlo comparison of seven normality tests. Journal of Statistical Computation and Simulation 81(8):965-972
https://www.researchgate.net/publication/232942214_Monte_Carlo_comparison_of_seven_normality_tests
Hadi Alizadeh Noughabi (2018) A Comprehensive Study on Power of Tests for Normality. Journal of Statistical Theory and Applications 17. 647 - 660
https://www.atlantis-press.com/journals/jsta/125905578/view
Razali, N. M. & Wah, Y. B. (2011), ‘Power comparisons of Shapiro-Wilk, Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests’, Journal of Statistical Modeling and Analytics 2, 21–33.
https://www.nrc.gov/docs/ML1714/ML17143A100.pdf
Danush K. Wijekularathna, Ananda B. W. Manage & Stephen M. Scariano (2019) Power analysis of several normality tests: A Monte Carlo simulation study, Communications in Statistics - Simulation and Computation, DOI: 10.1080/03610918.2019.1658780
Some older work is cited in Thode, H. C. (2002) Testing for Normality. Marcel Dekker Inc.
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
|
What can be simulated is the power of the Shapiro-Wilk test for detecting specific non-normal distributions. This depends strongly on the exact distribution you want to detect. For this reason a pleth
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
What can be simulated is the power of the Shapiro-Wilk test for detecting specific non-normal distributions. This depends strongly on the exact distribution you want to detect. For this reason a plethora of results can be considered, and you can find examples for the test working well and not so well. (This means that data from a certain non-normal distribution with a certain sample size is simulated, and by this you can determine, at least approximately, the probability for the S-W test to reject normality; the higher the better.)
Here is some work that simulates the power of the Shapiro-Wilk test:
Hadi Alizadeh, N. R. Arghami (2011) Monte Carlo comparison of seven normality tests. Journal of Statistical Computation and Simulation 81(8):965-972
https://www.researchgate.net/publication/232942214_Monte_Carlo_comparison_of_seven_normality_tests
Hadi Alizadeh Noughabi (2018) A Comprehensive Study on Power of Tests for Normality. Journal of Statistical Theory and Applications 17. 647 - 660
https://www.atlantis-press.com/journals/jsta/125905578/view
Razali, N. M. & Wah, Y. B. (2011), ‘Power comparisons of Shapiro-Wilk, Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests’, Journal of Statistical Modeling and Analytics 2, 21–33.
https://www.nrc.gov/docs/ML1714/ML17143A100.pdf
Danush K. Wijekularathna, Ananda B. W. Manage & Stephen M. Scariano (2019) Power analysis of several normality tests: A Monte Carlo simulation study, Communications in Statistics - Simulation and Computation, DOI: 10.1080/03610918.2019.1658780
Some older work is cited in Thode, H. C. (2002) Testing for Normality. Marcel Dekker Inc.
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
What can be simulated is the power of the Shapiro-Wilk test for detecting specific non-normal distributions. This depends strongly on the exact distribution you want to detect. For this reason a pleth
|
45,987
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
|
You are asking for the probability of a "reasonable conclusion". You can get this if and only if you give a precise enough definition of a reasonable conclusion. I too would love a procedure that reliably tells me when deviation from normality is important enough to matter, but there is a gradation from sample sizes of 1 and 2 -- for which any sample whatsoever is totally consistent with a normal distribution -- to arbitrarily large sample sizes -- for which trivial deviations will return significance levels below conventional thresholds.
What is important enough to matter depends on your purposes and on your view of the data, as statistics is a craft drawing on personal expertise and experience just as much as it is codified technique. For example:
Marginal normal distributions are only rarely required or even ideal.
In practice if I found very close approximations to conditional normal distributions -- e.g. in residuals from models known to be sound scientifically for high quality data -- I would suspect fraud more frequently than I would believe the result implicitly.
It's quite hard to teach beginners how to sit loose to significance testing, not least in disciplines that persist in over-rating it, and because you have to look at many datasets before you start getting your own independent sense of what helps. But the existence proof that beginners can grow into experts is the fact that there are experts.
EDIT A general purpose "test" is to post a normal quantile plot of the data together with several normal quantile plots for random samples of the same size from a normal. Convenient numbers of simulated samples might be 24, 35, 48, ... permitting, when combined with the original, a 5 x 5, 6 x 6, 7 x 7, ... display. This is the line-up test, similar to the idea that a suspect should be shown to witnesses together with various arbitrary people. If the suspect isn't identifiable from the others, the case for being different isn't supported. Although quite often re-invented fairly recently, the idea is in Walter Shewhart's main book (and may yet be older). One attraction of the test is the Anna Karenina principle that each non-normal distribution may be non-normal in its own different way.
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
|
You are asking for the probability of a "reasonable conclusion". You can get this if and only if you give a precise enough definition of a reasonable conclusion. I too would love a procedure that reli
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
You are asking for the probability of a "reasonable conclusion". You can get this if and only if you give a precise enough definition of a reasonable conclusion. I too would love a procedure that reliably tells me when deviation from normality is important enough to matter, but there is a gradation from sample sizes of 1 and 2 -- for which any sample whatsoever is totally consistent with a normal distribution -- to arbitrarily large sample sizes -- for which trivial deviations will return significance levels below conventional thresholds.
What is important enough to matter depends on your purposes and on your view of the data, as statistics is a craft drawing on personal expertise and experience just as much as it is codified technique. For example:
Marginal normal distributions are only rarely required or even ideal.
In practice if I found very close approximations to conditional normal distributions -- e.g. in residuals from models known to be sound scientifically for high quality data -- I would suspect fraud more frequently than I would believe the result implicitly.
It's quite hard to teach beginners how to sit loose to significance testing, not least in disciplines that persist in over-rating it, and because you have to look at many datasets before you start getting your own independent sense of what helps. But the existence proof that beginners can grow into experts is the fact that there are experts.
EDIT A general purpose "test" is to post a normal quantile plot of the data together with several normal quantile plots for random samples of the same size from a normal. Convenient numbers of simulated samples might be 24, 35, 48, ... permitting, when combined with the original, a 5 x 5, 6 x 6, 7 x 7, ... display. This is the line-up test, similar to the idea that a suspect should be shown to witnesses together with various arbitrary people. If the suspect isn't identifiable from the others, the case for being different isn't supported. Although quite often re-invented fairly recently, the idea is in Walter Shewhart's main book (and may yet be older). One attraction of the test is the Anna Karenina principle that each non-normal distribution may be non-normal in its own different way.
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
You are asking for the probability of a "reasonable conclusion". You can get this if and only if you give a precise enough definition of a reasonable conclusion. I too would love a procedure that reli
|
45,988
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
|
As you allude to when you bring up the use of graphical examination for this task of assessing normality, the answer is $0\%$ $\forall$ $n$.
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
|
As you allude to when you bring up the use of graphical examination for this task of assessing normality, the answer is $0\%$ $\forall$ $n$.
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
As you allude to when you bring up the use of graphical examination for this task of assessing normality, the answer is $0\%$ $\forall$ $n$.
|
Quantitatively, how powerful is Shapiro-Wilk or other distribution-fit tests for small sample sizes?
As you allude to when you bring up the use of graphical examination for this task of assessing normality, the answer is $0\%$ $\forall$ $n$.
|
45,989
|
Calculating the area under two overlapping distribution
|
The distributions $X\sim\mathsf{Norm}(100, 15)$ and $Y\sim\mathsf{Norm}(110,15)$ overlap, as in your figure.
The total overlap probability is
$$P(Y \le 125)+P(X> 125)\\ = P(Y \le 125) + 1 - P(X \le 125)\\
\approx 0.048 + 0.048 = 0.096.$$
R code for figure:
hdr="Densities of NORM(100,15) and NORM(150,15)"
curve(dnorm(x,100,15), 50, 200, ylab="PDF", main=hdr)
curve(dnorm(x,150,15), add=T)
abline(h=0, col = "green2")
abline(v=125, col = "red", lty="dotted")
R code for probability computation, where pnorm is a normal CDF:
pnorm(125, 150, 15)
[1] 0.04779035
1 - pnorm(125, 100, 15)
[1] 0.04779035
pnorm(125, 150, 15) + 1 - pnorm(125, 100, 15)
[1] 0.0955807
Note: The two probabilities might be Type I and Type II
error for a test of a hypothesis.
|
Calculating the area under two overlapping distribution
|
The distributions $X\sim\mathsf{Norm}(100, 15)$ and $Y\sim\mathsf{Norm}(110,15)$ overlap, as in your figure.
The total overlap probability is
$$P(Y \le 125)+P(X> 125)\\ = P(Y \le 125) + 1 - P(X \le 12
|
Calculating the area under two overlapping distribution
The distributions $X\sim\mathsf{Norm}(100, 15)$ and $Y\sim\mathsf{Norm}(110,15)$ overlap, as in your figure.
The total overlap probability is
$$P(Y \le 125)+P(X> 125)\\ = P(Y \le 125) + 1 - P(X \le 125)\\
\approx 0.048 + 0.048 = 0.096.$$
R code for figure:
hdr="Densities of NORM(100,15) and NORM(150,15)"
curve(dnorm(x,100,15), 50, 200, ylab="PDF", main=hdr)
curve(dnorm(x,150,15), add=T)
abline(h=0, col = "green2")
abline(v=125, col = "red", lty="dotted")
R code for probability computation, where pnorm is a normal CDF:
pnorm(125, 150, 15)
[1] 0.04779035
1 - pnorm(125, 100, 15)
[1] 0.04779035
pnorm(125, 150, 15) + 1 - pnorm(125, 100, 15)
[1] 0.0955807
Note: The two probabilities might be Type I and Type II
error for a test of a hypothesis.
|
Calculating the area under two overlapping distribution
The distributions $X\sim\mathsf{Norm}(100, 15)$ and $Y\sim\mathsf{Norm}(110,15)$ overlap, as in your figure.
The total overlap probability is
$$P(Y \le 125)+P(X> 125)\\ = P(Y \le 125) + 1 - P(X \le 12
|
45,990
|
Calculating the area under two overlapping distribution
|
Perhaps this is a more general solution than @BruceET's which doesn't assume normality or a preset reference point P. The OP says s/he has the PDF of the two distributions, so for example these may be:
pdf1 <- function(x, mean= 100, sd= 15) {
pdf <- (1 / (sd * sqrt(2 * pi))) * exp(-0.5 * ((x - mean)/sd)^2)
return(pdf)
}
pdf2 <- function(x, mean= 150, sd= 15) {
pdf <- (1 / (sd * sqrt(2 * pi))) * exp(-0.5 * ((x - mean)/sd)^2)
return(pdf)
}
(These are Gaussian but they may be any PDF)
At a grid of data points on the x-axis calculate each PDF, take the smallest of the two densities, weight it for the step size of the grid and sum across to get the intersection (this is a very crude integration - I'd like to see a better solution...):
step <- 0.1
at <- seq(20, 250, by= step)
x1 <- pdf1(at, 100, 15)
x2 <- pdf2(at, 150, 15)
area <- 0
for(i in 1:length(at)) {
area <- area + ifelse(x1[i] > x2[i], x2[i], x1[i]) * step
}
print(area)
0.09558193
|
Calculating the area under two overlapping distribution
|
Perhaps this is a more general solution than @BruceET's which doesn't assume normality or a preset reference point P. The OP says s/he has the PDF of the two distributions, so for example these may be
|
Calculating the area under two overlapping distribution
Perhaps this is a more general solution than @BruceET's which doesn't assume normality or a preset reference point P. The OP says s/he has the PDF of the two distributions, so for example these may be:
pdf1 <- function(x, mean= 100, sd= 15) {
pdf <- (1 / (sd * sqrt(2 * pi))) * exp(-0.5 * ((x - mean)/sd)^2)
return(pdf)
}
pdf2 <- function(x, mean= 150, sd= 15) {
pdf <- (1 / (sd * sqrt(2 * pi))) * exp(-0.5 * ((x - mean)/sd)^2)
return(pdf)
}
(These are Gaussian but they may be any PDF)
At a grid of data points on the x-axis calculate each PDF, take the smallest of the two densities, weight it for the step size of the grid and sum across to get the intersection (this is a very crude integration - I'd like to see a better solution...):
step <- 0.1
at <- seq(20, 250, by= step)
x1 <- pdf1(at, 100, 15)
x2 <- pdf2(at, 150, 15)
area <- 0
for(i in 1:length(at)) {
area <- area + ifelse(x1[i] > x2[i], x2[i], x1[i]) * step
}
print(area)
0.09558193
|
Calculating the area under two overlapping distribution
Perhaps this is a more general solution than @BruceET's which doesn't assume normality or a preset reference point P. The OP says s/he has the PDF of the two distributions, so for example these may be
|
45,991
|
Skewness of lognormal distribution
|
When a variable $X$ has a Normal distribution with mean $\mu$ and standard deviation $\sigma \gt 0,$ we say that $Z=e^X$ has a Lognormal$(\mu,\sigma)$ distribution.
The laws of logarithms show that $\mu$ (an additive location parameter for the Normal family of distributions) determines the scale of $Z.$ Because the skewness of a variable does not depend on its scale, we may take $\mu$ to be any convenient value.
Choosing $\mu=0,$ use the Normal density (which is proportional to the exponential of $-x^2/(2\sigma^2)$) to compute the (raw) $k^\text{th}$ moment of $Z$ via the substitution $y = x - k\sigma^2:$
$$\begin{aligned}
\mu_k(\sigma) &=E\left[Z^k\right] = E\left[\exp(X)^k\right] = E\left[\exp(kX)\right]\\\
&= \frac{1}{\sigma\sqrt{2\pi}}\int_{\mathbb{R}} \exp\left(\frac{1}{2\sigma^2}x^2 + kx\right)\,\mathrm{d}x\\
&= \frac{1}{\sigma\sqrt{2\pi}}\exp\left(k^2\sigma^2/2\right)\int_{\mathbb{R}} \exp\left(\frac{1}{2\sigma^2}x^2 + kx - k^2\sigma^2/2\right)\,\mathrm{d}x\\
&= \frac{1}{\sigma\sqrt{2\pi}}\exp\left(k^2\sigma^2/2\right)\int_{\mathbb{R}} \exp\left(\frac{1}{2\sigma^2}\left[x - k\sigma^2\right]^2\right)\,\mathrm{d}x\\
&= \exp\left(k^2\sigma^2/2\right)\left[\frac{1}{\sigma\sqrt{2\pi}}\int_{\mathbb{R}} \exp\left(\frac{1}{2\sigma^2}y^2\right)\,\mathrm{d}y\right]\\
&= \exp\left(k^2\sigma^2/2\right).
\end{aligned}\tag{*}$$
For $k=1$ this shows the mean is $\exp(\sigma^2/2)$ and from this we may compute the central moments from the Binomial Theorem as
$$\begin{aligned}
\mu^\prime_k(\sigma) &= E\left[(Z - E[Z])^k\right] = E\left[\sum_{i=0}^k \binom{k}{i} Z^i E(Z)^{k-i}\right] \\
&= \sum_{i=0}^k \binom{k}{i}(-1)^{i-k} \mu_i(\sigma) \mu_1(\sigma)^{k-i}
\end{aligned}.\tag{**}$$
Applying this to $k=2,3$ gives
$$\mu^\prime_2(\sigma) = \mu_0(\sigma)\mu_1(\sigma))^2 - 2\mu_1(\sigma)\mu_1(\sigma) + \mu_2(\sigma) = e^{\sigma^2}\left(e^{\sigma^2}-1\right)$$
and
$$\begin{aligned}\mu^\prime_3(\sigma) &= -\mu_0(\sigma)\mu_1(\sigma)^3 + 3\mu_1(\sigma)\mu_1(\sigma)^2 - 3\mu_2(\sigma)\mu_1(\sigma) + \mu_3(\sigma) \\
&= e^{3\sigma^2/2}\left(2 - 3 e^{\sigma^2} + e^{3\sigma^2}\right) \\
&= e^{3\sigma^2/2}\left(e^{\sigma^2}+2\right)\left(e^{\sigma^2}-1\right)^2.
\end{aligned}$$
By definition, the skewness is
$$\operatorname{Skew}(Z) = \frac{\mu^\prime_3(\sigma)}{\mu^\prime_2(\sigma)^{3/2}} = \frac{e^{3\sigma^2/2}\left(e^{\sigma^2}+2\right)\left(e^{\sigma^2}-1\right)^2}{\left[e^{\sigma^2}\left(e^{\sigma^2}-1\right)\right]^{3/2}} = \left(e^{\sigma^2}+2\right)\sqrt{e^{\sigma^2}-1}.$$
Comments and Generalizations
Higher standardized central moments (e.g. the kurtosis) are readily computed in the same way: $(*)$ and $(**)$ reduce the problem to polynomial algebra (the variable is $\exp(\sigma^2/2)$).
Because $\mu$ is a scale parameter for the Lognormal family (corresponding to a scale factor of $e^\mu$), it can be introduced into the formulas $(*)$ directly, where its $k^\text{th}$ power $\left(e^\mu\right)^k = e^{k\mu}$ will multiply the result, giving the general formulas
$$\mu_k(\mu,\sigma) = E\left[Z^k\right] = \exp\left(k\mu + k^2\sigma^2\right)$$
and then, of course,
$$\mu^\prime_k(\mu,\sigma) = E\left[\right(Z - E[Z]\left)^k\right] = e^{k\mu} \mu^\prime_k(\sigma).$$
|
Skewness of lognormal distribution
|
When a variable $X$ has a Normal distribution with mean $\mu$ and standard deviation $\sigma \gt 0,$ we say that $Z=e^X$ has a Lognormal$(\mu,\sigma)$ distribution.
The laws of logarithms show that $\
|
Skewness of lognormal distribution
When a variable $X$ has a Normal distribution with mean $\mu$ and standard deviation $\sigma \gt 0,$ we say that $Z=e^X$ has a Lognormal$(\mu,\sigma)$ distribution.
The laws of logarithms show that $\mu$ (an additive location parameter for the Normal family of distributions) determines the scale of $Z.$ Because the skewness of a variable does not depend on its scale, we may take $\mu$ to be any convenient value.
Choosing $\mu=0,$ use the Normal density (which is proportional to the exponential of $-x^2/(2\sigma^2)$) to compute the (raw) $k^\text{th}$ moment of $Z$ via the substitution $y = x - k\sigma^2:$
$$\begin{aligned}
\mu_k(\sigma) &=E\left[Z^k\right] = E\left[\exp(X)^k\right] = E\left[\exp(kX)\right]\\\
&= \frac{1}{\sigma\sqrt{2\pi}}\int_{\mathbb{R}} \exp\left(\frac{1}{2\sigma^2}x^2 + kx\right)\,\mathrm{d}x\\
&= \frac{1}{\sigma\sqrt{2\pi}}\exp\left(k^2\sigma^2/2\right)\int_{\mathbb{R}} \exp\left(\frac{1}{2\sigma^2}x^2 + kx - k^2\sigma^2/2\right)\,\mathrm{d}x\\
&= \frac{1}{\sigma\sqrt{2\pi}}\exp\left(k^2\sigma^2/2\right)\int_{\mathbb{R}} \exp\left(\frac{1}{2\sigma^2}\left[x - k\sigma^2\right]^2\right)\,\mathrm{d}x\\
&= \exp\left(k^2\sigma^2/2\right)\left[\frac{1}{\sigma\sqrt{2\pi}}\int_{\mathbb{R}} \exp\left(\frac{1}{2\sigma^2}y^2\right)\,\mathrm{d}y\right]\\
&= \exp\left(k^2\sigma^2/2\right).
\end{aligned}\tag{*}$$
For $k=1$ this shows the mean is $\exp(\sigma^2/2)$ and from this we may compute the central moments from the Binomial Theorem as
$$\begin{aligned}
\mu^\prime_k(\sigma) &= E\left[(Z - E[Z])^k\right] = E\left[\sum_{i=0}^k \binom{k}{i} Z^i E(Z)^{k-i}\right] \\
&= \sum_{i=0}^k \binom{k}{i}(-1)^{i-k} \mu_i(\sigma) \mu_1(\sigma)^{k-i}
\end{aligned}.\tag{**}$$
Applying this to $k=2,3$ gives
$$\mu^\prime_2(\sigma) = \mu_0(\sigma)\mu_1(\sigma))^2 - 2\mu_1(\sigma)\mu_1(\sigma) + \mu_2(\sigma) = e^{\sigma^2}\left(e^{\sigma^2}-1\right)$$
and
$$\begin{aligned}\mu^\prime_3(\sigma) &= -\mu_0(\sigma)\mu_1(\sigma)^3 + 3\mu_1(\sigma)\mu_1(\sigma)^2 - 3\mu_2(\sigma)\mu_1(\sigma) + \mu_3(\sigma) \\
&= e^{3\sigma^2/2}\left(2 - 3 e^{\sigma^2} + e^{3\sigma^2}\right) \\
&= e^{3\sigma^2/2}\left(e^{\sigma^2}+2\right)\left(e^{\sigma^2}-1\right)^2.
\end{aligned}$$
By definition, the skewness is
$$\operatorname{Skew}(Z) = \frac{\mu^\prime_3(\sigma)}{\mu^\prime_2(\sigma)^{3/2}} = \frac{e^{3\sigma^2/2}\left(e^{\sigma^2}+2\right)\left(e^{\sigma^2}-1\right)^2}{\left[e^{\sigma^2}\left(e^{\sigma^2}-1\right)\right]^{3/2}} = \left(e^{\sigma^2}+2\right)\sqrt{e^{\sigma^2}-1}.$$
Comments and Generalizations
Higher standardized central moments (e.g. the kurtosis) are readily computed in the same way: $(*)$ and $(**)$ reduce the problem to polynomial algebra (the variable is $\exp(\sigma^2/2)$).
Because $\mu$ is a scale parameter for the Lognormal family (corresponding to a scale factor of $e^\mu$), it can be introduced into the formulas $(*)$ directly, where its $k^\text{th}$ power $\left(e^\mu\right)^k = e^{k\mu}$ will multiply the result, giving the general formulas
$$\mu_k(\mu,\sigma) = E\left[Z^k\right] = \exp\left(k\mu + k^2\sigma^2\right)$$
and then, of course,
$$\mu^\prime_k(\mu,\sigma) = E\left[\right(Z - E[Z]\left)^k\right] = e^{k\mu} \mu^\prime_k(\sigma).$$
|
Skewness of lognormal distribution
When a variable $X$ has a Normal distribution with mean $\mu$ and standard deviation $\sigma \gt 0,$ we say that $Z=e^X$ has a Lognormal$(\mu,\sigma)$ distribution.
The laws of logarithms show that $\
|
45,992
|
Justifying the Need for Mixed Effects Models (aka. LME, MLM, etc.)
|
First of all, I agree with @EdM, you should first think if multilevel models in substantive terms instead of only looking for a statistical significance in model comparisons. But you may ask: how to do so? Well, asking yourself a few questions about your research hypothesis might help. Is it important to your research:
Assessing the effect of more than one second-level predictor?
Assessing the interaction between first and second level predictors (or third and second, etc.)?
The decomposition of between-effects and within-effects of first level predictors?
If you answered yes to any of these questions, then a multilevel model may be your best, if not only choice. I guess this reasoning comes from Gelman & Hill classic book on multilevel models. You can probably find it in other links as well. This classic paper Enders and Tofighi (2007) may help you with insights on these matters, and also is useful to learn how to avoid criticism for correlation problems within multilevel models (MLM). You also find similar rationale in this and this papers. I explain it a bit better below.
Second, you might be also interested in the intra-class correlation (ICC). That is, you want to know how much of your dependent variable variance is due to differences between or within second and third level groups. A high ICC is sometimes presented as an evidence that you need a MLM. It is in fact an evidence that you have a highly clustered data, which violates standard OLS regression assumptions (this is almost always the case with repeated measures/within-subject research designs). But you may correct it with fixed effects as well, as you may see in the aforementioned papers.
The problem with fixed effects is that only one variable will suck up all the variance from the higher levels groups. That is why if you are interested in more than one second level predictor, a MLM may be your best choice. In addition, the ICC may be an interesting measure itself. At the same time it provides some support for a multilevel model, and it is also an easy to understand and useful substantive interpretation of the multilevel structure of your data.
Third, although research hypothesis and substantive reasoning should come first in model choice, model fit statistics also matter. If your new model has a worse fit to your data than your previous model, you probably need to go back, or change something else in the new one.
Fourth, your question:
"method 1 justified MLM but method 2 doesn't. How can we interpret this discrepancy? and what method is more robust in order to study the feasibility of MLM?"
Well, there is not any discrepancy between the results. The problem is that in "method 1" you are comparing a one-level model with a two-level model. In "method 2" you are comparing a two-level model with a three-level model. That is why you got different results. You are comparing different stuff. The two methods are pretty much the same: a chi-square test. But what you put inside them that was different.
As a matter of fact, you are comparing four different models with only two pairwise comparisons. In M1 you have only one level. In M2 you have a two-level model, and your second level is item. In MN1 you have a two level-model, but your second level is subject. In MN2 you have a three-level model and your second level is subject, and your third level is item. You cannot say which of these four models is the best, at least not if you look only to the p-value, because you did not compare them all.
However, if you forgot a bit about the p-value, and take a look to other statistics, specially the Akaike Information Criteria (AIC) and the Bayesian Information Criteria (BIC), which are currently the standard for assessing model fit of multilevel models, you may see that your best model is between MN1 and MN2.
If you take a close look in the second test: You will see that your p-value is not super high. You also see that the AIC and the log-likelihood ratio test shows that your three-level model has a slight better fit than the two-level model. The BIC and Chi-square show the opposite. How can your p-value be higher than 0.05? Well, your p-value is based solely on the Chi-square test, which is probably the less used test (of the four shown) to compare MLM. But it is really a close call. So, you have a statistical tie, and you can decide based on your substantive questions.
Fifth, you may also consider that multilevel models have some assumptions and mathematical requirements. @EdM may be right when he says that MLM work with partial pooling and that you don’t need to worry so much about few first level observations per group. I also learned this way. However, this assumption is questioned by this paper. I never follow this last paper sample size requirements, and in fact, I don't know any multilevel model in social sciences that do. But it is more or less consolidated in the field that you need at least 50 higher level units/groups, as you can see here. If you have fewer than that, fixed effects might get you better estimates.
|
Justifying the Need for Mixed Effects Models (aka. LME, MLM, etc.)
|
First of all, I agree with @EdM, you should first think if multilevel models in substantive terms instead of only looking for a statistical significance in model comparisons. But you may ask: how to d
|
Justifying the Need for Mixed Effects Models (aka. LME, MLM, etc.)
First of all, I agree with @EdM, you should first think if multilevel models in substantive terms instead of only looking for a statistical significance in model comparisons. But you may ask: how to do so? Well, asking yourself a few questions about your research hypothesis might help. Is it important to your research:
Assessing the effect of more than one second-level predictor?
Assessing the interaction between first and second level predictors (or third and second, etc.)?
The decomposition of between-effects and within-effects of first level predictors?
If you answered yes to any of these questions, then a multilevel model may be your best, if not only choice. I guess this reasoning comes from Gelman & Hill classic book on multilevel models. You can probably find it in other links as well. This classic paper Enders and Tofighi (2007) may help you with insights on these matters, and also is useful to learn how to avoid criticism for correlation problems within multilevel models (MLM). You also find similar rationale in this and this papers. I explain it a bit better below.
Second, you might be also interested in the intra-class correlation (ICC). That is, you want to know how much of your dependent variable variance is due to differences between or within second and third level groups. A high ICC is sometimes presented as an evidence that you need a MLM. It is in fact an evidence that you have a highly clustered data, which violates standard OLS regression assumptions (this is almost always the case with repeated measures/within-subject research designs). But you may correct it with fixed effects as well, as you may see in the aforementioned papers.
The problem with fixed effects is that only one variable will suck up all the variance from the higher levels groups. That is why if you are interested in more than one second level predictor, a MLM may be your best choice. In addition, the ICC may be an interesting measure itself. At the same time it provides some support for a multilevel model, and it is also an easy to understand and useful substantive interpretation of the multilevel structure of your data.
Third, although research hypothesis and substantive reasoning should come first in model choice, model fit statistics also matter. If your new model has a worse fit to your data than your previous model, you probably need to go back, or change something else in the new one.
Fourth, your question:
"method 1 justified MLM but method 2 doesn't. How can we interpret this discrepancy? and what method is more robust in order to study the feasibility of MLM?"
Well, there is not any discrepancy between the results. The problem is that in "method 1" you are comparing a one-level model with a two-level model. In "method 2" you are comparing a two-level model with a three-level model. That is why you got different results. You are comparing different stuff. The two methods are pretty much the same: a chi-square test. But what you put inside them that was different.
As a matter of fact, you are comparing four different models with only two pairwise comparisons. In M1 you have only one level. In M2 you have a two-level model, and your second level is item. In MN1 you have a two level-model, but your second level is subject. In MN2 you have a three-level model and your second level is subject, and your third level is item. You cannot say which of these four models is the best, at least not if you look only to the p-value, because you did not compare them all.
However, if you forgot a bit about the p-value, and take a look to other statistics, specially the Akaike Information Criteria (AIC) and the Bayesian Information Criteria (BIC), which are currently the standard for assessing model fit of multilevel models, you may see that your best model is between MN1 and MN2.
If you take a close look in the second test: You will see that your p-value is not super high. You also see that the AIC and the log-likelihood ratio test shows that your three-level model has a slight better fit than the two-level model. The BIC and Chi-square show the opposite. How can your p-value be higher than 0.05? Well, your p-value is based solely on the Chi-square test, which is probably the less used test (of the four shown) to compare MLM. But it is really a close call. So, you have a statistical tie, and you can decide based on your substantive questions.
Fifth, you may also consider that multilevel models have some assumptions and mathematical requirements. @EdM may be right when he says that MLM work with partial pooling and that you don’t need to worry so much about few first level observations per group. I also learned this way. However, this assumption is questioned by this paper. I never follow this last paper sample size requirements, and in fact, I don't know any multilevel model in social sciences that do. But it is more or less consolidated in the field that you need at least 50 higher level units/groups, as you can see here. If you have fewer than that, fixed effects might get you better estimates.
|
Justifying the Need for Mixed Effects Models (aka. LME, MLM, etc.)
First of all, I agree with @EdM, you should first think if multilevel models in substantive terms instead of only looking for a statistical significance in model comparisons. But you may ask: how to d
|
45,993
|
Justifying the Need for Mixed Effects Models (aka. LME, MLM, etc.)
|
What you are testing for is the statistical "significance" of the random effect terms. As is so often the case in statistics, that can be a good deal different from their "importance." Note this part of the answer to one of the questions that you have read:
Random effects are typically included to account for the correlation of the measurements within a group/cluster.
If your experimental design involves correlations among observations, potentially invalidating the assumption of independent observations, those correlations need to be taken into account. If there are more than a few individuals/groups/clusters, modeling them with random effects provides a well documented way to do do. You might find that the random effects don't add anything "significant" to your model when you perform your tests, but your audience will expect that it is "important" to take such correlations into account.
In multi-level modeling you might even choose to incorporate predictors like gender, typically modeled as fixed effects, as random effects. Discussion on this page and this page cover circumstances in which this can make sense. If you are using frequentist tools like lmer() for multi-level modeling, this can provide an advantage. The random effects are modeled by partial pooling among all groups rather than estimating for each group separately. As this answer notes:
Partial pooling means that, if you have few data points in a group, the group's effect estimate will be based partially on the more abundant data from other groups. This can be a nice compromise between estimating an effect by completely pooling all groups, which masks group-level variation, and estimating an effect for all groups completely separately, which could give poor estimates for low-sample groups.
If you want the advantages of partial pooling, it would be "important" to model with random effects even if they don't turn out to be "significant."
So worry less about statistically justifying a choice of random-effect modeling; think more about whether such modeling will help strengthen your analysis.
|
Justifying the Need for Mixed Effects Models (aka. LME, MLM, etc.)
|
What you are testing for is the statistical "significance" of the random effect terms. As is so often the case in statistics, that can be a good deal different from their "importance." Note this part
|
Justifying the Need for Mixed Effects Models (aka. LME, MLM, etc.)
What you are testing for is the statistical "significance" of the random effect terms. As is so often the case in statistics, that can be a good deal different from their "importance." Note this part of the answer to one of the questions that you have read:
Random effects are typically included to account for the correlation of the measurements within a group/cluster.
If your experimental design involves correlations among observations, potentially invalidating the assumption of independent observations, those correlations need to be taken into account. If there are more than a few individuals/groups/clusters, modeling them with random effects provides a well documented way to do do. You might find that the random effects don't add anything "significant" to your model when you perform your tests, but your audience will expect that it is "important" to take such correlations into account.
In multi-level modeling you might even choose to incorporate predictors like gender, typically modeled as fixed effects, as random effects. Discussion on this page and this page cover circumstances in which this can make sense. If you are using frequentist tools like lmer() for multi-level modeling, this can provide an advantage. The random effects are modeled by partial pooling among all groups rather than estimating for each group separately. As this answer notes:
Partial pooling means that, if you have few data points in a group, the group's effect estimate will be based partially on the more abundant data from other groups. This can be a nice compromise between estimating an effect by completely pooling all groups, which masks group-level variation, and estimating an effect for all groups completely separately, which could give poor estimates for low-sample groups.
If you want the advantages of partial pooling, it would be "important" to model with random effects even if they don't turn out to be "significant."
So worry less about statistically justifying a choice of random-effect modeling; think more about whether such modeling will help strengthen your analysis.
|
Justifying the Need for Mixed Effects Models (aka. LME, MLM, etc.)
What you are testing for is the statistical "significance" of the random effect terms. As is so often the case in statistics, that can be a good deal different from their "importance." Note this part
|
45,994
|
What is the intuitive difference between Wasserstein-1 distance and Wasserstein-2 distance?
|
The answer boils down to the difference between the distance and its squared value. Assume we use the euclidean distance, and imagine we want to transform a histogram $P_S$ whose bins are $x\in \mathbb{R}^m$ to another histogram $P_T$ with bins $y \in \mathbb{R}^n$. The $W_1$ and $W_2$ distances between the two histograms are defined as follows:
$$W_1 (P_S, P_T) = \underset{\gamma \in \Pi}{\text{min }} \sum_{x,y} |x-y|\gamma(x,y)$$.
$$W_2 (P_S, P_T) = (\underset{\gamma \in \Pi}{\text{min }} \sum_{x,y} (x-y)^2\gamma(x,y))^{1/2}$$
where $\gamma$ denotes the transportation plan and $\Pi$ denotes all plans, whose marginals are $P_T$ and $P_S$. One example, in which the distances will be very different is dealing with outliers. Imagine that, 95% of the density of the source distribution is in the range [0,50] and the rest is in the range $[1000,1100] \sim $ outliers. The $L^2$ distance between the outlier and histogram $P_T$ will be way higher than the $L^1$ distance. Hence, in the $W_2$ case, the best transportation plan is very much dependent on the outlier, i.e., moving the outlier's mass effectively is very important even though it forms only 5% of the total data. While the $L^1$ distance penalises way less such outliers and in a sense it is more robust.
how to know which one to use?
This depends on the application and what you really want to measure with the Wasserstein distance. If you are working with measures that might contain outliers, then understanding how each distance deals with outliers is useful. In another context, imagine you are interested in the quantity $\frac{\partial W^{P}}{\partial (x_i-y_j)}$ (i.e., how much the distance between the two histograms change as a function of the difference between two bins) and note that it's different between $p=1$ and $p=2$.
|
What is the intuitive difference between Wasserstein-1 distance and Wasserstein-2 distance?
|
The answer boils down to the difference between the distance and its squared value. Assume we use the euclidean distance, and imagine we want to transform a histogram $P_S$ whose bins are $x\in \mathb
|
What is the intuitive difference between Wasserstein-1 distance and Wasserstein-2 distance?
The answer boils down to the difference between the distance and its squared value. Assume we use the euclidean distance, and imagine we want to transform a histogram $P_S$ whose bins are $x\in \mathbb{R}^m$ to another histogram $P_T$ with bins $y \in \mathbb{R}^n$. The $W_1$ and $W_2$ distances between the two histograms are defined as follows:
$$W_1 (P_S, P_T) = \underset{\gamma \in \Pi}{\text{min }} \sum_{x,y} |x-y|\gamma(x,y)$$.
$$W_2 (P_S, P_T) = (\underset{\gamma \in \Pi}{\text{min }} \sum_{x,y} (x-y)^2\gamma(x,y))^{1/2}$$
where $\gamma$ denotes the transportation plan and $\Pi$ denotes all plans, whose marginals are $P_T$ and $P_S$. One example, in which the distances will be very different is dealing with outliers. Imagine that, 95% of the density of the source distribution is in the range [0,50] and the rest is in the range $[1000,1100] \sim $ outliers. The $L^2$ distance between the outlier and histogram $P_T$ will be way higher than the $L^1$ distance. Hence, in the $W_2$ case, the best transportation plan is very much dependent on the outlier, i.e., moving the outlier's mass effectively is very important even though it forms only 5% of the total data. While the $L^1$ distance penalises way less such outliers and in a sense it is more robust.
how to know which one to use?
This depends on the application and what you really want to measure with the Wasserstein distance. If you are working with measures that might contain outliers, then understanding how each distance deals with outliers is useful. In another context, imagine you are interested in the quantity $\frac{\partial W^{P}}{\partial (x_i-y_j)}$ (i.e., how much the distance between the two histograms change as a function of the difference between two bins) and note that it's different between $p=1$ and $p=2$.
|
What is the intuitive difference between Wasserstein-1 distance and Wasserstein-2 distance?
The answer boils down to the difference between the distance and its squared value. Assume we use the euclidean distance, and imagine we want to transform a histogram $P_S$ whose bins are $x\in \mathb
|
45,995
|
Why GEE estimates are smaller than GLMM?
|
This actually depends on the link function -- eg, for a log link there is not a systematic difference, but for a logit link there is.
The reason is that the models are systematically different and the marginal likelihoods are systematically different. As the simplest example consider a logistic GLMM with a random intercept, for longitudinal data indexed by person $i$ and time $t$
$$\mathrm{logit} E[Y_{it}|X_{it}=x, a_i] = a_i+x\beta$$
where $a_i\sim N(\alpha, \tau^2)$
The GEE marginal mean model is
$$\mathrm{logit} E[Y_{it}|X_{it}]=\tilde\alpha+x\tilde\beta$$
So how are $\beta$ and $\tilde\beta$ related? Well, the GLMM has
$$E[Y_{it}|X_{it}=x, a_i] = \mathrm{expit}\,(a_i+x\beta)$$
so
$$E[Y_{it}|X_{it}=x] = E_a[E[Y_{it}|X_{it}=x, a_i]]=E_a[\mathrm{expit}\,(a_i+x\beta)]$$
so
$$\mathrm{logit}\, E[Y_{it}|X_{it}=x] = \mathrm{logit}\,E_a[\mathrm{expit}\,(a_i+x\beta)]$$
The GEE has
$$\mathrm{logit} E[Y_{it}|X_{it}=\tilde\alpha+x\tilde\beta$$
These would be the same if expectations and $\mathrm{expit}$ commuted, but they don't. For a log link, the $\beta$ would be the same, because you can take an $e^\beta$ multiplier through the expectation, but the $\alpha$ would be systematically different.
Ok, so we know $\beta\neq\tilde\beta$ (for the true parameters, not just the estimates). Why is $|\beta|>|\tilde\beta|$?
I think this is easiest with a picture
expit<- function(x) exp(x)/(1+exp(x))
x<-seq(-6,6,length=50)
eta_c <- 0+1*x
mu_c <- expit(eta_m)
plot(x, mu_c,ylab="P(Y=1)",lwd=2,type="n",xlim=c(-6,6))
a<-rnorm(20,s=2)
total_m<-numeric(50)
for(ai in a){
eta_c <- ai+0+1*x
mu_c <- expit(eta_c)
lines(x, mu_c, col="grey")
total_m<-total_m+mu_c
}
mu_m<-total_m/20
lines(x, mu_m, col="blue")
What we see here is 20 realisations in grey of the conditional mean functions for 20 random $a_i$, and the blue curve that is the average of the grey curves, which is the GEE mean curve. They are basically the same shape, but the population-average curve is flatter; $\tilde\beta<\beta$.
The grey curves are all the same shape. The derivative of $p= \mathrm{expit}\eta$ wrt $\eta$ is
$$\frac{\partial p}{\partial\eta} = \mathrm{expit}\eta$ (1-\mathrm{expit}\eta)=p(1-p)$$
so
$$\frac{\partial p}{\partial x} = p(1-p)\frac{\partial\eta}{\partial x}=p(1-p)\beta$$
That is, the grey curves all have slope $\beta/4$ where they cross $p=0.5$ and the blue curve will have slope $\tilde\beta/4$.
One issue I've avoided here is that the GEE and GLMM logistic models are incompatible; they can't both be exactly true. But you could pretend that I used a probit link instead, where they are compatible, or that I'd looked up the relevant bridge distribution to replace the Normal distribution for $a_i$.
|
Why GEE estimates are smaller than GLMM?
|
This actually depends on the link function -- eg, for a log link there is not a systematic difference, but for a logit link there is.
The reason is that the models are systematically different and the
|
Why GEE estimates are smaller than GLMM?
This actually depends on the link function -- eg, for a log link there is not a systematic difference, but for a logit link there is.
The reason is that the models are systematically different and the marginal likelihoods are systematically different. As the simplest example consider a logistic GLMM with a random intercept, for longitudinal data indexed by person $i$ and time $t$
$$\mathrm{logit} E[Y_{it}|X_{it}=x, a_i] = a_i+x\beta$$
where $a_i\sim N(\alpha, \tau^2)$
The GEE marginal mean model is
$$\mathrm{logit} E[Y_{it}|X_{it}]=\tilde\alpha+x\tilde\beta$$
So how are $\beta$ and $\tilde\beta$ related? Well, the GLMM has
$$E[Y_{it}|X_{it}=x, a_i] = \mathrm{expit}\,(a_i+x\beta)$$
so
$$E[Y_{it}|X_{it}=x] = E_a[E[Y_{it}|X_{it}=x, a_i]]=E_a[\mathrm{expit}\,(a_i+x\beta)]$$
so
$$\mathrm{logit}\, E[Y_{it}|X_{it}=x] = \mathrm{logit}\,E_a[\mathrm{expit}\,(a_i+x\beta)]$$
The GEE has
$$\mathrm{logit} E[Y_{it}|X_{it}=\tilde\alpha+x\tilde\beta$$
These would be the same if expectations and $\mathrm{expit}$ commuted, but they don't. For a log link, the $\beta$ would be the same, because you can take an $e^\beta$ multiplier through the expectation, but the $\alpha$ would be systematically different.
Ok, so we know $\beta\neq\tilde\beta$ (for the true parameters, not just the estimates). Why is $|\beta|>|\tilde\beta|$?
I think this is easiest with a picture
expit<- function(x) exp(x)/(1+exp(x))
x<-seq(-6,6,length=50)
eta_c <- 0+1*x
mu_c <- expit(eta_m)
plot(x, mu_c,ylab="P(Y=1)",lwd=2,type="n",xlim=c(-6,6))
a<-rnorm(20,s=2)
total_m<-numeric(50)
for(ai in a){
eta_c <- ai+0+1*x
mu_c <- expit(eta_c)
lines(x, mu_c, col="grey")
total_m<-total_m+mu_c
}
mu_m<-total_m/20
lines(x, mu_m, col="blue")
What we see here is 20 realisations in grey of the conditional mean functions for 20 random $a_i$, and the blue curve that is the average of the grey curves, which is the GEE mean curve. They are basically the same shape, but the population-average curve is flatter; $\tilde\beta<\beta$.
The grey curves are all the same shape. The derivative of $p= \mathrm{expit}\eta$ wrt $\eta$ is
$$\frac{\partial p}{\partial\eta} = \mathrm{expit}\eta$ (1-\mathrm{expit}\eta)=p(1-p)$$
so
$$\frac{\partial p}{\partial x} = p(1-p)\frac{\partial\eta}{\partial x}=p(1-p)\beta$$
That is, the grey curves all have slope $\beta/4$ where they cross $p=0.5$ and the blue curve will have slope $\tilde\beta/4$.
One issue I've avoided here is that the GEE and GLMM logistic models are incompatible; they can't both be exactly true. But you could pretend that I used a probit link instead, where they are compatible, or that I'd looked up the relevant bridge distribution to replace the Normal distribution for $a_i$.
|
Why GEE estimates are smaller than GLMM?
This actually depends on the link function -- eg, for a log link there is not a systematic difference, but for a logit link there is.
The reason is that the models are systematically different and the
|
45,996
|
Meaning of the value matrix in self-attention
|
Because Transformers are black-box models, it is hard to say, what the keys and values really are, but the motivation is that might want to retrieve something else than what is your search criterion.
Imagine something like SQL-like query: get phone numbers of people that have a similar name to "Jindrich". "Jindrich" is a query, the criterion for the search. But you do not want similar names from the database, you want the phone numbers. Phone numbers are the values in this case. The keys are the names already in the phonebook.
The projection for the keys and values in the Transformer model can be understood as extracting a relevant piece of information from the hidden states. E.g., in the Transformer Base architecture, the hidden states are 512-dimensional, but the "extracted" keys and values are only 64-dimensional.
Regarding the multiplication: For simplicity, let's assume we have just one query vector $q$ (and not the full matrix $Q$). First, you compute a similarity score for each of the keys:
$$ \alpha = \mathrm{softmax}(qK/\sqrt{d}) = \mathrm{softmax}\left( \frac{(qk_o, qk_1, \ldots, qk_n)}{\sqrt d} \right) $$
The distribution $\alpha$ is a single-dimensional vector, that only tells you how much each of the keys $k_i \in K$ is relevant for the query $q$. In other words, it says at what positions you should retrieve, but you need something to retrieve and these are the values:
$$\alpha V = \sum_{i=0}^m \alpha_i \cdot v_i $$
|
Meaning of the value matrix in self-attention
|
Because Transformers are black-box models, it is hard to say, what the keys and values really are, but the motivation is that might want to retrieve something else than what is your search criterion.
|
Meaning of the value matrix in self-attention
Because Transformers are black-box models, it is hard to say, what the keys and values really are, but the motivation is that might want to retrieve something else than what is your search criterion.
Imagine something like SQL-like query: get phone numbers of people that have a similar name to "Jindrich". "Jindrich" is a query, the criterion for the search. But you do not want similar names from the database, you want the phone numbers. Phone numbers are the values in this case. The keys are the names already in the phonebook.
The projection for the keys and values in the Transformer model can be understood as extracting a relevant piece of information from the hidden states. E.g., in the Transformer Base architecture, the hidden states are 512-dimensional, but the "extracted" keys and values are only 64-dimensional.
Regarding the multiplication: For simplicity, let's assume we have just one query vector $q$ (and not the full matrix $Q$). First, you compute a similarity score for each of the keys:
$$ \alpha = \mathrm{softmax}(qK/\sqrt{d}) = \mathrm{softmax}\left( \frac{(qk_o, qk_1, \ldots, qk_n)}{\sqrt d} \right) $$
The distribution $\alpha$ is a single-dimensional vector, that only tells you how much each of the keys $k_i \in K$ is relevant for the query $q$. In other words, it says at what positions you should retrieve, but you need something to retrieve and these are the values:
$$\alpha V = \sum_{i=0}^m \alpha_i \cdot v_i $$
|
Meaning of the value matrix in self-attention
Because Transformers are black-box models, it is hard to say, what the keys and values really are, but the motivation is that might want to retrieve something else than what is your search criterion.
|
45,997
|
Meaning of the value matrix in self-attention
|
K_V takes the word (or word-part, but let's assume whole words from this discussion) in embedded space, and changes it.
Learning K_V means learning how to change this embedded representation into another embedded representation.
In a sense, what you are asking is "why should we learn how to change the embedding of the words? Why can't we use the original embedding space?"
A fair question.
Consider the following:
After the first layer, we don't have the original words, we have words attended to by the attention mechanism (courtesy of the keys and queries, like you wrote). So we no longer have the word 'This', we have a weird hybrid of, let's say, 0.8*this, 0.15*forum and 0.05*is. We don't want the word that has this value in the original embedded space (if any), we want to make sense of this combination that is relevant to question (i.e. to what we are training this to do).
Please note that we actually have multiple heads of attention, which means that the original value is broken down and is re-concatenated after attention is applied. In order to make use of the information from the different attention heads we need to let the different parts of the value (of the specific word) to effect one another. This is carried out by the Position-wise Feed-Forward layer, but K_V allows more adaptability of the values, which serves their processing in the FF.
While the basic embedding (taking place before the first attention mechanism layer) can be learned specifically to better serve the target question, having learnable W_Vs allows more adaptability to different tasks, as well as allowing you to use the same basic embedding for different tasks (you don't retrain the basic embedding layer when fine-tuning, after all).
|
Meaning of the value matrix in self-attention
|
K_V takes the word (or word-part, but let's assume whole words from this discussion) in embedded space, and changes it.
Learning K_V means learning how to change this embedded representation into anot
|
Meaning of the value matrix in self-attention
K_V takes the word (or word-part, but let's assume whole words from this discussion) in embedded space, and changes it.
Learning K_V means learning how to change this embedded representation into another embedded representation.
In a sense, what you are asking is "why should we learn how to change the embedding of the words? Why can't we use the original embedding space?"
A fair question.
Consider the following:
After the first layer, we don't have the original words, we have words attended to by the attention mechanism (courtesy of the keys and queries, like you wrote). So we no longer have the word 'This', we have a weird hybrid of, let's say, 0.8*this, 0.15*forum and 0.05*is. We don't want the word that has this value in the original embedded space (if any), we want to make sense of this combination that is relevant to question (i.e. to what we are training this to do).
Please note that we actually have multiple heads of attention, which means that the original value is broken down and is re-concatenated after attention is applied. In order to make use of the information from the different attention heads we need to let the different parts of the value (of the specific word) to effect one another. This is carried out by the Position-wise Feed-Forward layer, but K_V allows more adaptability of the values, which serves their processing in the FF.
While the basic embedding (taking place before the first attention mechanism layer) can be learned specifically to better serve the target question, having learnable W_Vs allows more adaptability to different tasks, as well as allowing you to use the same basic embedding for different tasks (you don't retrain the basic embedding layer when fine-tuning, after all).
|
Meaning of the value matrix in self-attention
K_V takes the word (or word-part, but let's assume whole words from this discussion) in embedded space, and changes it.
Learning K_V means learning how to change this embedded representation into anot
|
45,998
|
Normality test for discrete values of a continuous variable
|
When you have many observations like the hundreds that you have, a goodness-of-fit test is going to pick up on subtle deviations that are unlikely to interest you.
You’re right: because of the discreteness of the measurements,$^{\dagger}$ your data cannot be normal, and your test is confirming that your data are not from a normal distribution.
But you already knew that.
The general sentiment on Cross Validated is that this type of testing is not that helpful. Either you lack the sample size to have adequate power to detect an interesting difference, or your test is overpowered and will detect differences that aren’t interesting.
Your plots, especially the quantile-quantile plot, are evidence to me that your data are normal enough for pretty much any purpose.
$^{\dagger}$ There may be other reasons. I was going to say that your values are bounded, but pH doesn’t have to fall between 0 and 14 like they told me in middle school, I’ve learned.
|
Normality test for discrete values of a continuous variable
|
When you have many observations like the hundreds that you have, a goodness-of-fit test is going to pick up on subtle deviations that are unlikely to interest you.
You’re right: because of the discret
|
Normality test for discrete values of a continuous variable
When you have many observations like the hundreds that you have, a goodness-of-fit test is going to pick up on subtle deviations that are unlikely to interest you.
You’re right: because of the discreteness of the measurements,$^{\dagger}$ your data cannot be normal, and your test is confirming that your data are not from a normal distribution.
But you already knew that.
The general sentiment on Cross Validated is that this type of testing is not that helpful. Either you lack the sample size to have adequate power to detect an interesting difference, or your test is overpowered and will detect differences that aren’t interesting.
Your plots, especially the quantile-quantile plot, are evidence to me that your data are normal enough for pretty much any purpose.
$^{\dagger}$ There may be other reasons. I was going to say that your values are bounded, but pH doesn’t have to fall between 0 and 14 like they told me in middle school, I’ve learned.
|
Normality test for discrete values of a continuous variable
When you have many observations like the hundreds that you have, a goodness-of-fit test is going to pick up on subtle deviations that are unlikely to interest you.
You’re right: because of the discret
|
45,999
|
How to show that a random factor is not needed in the model?
|
I have fitted a model to your data using the mixed_model function from the GLMMadaptive package without receiving any error or warning, and compared the output to that produced by glmer(with the singular fit):
(data is available here )
> library(lme4)
> library(GLMMadaptive)
> dt <- read.csv("PilotDataStacked-results.csv")
> dt$id <- as.factor(dt$id)
> m0_glmer <- glmer(isCorrect ~ condition + completion + (1|id), data = dt, nAGQ = 20, family="binomial"(link = logit))
> m0_GLMMadaptive <- mixed_model(fixed = isCorrect ~ condition + completion, random = ~ 1 | id, data = dt,
family = binomial())
> summary(m0_glmer)
Random effects:
Groups Name Variance Std.Dev.
id (Intercept) 0 0
Number of obs: 1160, groups: id, 290
Fixed effects:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 2.171244 0.233476 9.300 < 2e-16 ***
conditiongreen -0.831986 0.222863 -3.733 0.000189 ***
conditiongreen2 -1.139616 0.224589 -5.074 3.89e-07 ***
conditionred -0.753830 0.215395 -3.500 0.000466 ***
completion -0.050959 0.003675 -13.867 < 2e-16 ***
> summary(m0_GLMMadaptive)
Random effects covariance matrix:
StdDev
(Intercept) 0.1508784
Fixed effects:
Estimate Std.Err z-value p-value
(Intercept) 2.1786 0.2349 9.2745 < 1e-04
conditiongreen -0.8342 0.2248 -3.7110 0.00020646
conditiongreen2 -1.1428 0.2265 -5.0454 < 1e-04
conditionred -0.7560 0.2173 -3.4792 0.00050283
completion -0.0512 0.0037 -13.8441 < 1e-04
As you can see, the results are essentially the same. It is a mystery why glmer obtains a singular fit. The variance of the random intercept estimated by mixed_model is quite small, so that is my only idea, however it is not extremely small, so if I were you I would want to investigate a bit more before proceeding with either model. Ben Bolker is one of the authors of lme4 so he might see this message if I ping him in a comment, which I will do, but if not you might want to ask for input from lme4 specialists on the R-sig-ME mailing list:
https://stat.ethz.ch/mailman/listinfo/r-sig-mixed-models
Also Dimitris Rizopoulos (author of GLMMAdaptive) may have some input. I will also ping him.
Edit: As to your other questions:
completion is ordinal with 4 levels (although the underlying construct is continuous - should I model it as a continuous variable?)
Yes, you are losing information by modelling it as ordinal.
Am I actually testing my hypothesis like this? (I still get confused easily with linear models)
Since your hypothesis is whether the slope of completion changes at different levels of condition then your interest should center on the interaction between them. This will be easier to interpret if you switch to continuous completion.
|
How to show that a random factor is not needed in the model?
|
I have fitted a model to your data using the mixed_model function from the GLMMadaptive package without receiving any error or warning, and compared the output to that produced by glmer(with the singu
|
How to show that a random factor is not needed in the model?
I have fitted a model to your data using the mixed_model function from the GLMMadaptive package without receiving any error or warning, and compared the output to that produced by glmer(with the singular fit):
(data is available here )
> library(lme4)
> library(GLMMadaptive)
> dt <- read.csv("PilotDataStacked-results.csv")
> dt$id <- as.factor(dt$id)
> m0_glmer <- glmer(isCorrect ~ condition + completion + (1|id), data = dt, nAGQ = 20, family="binomial"(link = logit))
> m0_GLMMadaptive <- mixed_model(fixed = isCorrect ~ condition + completion, random = ~ 1 | id, data = dt,
family = binomial())
> summary(m0_glmer)
Random effects:
Groups Name Variance Std.Dev.
id (Intercept) 0 0
Number of obs: 1160, groups: id, 290
Fixed effects:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 2.171244 0.233476 9.300 < 2e-16 ***
conditiongreen -0.831986 0.222863 -3.733 0.000189 ***
conditiongreen2 -1.139616 0.224589 -5.074 3.89e-07 ***
conditionred -0.753830 0.215395 -3.500 0.000466 ***
completion -0.050959 0.003675 -13.867 < 2e-16 ***
> summary(m0_GLMMadaptive)
Random effects covariance matrix:
StdDev
(Intercept) 0.1508784
Fixed effects:
Estimate Std.Err z-value p-value
(Intercept) 2.1786 0.2349 9.2745 < 1e-04
conditiongreen -0.8342 0.2248 -3.7110 0.00020646
conditiongreen2 -1.1428 0.2265 -5.0454 < 1e-04
conditionred -0.7560 0.2173 -3.4792 0.00050283
completion -0.0512 0.0037 -13.8441 < 1e-04
As you can see, the results are essentially the same. It is a mystery why glmer obtains a singular fit. The variance of the random intercept estimated by mixed_model is quite small, so that is my only idea, however it is not extremely small, so if I were you I would want to investigate a bit more before proceeding with either model. Ben Bolker is one of the authors of lme4 so he might see this message if I ping him in a comment, which I will do, but if not you might want to ask for input from lme4 specialists on the R-sig-ME mailing list:
https://stat.ethz.ch/mailman/listinfo/r-sig-mixed-models
Also Dimitris Rizopoulos (author of GLMMAdaptive) may have some input. I will also ping him.
Edit: As to your other questions:
completion is ordinal with 4 levels (although the underlying construct is continuous - should I model it as a continuous variable?)
Yes, you are losing information by modelling it as ordinal.
Am I actually testing my hypothesis like this? (I still get confused easily with linear models)
Since your hypothesis is whether the slope of completion changes at different levels of condition then your interest should center on the interaction between them. This will be easier to interpret if you switch to continuous completion.
|
How to show that a random factor is not needed in the model?
I have fitted a model to your data using the mixed_model function from the GLMMadaptive package without receiving any error or warning, and compared the output to that produced by glmer(with the singu
|
46,000
|
When do we use a multivariate regression?
|
The multivariate regression can take into account potential dependence between the two dependent (response) variables. Running two regressions separately cannot.
|
When do we use a multivariate regression?
|
The multivariate regression can take into account potential dependence between the two dependent (response) variables. Running two regressions separately cannot.
|
When do we use a multivariate regression?
The multivariate regression can take into account potential dependence between the two dependent (response) variables. Running two regressions separately cannot.
|
When do we use a multivariate regression?
The multivariate regression can take into account potential dependence between the two dependent (response) variables. Running two regressions separately cannot.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.