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
32,401
What is meant by correlation between intercept and slope(s)
Broadly, the way we calculate an OLS estimate is to first find the point ($\bar{x},\bar{y}$). That point will be on the line which minimizes the mean squared error (MSE). Then we take a line that goes through that point and rotate it until we find the slope ($\hat{\beta}_1$) that minimizes the MSE. That point and slope combination define the OLS line (and thus the intercept). To find the intercept, we find where that line hits the y-axis. Each unit of $x$ that we move, we will move $\hat{\beta}_1$ units of $y$ from our initial point. Thus the intercept can be calculated as: $\hat{\beta}_0 = \bar{y}-\hat{\beta}_1\bar{x}$. This formulation makes it relatively clear why there is a relationship between our estimate of $\hat{\beta}_1$ and $\hat{\beta}_0$. Unless $\bar{x}=0$, if we slightly increase our estimate of the slope, our estimate of the intercept must also change slightly. In asymptotic arguments, as our sample changes slightly, this becomes a touch less clear, because the means ($\bar{x},\bar{y}$) also change. But within any given sample, there is a tight relationship between our beliefs about the slope and the intercept.
What is meant by correlation between intercept and slope(s)
Broadly, the way we calculate an OLS estimate is to first find the point ($\bar{x},\bar{y}$). That point will be on the line which minimizes the mean squared error (MSE). Then we take a line that goes
What is meant by correlation between intercept and slope(s) Broadly, the way we calculate an OLS estimate is to first find the point ($\bar{x},\bar{y}$). That point will be on the line which minimizes the mean squared error (MSE). Then we take a line that goes through that point and rotate it until we find the slope ($\hat{\beta}_1$) that minimizes the MSE. That point and slope combination define the OLS line (and thus the intercept). To find the intercept, we find where that line hits the y-axis. Each unit of $x$ that we move, we will move $\hat{\beta}_1$ units of $y$ from our initial point. Thus the intercept can be calculated as: $\hat{\beta}_0 = \bar{y}-\hat{\beta}_1\bar{x}$. This formulation makes it relatively clear why there is a relationship between our estimate of $\hat{\beta}_1$ and $\hat{\beta}_0$. Unless $\bar{x}=0$, if we slightly increase our estimate of the slope, our estimate of the intercept must also change slightly. In asymptotic arguments, as our sample changes slightly, this becomes a touch less clear, because the means ($\bar{x},\bar{y}$) also change. But within any given sample, there is a tight relationship between our beliefs about the slope and the intercept.
What is meant by correlation between intercept and slope(s) Broadly, the way we calculate an OLS estimate is to first find the point ($\bar{x},\bar{y}$). That point will be on the line which minimizes the mean squared error (MSE). Then we take a line that goes
32,402
What exactly makes a model "overparameterized"?
“Overparamized” model has more parameters then there were datapoints in training set. More formally, it’s not only about number of parameters, but capacity to memorize data, where number of parameters is just a cheap proxy for measuring it. You are correct that even huge models like GTP-3 are much smaller then would be needed to fully memorize the data. Overparametrized models are achievable on small datasets. For example, Neal et al (2018) trained such model on subsample of 100 examples from MNIST. There are not something that you would want to use on real tasks, since it’d be impractical, and need enormous computational power. Check this answer for some related references.
What exactly makes a model "overparameterized"?
“Overparamized” model has more parameters then there were datapoints in training set. More formally, it’s not only about number of parameters, but capacity to memorize data, where number of parameters
What exactly makes a model "overparameterized"? “Overparamized” model has more parameters then there were datapoints in training set. More formally, it’s not only about number of parameters, but capacity to memorize data, where number of parameters is just a cheap proxy for measuring it. You are correct that even huge models like GTP-3 are much smaller then would be needed to fully memorize the data. Overparametrized models are achievable on small datasets. For example, Neal et al (2018) trained such model on subsample of 100 examples from MNIST. There are not something that you would want to use on real tasks, since it’d be impractical, and need enormous computational power. Check this answer for some related references.
What exactly makes a model "overparameterized"? “Overparamized” model has more parameters then there were datapoints in training set. More formally, it’s not only about number of parameters, but capacity to memorize data, where number of parameters
32,403
Is permutation test superior to t-test in all cases?
I am a fan of permutation tests in general, but there are some important considerations to their construction that could be interpreted as disadvantages. They have benefits, too, though, that make me come down in favor of permutation tests in the vast majority of situations. Benefits For designed experiments, you can always construct a permutation test that matches your experimental design. There are a number of papers about this, but one of my favorites is Permutation Tests for Multi-Factorial Analysis of Variance by Marti Anderson. When constructed properly, the permutation test does not really rely on unverifiable assumptions about your data. This is discussed at length by Tukey in Tightening the Clinical Trial which is worth a read if you are interested in non-parametric analyses. These two benefits are worth a lot - the p-values (and confidence intervals) that are generated by a permutation test can justified with solely the construction of the test. Moreover, the main benefit to using an asymptotic test like the t-test is that it is much easier to compute, but asymptotic tests can never be more exact than the permutation test. Therefore, if computational power is not limiting, you should go for the permutation test. That's not to say permutation tests are perfect, however. Drawbacks Permutation tests are inefficient compared to asymptotic tests. When you have only a few observations, it might be impossible to control alpha at the level you want and still do a permutation test. This can be mitigated by collecting more data, however. Choice of test statistic is a much more important drawback to keep in mind. As a general rule of thumb, for any given metric $\beta$, you should use $\beta /s.e.(\beta)$ as the test statistic. Permutation tests tend to be sensitive to differences in distributions rather than differences in parameter, but using a pivotal (or approximately pivotal) test statistic fixes this problem. One handy way of doing that is just dividing your comparison of interest by an estimate of its standard error. This is discussed by Chung and Romano in Exact and asymptotically robust permutation tests. This does not completely fix the issue - comparing asymmetric distributions with massive heteroscedasticity is still difficult, but it's also quite difficult to do with asymptotic tests. On the whole, I come down on the side of the permutation test for two main reasons: 1. you can analyze any experimental design with a permutation test (though not necessarily an exact one) and 2. its drawbacks can be mitigated.
Is permutation test superior to t-test in all cases?
I am a fan of permutation tests in general, but there are some important considerations to their construction that could be interpreted as disadvantages. They have benefits, too, though, that make me
Is permutation test superior to t-test in all cases? I am a fan of permutation tests in general, but there are some important considerations to their construction that could be interpreted as disadvantages. They have benefits, too, though, that make me come down in favor of permutation tests in the vast majority of situations. Benefits For designed experiments, you can always construct a permutation test that matches your experimental design. There are a number of papers about this, but one of my favorites is Permutation Tests for Multi-Factorial Analysis of Variance by Marti Anderson. When constructed properly, the permutation test does not really rely on unverifiable assumptions about your data. This is discussed at length by Tukey in Tightening the Clinical Trial which is worth a read if you are interested in non-parametric analyses. These two benefits are worth a lot - the p-values (and confidence intervals) that are generated by a permutation test can justified with solely the construction of the test. Moreover, the main benefit to using an asymptotic test like the t-test is that it is much easier to compute, but asymptotic tests can never be more exact than the permutation test. Therefore, if computational power is not limiting, you should go for the permutation test. That's not to say permutation tests are perfect, however. Drawbacks Permutation tests are inefficient compared to asymptotic tests. When you have only a few observations, it might be impossible to control alpha at the level you want and still do a permutation test. This can be mitigated by collecting more data, however. Choice of test statistic is a much more important drawback to keep in mind. As a general rule of thumb, for any given metric $\beta$, you should use $\beta /s.e.(\beta)$ as the test statistic. Permutation tests tend to be sensitive to differences in distributions rather than differences in parameter, but using a pivotal (or approximately pivotal) test statistic fixes this problem. One handy way of doing that is just dividing your comparison of interest by an estimate of its standard error. This is discussed by Chung and Romano in Exact and asymptotically robust permutation tests. This does not completely fix the issue - comparing asymmetric distributions with massive heteroscedasticity is still difficult, but it's also quite difficult to do with asymptotic tests. On the whole, I come down on the side of the permutation test for two main reasons: 1. you can analyze any experimental design with a permutation test (though not necessarily an exact one) and 2. its drawbacks can be mitigated.
Is permutation test superior to t-test in all cases? I am a fan of permutation tests in general, but there are some important considerations to their construction that could be interpreted as disadvantages. They have benefits, too, though, that make me
32,404
Number of events in a segment if waiting times are drawn from a mixture of two exponential distributions
Part 1: fixed waiting times What is the probability for $n$ events to occur over a period of time $t$, if the duration of each individual event is $\tau_1$ with the probability $p$ and $\tau_2$ with the probability of $(1-p)$? There is a correspondence between waiting time and number of events per time see: https://stats.stackexchange.com/a/450135/164061 For time $t$ and number $n$ you get: $$\begin{array}{ccc} \overbrace{P(N \geq n| t)}^{\text{this is what you are looking for}} &=& \overbrace{P(T \leq t|n)}^{\text{we will express this instead}} \\ {\small\text{prob. counts $n$ or above given time $t$}} &=& {\small\text{prob. waiting time below $t$ given counts $n$}} \end{array} $$ In words: the probability to get more than $n$ counts within time $t$ equals the probability to need less than $t$ time to get $n$ counts. For all cases that got $n$ or more cases within time $t$, they must have had $n$ cases below time $t$ and none of them had $n$ cases in time $t$ or above. and this relates many distributions. Distribution of Distribution of Waiting time between events number of events Exponential Poisson Erlang/Gamma over/under-dispersed Poisson Geometric Binomial Negative Binomial over/under-dispersed Binomial So let's express the alternative: What is the probability for $n$ events to take time $t$ or less? The distribution of time for $n$ events can be expressed as a scaled and shifted binomial distribution. For $n$ events we have the number of events of type '1' and the events of type '2' which is binomial distributed. $$P(N_1 = n_1) = {{n}\choose{n_1}} p^{n_1} (1-p)^{n-n_1}$$ and CDF $$P(N_1 \leq n_1) = I_q(n-n_1,1+n_1)$$ where $I$ is the regularized beta function. Now we need to convert this to time which is quick step. The time $t$ is equal to $$t=\tau_1 n_1 + \tau_2 (n-n_1)$$ or $$t=(\tau_1-\tau_2) n_1 + \tau_2 n$$ So the time to handle $n$ patients is basically a scaled and shifted binomial variable. So, to know the probability for $N$ events being less or equal to $n$ given time $t$, we compute the probability for the probability that time $T$ given $n$ is larger than $t$, and this we do with a binomial distribution (where we need to take into account a shift and scaling). Step 2: exponentially distributed waiting times with the actual durations distributed exponentially. How many times would the doctor's door open during a period of half an hour? This will require some more steps... ...but it will follow the same lines. Convolute the individual waiting time distributions (in this case now it is a mixture of exponential distributions) to get the total waiting distributions, and then invert switch independent and dependent variables. The main problem is now that a sum of different exponentially distributed variables (with different $\tau$) is not easily expressed/computed. So you are likely gonna use an approximate method, of which there are many variations (4 of them below of which 2 computed in the code). The R-code below gives two examples We can compute the distribution (and the related mean) by simulating the process a lot of time. In the code below this is done by adding exponential variables until the time exceeds 30 minutes. Then after doing this a lot of times we can draw a histogram of the distribution of the times that we can add exponential variables untill we exceed 30 minutes. We can model the distribution as a continuous Markov process. And the distribution of the time $t$ until having $n$ patients is phase-type distributed. The transition matrix (for states 0,...,2k) has the form like (where $\lambda = 1/\tau$): $$\begin{bmatrix}{} 0& 0 & 0 & 0 & 0 & 0 & 0 \\ 0& -\lambda_1 & 0 & p_1 \lambda_1 & p_2 \lambda_1 & 0 & 0 \\ 0&0 & -\lambda_2 & p_1 \lambda_2 & p_2 \lambda_2 & 0 & 0 \\ 0&0&0& -\lambda_1 & 0 & p_1 \lambda_1 & p_2 \lambda_1 \\ 0&0&0&0& -\lambda_2 & p_1 \lambda_2 & p_2 \lambda_2 \\ \lambda_1&0&0&0&0& -\lambda_1 & 0 \\ \lambda_2&0&0&0&0&0& -\lambda_2 \end{bmatrix}$$ which has repeated blocks like $$\begin{bmatrix}{} -\lambda_1 & 0 & p_1 \lambda_1 & p_2 \lambda_1 \\ 0 & -\lambda_2 & p_1 \lambda_2 & p_2 \lambda_2 \\ \end{bmatrix}$$ The begin state is with fraction $p_1$ in $1$ and $p_2$ in $2$. The transitions will be going in steps from pairs to pairs, ie. from states $2k$ or $2k+1$ to states $2(k+1)$ or $2(k+1)+1$, and the rates by which a step is made will depend on whether the current state is odd or even. In the last two lines $$\begin{bmatrix}{} \lambda_1&0&0&0&0& -\lambda_1 & 0 \\ \lambda_2&0&0&0&0&0& -\lambda_2 \end{bmatrix}$$ The transition goes to the absorbing state 0. Not worked out in this answer and the code below is an exact expression of the distribution function Possibly there might be a way to express the waiting time for $n$ patients as a mixture of gamma distributions by expressing the characteristic function of the distribution of the waiting time for $n$ patients $$\varphi_{T \vert n}(t) = \left[ \frac{p_1}{1 - i \tau_1 t} + \frac{p_2}{1 - i \tau_2 t} \right]^n$$ in terms of a mixture of gamma distributions. Also we may use a normal distribution approximation and a Taylor series approximation. See here. If the waiting time for a single event has finite variance then the conditions of the CLT are fulfilled and the waiting time for more events will be asymptotically normal distributed. Then we can model the distribution of $m$ as an approximately normal distribution : $$P(M \leq m \vert x) \approx \Phi \left( \frac{m-x\theta_1}{\sqrt{x}\theta_2} \right)$$ Note that the CLT is more precisely $\sqrt{x}(M/x-\theta_1) \sim N(0,\theta_2)$ so this is where the distribution of $M$ and not $\sqrt{x}(M/x-\theta_1)$ may still differ from a normal distribution. But the scaled variable $M/x$ is approaching a normal dsitribution. and we can convert this into $$P(X < x \vert m) = P(M > m \vert x) \approx \Phi \left( \frac{x-m/\theta_1}{\sqrt{x}\theta_2/\theta_1} \right) \underbrace{\approx \Phi \left( \frac{x-m/\theta_1}{\theta_2\sqrt{m/\theta_1^3}} \right)}_{\text{Taylor series approximation}} $$ where $\theta_1$ and $\theta_2$ are respectively the mean and standard deviation of the waiting time for a single event. In our case the mean waiting time is $$\theta_1 = p_1 \tau_1 + p_2 \tau_2$$ and the standard deviation of the waiting time of a single event is (see here to derive the formula) $$\theta_2 = \sqrt{2 p_1 \tau_1^2 + 2 p_2 \tau_2^2 - (p_1 \tau_1 + p_2 \tau_2)^2 }$$ This approximation is not working well for small values of patients though, because in that case the approximation with a normal distribution is not a good approximation. Example image for case 1 and 2: Simulation and computation of the distribution of patients in half an hour. The mean/average will be around 4.38/3.38, depending on whether you count the times the door opens for a patient entering/leaving. Example code: ###################### library(actuar) set.seed(1) ## parameters for simulation n <- 10^5 nt <- rep(0,n) ## parameters describing problem tl <- 30 t1 <- 5 t2 <- 60 l1 <- 1/t1 l2 <- 1/t2 p1 <- 0.8 p2 <- 0.2 ## ## simulate patients ## for (i in 1:n) { t = 0 while (t <= tl) { lambda = l2 + (l1-l2) * rbinom(1,1,p1) t = t + rexp(1,lambda) nt[i]=nt[i]+1 } } ## ## computing patients with phase-type distribution ## #star transition matrix T <- rbind(c(-l1, 0 ), c( 0 , -l2)) pi <- c(p1,p2) # computing time within 30 min cump <- pphtype(30,pi,T) for (i in 1:20) { # extending transition matrix by 2 rows T <- rbind(c(-l1, 0 , p1*l1 , p2*l1, rep(0,length(T[,1])-2)), c( 0 , -l2 , p1*l2 , p2*l2, rep(0,length(T[,1])-2)), cbind(0,0, T) ) pi <- c(pi,0,0) # computing time within 30 min cump <- c(cump,pphtype(30,pi,T)) } ps <- (-diff(c(1,cump))) ## ## plotting histogram ## h <- hist(nt, breaks = seq(-0.5,20.5,1), main = "distribution n patients", freq = FALSE, xlab = "n") ### computed probabilities for bn patients lines(ps) points(ps, col = 1, bg = 1, pch = 21) ## expressing mean sum(h$density*h$mids) sum(ps*c(1:21)) tl/(p1*t1+p2*t2)+1 Example image for case 2: With this code we can compute/approximate the discrepancy between the expected number of patients and the inverse of the expected waiting time (1/16). The longer the time frame the closer the two will be. ### placing the computation with phase-type distribution in a function ptime <- function(minutes, ncomp = 100, t1 = 5, t2 = 60, p1 = 0.8, p2 = 0.2) { l1 <- 1/t1 l2 <- 1/t2 #star transition matrix T <- rbind(c(-l1, 0 ), c( 0 , -l2)) pi <- c(p1,p2) # computing time within minutes min cump <- pphtype(minutes,pi,T) for (i in 1:ncomp) { # extending transition matrix by 2 rows T <- rbind(c(-l1, 0 , p1*l1 , p2*l1, rep(0,length(T[,1])-2)), c( 0 , -l2 , p1*l2 , p2*l2, rep(0,length(T[,1])-2)), cbind(0,0, T) ) pi <- c(pi,0,0) # computing time within 30 min cump <- c(cump,pphtype(minutes,pi,T)) } ps <- (-diff(c(1,cump))) ps } ### computing distributions for different times meanout <- c() cmins <- 15*2^seq(0,6,0.25) nsim <- 150 plot(-100,-100, xlim = c(0,nsim), ylim = c(0,0.3)) for (mins in cmins) { ps <- ptime(mins, ncomp = nsim) lines(0:nsim,ps) meanout <- c(meanout,sum(ps*c(0:nsim))/mins) } ### plotting the means plot(cmins,meanout, ylim = c(0,0.15), main = "average patients\n per minute", xlab = "time frame in minutes", ylab = "patients per minute") lines(c(0,max(cmins)),rep(1/(p1*t1+p2*t2),2))
Number of events in a segment if waiting times are drawn from a mixture of two exponential distribut
Part 1: fixed waiting times What is the probability for $n$ events to occur over a period of time $t$, if the duration of each individual event is $\tau_1$ with the probability $p$ and $\tau_2$ with
Number of events in a segment if waiting times are drawn from a mixture of two exponential distributions Part 1: fixed waiting times What is the probability for $n$ events to occur over a period of time $t$, if the duration of each individual event is $\tau_1$ with the probability $p$ and $\tau_2$ with the probability of $(1-p)$? There is a correspondence between waiting time and number of events per time see: https://stats.stackexchange.com/a/450135/164061 For time $t$ and number $n$ you get: $$\begin{array}{ccc} \overbrace{P(N \geq n| t)}^{\text{this is what you are looking for}} &=& \overbrace{P(T \leq t|n)}^{\text{we will express this instead}} \\ {\small\text{prob. counts $n$ or above given time $t$}} &=& {\small\text{prob. waiting time below $t$ given counts $n$}} \end{array} $$ In words: the probability to get more than $n$ counts within time $t$ equals the probability to need less than $t$ time to get $n$ counts. For all cases that got $n$ or more cases within time $t$, they must have had $n$ cases below time $t$ and none of them had $n$ cases in time $t$ or above. and this relates many distributions. Distribution of Distribution of Waiting time between events number of events Exponential Poisson Erlang/Gamma over/under-dispersed Poisson Geometric Binomial Negative Binomial over/under-dispersed Binomial So let's express the alternative: What is the probability for $n$ events to take time $t$ or less? The distribution of time for $n$ events can be expressed as a scaled and shifted binomial distribution. For $n$ events we have the number of events of type '1' and the events of type '2' which is binomial distributed. $$P(N_1 = n_1) = {{n}\choose{n_1}} p^{n_1} (1-p)^{n-n_1}$$ and CDF $$P(N_1 \leq n_1) = I_q(n-n_1,1+n_1)$$ where $I$ is the regularized beta function. Now we need to convert this to time which is quick step. The time $t$ is equal to $$t=\tau_1 n_1 + \tau_2 (n-n_1)$$ or $$t=(\tau_1-\tau_2) n_1 + \tau_2 n$$ So the time to handle $n$ patients is basically a scaled and shifted binomial variable. So, to know the probability for $N$ events being less or equal to $n$ given time $t$, we compute the probability for the probability that time $T$ given $n$ is larger than $t$, and this we do with a binomial distribution (where we need to take into account a shift and scaling). Step 2: exponentially distributed waiting times with the actual durations distributed exponentially. How many times would the doctor's door open during a period of half an hour? This will require some more steps... ...but it will follow the same lines. Convolute the individual waiting time distributions (in this case now it is a mixture of exponential distributions) to get the total waiting distributions, and then invert switch independent and dependent variables. The main problem is now that a sum of different exponentially distributed variables (with different $\tau$) is not easily expressed/computed. So you are likely gonna use an approximate method, of which there are many variations (4 of them below of which 2 computed in the code). The R-code below gives two examples We can compute the distribution (and the related mean) by simulating the process a lot of time. In the code below this is done by adding exponential variables until the time exceeds 30 minutes. Then after doing this a lot of times we can draw a histogram of the distribution of the times that we can add exponential variables untill we exceed 30 minutes. We can model the distribution as a continuous Markov process. And the distribution of the time $t$ until having $n$ patients is phase-type distributed. The transition matrix (for states 0,...,2k) has the form like (where $\lambda = 1/\tau$): $$\begin{bmatrix}{} 0& 0 & 0 & 0 & 0 & 0 & 0 \\ 0& -\lambda_1 & 0 & p_1 \lambda_1 & p_2 \lambda_1 & 0 & 0 \\ 0&0 & -\lambda_2 & p_1 \lambda_2 & p_2 \lambda_2 & 0 & 0 \\ 0&0&0& -\lambda_1 & 0 & p_1 \lambda_1 & p_2 \lambda_1 \\ 0&0&0&0& -\lambda_2 & p_1 \lambda_2 & p_2 \lambda_2 \\ \lambda_1&0&0&0&0& -\lambda_1 & 0 \\ \lambda_2&0&0&0&0&0& -\lambda_2 \end{bmatrix}$$ which has repeated blocks like $$\begin{bmatrix}{} -\lambda_1 & 0 & p_1 \lambda_1 & p_2 \lambda_1 \\ 0 & -\lambda_2 & p_1 \lambda_2 & p_2 \lambda_2 \\ \end{bmatrix}$$ The begin state is with fraction $p_1$ in $1$ and $p_2$ in $2$. The transitions will be going in steps from pairs to pairs, ie. from states $2k$ or $2k+1$ to states $2(k+1)$ or $2(k+1)+1$, and the rates by which a step is made will depend on whether the current state is odd or even. In the last two lines $$\begin{bmatrix}{} \lambda_1&0&0&0&0& -\lambda_1 & 0 \\ \lambda_2&0&0&0&0&0& -\lambda_2 \end{bmatrix}$$ The transition goes to the absorbing state 0. Not worked out in this answer and the code below is an exact expression of the distribution function Possibly there might be a way to express the waiting time for $n$ patients as a mixture of gamma distributions by expressing the characteristic function of the distribution of the waiting time for $n$ patients $$\varphi_{T \vert n}(t) = \left[ \frac{p_1}{1 - i \tau_1 t} + \frac{p_2}{1 - i \tau_2 t} \right]^n$$ in terms of a mixture of gamma distributions. Also we may use a normal distribution approximation and a Taylor series approximation. See here. If the waiting time for a single event has finite variance then the conditions of the CLT are fulfilled and the waiting time for more events will be asymptotically normal distributed. Then we can model the distribution of $m$ as an approximately normal distribution : $$P(M \leq m \vert x) \approx \Phi \left( \frac{m-x\theta_1}{\sqrt{x}\theta_2} \right)$$ Note that the CLT is more precisely $\sqrt{x}(M/x-\theta_1) \sim N(0,\theta_2)$ so this is where the distribution of $M$ and not $\sqrt{x}(M/x-\theta_1)$ may still differ from a normal distribution. But the scaled variable $M/x$ is approaching a normal dsitribution. and we can convert this into $$P(X < x \vert m) = P(M > m \vert x) \approx \Phi \left( \frac{x-m/\theta_1}{\sqrt{x}\theta_2/\theta_1} \right) \underbrace{\approx \Phi \left( \frac{x-m/\theta_1}{\theta_2\sqrt{m/\theta_1^3}} \right)}_{\text{Taylor series approximation}} $$ where $\theta_1$ and $\theta_2$ are respectively the mean and standard deviation of the waiting time for a single event. In our case the mean waiting time is $$\theta_1 = p_1 \tau_1 + p_2 \tau_2$$ and the standard deviation of the waiting time of a single event is (see here to derive the formula) $$\theta_2 = \sqrt{2 p_1 \tau_1^2 + 2 p_2 \tau_2^2 - (p_1 \tau_1 + p_2 \tau_2)^2 }$$ This approximation is not working well for small values of patients though, because in that case the approximation with a normal distribution is not a good approximation. Example image for case 1 and 2: Simulation and computation of the distribution of patients in half an hour. The mean/average will be around 4.38/3.38, depending on whether you count the times the door opens for a patient entering/leaving. Example code: ###################### library(actuar) set.seed(1) ## parameters for simulation n <- 10^5 nt <- rep(0,n) ## parameters describing problem tl <- 30 t1 <- 5 t2 <- 60 l1 <- 1/t1 l2 <- 1/t2 p1 <- 0.8 p2 <- 0.2 ## ## simulate patients ## for (i in 1:n) { t = 0 while (t <= tl) { lambda = l2 + (l1-l2) * rbinom(1,1,p1) t = t + rexp(1,lambda) nt[i]=nt[i]+1 } } ## ## computing patients with phase-type distribution ## #star transition matrix T <- rbind(c(-l1, 0 ), c( 0 , -l2)) pi <- c(p1,p2) # computing time within 30 min cump <- pphtype(30,pi,T) for (i in 1:20) { # extending transition matrix by 2 rows T <- rbind(c(-l1, 0 , p1*l1 , p2*l1, rep(0,length(T[,1])-2)), c( 0 , -l2 , p1*l2 , p2*l2, rep(0,length(T[,1])-2)), cbind(0,0, T) ) pi <- c(pi,0,0) # computing time within 30 min cump <- c(cump,pphtype(30,pi,T)) } ps <- (-diff(c(1,cump))) ## ## plotting histogram ## h <- hist(nt, breaks = seq(-0.5,20.5,1), main = "distribution n patients", freq = FALSE, xlab = "n") ### computed probabilities for bn patients lines(ps) points(ps, col = 1, bg = 1, pch = 21) ## expressing mean sum(h$density*h$mids) sum(ps*c(1:21)) tl/(p1*t1+p2*t2)+1 Example image for case 2: With this code we can compute/approximate the discrepancy between the expected number of patients and the inverse of the expected waiting time (1/16). The longer the time frame the closer the two will be. ### placing the computation with phase-type distribution in a function ptime <- function(minutes, ncomp = 100, t1 = 5, t2 = 60, p1 = 0.8, p2 = 0.2) { l1 <- 1/t1 l2 <- 1/t2 #star transition matrix T <- rbind(c(-l1, 0 ), c( 0 , -l2)) pi <- c(p1,p2) # computing time within minutes min cump <- pphtype(minutes,pi,T) for (i in 1:ncomp) { # extending transition matrix by 2 rows T <- rbind(c(-l1, 0 , p1*l1 , p2*l1, rep(0,length(T[,1])-2)), c( 0 , -l2 , p1*l2 , p2*l2, rep(0,length(T[,1])-2)), cbind(0,0, T) ) pi <- c(pi,0,0) # computing time within 30 min cump <- c(cump,pphtype(minutes,pi,T)) } ps <- (-diff(c(1,cump))) ps } ### computing distributions for different times meanout <- c() cmins <- 15*2^seq(0,6,0.25) nsim <- 150 plot(-100,-100, xlim = c(0,nsim), ylim = c(0,0.3)) for (mins in cmins) { ps <- ptime(mins, ncomp = nsim) lines(0:nsim,ps) meanout <- c(meanout,sum(ps*c(0:nsim))/mins) } ### plotting the means plot(cmins,meanout, ylim = c(0,0.15), main = "average patients\n per minute", xlab = "time frame in minutes", ylab = "patients per minute") lines(c(0,max(cmins)),rep(1/(p1*t1+p2*t2),2))
Number of events in a segment if waiting times are drawn from a mixture of two exponential distribut Part 1: fixed waiting times What is the probability for $n$ events to occur over a period of time $t$, if the duration of each individual event is $\tau_1$ with the probability $p$ and $\tau_2$ with
32,405
Number of events in a segment if waiting times are drawn from a mixture of two exponential distributions
The distribution of waiting times you describe is a hyperexponential distribution. See the Wikipedia entry for details. each $Y_i$ is an exponentially distributed random variable with rate parameter $\lambda_i$, and $p_i$ is the probability that $X$ will take on the form of the exponential distribution with rate $\lambda_i$ The expected value of wait time is simply: $$E[X]=\sum_{i=1}^n \tfrac{p_i}{\lambda_i}$$ In your example, the average waiting time is $\tfrac{0.8}{1/5}+\tfrac{0.2}{1/60}=16$ minutes. The expected number of patients in a half-hour is $30/16=1.875$ Edit: I believe the final calculation for the expected number of patients per half-hour is correct for a random half-hour period but not necessarily the first half-hour. That is, if we look at a random half-hour period throughout the day it will work, but if we look at the first half-hour when the first patient arrives, or if we're assuming a patient arrives right at the beginning of the half-hour, then the answer will be different. This is because the hyperexponential distribution does not exhibit the memoryless property.
Number of events in a segment if waiting times are drawn from a mixture of two exponential distribut
The distribution of waiting times you describe is a hyperexponential distribution. See the Wikipedia entry for details. each $Y_i$ is an exponentially distributed random variable with rate parameter
Number of events in a segment if waiting times are drawn from a mixture of two exponential distributions The distribution of waiting times you describe is a hyperexponential distribution. See the Wikipedia entry for details. each $Y_i$ is an exponentially distributed random variable with rate parameter $\lambda_i$, and $p_i$ is the probability that $X$ will take on the form of the exponential distribution with rate $\lambda_i$ The expected value of wait time is simply: $$E[X]=\sum_{i=1}^n \tfrac{p_i}{\lambda_i}$$ In your example, the average waiting time is $\tfrac{0.8}{1/5}+\tfrac{0.2}{1/60}=16$ minutes. The expected number of patients in a half-hour is $30/16=1.875$ Edit: I believe the final calculation for the expected number of patients per half-hour is correct for a random half-hour period but not necessarily the first half-hour. That is, if we look at a random half-hour period throughout the day it will work, but if we look at the first half-hour when the first patient arrives, or if we're assuming a patient arrives right at the beginning of the half-hour, then the answer will be different. This is because the hyperexponential distribution does not exhibit the memoryless property.
Number of events in a segment if waiting times are drawn from a mixture of two exponential distribut The distribution of waiting times you describe is a hyperexponential distribution. See the Wikipedia entry for details. each $Y_i$ is an exponentially distributed random variable with rate parameter
32,406
Teaching students about non-significant results and large effect size
I wouldn't explain it to them in any of these ways. (Note also that the numbers in some of those explanations are wrong -- you need to be more careful of that) A) The results are statistically non-significant F(2,21) = 3.14, p-value = 0.12, eta = 0.20 thus the researcher's hypothesis (about the influence of alcoholism on working memory) is rejected. You can't support this statement -- the absence of evidence of the presence of the predicted effect is not the same thing as evidence the effect is absent. C) The results show that the data are consistent with null hypothesis of no-effect (of an alcoholism on a capacity), F(2,21) = 3.14, p-value = 0.20, but the large effect size η2 suggests that the research hypothesis may be correct. If you're trying to show them how to construct a conclusion I'd say the broad form of C is closest to being reasonable (though I think for that purpose you could do better as well), but for an explanation I'd lean more toward something roughly along the lines of "The results are consistent with the absence of an effect, but the estimated effect size is large; this occurs because the standard error of the effect size is also large -- we can't tell if the population effect is big or small from these data; the sample size is too small to estimate it well." I'd also add that reaction times are not going to be anywhere close to normally distributed in general; typically they're quite skew and tend to have spread related to the mean (smaller means are associated with smaller standard deviations). I wouldn't be using regression/ANOVA with reaction times; I'd be choosing a more suitable model.
Teaching students about non-significant results and large effect size
I wouldn't explain it to them in any of these ways. (Note also that the numbers in some of those explanations are wrong -- you need to be more careful of that) A) The results are statistically non-si
Teaching students about non-significant results and large effect size I wouldn't explain it to them in any of these ways. (Note also that the numbers in some of those explanations are wrong -- you need to be more careful of that) A) The results are statistically non-significant F(2,21) = 3.14, p-value = 0.12, eta = 0.20 thus the researcher's hypothesis (about the influence of alcoholism on working memory) is rejected. You can't support this statement -- the absence of evidence of the presence of the predicted effect is not the same thing as evidence the effect is absent. C) The results show that the data are consistent with null hypothesis of no-effect (of an alcoholism on a capacity), F(2,21) = 3.14, p-value = 0.20, but the large effect size η2 suggests that the research hypothesis may be correct. If you're trying to show them how to construct a conclusion I'd say the broad form of C is closest to being reasonable (though I think for that purpose you could do better as well), but for an explanation I'd lean more toward something roughly along the lines of "The results are consistent with the absence of an effect, but the estimated effect size is large; this occurs because the standard error of the effect size is also large -- we can't tell if the population effect is big or small from these data; the sample size is too small to estimate it well." I'd also add that reaction times are not going to be anywhere close to normally distributed in general; typically they're quite skew and tend to have spread related to the mean (smaller means are associated with smaller standard deviations). I wouldn't be using regression/ANOVA with reaction times; I'd be choosing a more suitable model.
Teaching students about non-significant results and large effect size I wouldn't explain it to them in any of these ways. (Note also that the numbers in some of those explanations are wrong -- you need to be more careful of that) A) The results are statistically non-si
32,407
Teaching students about non-significant results and large effect size
Excellent start with @Isabella's Comments. Here are some fake data that might be sufficiently similar to yours for purposes of discussion. I don't know if you use R statistical software, but other kinds of software will do about the same thing for data like these. set.seed(907) a = rnorm(8, 13, 7) # alcoholics n = rnorm(8, 15, 5) # non x = rnorm(8, 20, 5) # ex y=c(a,n,x) # data in stacked format g=as.factor(rep(1:3, 8)) # group number 1, 2, 3 First look at descriptive statistics, Maybe review what the DF's mean and what information goes into SS(Group) (group means) and into SS(Error) [group variances]. Then what divisions lead to the F-statistic. Then pick the ANOVA table apart. summary(a); sd(a) Min. 1st Qu. Median Mean 3rd Qu. Max. 3.655 8.117 12.896 12.464 15.293 20.847 [1] 5.919241 # sd of gp a summary(n); sd(n) Min. 1st Qu. Median Mean 3rd Qu. Max. 3.597 11.780 15.221 14.672 20.023 21.437 [1] 6.276581 summary(x); sd(x) Min. 1st Qu. Median Mean 3rd Qu. Max. 11.60 14.68 17.28 17.15 18.01 25.16 [1] 4.046853 Respective means are about 13, 15, 17, so there might be an effect. Medians show a similar pattern. Look at stripchart (or dotplot) of data. Do you see any difference? Why don't the differences among means show more clearly? stripchart(y ~ g, pch=19) Maybe also look at boxplots. Large variability obscures differences in medians. boxplot(y ~ g, col="skyblue2", horizontal=T) Now look at ANOVA table. anova(lm(y ~ g)) Analysis of Variance Table Response: y Df Sum Sq Mean Sq F value Pr(>F) g 2 16.65 8.324 0.2472 0.7832 Residuals 21 707.07 33.670 Residual (Error) line has huge Sum of Squares, so large Mean Square. F-statistic is ratio of MS(Group) to MS(Resid). So large MS(Error) makes the F-statistic small, hence P-value large, leading to a non-significant result. If you had more data, then DF's would be larger, MS(Error) smaller, F-larger, P-value smaller. Alternatively, if group variances were smaller, then MS(Error) might be small enough for a significant effect---even with the current sample sizes. Here is a plot of the distribution F(2, 21). The observed value of $F$ is shown as a vertical dotted line. The P-value is the area under the density curve to the right of the dotted line.
Teaching students about non-significant results and large effect size
Excellent start with @Isabella's Comments. Here are some fake data that might be sufficiently similar to yours for purposes of discussion. I don't know if you use R statistical software, but other ki
Teaching students about non-significant results and large effect size Excellent start with @Isabella's Comments. Here are some fake data that might be sufficiently similar to yours for purposes of discussion. I don't know if you use R statistical software, but other kinds of software will do about the same thing for data like these. set.seed(907) a = rnorm(8, 13, 7) # alcoholics n = rnorm(8, 15, 5) # non x = rnorm(8, 20, 5) # ex y=c(a,n,x) # data in stacked format g=as.factor(rep(1:3, 8)) # group number 1, 2, 3 First look at descriptive statistics, Maybe review what the DF's mean and what information goes into SS(Group) (group means) and into SS(Error) [group variances]. Then what divisions lead to the F-statistic. Then pick the ANOVA table apart. summary(a); sd(a) Min. 1st Qu. Median Mean 3rd Qu. Max. 3.655 8.117 12.896 12.464 15.293 20.847 [1] 5.919241 # sd of gp a summary(n); sd(n) Min. 1st Qu. Median Mean 3rd Qu. Max. 3.597 11.780 15.221 14.672 20.023 21.437 [1] 6.276581 summary(x); sd(x) Min. 1st Qu. Median Mean 3rd Qu. Max. 11.60 14.68 17.28 17.15 18.01 25.16 [1] 4.046853 Respective means are about 13, 15, 17, so there might be an effect. Medians show a similar pattern. Look at stripchart (or dotplot) of data. Do you see any difference? Why don't the differences among means show more clearly? stripchart(y ~ g, pch=19) Maybe also look at boxplots. Large variability obscures differences in medians. boxplot(y ~ g, col="skyblue2", horizontal=T) Now look at ANOVA table. anova(lm(y ~ g)) Analysis of Variance Table Response: y Df Sum Sq Mean Sq F value Pr(>F) g 2 16.65 8.324 0.2472 0.7832 Residuals 21 707.07 33.670 Residual (Error) line has huge Sum of Squares, so large Mean Square. F-statistic is ratio of MS(Group) to MS(Resid). So large MS(Error) makes the F-statistic small, hence P-value large, leading to a non-significant result. If you had more data, then DF's would be larger, MS(Error) smaller, F-larger, P-value smaller. Alternatively, if group variances were smaller, then MS(Error) might be small enough for a significant effect---even with the current sample sizes. Here is a plot of the distribution F(2, 21). The observed value of $F$ is shown as a vertical dotted line. The P-value is the area under the density curve to the right of the dotted line.
Teaching students about non-significant results and large effect size Excellent start with @Isabella's Comments. Here are some fake data that might be sufficiently similar to yours for purposes of discussion. I don't know if you use R statistical software, but other ki
32,408
Teaching students about non-significant results and large effect size
$F(2,21)=3.14;p=0.22,η^2=0.30.$ D) anything else The null is "accepted," that there probably is no effect. What does "non-rejection" mean? It can mean two things. First, it could mean you have no knowledge regarding the effect. If you took R.A. Fisher's understanding of a p-value, then the absence of rejection is the same as no added knowledge. If you approached this from a Pearson and Neyman decision-theoretic perspective, then it means that you should behave as if there is no relationship. From a Pearson and Neyman inferential perspective, however, you simply have no findings. The p-value gets knocked around quite a bit because people abuse it and ignore effect size. What it is telling you is that despite the possibly random appearance of a large effect size, it still cannot be shown that it is different from zero. Imagine I am a rookie major league baseball player and I am batting 800 with five at-bats. My effect size is HUGE, but I cannot falsify that my real batting average is 400 $(p<.058).$ The non-rejection of the null with a large observed effect could mean many things. First, it could mean there simply is no effect. If there is literature regarding this that there is an effect, then further investigation is warranted. The result could be a false negative. If there is no literature, it could mean that everyone is getting non-significant findings and so no editor is publishing the findings. So it could be that there is no effect. Second, there could be poor hypothesis or experimental design. It could be that there is an effect but either the hypothesis or the experiment was poorly constructed. For example, in a famous case of Yule's paradox, UC Berkley found that its admissions were gender-biased against women. In fact, the effect was strongly supported though the effect size wasn't necessarily that large. A deeper investigation determined that admissions were gender-biased against men, though again the effect size was small. The poor experimental design resulted in a conclusion that was the opposite of the facts. It could be that the experimental design was too simple. For example, there may be some hidden bias among who is an ex-alcoholic OR there could be a hidden bias among who said "yes" to participate. It is possible that gender matters. It is possible that a whole range of things actually matters, but that the division points into the three groups are a poor division. It could mean that ANOVA was the wrong test. For reaction times, there is a reasonable argument to be made that assumptions are violated. The difficulty is that Frequentist methods of statistical analysis assert that the null is 100% perfectly true. If you reject the null, then to some degree of confidence, you can assert it is not a true statement. However, if the null is not rejected, that does not imply that it is true. Frequentist methods of statistical analysis are a probabilistic form of modus tollens. If A then B, and NOT B, therefore NOT A. However, sentential logic does not imply "If A then B, and B, therefore A." In the case of B is true, then A can be true OR false. While it is true that if A is true then B must be true, we know B is true. If A is false, B can still be true. That is why Fisher held that failure to reject the null was the same as having no knowledge about the topic. Logically, non-rejection of the null implies that either A is true OR A is false. The effect size is irrelevant to that discussion. Since it is a tautology that A is true or false, what you do should not depend on the results of your experiment. If you believe that there should be an effect, then you could, for your own personal utility, expand your investigation. If you do not believe there should be an effect, you could, for your own personal utility, not continue to investigate. However, the results should not factor into your decision. It is as though you had never decided to look in the first place.
Teaching students about non-significant results and large effect size
$F(2,21)=3.14;p=0.22,η^2=0.30.$ D) anything else The null is "accepted," that there probably is no effect. What does "non-rejection" mean? It can mean two things. First, it could mean you have no k
Teaching students about non-significant results and large effect size $F(2,21)=3.14;p=0.22,η^2=0.30.$ D) anything else The null is "accepted," that there probably is no effect. What does "non-rejection" mean? It can mean two things. First, it could mean you have no knowledge regarding the effect. If you took R.A. Fisher's understanding of a p-value, then the absence of rejection is the same as no added knowledge. If you approached this from a Pearson and Neyman decision-theoretic perspective, then it means that you should behave as if there is no relationship. From a Pearson and Neyman inferential perspective, however, you simply have no findings. The p-value gets knocked around quite a bit because people abuse it and ignore effect size. What it is telling you is that despite the possibly random appearance of a large effect size, it still cannot be shown that it is different from zero. Imagine I am a rookie major league baseball player and I am batting 800 with five at-bats. My effect size is HUGE, but I cannot falsify that my real batting average is 400 $(p<.058).$ The non-rejection of the null with a large observed effect could mean many things. First, it could mean there simply is no effect. If there is literature regarding this that there is an effect, then further investigation is warranted. The result could be a false negative. If there is no literature, it could mean that everyone is getting non-significant findings and so no editor is publishing the findings. So it could be that there is no effect. Second, there could be poor hypothesis or experimental design. It could be that there is an effect but either the hypothesis or the experiment was poorly constructed. For example, in a famous case of Yule's paradox, UC Berkley found that its admissions were gender-biased against women. In fact, the effect was strongly supported though the effect size wasn't necessarily that large. A deeper investigation determined that admissions were gender-biased against men, though again the effect size was small. The poor experimental design resulted in a conclusion that was the opposite of the facts. It could be that the experimental design was too simple. For example, there may be some hidden bias among who is an ex-alcoholic OR there could be a hidden bias among who said "yes" to participate. It is possible that gender matters. It is possible that a whole range of things actually matters, but that the division points into the three groups are a poor division. It could mean that ANOVA was the wrong test. For reaction times, there is a reasonable argument to be made that assumptions are violated. The difficulty is that Frequentist methods of statistical analysis assert that the null is 100% perfectly true. If you reject the null, then to some degree of confidence, you can assert it is not a true statement. However, if the null is not rejected, that does not imply that it is true. Frequentist methods of statistical analysis are a probabilistic form of modus tollens. If A then B, and NOT B, therefore NOT A. However, sentential logic does not imply "If A then B, and B, therefore A." In the case of B is true, then A can be true OR false. While it is true that if A is true then B must be true, we know B is true. If A is false, B can still be true. That is why Fisher held that failure to reject the null was the same as having no knowledge about the topic. Logically, non-rejection of the null implies that either A is true OR A is false. The effect size is irrelevant to that discussion. Since it is a tautology that A is true or false, what you do should not depend on the results of your experiment. If you believe that there should be an effect, then you could, for your own personal utility, expand your investigation. If you do not believe there should be an effect, you could, for your own personal utility, not continue to investigate. However, the results should not factor into your decision. It is as though you had never decided to look in the first place.
Teaching students about non-significant results and large effect size $F(2,21)=3.14;p=0.22,η^2=0.30.$ D) anything else The null is "accepted," that there probably is no effect. What does "non-rejection" mean? It can mean two things. First, it could mean you have no k
32,409
Random effects model handling redundancies
As far as I can see with both the GEE or a mixed model for repeated binary observations, you will have the problem that the model will assign a positive probability for a ‘0’ after the first ‘1’ has been observed. In any case, given that you want to get estimates from a mixed effects logistic regression that will have the same interpretation as in the GEE (see here for more info), you could fit the model using the mixed_model() function from the GLMMadaptive package, and then use marginal_coefs(). For an example, see here.
Random effects model handling redundancies
As far as I can see with both the GEE or a mixed model for repeated binary observations, you will have the problem that the model will assign a positive probability for a ‘0’ after the first ‘1’ has b
Random effects model handling redundancies As far as I can see with both the GEE or a mixed model for repeated binary observations, you will have the problem that the model will assign a positive probability for a ‘0’ after the first ‘1’ has been observed. In any case, given that you want to get estimates from a mixed effects logistic regression that will have the same interpretation as in the GEE (see here for more info), you could fit the model using the mixed_model() function from the GLMMadaptive package, and then use marginal_coefs(). For an example, see here.
Random effects model handling redundancies As far as I can see with both the GEE or a mixed model for repeated binary observations, you will have the problem that the model will assign a positive probability for a ‘0’ after the first ‘1’ has b
32,410
Random effects model handling redundancies
Couple of thoughts about this: It seems that a mixed-effect model is fundamentally a 'conditional' probability model, i.e., what is the probability of an event for a subject that is at risk for that event. We know the probability of a '1' after the first '1' is one. Thus, there is no additional information in the subsequent '1' values. It seems that, because subsequent '1' values contain no additional information, they should have no impact on the likelihood function, and thus have no impact on standard errors of likelihood-based estimators, nor the estimates themselves. Indeed, there would be no impact of subsequent '1' values if p(y='1'|x)=1 regardless of model parameter values, as it should be. We might be able to force this behavior (i.e., p(y='1'|x)=1), and retain the desired mean function, by adding an indicator covariate to the model that marks subsequent ones, and by forcing its coefficient to be very large so that effectively p(y='1'|x)=1. As you mentioned, there may also be a way to force the first '1' and subsequent responses to have 100% correlation. But in a binomial model, that is the same as p(y='1'|x)=1 for subsequent responses.
Random effects model handling redundancies
Couple of thoughts about this: It seems that a mixed-effect model is fundamentally a 'conditional' probability model, i.e., what is the probability of an event for a subject that is at risk for that
Random effects model handling redundancies Couple of thoughts about this: It seems that a mixed-effect model is fundamentally a 'conditional' probability model, i.e., what is the probability of an event for a subject that is at risk for that event. We know the probability of a '1' after the first '1' is one. Thus, there is no additional information in the subsequent '1' values. It seems that, because subsequent '1' values contain no additional information, they should have no impact on the likelihood function, and thus have no impact on standard errors of likelihood-based estimators, nor the estimates themselves. Indeed, there would be no impact of subsequent '1' values if p(y='1'|x)=1 regardless of model parameter values, as it should be. We might be able to force this behavior (i.e., p(y='1'|x)=1), and retain the desired mean function, by adding an indicator covariate to the model that marks subsequent ones, and by forcing its coefficient to be very large so that effectively p(y='1'|x)=1. As you mentioned, there may also be a way to force the first '1' and subsequent responses to have 100% correlation. But in a binomial model, that is the same as p(y='1'|x)=1 for subsequent responses.
Random effects model handling redundancies Couple of thoughts about this: It seems that a mixed-effect model is fundamentally a 'conditional' probability model, i.e., what is the probability of an event for a subject that is at risk for that
32,411
Random effects model handling redundancies
I'm not exactly sure what you're trying to do, but can you fit a pooled logistic regression model (https://www.ncbi.nlm.nih.gov/pubmed/2281238)? In this case you would only include 1 during the interval of the terminal event -- it would not repeat after the event has occurred. You would include time in the model in a flexible manner (e.g., expanded using splines).
Random effects model handling redundancies
I'm not exactly sure what you're trying to do, but can you fit a pooled logistic regression model (https://www.ncbi.nlm.nih.gov/pubmed/2281238)? In this case you would only include 1 during the interv
Random effects model handling redundancies I'm not exactly sure what you're trying to do, but can you fit a pooled logistic regression model (https://www.ncbi.nlm.nih.gov/pubmed/2281238)? In this case you would only include 1 during the interval of the terminal event -- it would not repeat after the event has occurred. You would include time in the model in a flexible manner (e.g., expanded using splines).
Random effects model handling redundancies I'm not exactly sure what you're trying to do, but can you fit a pooled logistic regression model (https://www.ncbi.nlm.nih.gov/pubmed/2281238)? In this case you would only include 1 during the interv
32,412
How Many Moments Uniquely Define a Distribution with Finite Support?
Let $F$ be the distribution supported on the numbers $x_1 \lt x_2 \lt \ldots \lt x_n$ that assigns probabilities $p_i \gt 0$ to each $x_i.$ By definition, its (raw) moment of degree $k$ is $$\mu_k = \sum_{i=1}^n p_i x_i^k.$$ I will begin with a series of observations about this situation, each of interest in its own right. A basic tool is the sequence of vectors $\mathbf{x}_k = (x_1^k, x_2^k, \ldots, x_n^k)$ for $k=0, 1, \ldots,n-1.$ Writing $\mathbf{p} = (p_1,p_2,\ldots, p_n),$ each moment can be expressed as a vector product $$\mu_k = \sum_{i=1}^n p_i x_i^k = \mathbf{p}\, \mathbf{x}_k^\prime.$$ The collection $\{\mathbf{x}_0,\mathbf{x}_1, \ldots, \mathbf{x}_{n-1}\}$ is linearly independent. To show this, assume the contrary: that is, let coefficients $c_k$ not all zero be such that $$\sum_{k=0}^{n-1} c_k \mathbf{x}_k = \mathbf{0}.\tag{1}$$ Written out component-by-component, $(1)$ asserts that for each $i=1,2,\ldots, n,$ $$\sum_{k=0}^{n-1} c_k x_i^k = 0.$$ That exhibits each $x_i$ as a root of the polynomial $c(T)=c_{n-1}T^{n-1}+c_{n-2}T^{n-2}+\cdots + c_0.$ Such a polynomial has at most $\operatorname{deg}(c)\le n-1$ distinct roots, contradicting the distinctness of the $n$ $x_i.$ All moments are determined by the first $n$ moments $\mu_0,\mu_1,\ldots,\mu_{n-1}.$ The preceding result shows the vectors $\mathcal{X} = \{\mathbf{x}_k,k=0,1,\ldots, n-1\},$ are a basis for $\mathbb{R}^n.$ Therefore for any $m,$ $\mathbf{x}_m$ is a linear combination of the $\mathbf{x}^k,$ $k=0,1,\ldots,n-1;$ that is, there exist coefficients $\,_ma_k$ (determined solely by the $x_i$) for which $$\mathbf{x}_m = \,_ma_0\mathbf{x}_0 + \,_ma_1\mathbf{x}_1 + \cdots + \,_ma_{n-1}\mathbf{x}_{n-1}.$$ Consequently $$\mu_m = \mathbf{p}\,\mathbf{x}_m^\prime = \mathbf{p}\,\sum_{i=0}^{n-1}\,_ma_k \mathbf{x}_k^\prime = \sum_{i=0}^{n-1}\,_ma_k \mathbf{p}\,\mathbf{x}_k^\prime= \sum_{i=0}^{n-1}\,_ma_k \mu_k.$$ The numbers $x_i$ and the first $n$ moments determine $\mathbf{p}.$ Indeed, the first $n$ moments are the coefficients of $\mathbf{p}$ in the basis dual to $\mathcal X.$ The first $n$ moments of $F$ determine, and are determined by, the distribution shifted by a constant $\lambda.$ This is the distribution supported on $x_1-\lambda, x_2-\lambda, \ldots, x_n-\lambda$ with probabilities $p_i.$ The demonstration is straightforward: use the Binomial theorem to expand $(x_i-\lambda)^k$ in terms of $x_i^0, x_i^1, \ldots, x_i^k.$ Part of the question is whether there exist $n^\prime,$ a positive probability vector $\mathbf{q},$ and support points $y_1\lt y_2\lt \ldots \lt y_{n^\prime},$ determining a distribution $G$ having the same moments as $F.$ Suppose there is. Shift both distributions by $\lambda=-\min(x_1,y_1),$ simplifying the situation to distributions with nonnegative support. By taking $m$ arbitrarily large, the largest support points eventually dominate the moments: $$q_{n^\prime} y_{n^\prime}^m \approx \mu_m \approx p_n x_n^m$$ This is possible only when $q_{n^\prime}=p_n$ and $y_{n^\prime} = x_n.$ Continuing inductively, we conclude $n=n^\prime,$ $\mathbf{q}=\mathbf{p},$ and $\mathbf{x}_1=\mathbf{y}_1:$ that is, $G=F.$ Finally, how many moments need to be known to determine $\mathbf{p}$ and $\mathbf{x}$? Consider the map $f:\mathbb{R}^n\times \mathbb{R}^n\approx \mathbb{R}^{2n}\to\mathbb{R}^{2n}$ defined by $$f(\mathbf{p}^\prime, \mathbf{x}^\prime) = (\mathbf{p}\mathbf{x}_0^\prime, \mathbf{p}\mathbf{x}_1^\prime, \ldots, \mathbf{p}\mathbf{x}_{2n-1}^\prime)^\prime.$$ Its derivative is the $2n\times 2n$ matrix $$Df(\mathbf{p}^\prime, \mathbf{x}^\prime) = \pmatrix{1 & \cdots & 1 & 0 & \cdots & 0 \\ x_1 & \cdots & x_n & p_1 & \cdots & p_n \\ x_1^2 & \cdots & x_n^2 & 2p_1x_1 & \cdots & 2p_n x_n \\ \vdots & \cdots & \vdots & \vdots & \cdots & \vdots \\ x_1^{2n-1} & \cdots & x_n^{2n-1} & (2n-1)p_1x_1^{2n-2} & \cdots & (2n-1)p_nx_n^{2n-2}}$$ with a Vandermonde-like structure, enabling us to obtain a simple formula for its determinant, $$\operatorname{Det}\left(Df(\mathbf{p}^\prime, \mathbf{x}^\prime)\right) = -(p_1p_2\cdots p_n)^{2n} \left(\prod_{1\le i\lt j \le n}(x_i-x_j)\right)^4.$$ Because none of the $p_i$ is zero and all the $x_i$ are distinct, this is nonzero. The Inverse Function Theorem implies $f$ is locally invertible: that is, provided $\mathbf{\mu}=(\mu_0,\mu_1,\ldots,\mu_{2n-1})$ is in the range of $f$, there exists an inverse $f^{-1}\subset\mathbb{R}^n\times \mathbb{R}^n$ in a neighborhood of $\mathbf{\mu}.$ That is, The first $2n$ moments $\mu_0,\mu_1,\ldots,\mu_{2n-1}$ determine a discrete set of solutions $(\mathbf{p},\mathbf{x})$ corresponding to those moments. As we have already shown, all such solutions correspond to the same distribution: they differ only by permuting the indexes $1,2,\ldots, n$ of the variables.
How Many Moments Uniquely Define a Distribution with Finite Support?
Let $F$ be the distribution supported on the numbers $x_1 \lt x_2 \lt \ldots \lt x_n$ that assigns probabilities $p_i \gt 0$ to each $x_i.$ By definition, its (raw) moment of degree $k$ is $$\mu_k =
How Many Moments Uniquely Define a Distribution with Finite Support? Let $F$ be the distribution supported on the numbers $x_1 \lt x_2 \lt \ldots \lt x_n$ that assigns probabilities $p_i \gt 0$ to each $x_i.$ By definition, its (raw) moment of degree $k$ is $$\mu_k = \sum_{i=1}^n p_i x_i^k.$$ I will begin with a series of observations about this situation, each of interest in its own right. A basic tool is the sequence of vectors $\mathbf{x}_k = (x_1^k, x_2^k, \ldots, x_n^k)$ for $k=0, 1, \ldots,n-1.$ Writing $\mathbf{p} = (p_1,p_2,\ldots, p_n),$ each moment can be expressed as a vector product $$\mu_k = \sum_{i=1}^n p_i x_i^k = \mathbf{p}\, \mathbf{x}_k^\prime.$$ The collection $\{\mathbf{x}_0,\mathbf{x}_1, \ldots, \mathbf{x}_{n-1}\}$ is linearly independent. To show this, assume the contrary: that is, let coefficients $c_k$ not all zero be such that $$\sum_{k=0}^{n-1} c_k \mathbf{x}_k = \mathbf{0}.\tag{1}$$ Written out component-by-component, $(1)$ asserts that for each $i=1,2,\ldots, n,$ $$\sum_{k=0}^{n-1} c_k x_i^k = 0.$$ That exhibits each $x_i$ as a root of the polynomial $c(T)=c_{n-1}T^{n-1}+c_{n-2}T^{n-2}+\cdots + c_0.$ Such a polynomial has at most $\operatorname{deg}(c)\le n-1$ distinct roots, contradicting the distinctness of the $n$ $x_i.$ All moments are determined by the first $n$ moments $\mu_0,\mu_1,\ldots,\mu_{n-1}.$ The preceding result shows the vectors $\mathcal{X} = \{\mathbf{x}_k,k=0,1,\ldots, n-1\},$ are a basis for $\mathbb{R}^n.$ Therefore for any $m,$ $\mathbf{x}_m$ is a linear combination of the $\mathbf{x}^k,$ $k=0,1,\ldots,n-1;$ that is, there exist coefficients $\,_ma_k$ (determined solely by the $x_i$) for which $$\mathbf{x}_m = \,_ma_0\mathbf{x}_0 + \,_ma_1\mathbf{x}_1 + \cdots + \,_ma_{n-1}\mathbf{x}_{n-1}.$$ Consequently $$\mu_m = \mathbf{p}\,\mathbf{x}_m^\prime = \mathbf{p}\,\sum_{i=0}^{n-1}\,_ma_k \mathbf{x}_k^\prime = \sum_{i=0}^{n-1}\,_ma_k \mathbf{p}\,\mathbf{x}_k^\prime= \sum_{i=0}^{n-1}\,_ma_k \mu_k.$$ The numbers $x_i$ and the first $n$ moments determine $\mathbf{p}.$ Indeed, the first $n$ moments are the coefficients of $\mathbf{p}$ in the basis dual to $\mathcal X.$ The first $n$ moments of $F$ determine, and are determined by, the distribution shifted by a constant $\lambda.$ This is the distribution supported on $x_1-\lambda, x_2-\lambda, \ldots, x_n-\lambda$ with probabilities $p_i.$ The demonstration is straightforward: use the Binomial theorem to expand $(x_i-\lambda)^k$ in terms of $x_i^0, x_i^1, \ldots, x_i^k.$ Part of the question is whether there exist $n^\prime,$ a positive probability vector $\mathbf{q},$ and support points $y_1\lt y_2\lt \ldots \lt y_{n^\prime},$ determining a distribution $G$ having the same moments as $F.$ Suppose there is. Shift both distributions by $\lambda=-\min(x_1,y_1),$ simplifying the situation to distributions with nonnegative support. By taking $m$ arbitrarily large, the largest support points eventually dominate the moments: $$q_{n^\prime} y_{n^\prime}^m \approx \mu_m \approx p_n x_n^m$$ This is possible only when $q_{n^\prime}=p_n$ and $y_{n^\prime} = x_n.$ Continuing inductively, we conclude $n=n^\prime,$ $\mathbf{q}=\mathbf{p},$ and $\mathbf{x}_1=\mathbf{y}_1:$ that is, $G=F.$ Finally, how many moments need to be known to determine $\mathbf{p}$ and $\mathbf{x}$? Consider the map $f:\mathbb{R}^n\times \mathbb{R}^n\approx \mathbb{R}^{2n}\to\mathbb{R}^{2n}$ defined by $$f(\mathbf{p}^\prime, \mathbf{x}^\prime) = (\mathbf{p}\mathbf{x}_0^\prime, \mathbf{p}\mathbf{x}_1^\prime, \ldots, \mathbf{p}\mathbf{x}_{2n-1}^\prime)^\prime.$$ Its derivative is the $2n\times 2n$ matrix $$Df(\mathbf{p}^\prime, \mathbf{x}^\prime) = \pmatrix{1 & \cdots & 1 & 0 & \cdots & 0 \\ x_1 & \cdots & x_n & p_1 & \cdots & p_n \\ x_1^2 & \cdots & x_n^2 & 2p_1x_1 & \cdots & 2p_n x_n \\ \vdots & \cdots & \vdots & \vdots & \cdots & \vdots \\ x_1^{2n-1} & \cdots & x_n^{2n-1} & (2n-1)p_1x_1^{2n-2} & \cdots & (2n-1)p_nx_n^{2n-2}}$$ with a Vandermonde-like structure, enabling us to obtain a simple formula for its determinant, $$\operatorname{Det}\left(Df(\mathbf{p}^\prime, \mathbf{x}^\prime)\right) = -(p_1p_2\cdots p_n)^{2n} \left(\prod_{1\le i\lt j \le n}(x_i-x_j)\right)^4.$$ Because none of the $p_i$ is zero and all the $x_i$ are distinct, this is nonzero. The Inverse Function Theorem implies $f$ is locally invertible: that is, provided $\mathbf{\mu}=(\mu_0,\mu_1,\ldots,\mu_{2n-1})$ is in the range of $f$, there exists an inverse $f^{-1}\subset\mathbb{R}^n\times \mathbb{R}^n$ in a neighborhood of $\mathbf{\mu}.$ That is, The first $2n$ moments $\mu_0,\mu_1,\ldots,\mu_{2n-1}$ determine a discrete set of solutions $(\mathbf{p},\mathbf{x})$ corresponding to those moments. As we have already shown, all such solutions correspond to the same distribution: they differ only by permuting the indexes $1,2,\ldots, n$ of the variables.
How Many Moments Uniquely Define a Distribution with Finite Support? Let $F$ be the distribution supported on the numbers $x_1 \lt x_2 \lt \ldots \lt x_n$ that assigns probabilities $p_i \gt 0$ to each $x_i.$ By definition, its (raw) moment of degree $k$ is $$\mu_k =
32,413
Expected value notation in GAN loss
$E_{x\sim p(x)}[f(X)]$ means the expected value of $f(X)$ if its assumed to be distributed wrt $p(x)$, e.g. for a continuous distribution we have: $$E_{x\sim p(x)}[f(X)]=\int f(x)p(x)dx$$ It's used when the distribution of $x$ subject to change in an optimization problem. Specifically, in the paper, authors have two distributions (in page 5) $p_g$ and $p_{data}$. Edit: And, the $x$ in the subscript of the expected value notation is not a realization. It's the random variable; or more specifically, in the paper it is the random vector, $\mathbf{x}$ (It's also in bold in Page 5).
Expected value notation in GAN loss
$E_{x\sim p(x)}[f(X)]$ means the expected value of $f(X)$ if its assumed to be distributed wrt $p(x)$, e.g. for a continuous distribution we have: $$E_{x\sim p(x)}[f(X)]=\int f(x)p(x)dx$$ It's used wh
Expected value notation in GAN loss $E_{x\sim p(x)}[f(X)]$ means the expected value of $f(X)$ if its assumed to be distributed wrt $p(x)$, e.g. for a continuous distribution we have: $$E_{x\sim p(x)}[f(X)]=\int f(x)p(x)dx$$ It's used when the distribution of $x$ subject to change in an optimization problem. Specifically, in the paper, authors have two distributions (in page 5) $p_g$ and $p_{data}$. Edit: And, the $x$ in the subscript of the expected value notation is not a realization. It's the random variable; or more specifically, in the paper it is the random vector, $\mathbf{x}$ (It's also in bold in Page 5).
Expected value notation in GAN loss $E_{x\sim p(x)}[f(X)]$ means the expected value of $f(X)$ if its assumed to be distributed wrt $p(x)$, e.g. for a continuous distribution we have: $$E_{x\sim p(x)}[f(X)]=\int f(x)p(x)dx$$ It's used wh
32,414
Multiple comparisons correction for dependent comparisons
Let's consider a simpler, but closely related, problem. Assume you have a vector $x$ whose entries have a correlation matrix $R$. If $R$ is diagonal, then the variance of the sample mean of $x$ is $\sigma^2_{\bar{x}} = \sum \sigma^2_i/n^2$. If all the $\sigma^2_i$ are equal, this reduces to the more commonly seen $\sigma^2/n$, and we can rearrange terms to get the sample size as a function of the two variances: $$n = \sigma^2 / \sigma^2_{\bar{x}} $$ If, however, $R$ is not diagonal, then the variance of $\bar{x}$ is equal to: $$\sigma^2_{\bar{x}} = \sum_i\sum_j\sigma_i\sigma_jr_{ij}/n^2$$ In the case where $\sigma_i = \sigma_j \space \forall \space i,j$, this reduces to: $$\sigma^2_{\bar{x}} = \sigma^2 \sum_i\sum_jr_{ij}/n^2$$ By analogy with the expression for the sample size in the uncorrelated case, the ratio between this and $\sigma^2$ is the "effective sample size" $n_{ess}$: $$n_{ess} = \sigma^2 / \sigma^2_{\bar{x}} = {\sigma^2 \over \sigma^2\sum_i\sum_jr_{ij}/n^2} = {n^2 \over \sum_i\sum_jr_{ij}} $$ If $R$ is diagonal, then $\sum_i\sum_jr_{ij} = n$, as the $n$ diagonal elements of $R$ equal $1$ and all the off-diagonal elements equal $0$, and the effective sample size equals the actual sample size, as we would expect. Comparing the effective sample size to the actual sample size provides an estimate of the impact of nonzero correlation on your estimation problem. Clearly, if your correlations are high (either positive or negative), or you have a lot of them, the effects can be pretty substantial. The relationship between this example and your case is as follows. Instead of "sample size", consider $n$ as the number of quantiles being estimated. The basic Bonferroni correction adjusts for $n$ comparisons. Because the estimates of quantiles are known to be correlated, however, the Bonferroni correction will (in the case of positive correlations) be too pessimistic (even for Bonferroni, which in general is quite pessimistic to begin with). To see this, consider a situation where you are estimating ten quantiles and the errors in the quantile estimates are perfectly correlated. For example, assume you are estimating the quantiles of a Normal distribution with known variance equal to one; your estimates will all be of the form $\bar{x} \pm k$, where $k$ depends upon the quantile in question. The errors in your quantile estimates will all be exactly equal to the error in your estimate of the mean, so the collection of pointwise confidence intervals will equal the simultaneous confidence interval. In effect, you have just one estimate, but Bonferroni (without correction) will adjust your confidence intervals as though you had ten estimates, making it wider than it ought to be. The above calculation, with $r_{ij}=1 \space \forall \space i,j$, will result in $n_{ess} = 1$, as it should, and the Bonferroni interval using the effective sample size will, in this case, be correct. As for the source, it's in the paper (Solow-Polasky) linked to in the link you provide; the formula is equation (7), although the notation is completely different.
Multiple comparisons correction for dependent comparisons
Let's consider a simpler, but closely related, problem. Assume you have a vector $x$ whose entries have a correlation matrix $R$. If $R$ is diagonal, then the variance of the sample mean of $x$ is $
Multiple comparisons correction for dependent comparisons Let's consider a simpler, but closely related, problem. Assume you have a vector $x$ whose entries have a correlation matrix $R$. If $R$ is diagonal, then the variance of the sample mean of $x$ is $\sigma^2_{\bar{x}} = \sum \sigma^2_i/n^2$. If all the $\sigma^2_i$ are equal, this reduces to the more commonly seen $\sigma^2/n$, and we can rearrange terms to get the sample size as a function of the two variances: $$n = \sigma^2 / \sigma^2_{\bar{x}} $$ If, however, $R$ is not diagonal, then the variance of $\bar{x}$ is equal to: $$\sigma^2_{\bar{x}} = \sum_i\sum_j\sigma_i\sigma_jr_{ij}/n^2$$ In the case where $\sigma_i = \sigma_j \space \forall \space i,j$, this reduces to: $$\sigma^2_{\bar{x}} = \sigma^2 \sum_i\sum_jr_{ij}/n^2$$ By analogy with the expression for the sample size in the uncorrelated case, the ratio between this and $\sigma^2$ is the "effective sample size" $n_{ess}$: $$n_{ess} = \sigma^2 / \sigma^2_{\bar{x}} = {\sigma^2 \over \sigma^2\sum_i\sum_jr_{ij}/n^2} = {n^2 \over \sum_i\sum_jr_{ij}} $$ If $R$ is diagonal, then $\sum_i\sum_jr_{ij} = n$, as the $n$ diagonal elements of $R$ equal $1$ and all the off-diagonal elements equal $0$, and the effective sample size equals the actual sample size, as we would expect. Comparing the effective sample size to the actual sample size provides an estimate of the impact of nonzero correlation on your estimation problem. Clearly, if your correlations are high (either positive or negative), or you have a lot of them, the effects can be pretty substantial. The relationship between this example and your case is as follows. Instead of "sample size", consider $n$ as the number of quantiles being estimated. The basic Bonferroni correction adjusts for $n$ comparisons. Because the estimates of quantiles are known to be correlated, however, the Bonferroni correction will (in the case of positive correlations) be too pessimistic (even for Bonferroni, which in general is quite pessimistic to begin with). To see this, consider a situation where you are estimating ten quantiles and the errors in the quantile estimates are perfectly correlated. For example, assume you are estimating the quantiles of a Normal distribution with known variance equal to one; your estimates will all be of the form $\bar{x} \pm k$, where $k$ depends upon the quantile in question. The errors in your quantile estimates will all be exactly equal to the error in your estimate of the mean, so the collection of pointwise confidence intervals will equal the simultaneous confidence interval. In effect, you have just one estimate, but Bonferroni (without correction) will adjust your confidence intervals as though you had ten estimates, making it wider than it ought to be. The above calculation, with $r_{ij}=1 \space \forall \space i,j$, will result in $n_{ess} = 1$, as it should, and the Bonferroni interval using the effective sample size will, in this case, be correct. As for the source, it's in the paper (Solow-Polasky) linked to in the link you provide; the formula is equation (7), although the notation is completely different.
Multiple comparisons correction for dependent comparisons Let's consider a simpler, but closely related, problem. Assume you have a vector $x$ whose entries have a correlation matrix $R$. If $R$ is diagonal, then the variance of the sample mean of $x$ is $
32,415
When to prefer the moment generating function to the characteristic function?
That's a good question, but a broad one, so I can't promise I'll say everything about it that should be said. The short answer is that rival techniques differ not in what they can do, but in how neatly they can do it. Characteristic functions require extra caution because of the role of complex numbers. It's not even that the student needs to know about complex numbers; it's that the calculus involved has subtle pitfalls. For example, I can get a Normal distribution's MGF just by completing the square in a variable-shifting substitution, but a lot of sources carelessly pretend the approach using characteristic functions is just as easy. It isn't, because the famous normalisation of the Gaussian integral says nothing about integration on $ic+\mathbb{R}$ with $c\in\mathbb{R}\backslash\{ 0\}$. Oh, we can still evaluate the integral if we're careful with contours, and in fact there's an even easier approach, in which we show by integrating by parts that an $N(0,\,1)$ distribution's characteristic function $\phi (t)$ satisfies $\dot{\phi}=-t\phi$. But the MGF approach is even simpler, and most of the distributions students need early on have a convergent MGF on either a line segment (e.g. Laplace) or half-line (e.g. Gamma, geometric, negative binomial), or the whole of $\mathbb{R}$ (e.g. Beta, binomial, Poisson, Normal). Either way, that's enough to study moments. I don't think there's anything you can do only with the MGF, but you use what's easiest for the task at hand. Here's one for you: what's the easiest way to compute the moments of a Poisson distribution? I'd argue it's to use a different technique again, the probability-generating function $G(t)=\mathbb{E}t^X=\exp \lambda (t-1)$. Then the falling Pochhammer symbol $(X)_k$ gives $\mathbb{E}(X)_k=G^{(k)}(1)=\lambda^k$. In general it's usually worth using the PGF for discrete distributions, the MGF for continuous distributions that either are bounded or have superexponential decay in the PDF's tails, and the characteristic function when you really need it. And depending on the question you're asking, you may instead find it prudent to use the cumulant generating function, be it defined as the logarithm of the MGF or CF. For example, I'll leave it as an exercise that the log-MGF definition of cumulants for the maximum of $n$ $\operatorname{Exp}(1)$ iids gives $\kappa_m=(m-1)!\sum_{k=1}^n k^{-m}$, which provides a much easier computation of the mean and variance (respectively $\kappa_1$ and $\kappa_2$) than if you'd written them in terms of moments.
When to prefer the moment generating function to the characteristic function?
That's a good question, but a broad one, so I can't promise I'll say everything about it that should be said. The short answer is that rival techniques differ not in what they can do, but in how neatl
When to prefer the moment generating function to the characteristic function? That's a good question, but a broad one, so I can't promise I'll say everything about it that should be said. The short answer is that rival techniques differ not in what they can do, but in how neatly they can do it. Characteristic functions require extra caution because of the role of complex numbers. It's not even that the student needs to know about complex numbers; it's that the calculus involved has subtle pitfalls. For example, I can get a Normal distribution's MGF just by completing the square in a variable-shifting substitution, but a lot of sources carelessly pretend the approach using characteristic functions is just as easy. It isn't, because the famous normalisation of the Gaussian integral says nothing about integration on $ic+\mathbb{R}$ with $c\in\mathbb{R}\backslash\{ 0\}$. Oh, we can still evaluate the integral if we're careful with contours, and in fact there's an even easier approach, in which we show by integrating by parts that an $N(0,\,1)$ distribution's characteristic function $\phi (t)$ satisfies $\dot{\phi}=-t\phi$. But the MGF approach is even simpler, and most of the distributions students need early on have a convergent MGF on either a line segment (e.g. Laplace) or half-line (e.g. Gamma, geometric, negative binomial), or the whole of $\mathbb{R}$ (e.g. Beta, binomial, Poisson, Normal). Either way, that's enough to study moments. I don't think there's anything you can do only with the MGF, but you use what's easiest for the task at hand. Here's one for you: what's the easiest way to compute the moments of a Poisson distribution? I'd argue it's to use a different technique again, the probability-generating function $G(t)=\mathbb{E}t^X=\exp \lambda (t-1)$. Then the falling Pochhammer symbol $(X)_k$ gives $\mathbb{E}(X)_k=G^{(k)}(1)=\lambda^k$. In general it's usually worth using the PGF for discrete distributions, the MGF for continuous distributions that either are bounded or have superexponential decay in the PDF's tails, and the characteristic function when you really need it. And depending on the question you're asking, you may instead find it prudent to use the cumulant generating function, be it defined as the logarithm of the MGF or CF. For example, I'll leave it as an exercise that the log-MGF definition of cumulants for the maximum of $n$ $\operatorname{Exp}(1)$ iids gives $\kappa_m=(m-1)!\sum_{k=1}^n k^{-m}$, which provides a much easier computation of the mean and variance (respectively $\kappa_1$ and $\kappa_2$) than if you'd written them in terms of moments.
When to prefer the moment generating function to the characteristic function? That's a good question, but a broad one, so I can't promise I'll say everything about it that should be said. The short answer is that rival techniques differ not in what they can do, but in how neatl
32,416
When to prefer the moment generating function to the characteristic function?
If your random variable has all of its moments, then the MGF exists, and is generally at least as useful as the characteristic function for proofs. To answer your question, when the MGF exists, it provides the basis for many extreme-value calculations related to $X$. The simplest of which is (for $t\geq 0$), $$P(X>r)=P(e^{tX}>e^{tr})\leq M_X(t)/e^{tr}.$$ Here, the r.h.s. can now be minimized over $t$. Strangely, this bound is one of the few simple ways we know of to get estimates on rare events. The general area of this is Large Deviations Theory, where one must do a ton of work to obtain better (tighter) bounds. A common example of this is looking at $S_n=X_1+\cdots + X_n$, so that when the MGF of $X_1$ exists, then one can show $P(|S_n-E[X]|>nr)$ decays exponentially in $n$. This is more generally known as Cramer's Theorem. Here are some compact notes on this.
When to prefer the moment generating function to the characteristic function?
If your random variable has all of its moments, then the MGF exists, and is generally at least as useful as the characteristic function for proofs. To answer your question, when the MGF exists, it pro
When to prefer the moment generating function to the characteristic function? If your random variable has all of its moments, then the MGF exists, and is generally at least as useful as the characteristic function for proofs. To answer your question, when the MGF exists, it provides the basis for many extreme-value calculations related to $X$. The simplest of which is (for $t\geq 0$), $$P(X>r)=P(e^{tX}>e^{tr})\leq M_X(t)/e^{tr}.$$ Here, the r.h.s. can now be minimized over $t$. Strangely, this bound is one of the few simple ways we know of to get estimates on rare events. The general area of this is Large Deviations Theory, where one must do a ton of work to obtain better (tighter) bounds. A common example of this is looking at $S_n=X_1+\cdots + X_n$, so that when the MGF of $X_1$ exists, then one can show $P(|S_n-E[X]|>nr)$ decays exponentially in $n$. This is more generally known as Cramer's Theorem. Here are some compact notes on this.
When to prefer the moment generating function to the characteristic function? If your random variable has all of its moments, then the MGF exists, and is generally at least as useful as the characteristic function for proofs. To answer your question, when the MGF exists, it pro
32,417
What is a sensible order for parameter tuning in neural networks?
There are so many aspects one could possibly change in a deep neural network that it is generally not feasible to do a grid search over all of them. True. But an alternative to that, i.e. random search is feasible in many cases. Please have a look at this post for an interesting explanation. Hence, when tuning the various components of a neural network by hand, what is considered to be a sensible order? The hyper-parameters interact but for practical purposes they can be tuned independently, as these interactions have no apparent structure. So, the order in which the hyper-parameters need to be tuned is largely subjective. But one of the recommendations from this paper, which I do follow is, one should tune the learning rate first. That saves a lot of experimentation. For illustration of the importance of the learning rate have a look at the image taken from the linked paper. They have experimented with different variants of LSTM over three datasets and have presented the performance over the test set. The chart shows what fraction of the test set performance variance can be attributed to different hyper-parameters They also show that optimal value of learning rate is dependent on the dataset. So, if I have to answer the order that I follow for training neural networks I would stick with this: a) Optimizer b) Learning rate c) batch size d) Input noise e) Network design -number of hidden layers and number of neurons f) Regularizers - (L1, L2, dropout etc.) But, again, every dataset is different and hyper-parameters will surely be dependent on that. So, for every problem one approach won't do. Plotting the error will give the feel for the dataset and help in finding the 'optimal' hyper-parameters. Some posts that might be useful: a) In what order should we tune hyperparameters in Neural Networks? b) Hyperparameter tuning for machine learning models. c) A Conceptual Explanation of Bayesian Hyperparameter Optimization for Machine Learning d) Hyper parameters tuning: Random search vs Bayesian optimization e) hyperparameter tuning in neural networks
What is a sensible order for parameter tuning in neural networks?
There are so many aspects one could possibly change in a deep neural network that it is generally not feasible to do a grid search over all of them. True. But an alternative to that, i.e. random sear
What is a sensible order for parameter tuning in neural networks? There are so many aspects one could possibly change in a deep neural network that it is generally not feasible to do a grid search over all of them. True. But an alternative to that, i.e. random search is feasible in many cases. Please have a look at this post for an interesting explanation. Hence, when tuning the various components of a neural network by hand, what is considered to be a sensible order? The hyper-parameters interact but for practical purposes they can be tuned independently, as these interactions have no apparent structure. So, the order in which the hyper-parameters need to be tuned is largely subjective. But one of the recommendations from this paper, which I do follow is, one should tune the learning rate first. That saves a lot of experimentation. For illustration of the importance of the learning rate have a look at the image taken from the linked paper. They have experimented with different variants of LSTM over three datasets and have presented the performance over the test set. The chart shows what fraction of the test set performance variance can be attributed to different hyper-parameters They also show that optimal value of learning rate is dependent on the dataset. So, if I have to answer the order that I follow for training neural networks I would stick with this: a) Optimizer b) Learning rate c) batch size d) Input noise e) Network design -number of hidden layers and number of neurons f) Regularizers - (L1, L2, dropout etc.) But, again, every dataset is different and hyper-parameters will surely be dependent on that. So, for every problem one approach won't do. Plotting the error will give the feel for the dataset and help in finding the 'optimal' hyper-parameters. Some posts that might be useful: a) In what order should we tune hyperparameters in Neural Networks? b) Hyperparameter tuning for machine learning models. c) A Conceptual Explanation of Bayesian Hyperparameter Optimization for Machine Learning d) Hyper parameters tuning: Random search vs Bayesian optimization e) hyperparameter tuning in neural networks
What is a sensible order for parameter tuning in neural networks? There are so many aspects one could possibly change in a deep neural network that it is generally not feasible to do a grid search over all of them. True. But an alternative to that, i.e. random sear
32,418
Project new point into MDS space
If you're using Euclidean distances, then classical MDS is equivalent to PCA, which readily defines a mapping into the low dimensional space, as amoeba mentioned. There should be various threads on this site describing how to do this. Otherwise, De Silva and Tenenbaum (2004) describe how to perform this mapping for classical MDS with arbitrary distances (note that it won't work for non-classical variants of MDS, e.g. non-metric MDS, variants that minimize the stress criterion, etc.). They call this procedure "distance-based triangulation". Although not originally formulated as such, it turns out to work by using the Nyström approximation, which is a way to approximate the eigenvalues/eigenvectors of a large matrix using a smaller submatrix (see Platt 2005). Suppose we have $n$ training points. The squared distance between points $i$ and $j$ is stored in the $(i,j)$th entry of matrix $\Delta_n$. We use these distances with classical MDS to compute a $k$-dimensional embedding. Let each column of $k \times n$ matrix $L_k$ contain the low-dimensional embedding coordinates of a training point. Let $L_k^\#$ denote the transpose of the pseudoinverse of $L_k$. Instead of starting from scratch, this can be computed using components that were originally used to compute $L_k$ (see the paper for details). Let $\vec{\delta}_i$ denote the $i$th column of $\Delta_n$ (containing the squared distances from point $i$ to all other points), and let $\vec{\delta}_\mu = \frac{1}{n} \sum_{i=1}^n \vec{\delta}_i$ denote the mean of the columns. Now, suppose we want to map a new point $a$ into the low dimensional space. Compute vector $\vec{\delta}_a$, containing the squared distance from $a$ to every training point. The low dimensional emedding coordinates of $a$ are then given by: $$\vec{x}_a = -\frac{1}{2} L_k^\# (\vec{\delta}_a - \vec{\delta}_\mu)$$ References: De Silva and Tenenbaum (2004). Sparse multidimensional scaling using landmark points. Platt (2005). FastMap, MetricMap, and Landmark MDS are all Nystrom Algorithms.
Project new point into MDS space
If you're using Euclidean distances, then classical MDS is equivalent to PCA, which readily defines a mapping into the low dimensional space, as amoeba mentioned. There should be various threads on th
Project new point into MDS space If you're using Euclidean distances, then classical MDS is equivalent to PCA, which readily defines a mapping into the low dimensional space, as amoeba mentioned. There should be various threads on this site describing how to do this. Otherwise, De Silva and Tenenbaum (2004) describe how to perform this mapping for classical MDS with arbitrary distances (note that it won't work for non-classical variants of MDS, e.g. non-metric MDS, variants that minimize the stress criterion, etc.). They call this procedure "distance-based triangulation". Although not originally formulated as such, it turns out to work by using the Nyström approximation, which is a way to approximate the eigenvalues/eigenvectors of a large matrix using a smaller submatrix (see Platt 2005). Suppose we have $n$ training points. The squared distance between points $i$ and $j$ is stored in the $(i,j)$th entry of matrix $\Delta_n$. We use these distances with classical MDS to compute a $k$-dimensional embedding. Let each column of $k \times n$ matrix $L_k$ contain the low-dimensional embedding coordinates of a training point. Let $L_k^\#$ denote the transpose of the pseudoinverse of $L_k$. Instead of starting from scratch, this can be computed using components that were originally used to compute $L_k$ (see the paper for details). Let $\vec{\delta}_i$ denote the $i$th column of $\Delta_n$ (containing the squared distances from point $i$ to all other points), and let $\vec{\delta}_\mu = \frac{1}{n} \sum_{i=1}^n \vec{\delta}_i$ denote the mean of the columns. Now, suppose we want to map a new point $a$ into the low dimensional space. Compute vector $\vec{\delta}_a$, containing the squared distance from $a$ to every training point. The low dimensional emedding coordinates of $a$ are then given by: $$\vec{x}_a = -\frac{1}{2} L_k^\# (\vec{\delta}_a - \vec{\delta}_\mu)$$ References: De Silva and Tenenbaum (2004). Sparse multidimensional scaling using landmark points. Platt (2005). FastMap, MetricMap, and Landmark MDS are all Nystrom Algorithms.
Project new point into MDS space If you're using Euclidean distances, then classical MDS is equivalent to PCA, which readily defines a mapping into the low dimensional space, as amoeba mentioned. There should be various threads on th
32,419
Project new point into MDS space
As per amoeba's comment, another practical solution in R would be to use the stats::prcomp() and its associated predict() method if using the Euclidean distance for your MDS: set.seed(1) x <- matrix(rnorm(3*10), ncol = 3) # New data point to be projected A <- c(1, 2, 3) > predict(prcomp(x, rank. = 2), matrix(A, nrow = 1)) PC1 PC2 [1,] -2.759456 -0.5927178
Project new point into MDS space
As per amoeba's comment, another practical solution in R would be to use the stats::prcomp() and its associated predict() method if using the Euclidean distance for your MDS: set.seed(1) x <- matrix(r
Project new point into MDS space As per amoeba's comment, another practical solution in R would be to use the stats::prcomp() and its associated predict() method if using the Euclidean distance for your MDS: set.seed(1) x <- matrix(rnorm(3*10), ncol = 3) # New data point to be projected A <- c(1, 2, 3) > predict(prcomp(x, rank. = 2), matrix(A, nrow = 1)) PC1 PC2 [1,] -2.759456 -0.5927178
Project new point into MDS space As per amoeba's comment, another practical solution in R would be to use the stats::prcomp() and its associated predict() method if using the Euclidean distance for your MDS: set.seed(1) x <- matrix(r
32,420
Can F1-Score be higher than accuracy?
This is definitely possible, and not strange at all. Recall how accuracy and the F1 score are defined: $$\text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN}\quad\text{and}\quad \text{F1}=\frac{2TP}{2TP+FP+FN}. $$ Now, probably the simplest possible way your F1 score can be greater than your accuracy is if you have just two observations, one TRUE and one FALSE. Suppose you classify both as TRUE. Then $$ TP=1,\quad TN=0,\quad FP=1,\quad FN=0, $$ so $$\text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN}=\frac{1+0}{1+0+1+0}=\frac{1}{2}$$ and $$\text{F1}=\frac{2TP}{2TP+FP+FN}=\frac{2\times 1}{2\times 1+1+0}=\frac{2}{3} $$ and there you are. Actually, you can create slightly bigger examples with the following R script. It considers pp TRUE and nn FALSE observations, and rolls out all the different combinations of predictions you might have. (It actually double-counts some constellations, but reducing these out would have made the script less legible.) pp <- 2 nn <- 2 actuals <- c(rep(T,pp),rep(F,nn)) predictions <- expand.grid(lapply(1:(pp+nn),function(xx)c(T,F))) accuracy_and_F1 <- function(actuals,pred) { TP <- sum(actuals & pred) TN <- sum(!actuals & !pred) FP <- sum(!actuals & pred) FN <- sum(actuals & !pred) structure(c((TP+TN)/(TP+TN+FP+FN),2*TP/(2*TP+FP+FN)),.Names=c("Accuracy","F1")) } result <- cbind(predictions, t(apply(predictions,1,function(xx)accuracy_and_F1(actuals,xx)))) result$F1_greater_than_Accuracy <- with(result,F1>Accuracy) result In this example with pp=2 and nn=2, the result is Var1 Var2 Var3 Var4 Accuracy F1 F1_greater_than_Accuracy 1 TRUE TRUE TRUE TRUE 0.50 0.6666667 TRUE 2 FALSE TRUE TRUE TRUE 0.25 0.4000000 TRUE 3 TRUE FALSE TRUE TRUE 0.25 0.4000000 TRUE 4 FALSE FALSE TRUE TRUE 0.00 0.0000000 FALSE 5 TRUE TRUE FALSE TRUE 0.75 0.8000000 TRUE 6 FALSE TRUE FALSE TRUE 0.50 0.5000000 FALSE 7 TRUE FALSE FALSE TRUE 0.50 0.5000000 FALSE 8 FALSE FALSE FALSE TRUE 0.25 0.0000000 FALSE 9 TRUE TRUE TRUE FALSE 0.75 0.8000000 TRUE 10 FALSE TRUE TRUE FALSE 0.50 0.5000000 FALSE 11 TRUE FALSE TRUE FALSE 0.50 0.5000000 FALSE 12 FALSE FALSE TRUE FALSE 0.25 0.0000000 FALSE 13 TRUE TRUE FALSE FALSE 1.00 1.0000000 FALSE 14 FALSE TRUE FALSE FALSE 0.75 0.6666667 FALSE 15 TRUE FALSE FALSE FALSE 0.75 0.6666667 FALSE 16 FALSE FALSE FALSE FALSE 0.50 0.0000000 FALSE So we see that having an F1 score greater than accuracy is a pretty common occurrence in this simple example already. That said, accuracy is not a very good measure of predictive power: Why is accuracy not the best measure for assessing classification models? And every criticism against accuracy there applies equally to the F1 (and every other F$\beta$) score.
Can F1-Score be higher than accuracy?
This is definitely possible, and not strange at all. Recall how accuracy and the F1 score are defined: $$\text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN}\quad\text{and}\quad \text{F1}=\frac{2TP}{2TP+FP+FN}.
Can F1-Score be higher than accuracy? This is definitely possible, and not strange at all. Recall how accuracy and the F1 score are defined: $$\text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN}\quad\text{and}\quad \text{F1}=\frac{2TP}{2TP+FP+FN}. $$ Now, probably the simplest possible way your F1 score can be greater than your accuracy is if you have just two observations, one TRUE and one FALSE. Suppose you classify both as TRUE. Then $$ TP=1,\quad TN=0,\quad FP=1,\quad FN=0, $$ so $$\text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN}=\frac{1+0}{1+0+1+0}=\frac{1}{2}$$ and $$\text{F1}=\frac{2TP}{2TP+FP+FN}=\frac{2\times 1}{2\times 1+1+0}=\frac{2}{3} $$ and there you are. Actually, you can create slightly bigger examples with the following R script. It considers pp TRUE and nn FALSE observations, and rolls out all the different combinations of predictions you might have. (It actually double-counts some constellations, but reducing these out would have made the script less legible.) pp <- 2 nn <- 2 actuals <- c(rep(T,pp),rep(F,nn)) predictions <- expand.grid(lapply(1:(pp+nn),function(xx)c(T,F))) accuracy_and_F1 <- function(actuals,pred) { TP <- sum(actuals & pred) TN <- sum(!actuals & !pred) FP <- sum(!actuals & pred) FN <- sum(actuals & !pred) structure(c((TP+TN)/(TP+TN+FP+FN),2*TP/(2*TP+FP+FN)),.Names=c("Accuracy","F1")) } result <- cbind(predictions, t(apply(predictions,1,function(xx)accuracy_and_F1(actuals,xx)))) result$F1_greater_than_Accuracy <- with(result,F1>Accuracy) result In this example with pp=2 and nn=2, the result is Var1 Var2 Var3 Var4 Accuracy F1 F1_greater_than_Accuracy 1 TRUE TRUE TRUE TRUE 0.50 0.6666667 TRUE 2 FALSE TRUE TRUE TRUE 0.25 0.4000000 TRUE 3 TRUE FALSE TRUE TRUE 0.25 0.4000000 TRUE 4 FALSE FALSE TRUE TRUE 0.00 0.0000000 FALSE 5 TRUE TRUE FALSE TRUE 0.75 0.8000000 TRUE 6 FALSE TRUE FALSE TRUE 0.50 0.5000000 FALSE 7 TRUE FALSE FALSE TRUE 0.50 0.5000000 FALSE 8 FALSE FALSE FALSE TRUE 0.25 0.0000000 FALSE 9 TRUE TRUE TRUE FALSE 0.75 0.8000000 TRUE 10 FALSE TRUE TRUE FALSE 0.50 0.5000000 FALSE 11 TRUE FALSE TRUE FALSE 0.50 0.5000000 FALSE 12 FALSE FALSE TRUE FALSE 0.25 0.0000000 FALSE 13 TRUE TRUE FALSE FALSE 1.00 1.0000000 FALSE 14 FALSE TRUE FALSE FALSE 0.75 0.6666667 FALSE 15 TRUE FALSE FALSE FALSE 0.75 0.6666667 FALSE 16 FALSE FALSE FALSE FALSE 0.50 0.0000000 FALSE So we see that having an F1 score greater than accuracy is a pretty common occurrence in this simple example already. That said, accuracy is not a very good measure of predictive power: Why is accuracy not the best measure for assessing classification models? And every criticism against accuracy there applies equally to the F1 (and every other F$\beta$) score.
Can F1-Score be higher than accuracy? This is definitely possible, and not strange at all. Recall how accuracy and the F1 score are defined: $$\text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN}\quad\text{and}\quad \text{F1}=\frac{2TP}{2TP+FP+FN}.
32,421
Understanding gradient boosting
I've answered question 2a on this site before. The answer to 2b, as you suspect, is the same. In general, gradient boosting, when used for classification, fits trees not on the level of the gradient of predicted probabilities, but to the gradient of the predicted log-odds. Because of this, 2b reduces to 2a in principle. As for 1: Here there is an example of ensemble of simple trees (stumps) for regression. So why is the approach with gradient boosting better than a single more complicated tree of greater depth? The power of gradient boosting is that it allows us to build predictive functions of great complexity. The issue with building predictive functions of great complexity is in the bias variance tradeoff. Large complexity means very low bias, which unfortunately is wed to very high variance. If you fit a complex model in one go (like a deep decision tree for example) you have done nothing to deal with this variance explosion, and you will find that your test error is very poor. Boosting is essentially a principled way of carefully controlling the variance of a model when attempting to build a complex predictive function. The main idea is that we should build the predictive function very slowly, and constantly check our work to see if we should stop building. This is why using a small learning rate and weak individual learners is so important to using boosting effectively. These choices allow us to layer on complexity very slowly, and apply a lot of care to constructing out predictive function. It allows us many places to stop, by monitoring the test error at each stage in the construction. If you do not do this, your boosted model will be poor, often as poor as a single decision tree. Try setting the learning rate to $1.0$ in a gradient boosted model, or using very deep trees as individual learners.
Understanding gradient boosting
I've answered question 2a on this site before. The answer to 2b, as you suspect, is the same. In general, gradient boosting, when used for classification, fits trees not on the level of the gradient
Understanding gradient boosting I've answered question 2a on this site before. The answer to 2b, as you suspect, is the same. In general, gradient boosting, when used for classification, fits trees not on the level of the gradient of predicted probabilities, but to the gradient of the predicted log-odds. Because of this, 2b reduces to 2a in principle. As for 1: Here there is an example of ensemble of simple trees (stumps) for regression. So why is the approach with gradient boosting better than a single more complicated tree of greater depth? The power of gradient boosting is that it allows us to build predictive functions of great complexity. The issue with building predictive functions of great complexity is in the bias variance tradeoff. Large complexity means very low bias, which unfortunately is wed to very high variance. If you fit a complex model in one go (like a deep decision tree for example) you have done nothing to deal with this variance explosion, and you will find that your test error is very poor. Boosting is essentially a principled way of carefully controlling the variance of a model when attempting to build a complex predictive function. The main idea is that we should build the predictive function very slowly, and constantly check our work to see if we should stop building. This is why using a small learning rate and weak individual learners is so important to using boosting effectively. These choices allow us to layer on complexity very slowly, and apply a lot of care to constructing out predictive function. It allows us many places to stop, by monitoring the test error at each stage in the construction. If you do not do this, your boosted model will be poor, often as poor as a single decision tree. Try setting the learning rate to $1.0$ in a gradient boosted model, or using very deep trees as individual learners.
Understanding gradient boosting I've answered question 2a on this site before. The answer to 2b, as you suspect, is the same. In general, gradient boosting, when used for classification, fits trees not on the level of the gradient
32,422
Understanding gradient boosting
I would like to provide several references to answer your question. I would argue that depending on data, boosted stumps are not necessary better than deep trees. They are different. A visualization on difference can be found here How does linear base learner works in boosting? And how does it works in the xgboost library? Do all machine learning algorithms separate data linearly? for the discussions on boosting with linear model, my first link gives answer. In additon, @Matthew Drury had a good answer here. Gradient Boosting for Linear Regression - why does it not work?
Understanding gradient boosting
I would like to provide several references to answer your question. I would argue that depending on data, boosted stumps are not necessary better than deep trees. They are different. A visualization
Understanding gradient boosting I would like to provide several references to answer your question. I would argue that depending on data, boosted stumps are not necessary better than deep trees. They are different. A visualization on difference can be found here How does linear base learner works in boosting? And how does it works in the xgboost library? Do all machine learning algorithms separate data linearly? for the discussions on boosting with linear model, my first link gives answer. In additon, @Matthew Drury had a good answer here. Gradient Boosting for Linear Regression - why does it not work?
Understanding gradient boosting I would like to provide several references to answer your question. I would argue that depending on data, boosted stumps are not necessary better than deep trees. They are different. A visualization
32,423
Understanding gradient boosting
To complement the above answers, I would like to give my opinion purely from an intuitive standpoint. "No Free Lunch (NFL)" theorem states that no algorithm is better than another, on average across all possible data distributions. However, since real-world datasets are limited to few specific distributions, some models can be tuned well to show high performance in real-world scenarios. Gradient boosting provides an ensemble of weak learners. If we assume that the dataset is best modeled using a mixture of distributions, then each of these weak-learners could be learning only to perform well in certain distributions. Hence, when you take the average of all such weak learners, it has a very high overall performance across the whole dataset in contrast to a heavily overfitted single model which can perform well only in very few distributions or part of the dataset (aka Wisdom of Crowd). In short the single model attempt to generalize and lose the prediction power, whereas multiple models specialize and improve by the consensus. This is purely my opinion, either take it or leave it :)
Understanding gradient boosting
To complement the above answers, I would like to give my opinion purely from an intuitive standpoint. "No Free Lunch (NFL)" theorem states that no algorithm is better than another, on average across a
Understanding gradient boosting To complement the above answers, I would like to give my opinion purely from an intuitive standpoint. "No Free Lunch (NFL)" theorem states that no algorithm is better than another, on average across all possible data distributions. However, since real-world datasets are limited to few specific distributions, some models can be tuned well to show high performance in real-world scenarios. Gradient boosting provides an ensemble of weak learners. If we assume that the dataset is best modeled using a mixture of distributions, then each of these weak-learners could be learning only to perform well in certain distributions. Hence, when you take the average of all such weak learners, it has a very high overall performance across the whole dataset in contrast to a heavily overfitted single model which can perform well only in very few distributions or part of the dataset (aka Wisdom of Crowd). In short the single model attempt to generalize and lose the prediction power, whereas multiple models specialize and improve by the consensus. This is purely my opinion, either take it or leave it :)
Understanding gradient boosting To complement the above answers, I would like to give my opinion purely from an intuitive standpoint. "No Free Lunch (NFL)" theorem states that no algorithm is better than another, on average across a
32,424
How to interpret t-SNE plot?
Unlike PCA, axes in the low dimensional space don't have a particular meaning. In fact, one could arbitrarily rotate the low dimensional points and the t-SNE cost function wouldn't change. Furthermore, t-SNE doesn't construct explicit mappings relating the high dimensional and low dimensional spaces. Rather, the relevant information is in the relative distances between low dimensional points. t-SNE captures structure in the sense that neighboring points in the input space will tend to be neighbors in the low dimensional space. But, some care is needed because larger distances can't necessarily be interpreted. If points are separated in input space, t-SNE would like to separate them in the low dimensional space. But, it doesn't care how far they are (unlike PCA, MDS, or isomap, for example). Another issue is that t-SNE sometimes breaks continuous segments of data into pieces and artificially separates them, particularly at low perplexity settings. See here for a good example. t-SNE is framed as a visualization tool rather than a pre-processing or analysis tool, and doing things like clustering in the low dimensional space can be dangerous because of these issues. The upshot is that distorting distances sometimes lets t-SNE produce good 2/3d visualizations of data that are intrinsically higher dimensional. One way that t-SNE visualizations can be useful is by combining them with external information. This can reveal patterns in the data that we may not have been aware of. For example, the t-SNE papers show visualizations of the MNIST dataset (images of handwritten digits). Images are clustered according to the digit they represent--which we already knew, of course. But, looking within a cluster, similar images tend to be grouped together (for example, images of the digit '1' that are slanted to the left vs. right). And, points that appear in the 'wrong' cluster are sometimes actually mislabelled in the original dataset, or ambiguously written (e.g. something between '4'and a '9').
How to interpret t-SNE plot?
Unlike PCA, axes in the low dimensional space don't have a particular meaning. In fact, one could arbitrarily rotate the low dimensional points and the t-SNE cost function wouldn't change. Furthermore
How to interpret t-SNE plot? Unlike PCA, axes in the low dimensional space don't have a particular meaning. In fact, one could arbitrarily rotate the low dimensional points and the t-SNE cost function wouldn't change. Furthermore, t-SNE doesn't construct explicit mappings relating the high dimensional and low dimensional spaces. Rather, the relevant information is in the relative distances between low dimensional points. t-SNE captures structure in the sense that neighboring points in the input space will tend to be neighbors in the low dimensional space. But, some care is needed because larger distances can't necessarily be interpreted. If points are separated in input space, t-SNE would like to separate them in the low dimensional space. But, it doesn't care how far they are (unlike PCA, MDS, or isomap, for example). Another issue is that t-SNE sometimes breaks continuous segments of data into pieces and artificially separates them, particularly at low perplexity settings. See here for a good example. t-SNE is framed as a visualization tool rather than a pre-processing or analysis tool, and doing things like clustering in the low dimensional space can be dangerous because of these issues. The upshot is that distorting distances sometimes lets t-SNE produce good 2/3d visualizations of data that are intrinsically higher dimensional. One way that t-SNE visualizations can be useful is by combining them with external information. This can reveal patterns in the data that we may not have been aware of. For example, the t-SNE papers show visualizations of the MNIST dataset (images of handwritten digits). Images are clustered according to the digit they represent--which we already knew, of course. But, looking within a cluster, similar images tend to be grouped together (for example, images of the digit '1' that are slanted to the left vs. right). And, points that appear in the 'wrong' cluster are sometimes actually mislabelled in the original dataset, or ambiguously written (e.g. something between '4'and a '9').
How to interpret t-SNE plot? Unlike PCA, axes in the low dimensional space don't have a particular meaning. In fact, one could arbitrarily rotate the low dimensional points and the t-SNE cost function wouldn't change. Furthermore
32,425
How to normalize gps coordinates for deep learning
Not all models are sensitive to data normalization. For example, models with batch-norm layer have a built-in mechanism to fix activations distribution. Others are more sensitive and may even diverge just because of lack of normalization (E.g., try to train a CNN on CIFAR-10 dataset with training images, which pixels are in range $[0, 255]$). But I'm not aware of any model that would suffer from data normalization. So even though the house prediction model (btw, which one exactly?) may not do it, the model is likely to improve if the data is normalized, and you should do it too. GPS data has roughly these bounds: the latitude is in $[-100, 100]$, the longitude is in $[-200, 200]$. The coordinates for the populated area are much narrower, but it's not it's not a big deal to assume these wide ranges. This means that the transformation... $$ x \mapsto \frac{x}{100}$$ ... will ensure that the latitude is in $[-1, 1]$ and longitude is in $[-2, 2]$ (and very likely in $[-1, 1]$ as well), which are fairly robust ranges for deep learning. The transformation is easy (in numpy it takes just one line of code) and doesn't require you to compute the statistics from the training data.
How to normalize gps coordinates for deep learning
Not all models are sensitive to data normalization. For example, models with batch-norm layer have a built-in mechanism to fix activations distribution. Others are more sensitive and may even diverge
How to normalize gps coordinates for deep learning Not all models are sensitive to data normalization. For example, models with batch-norm layer have a built-in mechanism to fix activations distribution. Others are more sensitive and may even diverge just because of lack of normalization (E.g., try to train a CNN on CIFAR-10 dataset with training images, which pixels are in range $[0, 255]$). But I'm not aware of any model that would suffer from data normalization. So even though the house prediction model (btw, which one exactly?) may not do it, the model is likely to improve if the data is normalized, and you should do it too. GPS data has roughly these bounds: the latitude is in $[-100, 100]$, the longitude is in $[-200, 200]$. The coordinates for the populated area are much narrower, but it's not it's not a big deal to assume these wide ranges. This means that the transformation... $$ x \mapsto \frac{x}{100}$$ ... will ensure that the latitude is in $[-1, 1]$ and longitude is in $[-2, 2]$ (and very likely in $[-1, 1]$ as well), which are fairly robust ranges for deep learning. The transformation is easy (in numpy it takes just one line of code) and doesn't require you to compute the statistics from the training data.
How to normalize gps coordinates for deep learning Not all models are sensitive to data normalization. For example, models with batch-norm layer have a built-in mechanism to fix activations distribution. Others are more sensitive and may even diverge
32,426
How to normalize gps coordinates for deep learning
I think the answer of Maxim is not wrong, but might be misleading. When you use lon, lat values for tasks like vehicle stop classification, you probably look for a normalized space, where you can simply learn latent features like distances, speed or acceleration. The problem with longitude and latitude values is, that you can not simply infer the distances from it. A $\Delta(lon, lat)$ would lead to different distances depending, if you are at the equator or at one of the polar circle. For your task I would recommend something proposed by this answer of Jan van der Vegt: x = cos(lat) * cos(lon) y = cos(lat) * sin(lon), z = sin(lat) These features can then be standardized properly.
How to normalize gps coordinates for deep learning
I think the answer of Maxim is not wrong, but might be misleading. When you use lon, lat values for tasks like vehicle stop classification, you probably look for a normalized space, where you can simp
How to normalize gps coordinates for deep learning I think the answer of Maxim is not wrong, but might be misleading. When you use lon, lat values for tasks like vehicle stop classification, you probably look for a normalized space, where you can simply learn latent features like distances, speed or acceleration. The problem with longitude and latitude values is, that you can not simply infer the distances from it. A $\Delta(lon, lat)$ would lead to different distances depending, if you are at the equator or at one of the polar circle. For your task I would recommend something proposed by this answer of Jan van der Vegt: x = cos(lat) * cos(lon) y = cos(lat) * sin(lon), z = sin(lat) These features can then be standardized properly.
How to normalize gps coordinates for deep learning I think the answer of Maxim is not wrong, but might be misleading. When you use lon, lat values for tasks like vehicle stop classification, you probably look for a normalized space, where you can simp
32,427
Why does k-fold cross validation generate an MSE estimator that has higher bias, but lower variance then leave-one-out cross-validation?
There has been much debate, confusion and contradiction on this topic, both on stats.stackexchange and in scientific literature. A useful paper is the 2004 study by Bengio & Grandvalet which argues that the variance of the cross validation estimator is a linear combination of three moments: $$ var = \frac{1}{n^2} \sum_{i,j} Cov(e_i,e_j)$$ $$= \frac{1}{n}\sigma^2 + \frac{m-1}{n}\omega + \frac{n-m}{n} \gamma$$ Where each term is a particular component of the $n \times n$ covariance matrix $\Sigma$ of cross validation errors $\mathbf{e} = (e_1,...,e_n)^T$ As @Amoeba points out in a comment above, this variance is not a straightforward function of $K$. Each data point $x_i$ contributes to an error term $\epsilon_i$ which are summed up into the MSE. Varying $K$ does not have a direct, algebraically straightforward impact on the variance of the CV estimator. $k$-fold CV with any value of $k$ produces an error for each of the $n$ observations. So MSE estimate always has the denominator $n$. This denominator does not change between LOOCV and e.g. 10-fold CV. This is your main confusion here. Now, there is a lot more subtlety in this equation of variance than it seems. In particular the terms $\omega$ and $\gamma$ are influenced by correlation between the data sets, training sets, testing sets etc.. and instability of the model. These two effects are influenced by the value of $K$ which explains why different datasets and models will lead to different behaviours, You will need to read through the extensive (and technical) literature to really grasp the subtlety and special cases.
Why does k-fold cross validation generate an MSE estimator that has higher bias, but lower variance
There has been much debate, confusion and contradiction on this topic, both on stats.stackexchange and in scientific literature. A useful paper is the 2004 study by Bengio & Grandvalet which argues t
Why does k-fold cross validation generate an MSE estimator that has higher bias, but lower variance then leave-one-out cross-validation? There has been much debate, confusion and contradiction on this topic, both on stats.stackexchange and in scientific literature. A useful paper is the 2004 study by Bengio & Grandvalet which argues that the variance of the cross validation estimator is a linear combination of three moments: $$ var = \frac{1}{n^2} \sum_{i,j} Cov(e_i,e_j)$$ $$= \frac{1}{n}\sigma^2 + \frac{m-1}{n}\omega + \frac{n-m}{n} \gamma$$ Where each term is a particular component of the $n \times n$ covariance matrix $\Sigma$ of cross validation errors $\mathbf{e} = (e_1,...,e_n)^T$ As @Amoeba points out in a comment above, this variance is not a straightforward function of $K$. Each data point $x_i$ contributes to an error term $\epsilon_i$ which are summed up into the MSE. Varying $K$ does not have a direct, algebraically straightforward impact on the variance of the CV estimator. $k$-fold CV with any value of $k$ produces an error for each of the $n$ observations. So MSE estimate always has the denominator $n$. This denominator does not change between LOOCV and e.g. 10-fold CV. This is your main confusion here. Now, there is a lot more subtlety in this equation of variance than it seems. In particular the terms $\omega$ and $\gamma$ are influenced by correlation between the data sets, training sets, testing sets etc.. and instability of the model. These two effects are influenced by the value of $K$ which explains why different datasets and models will lead to different behaviours, You will need to read through the extensive (and technical) literature to really grasp the subtlety and special cases.
Why does k-fold cross validation generate an MSE estimator that has higher bias, but lower variance There has been much debate, confusion and contradiction on this topic, both on stats.stackexchange and in scientific literature. A useful paper is the 2004 study by Bengio & Grandvalet which argues t
32,428
Why does k-fold cross validation generate an MSE estimator that has higher bias, but lower variance then leave-one-out cross-validation?
In addition to Xavier's answer: why does LOOCV still have higher variance in estimating MSE and why does it have lower bias Do we know whether the situations where high variance for LOO is observed are the same where it also has low bias? I'm aware of one particular situation (LOO, small sample size, classifiers that take into account relative frequency of classes in training) which causes high pessimistic bias. Now for certain highly used figures of merit such as % misclassifications or accuracy or a similar fraction of tested cases, the large pessimistic bias often leads to larger variance because for these figures of merit the variance is mathematically tied to their size (with highest variance for 50 %). The "low [pessimistic] bias of LOO" is usually argued from the learning curve: if, instead of taking away $m$ training cases, only 1 training case is left out, the surrogate models are on average less worse than those where $m$ cases were removed. Implied: All other things being equal (which is not the case in the peculair situation above). One would also expect the instability (B&G's ω variance component) to be lower for LOO as more training cases are available. Unfortunately, for LOO this cannot be measured.
Why does k-fold cross validation generate an MSE estimator that has higher bias, but lower variance
In addition to Xavier's answer: why does LOOCV still have higher variance in estimating MSE and why does it have lower bias Do we know whether the situations where high variance for LOO is observed
Why does k-fold cross validation generate an MSE estimator that has higher bias, but lower variance then leave-one-out cross-validation? In addition to Xavier's answer: why does LOOCV still have higher variance in estimating MSE and why does it have lower bias Do we know whether the situations where high variance for LOO is observed are the same where it also has low bias? I'm aware of one particular situation (LOO, small sample size, classifiers that take into account relative frequency of classes in training) which causes high pessimistic bias. Now for certain highly used figures of merit such as % misclassifications or accuracy or a similar fraction of tested cases, the large pessimistic bias often leads to larger variance because for these figures of merit the variance is mathematically tied to their size (with highest variance for 50 %). The "low [pessimistic] bias of LOO" is usually argued from the learning curve: if, instead of taking away $m$ training cases, only 1 training case is left out, the surrogate models are on average less worse than those where $m$ cases were removed. Implied: All other things being equal (which is not the case in the peculair situation above). One would also expect the instability (B&G's ω variance component) to be lower for LOO as more training cases are available. Unfortunately, for LOO this cannot be measured.
Why does k-fold cross validation generate an MSE estimator that has higher bias, but lower variance In addition to Xavier's answer: why does LOOCV still have higher variance in estimating MSE and why does it have lower bias Do we know whether the situations where high variance for LOO is observed
32,429
Why is the Bayesian credible interval in this polynomial regression biased whereas the confidence interval is correct?
For a frequentist model, the variance of the prediction magnifies in proportion to the square of the distance from the centroid of $X$. Your method of calculating prediction intervals for a Bayesian GLM uses empirical quantiles based on the fitted probability curve, but does not account for $X$'s leverage. A binomial frequentist GLM is no different from a GLM with identity link except that the variance is proportional to the mean. Note that any polynomial representation of logit probabilities leads to risk predictions that converge to 0 as $X\rightarrow -\infty$ and 1 as $X\rightarrow \infty$ or vice versa, depending on the sign of the highest polynomial order term. For frequentist prediction, the squared deviation (leverage) proportional increase in variance of predictions dominates this tendency. This is why the rate of convergence to prediction intervals approximately equal to [0, 1] is faster than the third order polynomial logit convergence to probabilities of 0 or 1 singularly. This is not so for Bayesian posterior fitted quantiles. There is no explicit use of squared deviation, so we rely simply on the proportion of dominating 0 or 1 tendencies to construct long term prediction intervals. This is made apparent by extrapolating very far out into the extremes of $X$. Using the code I supplied above we get: > x_pred_dom <- model.matrix(~ x + I(x^2) + I(x^3), data=data.frame('x'=c(1000))) > gibbs_preds <- plogis(apply(gibbs_samps[1000:10000, ], 1, `%*%`, t(x_pred_dom))) # a bunch of 0/1s basically past machine precision > prop.table(table(gibbs_preds)) gibbs_preds 0 1 0.97733585 0.02266415 > So 97.75% of the time, the third polynomial term was negative. This is verifiable from the Gibbs samples: > prop.table(table(gibbs_samps[, 4]< 0)) FALSE TRUE 0.0225 0.9775 Hence the predicted probability converges to 0 as $X$ goes to infinity. If we inspect the SEs of the Bayesian model, we find the estimate of the third polynomial term is -185.25 with se 108.81 meaning it is 1.70 SDs from 0, so using normal probability laws, it should fall below 0 95.5% of the time (not a terribly different prediction based on 10,000 iterations). Just another way of understanding this phenomenon. On the other hand, the frequentist fit blows up to 0,1 as expected: freq <- predict(fit, newdata = data.frame(x=1000), se.fit=T) plogis(freq$fit + c(-1.96, 1.96) %o% freq$se.fit) gives: > plogis(freq$fit + c(-1.96, 1.96) %o% freq$se.fit) [,1] [1,] 0 [2,] 1
Why is the Bayesian credible interval in this polynomial regression biased whereas the confidence in
For a frequentist model, the variance of the prediction magnifies in proportion to the square of the distance from the centroid of $X$. Your method of calculating prediction intervals for a Bayesian G
Why is the Bayesian credible interval in this polynomial regression biased whereas the confidence interval is correct? For a frequentist model, the variance of the prediction magnifies in proportion to the square of the distance from the centroid of $X$. Your method of calculating prediction intervals for a Bayesian GLM uses empirical quantiles based on the fitted probability curve, but does not account for $X$'s leverage. A binomial frequentist GLM is no different from a GLM with identity link except that the variance is proportional to the mean. Note that any polynomial representation of logit probabilities leads to risk predictions that converge to 0 as $X\rightarrow -\infty$ and 1 as $X\rightarrow \infty$ or vice versa, depending on the sign of the highest polynomial order term. For frequentist prediction, the squared deviation (leverage) proportional increase in variance of predictions dominates this tendency. This is why the rate of convergence to prediction intervals approximately equal to [0, 1] is faster than the third order polynomial logit convergence to probabilities of 0 or 1 singularly. This is not so for Bayesian posterior fitted quantiles. There is no explicit use of squared deviation, so we rely simply on the proportion of dominating 0 or 1 tendencies to construct long term prediction intervals. This is made apparent by extrapolating very far out into the extremes of $X$. Using the code I supplied above we get: > x_pred_dom <- model.matrix(~ x + I(x^2) + I(x^3), data=data.frame('x'=c(1000))) > gibbs_preds <- plogis(apply(gibbs_samps[1000:10000, ], 1, `%*%`, t(x_pred_dom))) # a bunch of 0/1s basically past machine precision > prop.table(table(gibbs_preds)) gibbs_preds 0 1 0.97733585 0.02266415 > So 97.75% of the time, the third polynomial term was negative. This is verifiable from the Gibbs samples: > prop.table(table(gibbs_samps[, 4]< 0)) FALSE TRUE 0.0225 0.9775 Hence the predicted probability converges to 0 as $X$ goes to infinity. If we inspect the SEs of the Bayesian model, we find the estimate of the third polynomial term is -185.25 with se 108.81 meaning it is 1.70 SDs from 0, so using normal probability laws, it should fall below 0 95.5% of the time (not a terribly different prediction based on 10,000 iterations). Just another way of understanding this phenomenon. On the other hand, the frequentist fit blows up to 0,1 as expected: freq <- predict(fit, newdata = data.frame(x=1000), se.fit=T) plogis(freq$fit + c(-1.96, 1.96) %o% freq$se.fit) gives: > plogis(freq$fit + c(-1.96, 1.96) %o% freq$se.fit) [,1] [1,] 0 [2,] 1
Why is the Bayesian credible interval in this polynomial regression biased whereas the confidence in For a frequentist model, the variance of the prediction magnifies in proportion to the square of the distance from the centroid of $X$. Your method of calculating prediction intervals for a Bayesian G
32,430
Gradient descent to optimize regularization parameter $\lambda$ instead of doing grid search?
Short answer: Yes, gradient descent could conceivably be used in this situation because of the special form of ridge regression. Below, I derive an expression for the derivative of the validation set error w.r.t. $\lambda$. But, other optimization methods may be more efficient and more broadly applicable. Longer answer: The validation set error as a function of $\lambda$ isn't convex but, empirically, it does tend to be well-behaved--e.g. smooth with a single minimum (perhaps pseudoconvex? If anyone could elaborate on its properties I'd be interested to hear). This means there's structure that can be exploited to optimize $\lambda$ more efficiently than grid search. Gradient descent could conceivably be used to exploit some of this structure, although I've never seen anybody use it in this context. It would require differentiating the validation set error with respect to $\lambda$, which in turn requires differentiating the optimal weights (on the training set) with respect to $\lambda$. Because of the convenient form of ridge regression, it turns out that a closed form expression for the derivative exists (see below). A further tweak is needed: $\lambda$ must be constrained to be nonnegative. This could be done trivially using projected gradient descent (in this case, simply thresholding $\lambda$ after each step). But, we can probably do better than gradient descent. For example, methods incorporating quadratic interpolation can exploit curvature information, which gradient descent can't. We could use a root finding algorithm like Brent's method to solve for $\lambda$ where the derivative is zero. Because this is a 1d optimization problem, we could also use methods like golden section search (or again, Brent's method) to directly optimize $\lambda$. These methods can exploit local structure in the objective function, but don't require an expression for the gradient. This means we can also apply them in cases where one doesn't exist. For example, there's almost certainly no closed-form expression for the derivative of the validation set error w.r.t. the lasso regularization parameter. All of these methods only find local minima so, unlike grid search, they may not be good choices when multiple local minima exist. But, there are global search techniques that can still beat grid search in this situation by exploiting structure in the objective function. Derivative of validation set error w.r.t. $\lambda$: Say the training set contains inputs stored in matrix $X$ (with points on the rows, features on the columns) and outputs stored in column vector $y$. The validation set contains inputs $\tilde{X}$ and outputs $\tilde{y}$. Assume that the columns of $X$ and $\tilde{X}$ have been standardized (using the mean and standard deviation of $X$), and that $y$ and $\tilde{y}$ have been centered (using the mean of $y$). This is done to avoid including a constant term in the model. Given $\lambda$, the weights are learned on the training set: $$w_\lambda = \underset{w}{\arg \min} \| y - X w \|^2 + \lambda \|w\|^2$$ Ridge regression has a well known closed form solution: $$w_\lambda = (X^T X + \lambda I)^{-1} X^T y$$ We want to find $\lambda$ that minimizes the error on the validation set: $$\min_\lambda \| \tilde{y} - \tilde{X} w_\lambda \|^2$$ Let $L$ denote the validation set error. Its derivative is: $$\frac{d}{d\lambda} L = \frac{d}{d\lambda} \| \tilde{y} - \tilde{X} w_\lambda \|^2 $$ After some matrix wrangling, we have: $$\frac{d}{d\lambda} L = -2(\tilde{y} - \tilde{X} w_\lambda)^T \tilde{X} \frac{d}{d\lambda} w_\lambda$$ Now we must differentiate $w_\lambda$: $$\frac{d}{d\lambda} w_\lambda = \frac{d}{d\lambda} (X^T X + \lambda I)^{-1} X^T y$$ If $A$ is an invertible square matrix that's a function of $t$ then $\frac{d}{dt} A^{-1} = -A^{-1} (\frac{d}{dt} A) A^{-1}$ (proof here). Using this identity and more matrix wrangling, we have: $$\frac{d}{d\lambda} w_\lambda = -(X^T X + \lambda I)^{-2} X^T y$$ Plug this back into the derivative of the validation set error, along with the expression for $w_\lambda$. Let $M = X^T X + \lambda I$. Then: $$\frac{d}{d\lambda} L = 2 (\tilde{y} - \tilde{X} M^{-1} X^T y)^T \tilde{X} M^{-2} X^T y$$ Naively computing this expression for different values of $\lambda$ would be computationally inefficient because it would require many matrix inversions. Matrix inversion may also be numerically unstable for small values of $\lambda$. To avoid this, re-express using the eigenvalue decomposition of $X^T X$. Let matrix $V$ contain the eigenvectors on the columns and $\gamma$ be a vector containing the corresponding eigenvalues. So $X^T X = V \text{diag}(\gamma) V^T$. The eigenvectors of $M = X^T X + \lambda I$ are also given by $V$, and its eigenvalues are $\gamma + \lambda$. So $M = V \text{diag}(\gamma + \lambda) V^T$. The inverse of a matrix can be found by inverting the eigenvalues so, letting $D = \text{diag}((\gamma + \lambda)^{-1})$, $M^{-1} = V D V^T$. Because $V$ is orthonormal, $M^{-2}$ simplifies to $V D^2 V^T$. Plug these expressions in: $$\frac{d}{d\lambda} L = 2 (\tilde{y} - \tilde{X} V D V^T X^T y)^T \tilde{X} V D^2 V^T X^T y$$ Computational efficiency can be increased by pre-computing parts of the expression that don't depend on $\lambda$. Let: $$A = 2 V^T X^T y$$ $$B = V^T \tilde{X}^T \tilde{X} V$$ $$q=\tilde{y}^T \tilde{X} V$$ $$r=y^T X V$$ Then: $$\frac{d}{d\lambda} L = (q - r D B) D^2 A$$ Further computational gains can be had by replacing matrix operations involving $D$ with element-wise operations involving its diagonal.
Gradient descent to optimize regularization parameter $\lambda$ instead of doing grid search?
Short answer: Yes, gradient descent could conceivably be used in this situation because of the special form of ridge regression. Below, I derive an expression for the derivative of the validation set
Gradient descent to optimize regularization parameter $\lambda$ instead of doing grid search? Short answer: Yes, gradient descent could conceivably be used in this situation because of the special form of ridge regression. Below, I derive an expression for the derivative of the validation set error w.r.t. $\lambda$. But, other optimization methods may be more efficient and more broadly applicable. Longer answer: The validation set error as a function of $\lambda$ isn't convex but, empirically, it does tend to be well-behaved--e.g. smooth with a single minimum (perhaps pseudoconvex? If anyone could elaborate on its properties I'd be interested to hear). This means there's structure that can be exploited to optimize $\lambda$ more efficiently than grid search. Gradient descent could conceivably be used to exploit some of this structure, although I've never seen anybody use it in this context. It would require differentiating the validation set error with respect to $\lambda$, which in turn requires differentiating the optimal weights (on the training set) with respect to $\lambda$. Because of the convenient form of ridge regression, it turns out that a closed form expression for the derivative exists (see below). A further tweak is needed: $\lambda$ must be constrained to be nonnegative. This could be done trivially using projected gradient descent (in this case, simply thresholding $\lambda$ after each step). But, we can probably do better than gradient descent. For example, methods incorporating quadratic interpolation can exploit curvature information, which gradient descent can't. We could use a root finding algorithm like Brent's method to solve for $\lambda$ where the derivative is zero. Because this is a 1d optimization problem, we could also use methods like golden section search (or again, Brent's method) to directly optimize $\lambda$. These methods can exploit local structure in the objective function, but don't require an expression for the gradient. This means we can also apply them in cases where one doesn't exist. For example, there's almost certainly no closed-form expression for the derivative of the validation set error w.r.t. the lasso regularization parameter. All of these methods only find local minima so, unlike grid search, they may not be good choices when multiple local minima exist. But, there are global search techniques that can still beat grid search in this situation by exploiting structure in the objective function. Derivative of validation set error w.r.t. $\lambda$: Say the training set contains inputs stored in matrix $X$ (with points on the rows, features on the columns) and outputs stored in column vector $y$. The validation set contains inputs $\tilde{X}$ and outputs $\tilde{y}$. Assume that the columns of $X$ and $\tilde{X}$ have been standardized (using the mean and standard deviation of $X$), and that $y$ and $\tilde{y}$ have been centered (using the mean of $y$). This is done to avoid including a constant term in the model. Given $\lambda$, the weights are learned on the training set: $$w_\lambda = \underset{w}{\arg \min} \| y - X w \|^2 + \lambda \|w\|^2$$ Ridge regression has a well known closed form solution: $$w_\lambda = (X^T X + \lambda I)^{-1} X^T y$$ We want to find $\lambda$ that minimizes the error on the validation set: $$\min_\lambda \| \tilde{y} - \tilde{X} w_\lambda \|^2$$ Let $L$ denote the validation set error. Its derivative is: $$\frac{d}{d\lambda} L = \frac{d}{d\lambda} \| \tilde{y} - \tilde{X} w_\lambda \|^2 $$ After some matrix wrangling, we have: $$\frac{d}{d\lambda} L = -2(\tilde{y} - \tilde{X} w_\lambda)^T \tilde{X} \frac{d}{d\lambda} w_\lambda$$ Now we must differentiate $w_\lambda$: $$\frac{d}{d\lambda} w_\lambda = \frac{d}{d\lambda} (X^T X + \lambda I)^{-1} X^T y$$ If $A$ is an invertible square matrix that's a function of $t$ then $\frac{d}{dt} A^{-1} = -A^{-1} (\frac{d}{dt} A) A^{-1}$ (proof here). Using this identity and more matrix wrangling, we have: $$\frac{d}{d\lambda} w_\lambda = -(X^T X + \lambda I)^{-2} X^T y$$ Plug this back into the derivative of the validation set error, along with the expression for $w_\lambda$. Let $M = X^T X + \lambda I$. Then: $$\frac{d}{d\lambda} L = 2 (\tilde{y} - \tilde{X} M^{-1} X^T y)^T \tilde{X} M^{-2} X^T y$$ Naively computing this expression for different values of $\lambda$ would be computationally inefficient because it would require many matrix inversions. Matrix inversion may also be numerically unstable for small values of $\lambda$. To avoid this, re-express using the eigenvalue decomposition of $X^T X$. Let matrix $V$ contain the eigenvectors on the columns and $\gamma$ be a vector containing the corresponding eigenvalues. So $X^T X = V \text{diag}(\gamma) V^T$. The eigenvectors of $M = X^T X + \lambda I$ are also given by $V$, and its eigenvalues are $\gamma + \lambda$. So $M = V \text{diag}(\gamma + \lambda) V^T$. The inverse of a matrix can be found by inverting the eigenvalues so, letting $D = \text{diag}((\gamma + \lambda)^{-1})$, $M^{-1} = V D V^T$. Because $V$ is orthonormal, $M^{-2}$ simplifies to $V D^2 V^T$. Plug these expressions in: $$\frac{d}{d\lambda} L = 2 (\tilde{y} - \tilde{X} V D V^T X^T y)^T \tilde{X} V D^2 V^T X^T y$$ Computational efficiency can be increased by pre-computing parts of the expression that don't depend on $\lambda$. Let: $$A = 2 V^T X^T y$$ $$B = V^T \tilde{X}^T \tilde{X} V$$ $$q=\tilde{y}^T \tilde{X} V$$ $$r=y^T X V$$ Then: $$\frac{d}{d\lambda} L = (q - r D B) D^2 A$$ Further computational gains can be had by replacing matrix operations involving $D$ with element-wise operations involving its diagonal.
Gradient descent to optimize regularization parameter $\lambda$ instead of doing grid search? Short answer: Yes, gradient descent could conceivably be used in this situation because of the special form of ridge regression. Below, I derive an expression for the derivative of the validation set
32,431
Time-series logistic regression
Keras is a high-level API that allows implementation of recurrent neural networks (RNNs). RNNs like LSTMs might be good models for your data, depending on how much there is. Here is a good introductory tutorial. What you suggest with the time window and logistic regression may perform better or it may perform much worse. Sometimes aggregating past time events is very effective, sometimes not so much. In my experience, it's more effective when there is less data and the function from previous time steps to the response variable is too complicated to learn given the small amount of data. Aggregating might allow you to kind of guide this learning with some domain expertise. (For me, this once outperformed a self-written vanilla RNN, but it may not have outperformed an LSTM or GRU). With a large amount of data, RNNs should outperform this method in terms of predictive performance. Another option is a Hidden Markov Model. One huge benefit of the time-window method however is that the aggregated features are interpretable. I would try both methods and see which is best. In terms of overfitting, you can use shrinkage with logistic regression or dropout, shrinkage, or decreased nodes with an RNN. If you make sure to check error on a validation set, you can be vigilant about preventing overfitting. You would have to resample for the RNN to take time into account (they naturally process sequences and it is up to you to make sure that the events in the sequence are evenly spaced). Pandas has a resampling functionality that may come in handy, although it's also possible that processing raw sequences rather than resampled sequences might give better results---again, would not hurt to try both ways. A good general introduction and more to RNNs is Andrej Karpathy's blog post. Aslo, see Goodfellow et als text Chapter 10.
Time-series logistic regression
Keras is a high-level API that allows implementation of recurrent neural networks (RNNs). RNNs like LSTMs might be good models for your data, depending on how much there is. Here is a good introduct
Time-series logistic regression Keras is a high-level API that allows implementation of recurrent neural networks (RNNs). RNNs like LSTMs might be good models for your data, depending on how much there is. Here is a good introductory tutorial. What you suggest with the time window and logistic regression may perform better or it may perform much worse. Sometimes aggregating past time events is very effective, sometimes not so much. In my experience, it's more effective when there is less data and the function from previous time steps to the response variable is too complicated to learn given the small amount of data. Aggregating might allow you to kind of guide this learning with some domain expertise. (For me, this once outperformed a self-written vanilla RNN, but it may not have outperformed an LSTM or GRU). With a large amount of data, RNNs should outperform this method in terms of predictive performance. Another option is a Hidden Markov Model. One huge benefit of the time-window method however is that the aggregated features are interpretable. I would try both methods and see which is best. In terms of overfitting, you can use shrinkage with logistic regression or dropout, shrinkage, or decreased nodes with an RNN. If you make sure to check error on a validation set, you can be vigilant about preventing overfitting. You would have to resample for the RNN to take time into account (they naturally process sequences and it is up to you to make sure that the events in the sequence are evenly spaced). Pandas has a resampling functionality that may come in handy, although it's also possible that processing raw sequences rather than resampled sequences might give better results---again, would not hurt to try both ways. A good general introduction and more to RNNs is Andrej Karpathy's blog post. Aslo, see Goodfellow et als text Chapter 10.
Time-series logistic regression Keras is a high-level API that allows implementation of recurrent neural networks (RNNs). RNNs like LSTMs might be good models for your data, depending on how much there is. Here is a good introduct
32,432
How can mixed-effect and fixed-effect generalised linear models be compared using BIC?
As far as I can tell, you can compare the likelihoods of glmer() and glm() models, at least for family=binomial (haven't tested this for other families). If the variance components are estimated to be zero, then the likelihood should be identical and that is clearly the case. Here is an example to illustrate this: dat <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 13L, 14L, 14L, 14L, 14L, 14L, 15L, 15L, 15L, 15L, 15L, 16L, 16L, 16L, 16L, 16L, 17L, 17L, 17L, 17L, 17L, 18L, 18L, 18L, 18L, 18L, 19L, 19L, 19L, 19L, 19L, 20L, 20L, 20L, 20L, 20L), xi = c(0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0.8, 0.8, 0.8, 0.8, 0.8, -0.9, -0.9, -0.9, -0.9, -0.9, 0.7, 0.7, 0.7, 0.7, 0.7, 0.1, 0.1, 0.1, 0.1, 0.1, -1.7, -1.7, -1.7, -1.7, -1.7, 0.3, 0.3, 0.3, 0.3, 0.3, -2.8, -2.8, -2.8, -2.8, -2.8, 2.7, 2.7, 2.7, 2.7, 2.7, -0.1, -0.1, -0.1, -0.1, -0.1, -0.2, -0.2, -0.2, -0.2, -0.2, 2, 2, 2, 2, 2, -0.6, -0.6, -0.6, -0.6, -0.6, 1.1, 1.1, 1.1, 1.1, 1.1, 0.2, 0.2, 0.2, 0.2, 0.2, -0.4, -0.4, -0.4, -0.4, -0.4, 2, 2, 2, 2, 2, -1.1, -1.1, -1.1, -1.1, -1.1), xij = c(1.1, 1.1, 0.2, 0.9, 0.4, -2.1, -0.4, -0.7, 0, 0.8, -0.4, 0.2, -1, 0, -1.2, 1.1, 1.9, 0.9, -1.4, -0.8, -0.3, -0.7, 0.7, -1.2, 1.1, -1.5, 0.3, -1.7, -2, 0.2, 2, -0.5, -1.2, -0.2, -2.3, -0.6, -0.6, -1.6, -0.4, -1.5, -0.5, 0.8, 0.1, -0.3, -0.7, 0.7, 0.3, -0.4, 0.4, 0.5, -0.8, 0.6, 0.3, 0.6, 0.2, -0.8, 0, -2.3, 0.5, 0, 0.9, 0.6, 2.2, 0.6, -0.3, 0.3, 0.5, -2.2, 2, -0.6, -0.7, -0.3, -0.7, 1.7, -0.7, -0.3, 0.6, -0.9, -1.9, -0.5, 1.6, -0.5, 0.4, 1.1, 0.5, -1.8, 1.2, 1.7, -1.1, 0.2, -0.6, -1.1, 2.1, 0.4, 0.9, 0.5, -2, 1.6, 0.1, 0.7), yi = c(0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L)), .Names = c("id", "xi", "xij", "yi"), row.names = c(NA, -100L), class = "data.frame") library(lme4) res0 <- glm(yi ~ xi + xij, data=dat, family=binomial) summary(res0) res1 <- glmer(yi ~ xi + xij + (1 | id), data=dat, family=binomial) summary(res1) logLik(res0) logLik(res1) anova(res1, res0) The last three lines yield: > logLik(res0) 'log Lik.' -29.96427 (df=3) > logLik(res1) 'log Lik.' -29.96427 (df=4) > > anova(res1, res0) Data: dat Models: res0: yi ~ xi + xij res1: yi ~ xi + xij + (1 | id) Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq) res0 3 65.929 73.744 -29.964 59.929 res1 4 67.929 78.349 -29.964 59.929 0 1 1 So, the (log)-likelihoods are identical, since the id level variance component is estimated to be zero. The AIC value of the mixed-effects model is therefore 2 points larger, as expected (since the model has one more parameter). One thing to note though: The default for glmer() is nAGQ=1, which means that the Laplace approximation is used. Let's use "proper" adaptive quadrature: res1 <- glmer(yi ~ xi + xij + (1 | id), data=dat, family=binomial, nAGQ=7) logLik(res0) logLik(res1) anova(res1, res0) This yields: > logLik(res0) 'log Lik.' -29.96427 (df=3) > logLik(res1) 'log Lik.' -29.96427 (df=4) > anova(res1, res0) Error in anova.merMod(res1, res0) : GLMMs with nAGQ>1 have log-likelihoods incommensurate with glm() objects The variance component is still estimated to be zero and the (log)-likelihoods are identical. But anova() spits out an error that indicates that these models should not not be compared against each other.
How can mixed-effect and fixed-effect generalised linear models be compared using BIC?
As far as I can tell, you can compare the likelihoods of glmer() and glm() models, at least for family=binomial (haven't tested this for other families). If the variance components are estimated to be
How can mixed-effect and fixed-effect generalised linear models be compared using BIC? As far as I can tell, you can compare the likelihoods of glmer() and glm() models, at least for family=binomial (haven't tested this for other families). If the variance components are estimated to be zero, then the likelihood should be identical and that is clearly the case. Here is an example to illustrate this: dat <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 13L, 14L, 14L, 14L, 14L, 14L, 15L, 15L, 15L, 15L, 15L, 16L, 16L, 16L, 16L, 16L, 17L, 17L, 17L, 17L, 17L, 18L, 18L, 18L, 18L, 18L, 19L, 19L, 19L, 19L, 19L, 20L, 20L, 20L, 20L, 20L), xi = c(0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0.8, 0.8, 0.8, 0.8, 0.8, -0.9, -0.9, -0.9, -0.9, -0.9, 0.7, 0.7, 0.7, 0.7, 0.7, 0.1, 0.1, 0.1, 0.1, 0.1, -1.7, -1.7, -1.7, -1.7, -1.7, 0.3, 0.3, 0.3, 0.3, 0.3, -2.8, -2.8, -2.8, -2.8, -2.8, 2.7, 2.7, 2.7, 2.7, 2.7, -0.1, -0.1, -0.1, -0.1, -0.1, -0.2, -0.2, -0.2, -0.2, -0.2, 2, 2, 2, 2, 2, -0.6, -0.6, -0.6, -0.6, -0.6, 1.1, 1.1, 1.1, 1.1, 1.1, 0.2, 0.2, 0.2, 0.2, 0.2, -0.4, -0.4, -0.4, -0.4, -0.4, 2, 2, 2, 2, 2, -1.1, -1.1, -1.1, -1.1, -1.1), xij = c(1.1, 1.1, 0.2, 0.9, 0.4, -2.1, -0.4, -0.7, 0, 0.8, -0.4, 0.2, -1, 0, -1.2, 1.1, 1.9, 0.9, -1.4, -0.8, -0.3, -0.7, 0.7, -1.2, 1.1, -1.5, 0.3, -1.7, -2, 0.2, 2, -0.5, -1.2, -0.2, -2.3, -0.6, -0.6, -1.6, -0.4, -1.5, -0.5, 0.8, 0.1, -0.3, -0.7, 0.7, 0.3, -0.4, 0.4, 0.5, -0.8, 0.6, 0.3, 0.6, 0.2, -0.8, 0, -2.3, 0.5, 0, 0.9, 0.6, 2.2, 0.6, -0.3, 0.3, 0.5, -2.2, 2, -0.6, -0.7, -0.3, -0.7, 1.7, -0.7, -0.3, 0.6, -0.9, -1.9, -0.5, 1.6, -0.5, 0.4, 1.1, 0.5, -1.8, 1.2, 1.7, -1.1, 0.2, -0.6, -1.1, 2.1, 0.4, 0.9, 0.5, -2, 1.6, 0.1, 0.7), yi = c(0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L)), .Names = c("id", "xi", "xij", "yi"), row.names = c(NA, -100L), class = "data.frame") library(lme4) res0 <- glm(yi ~ xi + xij, data=dat, family=binomial) summary(res0) res1 <- glmer(yi ~ xi + xij + (1 | id), data=dat, family=binomial) summary(res1) logLik(res0) logLik(res1) anova(res1, res0) The last three lines yield: > logLik(res0) 'log Lik.' -29.96427 (df=3) > logLik(res1) 'log Lik.' -29.96427 (df=4) > > anova(res1, res0) Data: dat Models: res0: yi ~ xi + xij res1: yi ~ xi + xij + (1 | id) Df AIC BIC logLik deviance Chisq Chi Df Pr(>Chisq) res0 3 65.929 73.744 -29.964 59.929 res1 4 67.929 78.349 -29.964 59.929 0 1 1 So, the (log)-likelihoods are identical, since the id level variance component is estimated to be zero. The AIC value of the mixed-effects model is therefore 2 points larger, as expected (since the model has one more parameter). One thing to note though: The default for glmer() is nAGQ=1, which means that the Laplace approximation is used. Let's use "proper" adaptive quadrature: res1 <- glmer(yi ~ xi + xij + (1 | id), data=dat, family=binomial, nAGQ=7) logLik(res0) logLik(res1) anova(res1, res0) This yields: > logLik(res0) 'log Lik.' -29.96427 (df=3) > logLik(res1) 'log Lik.' -29.96427 (df=4) > anova(res1, res0) Error in anova.merMod(res1, res0) : GLMMs with nAGQ>1 have log-likelihoods incommensurate with glm() objects The variance component is still estimated to be zero and the (log)-likelihoods are identical. But anova() spits out an error that indicates that these models should not not be compared against each other.
How can mixed-effect and fixed-effect generalised linear models be compared using BIC? As far as I can tell, you can compare the likelihoods of glmer() and glm() models, at least for family=binomial (haven't tested this for other families). If the variance components are estimated to be
32,433
"Unbiased" hypothesis test --- what does it mean actually? [duplicate]
It means that the probability that the test rejects (its power) is always higher when the alternative is true than when the null is true. Suppose, for example, that you use a standard t-test for the null $\theta\leq0$ against the alternative $\theta>0$. The standard rejection rule at $\alpha=0.05$ would be to reject if $t>1.645$ (for either a sample from a normal distribution or asymptotically, when a central limit theorem applies). Now, suppose you were to use that rule (reject if $t>1.645$) to test $\theta=0$ against $\theta\neq0$. The probability that the test will reject will decrease the more negative the true $\theta$, as we shall rarely observe large positive t-ratios in that case. In particular, this test is be biased, as $\beta(\theta)<\alpha$ when $\theta\in\Theta_1\cap(-\infty,0)$. For concreteness, we may compute this probability explicitly in the normal case, $X_i\sim N(\theta,1)$, with $\sigma^2=1$ assumed known for simplicity. Then, the t-statistic for $\theta=0$ simply is $t=\sqrt{n}\bar{X}$ and $$\sqrt{n}(\bar{X}-\theta)\sim N(0,1)$$ Thus, \begin{align*} \beta(\theta)&=P(t>1.645)\\ &=1-P(t<1.645)\\ &=1-P(\sqrt{n}(\bar{X}-\theta)<1.645-\sqrt{n}\theta)\\ &=1-\Phi(1.645-\sqrt{n}\theta), \end{align*} which tends to 0 as $\theta\to-\infty$. Graphically: theta.grid <- seq(-.8,.8,by=.01) n <- seq(10,90,by=20) power <- 1-pnorm(qnorm(.95)-outer(theta.grid,sqrt(n),"*")) colors <- c("#DB2828", "#40AD64", "#E0B43A", "#2A49A1", "#7A7969") matplot(theta.grid,power, type="l", lwd=2, lty=1, col=colors) legend("topleft", legend=paste0("n=",n), col=colors, lty=1, lwd=2) abline(h=0.05)
"Unbiased" hypothesis test --- what does it mean actually? [duplicate]
It means that the probability that the test rejects (its power) is always higher when the alternative is true than when the null is true. Suppose, for example, that you use a standard t-test for the
"Unbiased" hypothesis test --- what does it mean actually? [duplicate] It means that the probability that the test rejects (its power) is always higher when the alternative is true than when the null is true. Suppose, for example, that you use a standard t-test for the null $\theta\leq0$ against the alternative $\theta>0$. The standard rejection rule at $\alpha=0.05$ would be to reject if $t>1.645$ (for either a sample from a normal distribution or asymptotically, when a central limit theorem applies). Now, suppose you were to use that rule (reject if $t>1.645$) to test $\theta=0$ against $\theta\neq0$. The probability that the test will reject will decrease the more negative the true $\theta$, as we shall rarely observe large positive t-ratios in that case. In particular, this test is be biased, as $\beta(\theta)<\alpha$ when $\theta\in\Theta_1\cap(-\infty,0)$. For concreteness, we may compute this probability explicitly in the normal case, $X_i\sim N(\theta,1)$, with $\sigma^2=1$ assumed known for simplicity. Then, the t-statistic for $\theta=0$ simply is $t=\sqrt{n}\bar{X}$ and $$\sqrt{n}(\bar{X}-\theta)\sim N(0,1)$$ Thus, \begin{align*} \beta(\theta)&=P(t>1.645)\\ &=1-P(t<1.645)\\ &=1-P(\sqrt{n}(\bar{X}-\theta)<1.645-\sqrt{n}\theta)\\ &=1-\Phi(1.645-\sqrt{n}\theta), \end{align*} which tends to 0 as $\theta\to-\infty$. Graphically: theta.grid <- seq(-.8,.8,by=.01) n <- seq(10,90,by=20) power <- 1-pnorm(qnorm(.95)-outer(theta.grid,sqrt(n),"*")) colors <- c("#DB2828", "#40AD64", "#E0B43A", "#2A49A1", "#7A7969") matplot(theta.grid,power, type="l", lwd=2, lty=1, col=colors) legend("topleft", legend=paste0("n=",n), col=colors, lty=1, lwd=2) abline(h=0.05)
"Unbiased" hypothesis test --- what does it mean actually? [duplicate] It means that the probability that the test rejects (its power) is always higher when the alternative is true than when the null is true. Suppose, for example, that you use a standard t-test for the
32,434
Why is the estimated variance of a random effect not equal to the variance of its BLUP estimates? [duplicate]
What you examined by var(as.numeric(getME(m, "b"))) is the variance of the conditional mode of the random effects. The conditional mode is the best linear unbiased predictors (BLUP) of the random effects and is computed as the product of the relative covariance factor of the random effects $\Lambda$ and $u$ the conditional mode of the spherical random effects variable used during the optimisation of the profiled deviance. (ie. all.equal( var( as.numeric(getME(m, "b"))), var( as.numeric( crossprod(getME(m, "Lambdat"), getME(m, "u"))) ) ) # TRUE 1.10...); see here Eq. 10. The key to remember here is optimisation. That is because during that optimisation what we optimised against ($\theta$) is the ratio of the residual deviation (see this excellent thread on details on this matter) against the REML/ML random effects deviation; formally put the relative Cholesky factor of the random effects in $Z$. So if we multiply the estimated standard deviation of the errors $\hat{\sigma}$ with $\theta$ we will get the variance (ie. all.equal( (sigma(m) * m@theta)^2, summary(m)$varcor$DID[1] ) #TRUE 1.14.... This how the inequality is materialised. But why are these not the same? This goes back to the issue of BLUP and REML estimation; they are not guaranteed to be the same (Elvis' answer explains that too - yes, upvote it in case you haven't already; gung's answer here is highly relevant). Note also that exactly because we work on the standard deviation plane these difference will be amplified when examining the variances.
Why is the estimated variance of a random effect not equal to the variance of its BLUP estimates? [d
What you examined by var(as.numeric(getME(m, "b"))) is the variance of the conditional mode of the random effects. The conditional mode is the best linear unbiased predictors (BLUP) of the random effe
Why is the estimated variance of a random effect not equal to the variance of its BLUP estimates? [duplicate] What you examined by var(as.numeric(getME(m, "b"))) is the variance of the conditional mode of the random effects. The conditional mode is the best linear unbiased predictors (BLUP) of the random effects and is computed as the product of the relative covariance factor of the random effects $\Lambda$ and $u$ the conditional mode of the spherical random effects variable used during the optimisation of the profiled deviance. (ie. all.equal( var( as.numeric(getME(m, "b"))), var( as.numeric( crossprod(getME(m, "Lambdat"), getME(m, "u"))) ) ) # TRUE 1.10...); see here Eq. 10. The key to remember here is optimisation. That is because during that optimisation what we optimised against ($\theta$) is the ratio of the residual deviation (see this excellent thread on details on this matter) against the REML/ML random effects deviation; formally put the relative Cholesky factor of the random effects in $Z$. So if we multiply the estimated standard deviation of the errors $\hat{\sigma}$ with $\theta$ we will get the variance (ie. all.equal( (sigma(m) * m@theta)^2, summary(m)$varcor$DID[1] ) #TRUE 1.14.... This how the inequality is materialised. But why are these not the same? This goes back to the issue of BLUP and REML estimation; they are not guaranteed to be the same (Elvis' answer explains that too - yes, upvote it in case you haven't already; gung's answer here is highly relevant). Note also that exactly because we work on the standard deviation plane these difference will be amplified when examining the variances.
Why is the estimated variance of a random effect not equal to the variance of its BLUP estimates? [d What you examined by var(as.numeric(getME(m, "b"))) is the variance of the conditional mode of the random effects. The conditional mode is the best linear unbiased predictors (BLUP) of the random effe
32,435
Why is the estimated variance of a random effect not equal to the variance of its BLUP estimates? [duplicate]
The variance in the mixed model is not the variance of the shrunken BLUP random effects but the variance of what could be called the un-shrunken fixed effects (obtained from a dummy for each group) that is treating the effect for a group as a separate estimate and not as part of distribution for which you have an estimated variance. Consequently the mixed higher-level variance is not the estimated between group variance of the sample, but the estimated between-group variance in the population. This might help https://www.researchgate.net/publication/225303298_Contextual_Models_of_Urban_House_Prices_A_Comparison_of_Fixed-_and_Random-Coefficient_Models_Developed_by_Expansion and this https://www.researchgate.net/publication/252146040_Do_multilevel_models_ever_give_different_results
Why is the estimated variance of a random effect not equal to the variance of its BLUP estimates? [d
The variance in the mixed model is not the variance of the shrunken BLUP random effects but the variance of what could be called the un-shrunken fixed effects (obtained from a dummy for each group) th
Why is the estimated variance of a random effect not equal to the variance of its BLUP estimates? [duplicate] The variance in the mixed model is not the variance of the shrunken BLUP random effects but the variance of what could be called the un-shrunken fixed effects (obtained from a dummy for each group) that is treating the effect for a group as a separate estimate and not as part of distribution for which you have an estimated variance. Consequently the mixed higher-level variance is not the estimated between group variance of the sample, but the estimated between-group variance in the population. This might help https://www.researchgate.net/publication/225303298_Contextual_Models_of_Urban_House_Prices_A_Comparison_of_Fixed-_and_Random-Coefficient_Models_Developed_by_Expansion and this https://www.researchgate.net/publication/252146040_Do_multilevel_models_ever_give_different_results
Why is the estimated variance of a random effect not equal to the variance of its BLUP estimates? [d The variance in the mixed model is not the variance of the shrunken BLUP random effects but the variance of what could be called the un-shrunken fixed effects (obtained from a dummy for each group) th
32,436
What is the difference between Cross Correlation and Correlation Matrix
When it comes to correlation, there are several types in the realm of time series analysis. Cross correlation is only one measure - which is referring to the correlation of one signal with another. However, remember that a time series can also be autocorrelated, i.e. a signal for a particular time period can be correlated with the one previous. So, correlation is not necessarily time independent as you have said. When you say one signal is delayed relative to the other, you are referring to the time period for which one signal is expected to follow another. e.g. during a thunderstorm, you will first see light and then hear thunder X seconds later. However, cross-correlation of a signal does not necessarily imply Granger Causality, i.e. that one causes the other, so this would still have to be investigated separately: Cross Correlation Does Not Imply Granger Causation Your question is somewhat broad, but hopefully this clears up some of the main points for you.
What is the difference between Cross Correlation and Correlation Matrix
When it comes to correlation, there are several types in the realm of time series analysis. Cross correlation is only one measure - which is referring to the correlation of one signal with another. H
What is the difference between Cross Correlation and Correlation Matrix When it comes to correlation, there are several types in the realm of time series analysis. Cross correlation is only one measure - which is referring to the correlation of one signal with another. However, remember that a time series can also be autocorrelated, i.e. a signal for a particular time period can be correlated with the one previous. So, correlation is not necessarily time independent as you have said. When you say one signal is delayed relative to the other, you are referring to the time period for which one signal is expected to follow another. e.g. during a thunderstorm, you will first see light and then hear thunder X seconds later. However, cross-correlation of a signal does not necessarily imply Granger Causality, i.e. that one causes the other, so this would still have to be investigated separately: Cross Correlation Does Not Imply Granger Causation Your question is somewhat broad, but hopefully this clears up some of the main points for you.
What is the difference between Cross Correlation and Correlation Matrix When it comes to correlation, there are several types in the realm of time series analysis. Cross correlation is only one measure - which is referring to the correlation of one signal with another. H
32,437
Third central moment of a sum of a random number of iid random variables
Your steps look right to me. We need to assume that the moments exist. The only step I was unsure about was $\mu_3(S | X) = N \cdot \mu_3[X]$. But, we can prove that: \begin{align} \mu_3(S | X) &= E\left[(S - E[S])^3 | N \right] \\ &= E\left[ \left( \sum_{i=1}^N (X_i - E[X]) \right)^3 \middle| N \right] \\ &= E \left[ \sum_{i=1}^N (X_i - E[X])^3 \middle| N\right] \end{align} where to establish the last equality, we can use the multinomial theorem. For a given $n$, \begin{align} E\left[ \left( \sum_{i=1}^n (X_i - E[X]) \right)^3 \right] &= E \left[ \sum_{\sum_{i=1}^n k_i = 3} {3 \choose{k_1, \ldots, k_n}} (X_1 - E[X])^{k_1} \cdots (X_n - E[X])^{k_n} \right] \\ &= E\left[ \sum_{i=1}^n (X_i - E[X])^3 \right], \end{align} because when $k_i = 2$ for any $i$, there exists another $j$ where $k_j=1$ (Due to independence of $X_i$ and $X_j$ and the fact that the expectation of $X_j - E[X]$ is zero, causing that particular term to become zero). Now it should be clear that $\mu_3(S | X) = N \cdot \mu_3[X]$.
Third central moment of a sum of a random number of iid random variables
Your steps look right to me. We need to assume that the moments exist. The only step I was unsure about was $\mu_3(S | X) = N \cdot \mu_3[X]$. But, we can prove that: \begin{align} \mu_3(S | X) &= E\l
Third central moment of a sum of a random number of iid random variables Your steps look right to me. We need to assume that the moments exist. The only step I was unsure about was $\mu_3(S | X) = N \cdot \mu_3[X]$. But, we can prove that: \begin{align} \mu_3(S | X) &= E\left[(S - E[S])^3 | N \right] \\ &= E\left[ \left( \sum_{i=1}^N (X_i - E[X]) \right)^3 \middle| N \right] \\ &= E \left[ \sum_{i=1}^N (X_i - E[X])^3 \middle| N\right] \end{align} where to establish the last equality, we can use the multinomial theorem. For a given $n$, \begin{align} E\left[ \left( \sum_{i=1}^n (X_i - E[X]) \right)^3 \right] &= E \left[ \sum_{\sum_{i=1}^n k_i = 3} {3 \choose{k_1, \ldots, k_n}} (X_1 - E[X])^{k_1} \cdots (X_n - E[X])^{k_n} \right] \\ &= E\left[ \sum_{i=1}^n (X_i - E[X])^3 \right], \end{align} because when $k_i = 2$ for any $i$, there exists another $j$ where $k_j=1$ (Due to independence of $X_i$ and $X_j$ and the fact that the expectation of $X_j - E[X]$ is zero, causing that particular term to become zero). Now it should be clear that $\mu_3(S | X) = N \cdot \mu_3[X]$.
Third central moment of a sum of a random number of iid random variables Your steps look right to me. We need to assume that the moments exist. The only step I was unsure about was $\mu_3(S | X) = N \cdot \mu_3[X]$. But, we can prove that: \begin{align} \mu_3(S | X) &= E\l
32,438
Identifiability in a nonlinear regression problem
There is no identifiability problem, except in the trivial sense that any one particular model can have two descriptions. The real problem appears to be the difficulty in fitting the model--but that's due to how the models are parameterized rather than lack of identifiability. This problem has an equally trivial solution: declare, without any loss of generality, that $\beta \ge \delta$. If you want to be really fussy, also insist that if $\beta=\delta$, then $\alpha \ge \gamma$. Unfortunately, that requires any procedure to fit the model to respect these constraints. Introducing a constraint here is not so bad though, because the application is such that obviously all parameters are non-negative anyway: the parameter space already has sharp boundaries. Including one more constraint won't force any changes in how we go about fitting the model. One well-known method to convert a constrained optimization into an unconstrained one is to reparameterize the problem so that in the new parameter space the boundaries are pushed out to infinity. There are many ways to accomplish that here. A consideration of what the parameters mean will guide us. In particular, $\nu = \alpha + \gamma$ is the maximum attained by the function $$t\to g(t; \alpha,\beta,\gamma,\delta) = \alpha\left(1 - e^{-\beta t}\right) + \gamma\left(1 - e^{-\delta t}\right)$$ for $t \ge 0$. Given $\nu$, then necessarily $0 \le \alpha\le \nu$ and $\gamma = \nu - \alpha$. When non-negative values sum to a fixed whole, it often works to parameterize their proportions of the whole in terms of angles: let one proportion be the squared cosine and the other be the squared sine. Furthermore, a simple way to ensure $\nu$, $\beta$, and $\delta$ are positive is to make them exponentials--that is, use their logarithms as parameters. Finally, to enforce $\delta \le \beta$, set $\delta$ to be the squared cosine of some angle times $\beta$. Thus we might reparameterize the problem by fitting the function $$t \to f(t;n,a,b,d) = e^n\left(1 - \cos(a)^2\exp\left(-e^{b} t\right) - \sin(a)^2\exp\left(-e^{b\cos(d)^2} t\right)\right).$$ From estimates of these parameters (which, by the way, are not "identifiable" due to the ambiguity in the angles $a$ and $d$) you can recover the original ones as $$\eqalign{ \alpha &= e^n\cos(a)^2 \\ \beta &=e^b \\ \gamma &=e^n\sin(a)^2 \\ \delta &= e^b\cos(d)^2. }$$ Properties of the exponential and trig functions assure all the constraints hold: $\alpha \gt 0$, $\beta \ge \delta \gt 0$, and $\gamma \gt 0$. (Since double precision floats can become astronomically small, there is no practical distinction between $\gt$ and $\ge$ in these constraints.) In this well-defined sense the model is identifiable even though the parameters used to fit it are not identifiable. Although one could use MCMC, if the purpose is just to fit the curve then it's more straightforward to use a numerical solver such as Newton-Raphson. The trick is to find a good starting value. The maximum of the $y_i$ would be a slight overestimate of $e^n$; so start, perhaps with $n=\log(\max(y_i)/2)$. You might begin with $a=\pi/4$, supposing each component makes a substantial contribution to the whole. Make some reasonable guesses about $e^b$ and $e^d$ based on expected decay rates. For instance, if the range of $t$ is reasonable, then take $b$ to be some fraction of the largest $t$ and perhaps arbitrarily pick $d=\pi/4$; maybe use a smaller starting value. (You will often get different values for the parameter estimates depending on these choices, but typically they will not appreciably affect the function $f$ itself.) In many circumstances, this approach works strikingly well. Except when the variance of the errors is the same size as $\max{y_i}$ or larger (where it will be hard to discern any signal at all without a large amount of data), the fit works even with tiny amounts of data: all it needs is four. Note that regardless of how the model is fit, there ordinarily will be huge uncertainty in the parameters: this family of curves is essentially a tiny perturbation of the two-parameter exponential family $t\to Ae^{-Bt}$. In many circumstances, then, two of the parameters (corresponding to the amplitude $A$ and longest decay rate $B$) can be identified with reasonable precision but the other two parameters, which reflect small variations from this exponential shape, will usually be highly uncertain. The figure shows an example of a challenging fit. The underlying curve is shown in black. Ultimately it reaches a maximum of $4/3$, very slowly. Only $24$ data points are available, plotted as gray dots. The standard deviation of the random errors is $1/2$, a sizable proportion of that maximum. Many of the errors were positive, causing the fitted curve in red to be a little higher. The two exponential components of the fitted curve are shown as dashed and dotted gray lines. One shows a rapid rise to a threshold of $1/3$ by the time $t=1$; the other reflects the other exponential rising to its threshold of $1$. (You will have little hope of reproducing that sharp "shoulder" near $t=1$ until you have a $1000$ data points or more: try it out by varying n in the code below.) Your success in any particular problem will depend on the magnitudes of the errors; the range of values of $t$ that are sampled; how those values are spaced; how many values are available; and choice of starting values. Nevertheless this appears to be a tractable problem in general, with solutions that can be obtained rapidly. Moreover, any maximum likelihood fitter will proceed similarly to minimize the sum of squares of residuals--and will, in addition, provide confidence regions for the parameters. This is the R code I used to test this proposal. It will reproduce the figure and is easily modified--change the values of the variables at the beginning--to study data that look like any you might have. # # Describe the underlying model # set.seed(17) alpha <- 1 beta <- 2 gamma <- 1/3 delta <- 1/10 sigma <- 1/2 # Error SD. n <- 24 x.max <- 20 # Largest value of t. # # The original parameterization. # g <- function(x, alpha, beta, gamma, delta) { alpha * (1 - exp(-beta * x)) + gamma * (1 - exp(-delta * x)) } # # The re-parameterization. `f.1` and `f.2` are the two exponential components. # f <- function(x, nu, t.a, log.b, t.d) { n <- exp(nu) a <- cos(t.a)^2 alpha <- n*a gamma <- n*(1-a) beta <- exp(log.b) delta <- cos(t.d)^2 * beta n - alpha * exp(-beta * x) - gamma * exp(-delta * x) } f.1 <- function(x, nu, t.a, log.b, t.d) { n <- exp(nu) a <- cos(t.a)^2 alpha <- n*a beta <- exp(log.b) alpha * (1 - exp(-beta * x)) } f.2 <- function(x, nu, t.a, log.b, t.d) { n <- exp(nu) a <- cos(t.a)^2 gamma <- n*(1-a) beta <- exp(log.b) delta <- cos(t.d)^2 * beta gamma * (1 - exp(-delta * x)) } # # The objective to minimize is the mean squared residual. # This is equivalent to finding the MLE for Gaussian errors. # obj <- function(theta, x, y) { crossprod(y - f(x, theta[1], theta[2], theta[3], theta[4])) / length(x) } # # Create data and plot them. # x <- seq(0, x.max, length.out=n) y <- g(x, alpha, beta, gamma, delta) + rnorm(length(x), 0, sigma) plot(x,y, pch=16, col="#00000040", xlab="t") # # Fit the curve. # theta <- c(nu=log(max(y)/2), t.a=pi/4, log.b=log(max(x)/10), t.d=pi/4) fit <- nlm(obj, theta, x=x, y=y, gradtol=1e-14) theta.hat <- fit$estimate # # Plot relevant curves. # curve(g(x, alpha, beta, gamma, delta), add=TRUE, lwd=2) curve(f(x, theta.hat[1], theta.hat[2], theta.hat[3], theta.hat[4]), add=TRUE, col="Red", lwd=2) curve(f.1(x, theta.hat[1], theta.hat[2], theta.hat[3], theta.hat[4]), add=TRUE, col="Gray", lty=2, lwd=2) curve(f.2(x, theta.hat[1], theta.hat[2], theta.hat[3], theta.hat[4]), add=TRUE, col="Gray", lty=3, lwd=2)
Identifiability in a nonlinear regression problem
There is no identifiability problem, except in the trivial sense that any one particular model can have two descriptions. The real problem appears to be the difficulty in fitting the model--but that'
Identifiability in a nonlinear regression problem There is no identifiability problem, except in the trivial sense that any one particular model can have two descriptions. The real problem appears to be the difficulty in fitting the model--but that's due to how the models are parameterized rather than lack of identifiability. This problem has an equally trivial solution: declare, without any loss of generality, that $\beta \ge \delta$. If you want to be really fussy, also insist that if $\beta=\delta$, then $\alpha \ge \gamma$. Unfortunately, that requires any procedure to fit the model to respect these constraints. Introducing a constraint here is not so bad though, because the application is such that obviously all parameters are non-negative anyway: the parameter space already has sharp boundaries. Including one more constraint won't force any changes in how we go about fitting the model. One well-known method to convert a constrained optimization into an unconstrained one is to reparameterize the problem so that in the new parameter space the boundaries are pushed out to infinity. There are many ways to accomplish that here. A consideration of what the parameters mean will guide us. In particular, $\nu = \alpha + \gamma$ is the maximum attained by the function $$t\to g(t; \alpha,\beta,\gamma,\delta) = \alpha\left(1 - e^{-\beta t}\right) + \gamma\left(1 - e^{-\delta t}\right)$$ for $t \ge 0$. Given $\nu$, then necessarily $0 \le \alpha\le \nu$ and $\gamma = \nu - \alpha$. When non-negative values sum to a fixed whole, it often works to parameterize their proportions of the whole in terms of angles: let one proportion be the squared cosine and the other be the squared sine. Furthermore, a simple way to ensure $\nu$, $\beta$, and $\delta$ are positive is to make them exponentials--that is, use their logarithms as parameters. Finally, to enforce $\delta \le \beta$, set $\delta$ to be the squared cosine of some angle times $\beta$. Thus we might reparameterize the problem by fitting the function $$t \to f(t;n,a,b,d) = e^n\left(1 - \cos(a)^2\exp\left(-e^{b} t\right) - \sin(a)^2\exp\left(-e^{b\cos(d)^2} t\right)\right).$$ From estimates of these parameters (which, by the way, are not "identifiable" due to the ambiguity in the angles $a$ and $d$) you can recover the original ones as $$\eqalign{ \alpha &= e^n\cos(a)^2 \\ \beta &=e^b \\ \gamma &=e^n\sin(a)^2 \\ \delta &= e^b\cos(d)^2. }$$ Properties of the exponential and trig functions assure all the constraints hold: $\alpha \gt 0$, $\beta \ge \delta \gt 0$, and $\gamma \gt 0$. (Since double precision floats can become astronomically small, there is no practical distinction between $\gt$ and $\ge$ in these constraints.) In this well-defined sense the model is identifiable even though the parameters used to fit it are not identifiable. Although one could use MCMC, if the purpose is just to fit the curve then it's more straightforward to use a numerical solver such as Newton-Raphson. The trick is to find a good starting value. The maximum of the $y_i$ would be a slight overestimate of $e^n$; so start, perhaps with $n=\log(\max(y_i)/2)$. You might begin with $a=\pi/4$, supposing each component makes a substantial contribution to the whole. Make some reasonable guesses about $e^b$ and $e^d$ based on expected decay rates. For instance, if the range of $t$ is reasonable, then take $b$ to be some fraction of the largest $t$ and perhaps arbitrarily pick $d=\pi/4$; maybe use a smaller starting value. (You will often get different values for the parameter estimates depending on these choices, but typically they will not appreciably affect the function $f$ itself.) In many circumstances, this approach works strikingly well. Except when the variance of the errors is the same size as $\max{y_i}$ or larger (where it will be hard to discern any signal at all without a large amount of data), the fit works even with tiny amounts of data: all it needs is four. Note that regardless of how the model is fit, there ordinarily will be huge uncertainty in the parameters: this family of curves is essentially a tiny perturbation of the two-parameter exponential family $t\to Ae^{-Bt}$. In many circumstances, then, two of the parameters (corresponding to the amplitude $A$ and longest decay rate $B$) can be identified with reasonable precision but the other two parameters, which reflect small variations from this exponential shape, will usually be highly uncertain. The figure shows an example of a challenging fit. The underlying curve is shown in black. Ultimately it reaches a maximum of $4/3$, very slowly. Only $24$ data points are available, plotted as gray dots. The standard deviation of the random errors is $1/2$, a sizable proportion of that maximum. Many of the errors were positive, causing the fitted curve in red to be a little higher. The two exponential components of the fitted curve are shown as dashed and dotted gray lines. One shows a rapid rise to a threshold of $1/3$ by the time $t=1$; the other reflects the other exponential rising to its threshold of $1$. (You will have little hope of reproducing that sharp "shoulder" near $t=1$ until you have a $1000$ data points or more: try it out by varying n in the code below.) Your success in any particular problem will depend on the magnitudes of the errors; the range of values of $t$ that are sampled; how those values are spaced; how many values are available; and choice of starting values. Nevertheless this appears to be a tractable problem in general, with solutions that can be obtained rapidly. Moreover, any maximum likelihood fitter will proceed similarly to minimize the sum of squares of residuals--and will, in addition, provide confidence regions for the parameters. This is the R code I used to test this proposal. It will reproduce the figure and is easily modified--change the values of the variables at the beginning--to study data that look like any you might have. # # Describe the underlying model # set.seed(17) alpha <- 1 beta <- 2 gamma <- 1/3 delta <- 1/10 sigma <- 1/2 # Error SD. n <- 24 x.max <- 20 # Largest value of t. # # The original parameterization. # g <- function(x, alpha, beta, gamma, delta) { alpha * (1 - exp(-beta * x)) + gamma * (1 - exp(-delta * x)) } # # The re-parameterization. `f.1` and `f.2` are the two exponential components. # f <- function(x, nu, t.a, log.b, t.d) { n <- exp(nu) a <- cos(t.a)^2 alpha <- n*a gamma <- n*(1-a) beta <- exp(log.b) delta <- cos(t.d)^2 * beta n - alpha * exp(-beta * x) - gamma * exp(-delta * x) } f.1 <- function(x, nu, t.a, log.b, t.d) { n <- exp(nu) a <- cos(t.a)^2 alpha <- n*a beta <- exp(log.b) alpha * (1 - exp(-beta * x)) } f.2 <- function(x, nu, t.a, log.b, t.d) { n <- exp(nu) a <- cos(t.a)^2 gamma <- n*(1-a) beta <- exp(log.b) delta <- cos(t.d)^2 * beta gamma * (1 - exp(-delta * x)) } # # The objective to minimize is the mean squared residual. # This is equivalent to finding the MLE for Gaussian errors. # obj <- function(theta, x, y) { crossprod(y - f(x, theta[1], theta[2], theta[3], theta[4])) / length(x) } # # Create data and plot them. # x <- seq(0, x.max, length.out=n) y <- g(x, alpha, beta, gamma, delta) + rnorm(length(x), 0, sigma) plot(x,y, pch=16, col="#00000040", xlab="t") # # Fit the curve. # theta <- c(nu=log(max(y)/2), t.a=pi/4, log.b=log(max(x)/10), t.d=pi/4) fit <- nlm(obj, theta, x=x, y=y, gradtol=1e-14) theta.hat <- fit$estimate # # Plot relevant curves. # curve(g(x, alpha, beta, gamma, delta), add=TRUE, lwd=2) curve(f(x, theta.hat[1], theta.hat[2], theta.hat[3], theta.hat[4]), add=TRUE, col="Red", lwd=2) curve(f.1(x, theta.hat[1], theta.hat[2], theta.hat[3], theta.hat[4]), add=TRUE, col="Gray", lty=2, lwd=2) curve(f.2(x, theta.hat[1], theta.hat[2], theta.hat[3], theta.hat[4]), add=TRUE, col="Gray", lty=3, lwd=2)
Identifiability in a nonlinear regression problem There is no identifiability problem, except in the trivial sense that any one particular model can have two descriptions. The real problem appears to be the difficulty in fitting the model--but that'
32,439
nonlinear least squares versus maximum likelihood in R, nls() or nlm()?
To derive the expectation the assumption was made that the errors are normal and mean zero. If that is your assumption, MLE and NLS should be mathematically identical, and differences would probably be explained by the choice / setting of the optimizer. Whether a normal distribution for a binary response is a good idea is another question. An alternative would be a logistic glm with your nonlinear predictor, estimated with MLE. If you do MLE, you might want to consider using https://cran.r-project.org/web/packages/bbmle/index.html instead of nlm(), more options for CIs and so on.
nonlinear least squares versus maximum likelihood in R, nls() or nlm()?
To derive the expectation the assumption was made that the errors are normal and mean zero. If that is your assumption, MLE and NLS should be mathematically identical, and differences would probabl
nonlinear least squares versus maximum likelihood in R, nls() or nlm()? To derive the expectation the assumption was made that the errors are normal and mean zero. If that is your assumption, MLE and NLS should be mathematically identical, and differences would probably be explained by the choice / setting of the optimizer. Whether a normal distribution for a binary response is a good idea is another question. An alternative would be a logistic glm with your nonlinear predictor, estimated with MLE. If you do MLE, you might want to consider using https://cran.r-project.org/web/packages/bbmle/index.html instead of nlm(), more options for CIs and so on.
nonlinear least squares versus maximum likelihood in R, nls() or nlm()? To derive the expectation the assumption was made that the errors are normal and mean zero. If that is your assumption, MLE and NLS should be mathematically identical, and differences would probabl
32,440
Monotone machine learning
While it's an old question, I have just found that gradient boosted trees support such functionality and it is already implemented with at XGBoost. Check here for more details
Monotone machine learning
While it's an old question, I have just found that gradient boosted trees support such functionality and it is already implemented with at XGBoost. Check here for more details
Monotone machine learning While it's an old question, I have just found that gradient boosted trees support such functionality and it is already implemented with at XGBoost. Check here for more details
Monotone machine learning While it's an old question, I have just found that gradient boosted trees support such functionality and it is already implemented with at XGBoost. Check here for more details
32,441
Monotone machine learning
You can always constrain a neural network to be monotonic by constraining the weights to be positive and using monotonic activations as discussed here. See here for a practical tutorial with an open source implementation.
Monotone machine learning
You can always constrain a neural network to be monotonic by constraining the weights to be positive and using monotonic activations as discussed here. See here for a practical tutorial with an open s
Monotone machine learning You can always constrain a neural network to be monotonic by constraining the weights to be positive and using monotonic activations as discussed here. See here for a practical tutorial with an open source implementation.
Monotone machine learning You can always constrain a neural network to be monotonic by constraining the weights to be positive and using monotonic activations as discussed here. See here for a practical tutorial with an open s
32,442
Binomial GLM in R: the same data, but two different models
The model is $$\operatorname{E}Y = \frac{1}{1+ \exp[-(\beta_0 + \beta_1 x_1 + \beta_2 x_2)]}$$ & it's saturated, having as many parameters to estimate as the no. distinct covariate patterns. So the equations to solve are as follows: For $x_1=1$, $x_2 =0$, $\operatorname{E}Y=\frac{1}{2}$ $\beta_0 + \beta_1 = 0$ For $x_1=0$, $x_2 =1$, $\operatorname{E}Y=\frac{1}{4}$ $\beta_0 + \beta_2 = -\log 3$ For $x_1=1$, $x_2=1$, $\operatorname{E}Y=1$ $\beta_0 + \beta_1 + \beta_2 = \infty$ There is quasi-complete separation (if $x_1+x_2>1$ then $E{Y}=1$), so maximum-likelihood estimates of the coefficients are unbounded. But any sufficiently large value $c$ can stand in for infinity, giving the solutions: $\beta_0 = -(c + \log 3)$ $\beta_1 = c + \log3$ $\beta_2 = c$ I don't know why glm gives up trying to maximize the likelihood at different values for $c$ depending on the data structure, but it's of no practical consequence: predictions & differences in likelihoods will be almost the same.
Binomial GLM in R: the same data, but two different models
The model is $$\operatorname{E}Y = \frac{1}{1+ \exp[-(\beta_0 + \beta_1 x_1 + \beta_2 x_2)]}$$ & it's saturated, having as many parameters to estimate as the no. distinct covariate patterns. So the eq
Binomial GLM in R: the same data, but two different models The model is $$\operatorname{E}Y = \frac{1}{1+ \exp[-(\beta_0 + \beta_1 x_1 + \beta_2 x_2)]}$$ & it's saturated, having as many parameters to estimate as the no. distinct covariate patterns. So the equations to solve are as follows: For $x_1=1$, $x_2 =0$, $\operatorname{E}Y=\frac{1}{2}$ $\beta_0 + \beta_1 = 0$ For $x_1=0$, $x_2 =1$, $\operatorname{E}Y=\frac{1}{4}$ $\beta_0 + \beta_2 = -\log 3$ For $x_1=1$, $x_2=1$, $\operatorname{E}Y=1$ $\beta_0 + \beta_1 + \beta_2 = \infty$ There is quasi-complete separation (if $x_1+x_2>1$ then $E{Y}=1$), so maximum-likelihood estimates of the coefficients are unbounded. But any sufficiently large value $c$ can stand in for infinity, giving the solutions: $\beta_0 = -(c + \log 3)$ $\beta_1 = c + \log3$ $\beta_2 = c$ I don't know why glm gives up trying to maximize the likelihood at different values for $c$ depending on the data structure, but it's of no practical consequence: predictions & differences in likelihoods will be almost the same.
Binomial GLM in R: the same data, but two different models The model is $$\operatorname{E}Y = \frac{1}{1+ \exp[-(\beta_0 + \beta_1 x_1 + \beta_2 x_2)]}$$ & it's saturated, having as many parameters to estimate as the no. distinct covariate patterns. So the eq
32,443
Binomial GLM in R: the same data, but two different models
Despite the converge fail that was illustrated in this example, it should be noted there are indeed some key differences in these applications. A weighted GLM has number of observations equal to the number of response levels, even when the weights are frequency weights. On the other hand, if you replicate the factor levels according to the frequency weights, the number of observations is equal to the sum of the weights (appropriately). Ultimately, they will converge to the same thing, but interesting behavior is observed when you inspect the properties of the one-step estimators: set.seed(123) x <- 0:2 y <- c(1,0,2)/2 w <- 1:3*10 ## weighted and unweighted one step glms summary(glm(y ~ x, family=binomial, weights=w, control=list(maxit = 1))) summary(glm(y ~ x, family=binomial, data.frame('y'=rep.int(y, w), 'x'=rep.int(x,w)), control=list(maxit = 1))) Give the following (different) results: Call: glm(formula = y ~ x, family = binomial, weights = w, control = list(maxit = 1)) Deviance Residuals: 1 2 3 0.8269 -7.0855 2.3210 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) -0.5260 0.6210 -0.847 0.3970 x 1.4456 0.7484 1.932 0.0534 . --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for binomial family taken to be 1) Null deviance: 67.640 on 2 degrees of freedom Residual deviance: 56.275 on 1 degrees of freedom AIC: 63.079 Number of Fisher Scoring iterations: 1 Warning message: glm.fit: algorithm did not converge > Call: glm(formula = y ~ x, family = binomial, data = data.frame(y = rep.int(y, w), x = rep.int(x, w)), control = list(maxit = 1)) Deviance Residuals: Min 1Q Median 3Q Max -1.1496 -1.1496 0.5946 0.5946 0.8376 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) -1.7747 0.5502 -3.226 0.00126 ** x 1.7089 0.3700 4.618 3.87e-06 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for binomial family taken to be 1) Null deviance: 67.640 on 59 degrees of freedom Residual deviance: 44.055 on 58 degrees of freedom AIC: 44.171 Number of Fisher Scoring iterations: 1 Warning messages: 1: In eval(expr, envir, enclos) : non-integer #successes in a binomial glm! 2: glm.fit: algorithm did not converge > So to answer OP's question, the reason why these are irreconcilable results (despite the converge fail) is that the actual trace of the Fisher Scoring differs for weighted and unweighted analyses because in the weighted case, the Fisher information is based on the 3 observation weighted sample, in the unweighted case, the Fisher Information is based on the 60 observation unweighted information. The 3 observation weighted and 60 observation unweighted likelihoods only agree when Fisher scoring actually obtains a beta estimate giving a 0 sum-score solution.
Binomial GLM in R: the same data, but two different models
Despite the converge fail that was illustrated in this example, it should be noted there are indeed some key differences in these applications. A weighted GLM has number of observations equal to the n
Binomial GLM in R: the same data, but two different models Despite the converge fail that was illustrated in this example, it should be noted there are indeed some key differences in these applications. A weighted GLM has number of observations equal to the number of response levels, even when the weights are frequency weights. On the other hand, if you replicate the factor levels according to the frequency weights, the number of observations is equal to the sum of the weights (appropriately). Ultimately, they will converge to the same thing, but interesting behavior is observed when you inspect the properties of the one-step estimators: set.seed(123) x <- 0:2 y <- c(1,0,2)/2 w <- 1:3*10 ## weighted and unweighted one step glms summary(glm(y ~ x, family=binomial, weights=w, control=list(maxit = 1))) summary(glm(y ~ x, family=binomial, data.frame('y'=rep.int(y, w), 'x'=rep.int(x,w)), control=list(maxit = 1))) Give the following (different) results: Call: glm(formula = y ~ x, family = binomial, weights = w, control = list(maxit = 1)) Deviance Residuals: 1 2 3 0.8269 -7.0855 2.3210 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) -0.5260 0.6210 -0.847 0.3970 x 1.4456 0.7484 1.932 0.0534 . --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for binomial family taken to be 1) Null deviance: 67.640 on 2 degrees of freedom Residual deviance: 56.275 on 1 degrees of freedom AIC: 63.079 Number of Fisher Scoring iterations: 1 Warning message: glm.fit: algorithm did not converge > Call: glm(formula = y ~ x, family = binomial, data = data.frame(y = rep.int(y, w), x = rep.int(x, w)), control = list(maxit = 1)) Deviance Residuals: Min 1Q Median 3Q Max -1.1496 -1.1496 0.5946 0.5946 0.8376 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) -1.7747 0.5502 -3.226 0.00126 ** x 1.7089 0.3700 4.618 3.87e-06 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for binomial family taken to be 1) Null deviance: 67.640 on 59 degrees of freedom Residual deviance: 44.055 on 58 degrees of freedom AIC: 44.171 Number of Fisher Scoring iterations: 1 Warning messages: 1: In eval(expr, envir, enclos) : non-integer #successes in a binomial glm! 2: glm.fit: algorithm did not converge > So to answer OP's question, the reason why these are irreconcilable results (despite the converge fail) is that the actual trace of the Fisher Scoring differs for weighted and unweighted analyses because in the weighted case, the Fisher information is based on the 3 observation weighted sample, in the unweighted case, the Fisher Information is based on the 60 observation unweighted information. The 3 observation weighted and 60 observation unweighted likelihoods only agree when Fisher scoring actually obtains a beta estimate giving a 0 sum-score solution.
Binomial GLM in R: the same data, but two different models Despite the converge fail that was illustrated in this example, it should be noted there are indeed some key differences in these applications. A weighted GLM has number of observations equal to the n
32,444
Posterior predictive distribution vs MAP estimate
I often think of it this way. In the fully Bayesian approach, we find the integral $$p(x^*|X) = \int p(x^*|\theta) p(\theta|X) \text{ d}\theta$$ as integrating over all possible models (infinitely many in fact), and we make a prediction taking all of these models "into consideration". As this is often intractable, we use the MAP estimate of the posterior $p(\theta|X)$, which corresponds to evaluating the same integral but this time using a infinitely small part of $p(\theta|X)$, namely at its maximum. In other words, we multiply $p(x^*|\theta)$ with a new "delta-distribution" located at the max of the posterior distribution and integrate this to obtain the prediction. The difference is therefore rather obvious: a fully Bayesian treatment corresponds to an infinite ensemble of models, where a given prediction $p(x|\textbf{x},\theta)$ is weighted by the model probability $p(\theta|\textbf{x})$, i.e. more likely models will contribute more to the prediction. The MAP estimate of the parameters will give you the prediction from one specific model, namely the most likely one according to Bayes theorem. Ensemble theory shows us that we often obtain better generalization and more accurate predictions and therefore this will often be "better" than the MAP. Hope this helps.
Posterior predictive distribution vs MAP estimate
I often think of it this way. In the fully Bayesian approach, we find the integral $$p(x^*|X) = \int p(x^*|\theta) p(\theta|X) \text{ d}\theta$$ as integrating over all possible models (infinitely man
Posterior predictive distribution vs MAP estimate I often think of it this way. In the fully Bayesian approach, we find the integral $$p(x^*|X) = \int p(x^*|\theta) p(\theta|X) \text{ d}\theta$$ as integrating over all possible models (infinitely many in fact), and we make a prediction taking all of these models "into consideration". As this is often intractable, we use the MAP estimate of the posterior $p(\theta|X)$, which corresponds to evaluating the same integral but this time using a infinitely small part of $p(\theta|X)$, namely at its maximum. In other words, we multiply $p(x^*|\theta)$ with a new "delta-distribution" located at the max of the posterior distribution and integrate this to obtain the prediction. The difference is therefore rather obvious: a fully Bayesian treatment corresponds to an infinite ensemble of models, where a given prediction $p(x|\textbf{x},\theta)$ is weighted by the model probability $p(\theta|\textbf{x})$, i.e. more likely models will contribute more to the prediction. The MAP estimate of the parameters will give you the prediction from one specific model, namely the most likely one according to Bayes theorem. Ensemble theory shows us that we often obtain better generalization and more accurate predictions and therefore this will often be "better" than the MAP. Hope this helps.
Posterior predictive distribution vs MAP estimate I often think of it this way. In the fully Bayesian approach, we find the integral $$p(x^*|X) = \int p(x^*|\theta) p(\theta|X) \text{ d}\theta$$ as integrating over all possible models (infinitely man
32,445
Posterior predictive distribution vs MAP estimate
Assuming your model is correctly specified, the predictive distribution gives an estimate of the new data point that takes account of all the uncertainty in the unknown parameter $\theta$. In the second method, where you merely use a parameter-substitution using your estimator, you are effectively treating this as a perfect estimator of the unknown parameter, and so the resulting "predictive" distribution does not take account of the uncertainty in the unknown parameter $\theta$. For this reason, the latter distribution will tend to have lower variability than the former, and if your model is correctly specified, this means that it underestimates the variability of the new data point. So yes, the predictive distribution is generally regarded as being "better". Incidentally, this kind of comparison is not exclusive to Bayesian statistics. This methods you are comparing are very much like the analogous methods that occurs in frequentist methodology, where one can use a pivotal quantity to get a proper confidence interval for a new data point (analogous to a Bayesian predictive interval), or one can merely substitute the MLE as if it were a known parameter value and obtain an interval for a new data point from the sampling distribution (analogous to the Bayesian parameter-substitution method).
Posterior predictive distribution vs MAP estimate
Assuming your model is correctly specified, the predictive distribution gives an estimate of the new data point that takes account of all the uncertainty in the unknown parameter $\theta$. In the sec
Posterior predictive distribution vs MAP estimate Assuming your model is correctly specified, the predictive distribution gives an estimate of the new data point that takes account of all the uncertainty in the unknown parameter $\theta$. In the second method, where you merely use a parameter-substitution using your estimator, you are effectively treating this as a perfect estimator of the unknown parameter, and so the resulting "predictive" distribution does not take account of the uncertainty in the unknown parameter $\theta$. For this reason, the latter distribution will tend to have lower variability than the former, and if your model is correctly specified, this means that it underestimates the variability of the new data point. So yes, the predictive distribution is generally regarded as being "better". Incidentally, this kind of comparison is not exclusive to Bayesian statistics. This methods you are comparing are very much like the analogous methods that occurs in frequentist methodology, where one can use a pivotal quantity to get a proper confidence interval for a new data point (analogous to a Bayesian predictive interval), or one can merely substitute the MLE as if it were a known parameter value and obtain an interval for a new data point from the sampling distribution (analogous to the Bayesian parameter-substitution method).
Posterior predictive distribution vs MAP estimate Assuming your model is correctly specified, the predictive distribution gives an estimate of the new data point that takes account of all the uncertainty in the unknown parameter $\theta$. In the sec
32,446
Parameter estimates for the triangular distribution
Using the extreme-order statistics as estimators for the boundaries $a,b$ and then using $$E(X) = \frac {a+b+c}{3}$$ to estimate $c$ by method of moments is so ...maddeningly easy, $$\hat a = X_{(1)},\;\; \hat b = X_{(n)},\;\;\hat c = 3\bar X - \hat a - \hat b$$ it made me think how I could start by estimating $c$ first, just for the twist of it. Here it is but not yet with any properties of the estimator. I will make this community wiki in case any one is interested in working it further. 1) Obtain the empirical quartiles $\hat q_1, \hat q_3$ and form the Interquartile Range $\text{IQR} = \hat q_3 - \hat q_1$ 2) Use the Friedman-Diaconis rule to bin the data. $$\text{Bin size}=2\, { \text{IQR} \over{ {n^{1/3}} }}$$ 3) Form the empirical histogram and estimate $\hat c$ as the mid-point of the bin with the highest empirical frequency. 4) Then solve for $a,b$ the system of equations $$q_1 = a + \frac {\sqrt{(c-a)(b-a)}}{2}$$ $$q_3 = b + \frac {\sqrt{(b-c)(b-a)}}{2}$$ using the estimated $\hat q_1, \hat q_3, \hat c$ (the inverse CDF expressions I took from the book chapter the OP links to, page 8).
Parameter estimates for the triangular distribution
Using the extreme-order statistics as estimators for the boundaries $a,b$ and then using $$E(X) = \frac {a+b+c}{3}$$ to estimate $c$ by method of moments is so ...maddeningly easy, $$\hat a = X_{(1
Parameter estimates for the triangular distribution Using the extreme-order statistics as estimators for the boundaries $a,b$ and then using $$E(X) = \frac {a+b+c}{3}$$ to estimate $c$ by method of moments is so ...maddeningly easy, $$\hat a = X_{(1)},\;\; \hat b = X_{(n)},\;\;\hat c = 3\bar X - \hat a - \hat b$$ it made me think how I could start by estimating $c$ first, just for the twist of it. Here it is but not yet with any properties of the estimator. I will make this community wiki in case any one is interested in working it further. 1) Obtain the empirical quartiles $\hat q_1, \hat q_3$ and form the Interquartile Range $\text{IQR} = \hat q_3 - \hat q_1$ 2) Use the Friedman-Diaconis rule to bin the data. $$\text{Bin size}=2\, { \text{IQR} \over{ {n^{1/3}} }}$$ 3) Form the empirical histogram and estimate $\hat c$ as the mid-point of the bin with the highest empirical frequency. 4) Then solve for $a,b$ the system of equations $$q_1 = a + \frac {\sqrt{(c-a)(b-a)}}{2}$$ $$q_3 = b + \frac {\sqrt{(b-c)(b-a)}}{2}$$ using the estimated $\hat q_1, \hat q_3, \hat c$ (the inverse CDF expressions I took from the book chapter the OP links to, page 8).
Parameter estimates for the triangular distribution Using the extreme-order statistics as estimators for the boundaries $a,b$ and then using $$E(X) = \frac {a+b+c}{3}$$ to estimate $c$ by method of moments is so ...maddeningly easy, $$\hat a = X_{(1
32,447
Parameter estimates for the triangular distribution
Assume that one has a sufficient sample size $n$ where the sample mode and mean suggest an estimate of $c$. Proceeding conditionally, based on this information, there are thus $h$ values of the triangular random deviate observed that fall below the assumed $c$ value, and also correspondingly $k$ above. Then, the derivative of the conditional log-likelihood function, set equal to zero, facilely renders the answer: $$\hat c = \frac {h*a + k*b}{n}$$ which equates to the known value of $c$ in the case of the Symmetric Triangular Distribution: $$c = \frac {a + b}{2}$$
Parameter estimates for the triangular distribution
Assume that one has a sufficient sample size $n$ where the sample mode and mean suggest an estimate of $c$. Proceeding conditionally, based on this information, there are thus $h$ values of the triang
Parameter estimates for the triangular distribution Assume that one has a sufficient sample size $n$ where the sample mode and mean suggest an estimate of $c$. Proceeding conditionally, based on this information, there are thus $h$ values of the triangular random deviate observed that fall below the assumed $c$ value, and also correspondingly $k$ above. Then, the derivative of the conditional log-likelihood function, set equal to zero, facilely renders the answer: $$\hat c = \frac {h*a + k*b}{n}$$ which equates to the known value of $c$ in the case of the Symmetric Triangular Distribution: $$c = \frac {a + b}{2}$$
Parameter estimates for the triangular distribution Assume that one has a sufficient sample size $n$ where the sample mode and mean suggest an estimate of $c$. Proceeding conditionally, based on this information, there are thus $h$ values of the triang
32,448
Bayesian online changepoint detection (marginal predictive distribution)
Both (1) and (1b) are correct. The OP has it right that (in this model) there might be a changepoint at $t+1$, and $x_{t+1}$ depends on whether there is a changepoint. This does not imply any problems with (1) as the possible values of $r_{t+1}$ are fully "covered" by $P(x_{t+1} \mid r_t, x_{1:t})$. $P(x_{t+1} | r_t, x_{1:t})$ means the conditional distribution of $x_{t+1}$ conditional on $(r_t, x_{1:t})$. This conditional distribution averages over "everything else", including $r_{t+1}$, conditional on $(r_t, x_{1:t})$. Just like one could write, say, $P(x_{t+1000} | x_t)$, which would take into account all possible configurations of changepoints as well as values of $x_i$s occurring between $t$ and $t+1000$. In the remainder, I first derive (1) and then (1b) based on (1). Derivation of (1) For any random variables $A,B,C$, we have \begin{equation} P(A \mid B) = \sum_c P(A \mid B, C=c)\,P(C=c \mid B), \end{equation} as long as $C$ is discrete (otherwise the sum needs to be replaced by an integral). Applying this to $x_{t+1},x_{1:t},r_t$: \begin{equation} P(x_{t+1} \mid x_{1:t}) = \sum_{r_t} P(x_{t+1} \mid r_t, x_{1:t})\,P(r_t \mid x_{1:t}), \end{equation} which holds no matter what the dependencies between $r_t$, $x_{1:t}$, $x_{t+1}$ are, that is, no model assumptions have yet been used. In the present model, $x_{t+1}$ given $r_t,x^{(r)}_t$ is assumed* to be conditionally independent of the values of $x$ from the runs before $x^{(r)}_t$. This implies $P(x_{t+1} \mid r_t, x_{1:t}) = P(x_{t+1} \mid r_t, x^{(r)}_t)$. Substituting this into the previous equation, we get \begin{equation} P(x_{t+1} \mid x_{1:t}) = \sum_{r_t} P(x_{t+1} \mid r_t, x^{(r)}_t)\,P(r_t \mid x_{1:t}), \qquad \qquad \qquad (1) \end{equation} which is (1) in OP. Derivation of (1b) Let us consider the decomposition of $P(x_{t+1} \mid r_t, x^{(r)}_t)$ over possible values of $r_{t+1}$: \begin{equation} P(x_{t+1} \mid r_t, x^{(r)}_t) = \sum_{r_{t+1}} P(x_{t+1} \mid r_{t+1}, r_t, x^{(r)}_t)P(r_{t+1} \mid r_t, x^{(r)}_t). \end{equation} Since it is assumed* that whether a changepoint occurs at $t+1$ (between $x_t$ and $x_{t+1}$) does not depend on the history of $x$, we have $P(r_{t+1} \mid r_t, x^{(r)}_t) = P(r_{t+1} \mid r_t)$. Furthermore, since $r_{t+1}$ determines whether $x_{t+1}$ belongs into the same run as $x_t$, we have $P(x_{t+1} \mid r_{t+1}, r_t, x^{(r)}_t)=P(x_{t+1} \mid r_{t+1}, x^{(r)}_t)$. Substituting these two simplifications into the factorization above, we get \begin{equation} P(x_{t+1} \mid r_t, x^{(r)}_t) = \sum_{r_{t+1}} P(x_{t+1} \mid r_{t+1}, x^{(r)}_t)P(r_{t+1} \mid r_t). \end{equation} Substituting this into (1), we get \begin{equation} P(x_{t+1} \mid x_{1:t}) = \sum_{r_t} \left(\sum_{r_{t+1}} P(x_{t+1} \mid r_{t+1}, x^{(r)}_t)P(r_{t+1} \mid r_t)\right)\,P(r_t \mid x_{1:t}), \qquad (1b) \end{equation} which is OP's (1b). * Remark on the model's conditional independence assumptions Based on quickly browsing the paper, I would personally like the conditional independence properties to be more explicitly stated somewhere, but I suppose that the intention is that $r$ is Markovian and the $x$:s associated to different runs are independent (given the runs).
Bayesian online changepoint detection (marginal predictive distribution)
Both (1) and (1b) are correct. The OP has it right that (in this model) there might be a changepoint at $t+1$, and $x_{t+1}$ depends on whether there is a changepoint. This does not imply any problems
Bayesian online changepoint detection (marginal predictive distribution) Both (1) and (1b) are correct. The OP has it right that (in this model) there might be a changepoint at $t+1$, and $x_{t+1}$ depends on whether there is a changepoint. This does not imply any problems with (1) as the possible values of $r_{t+1}$ are fully "covered" by $P(x_{t+1} \mid r_t, x_{1:t})$. $P(x_{t+1} | r_t, x_{1:t})$ means the conditional distribution of $x_{t+1}$ conditional on $(r_t, x_{1:t})$. This conditional distribution averages over "everything else", including $r_{t+1}$, conditional on $(r_t, x_{1:t})$. Just like one could write, say, $P(x_{t+1000} | x_t)$, which would take into account all possible configurations of changepoints as well as values of $x_i$s occurring between $t$ and $t+1000$. In the remainder, I first derive (1) and then (1b) based on (1). Derivation of (1) For any random variables $A,B,C$, we have \begin{equation} P(A \mid B) = \sum_c P(A \mid B, C=c)\,P(C=c \mid B), \end{equation} as long as $C$ is discrete (otherwise the sum needs to be replaced by an integral). Applying this to $x_{t+1},x_{1:t},r_t$: \begin{equation} P(x_{t+1} \mid x_{1:t}) = \sum_{r_t} P(x_{t+1} \mid r_t, x_{1:t})\,P(r_t \mid x_{1:t}), \end{equation} which holds no matter what the dependencies between $r_t$, $x_{1:t}$, $x_{t+1}$ are, that is, no model assumptions have yet been used. In the present model, $x_{t+1}$ given $r_t,x^{(r)}_t$ is assumed* to be conditionally independent of the values of $x$ from the runs before $x^{(r)}_t$. This implies $P(x_{t+1} \mid r_t, x_{1:t}) = P(x_{t+1} \mid r_t, x^{(r)}_t)$. Substituting this into the previous equation, we get \begin{equation} P(x_{t+1} \mid x_{1:t}) = \sum_{r_t} P(x_{t+1} \mid r_t, x^{(r)}_t)\,P(r_t \mid x_{1:t}), \qquad \qquad \qquad (1) \end{equation} which is (1) in OP. Derivation of (1b) Let us consider the decomposition of $P(x_{t+1} \mid r_t, x^{(r)}_t)$ over possible values of $r_{t+1}$: \begin{equation} P(x_{t+1} \mid r_t, x^{(r)}_t) = \sum_{r_{t+1}} P(x_{t+1} \mid r_{t+1}, r_t, x^{(r)}_t)P(r_{t+1} \mid r_t, x^{(r)}_t). \end{equation} Since it is assumed* that whether a changepoint occurs at $t+1$ (between $x_t$ and $x_{t+1}$) does not depend on the history of $x$, we have $P(r_{t+1} \mid r_t, x^{(r)}_t) = P(r_{t+1} \mid r_t)$. Furthermore, since $r_{t+1}$ determines whether $x_{t+1}$ belongs into the same run as $x_t$, we have $P(x_{t+1} \mid r_{t+1}, r_t, x^{(r)}_t)=P(x_{t+1} \mid r_{t+1}, x^{(r)}_t)$. Substituting these two simplifications into the factorization above, we get \begin{equation} P(x_{t+1} \mid r_t, x^{(r)}_t) = \sum_{r_{t+1}} P(x_{t+1} \mid r_{t+1}, x^{(r)}_t)P(r_{t+1} \mid r_t). \end{equation} Substituting this into (1), we get \begin{equation} P(x_{t+1} \mid x_{1:t}) = \sum_{r_t} \left(\sum_{r_{t+1}} P(x_{t+1} \mid r_{t+1}, x^{(r)}_t)P(r_{t+1} \mid r_t)\right)\,P(r_t \mid x_{1:t}), \qquad (1b) \end{equation} which is OP's (1b). * Remark on the model's conditional independence assumptions Based on quickly browsing the paper, I would personally like the conditional independence properties to be more explicitly stated somewhere, but I suppose that the intention is that $r$ is Markovian and the $x$:s associated to different runs are independent (given the runs).
Bayesian online changepoint detection (marginal predictive distribution) Both (1) and (1b) are correct. The OP has it right that (in this model) there might be a changepoint at $t+1$, and $x_{t+1}$ depends on whether there is a changepoint. This does not imply any problems
32,449
How should I deal with highly correlated features?
In theory, this should not affect your ability to make predictions - after all, the only truly useless data would be a restated column (or a column whose values can be directly derived from some other - e.g. having radius and circumference in two columns). Just because your features are correlated does not mean they are not useful, in fact, this correlation could be valuable if your dataset is in fact representative of what is out there "in the wild". However, if your dataset is limited, then you may run into trouble, as highly correlated data will provide precious little extra information about the subject. PCA is a great candidate for this, as mentioned in the above comment. Random Forests are also promising, as they can inform you which columns play the biggest part in classifying your data. Gradient Boosting classifiers can also help with data that is resistant to classification by more elementary methods. At any rate, I'm curious to hear what your baseline is with basic classifiers!
How should I deal with highly correlated features?
In theory, this should not affect your ability to make predictions - after all, the only truly useless data would be a restated column (or a column whose values can be directly derived from some other
How should I deal with highly correlated features? In theory, this should not affect your ability to make predictions - after all, the only truly useless data would be a restated column (or a column whose values can be directly derived from some other - e.g. having radius and circumference in two columns). Just because your features are correlated does not mean they are not useful, in fact, this correlation could be valuable if your dataset is in fact representative of what is out there "in the wild". However, if your dataset is limited, then you may run into trouble, as highly correlated data will provide precious little extra information about the subject. PCA is a great candidate for this, as mentioned in the above comment. Random Forests are also promising, as they can inform you which columns play the biggest part in classifying your data. Gradient Boosting classifiers can also help with data that is resistant to classification by more elementary methods. At any rate, I'm curious to hear what your baseline is with basic classifiers!
How should I deal with highly correlated features? In theory, this should not affect your ability to make predictions - after all, the only truly useless data would be a restated column (or a column whose values can be directly derived from some other
32,450
Neural networks - Switching loss function during training for better gradients
yes you can do it. It's your network, anything you can code, you can do to it. As was mentioned in the comments, it's just getting a starting point for different optimization problem. Your errors having the same minimum, doesn't matter that much, because the whole problem is nonconvex and you might get stuck in different local minimals/plateaus. did you hear about pre-training? Although I don't know about any published network that would use this method to get faster convergence, it's common to pre-train the network in some way before you actually train it with your final loss function. But usually it is done in unsupervised way. You just answered yourself. It's getting you a better gradients, so it's worth it with respect to gradients. The question is, if you can get better results by doing something else. E.g: using momentum, changing your alpha on the way or as was mentioned before, to use some pre-training methods
Neural networks - Switching loss function during training for better gradients
yes you can do it. It's your network, anything you can code, you can do to it. As was mentioned in the comments, it's just getting a starting point for different optimization problem. Your errors havi
Neural networks - Switching loss function during training for better gradients yes you can do it. It's your network, anything you can code, you can do to it. As was mentioned in the comments, it's just getting a starting point for different optimization problem. Your errors having the same minimum, doesn't matter that much, because the whole problem is nonconvex and you might get stuck in different local minimals/plateaus. did you hear about pre-training? Although I don't know about any published network that would use this method to get faster convergence, it's common to pre-train the network in some way before you actually train it with your final loss function. But usually it is done in unsupervised way. You just answered yourself. It's getting you a better gradients, so it's worth it with respect to gradients. The question is, if you can get better results by doing something else. E.g: using momentum, changing your alpha on the way or as was mentioned before, to use some pre-training methods
Neural networks - Switching loss function during training for better gradients yes you can do it. It's your network, anything you can code, you can do to it. As was mentioned in the comments, it's just getting a starting point for different optimization problem. Your errors havi
32,451
beta-regression accounting for residual spatial auto-correlation in R
We can think of our observations as arising from some distribution with a mean structure component and a covariance component. Essentially we have $$y = \boldsymbol{X\beta} + \mathbf{Zb} + \epsilon$$ where $\mathbf{X}$ and $\mathbf{Z}$ are design matrices of fixed and random effects respectively and $\epsilon$ is the unexplained variation. We can model spatial or temporal autocorrelation by including in our model something that accounts for the spatial or temporal separation of the observations. We can do this either in the fixed/random effects part of the model or in the covariance structure of model. For example, in a simple linear regression model assuming independent observations we have $$y \sim \mathcal{N}(\boldsymbol{X\beta}, \sigma_{\epsilon}^2\mathbf{I})$$ where $\mathbf{I}$ is an identity matrix (hence the i.i.d. assumption). We might proceed to include a spatial or temporal correlation effect via $\mathbf{Zb}$, using basis functions, such that our model becomes $$y \sim \mathcal{N}(\boldsymbol{X\beta} + \mathbf{Zb}, \sigma_{\epsilon}^2\mathbf{I})$$ This is known as the first-order form. Alternatively we include the spatial or temporal correlation in the covariance function of the random effects, in that case our model might be $$y = \boldsymbol{X\beta} + \boldsymbol{\eta} + \epsilon$$ where $\boldsymbol{\epsilon} \sim \mathcal{N}(0, \sigma_{\epsilon}^2\mathbf{I})$ and $\boldsymbol{\eta} \sim \mathcal{N}(0, \sigma_{\alpha}^2\mathbf{R})$ where the random effect $\boldsymbol{\eta}$ results in correlated errors, resulting in $$y \sim \mathcal{N}(\mathbf{X\beta}, \sigma_{\epsilon}^2\mathbf{I} + \sigma_{\alpha}^2\mathbf{R})$$ Here $\mathbf{R}$ is specified via a correlation function such as the exponential correlation function you mentions. This is known as the second-order form. The second-order form might be more common, especially in spatial statistics with the ecological and environmental sciences, but the first-order form is useful too. These two forms can be equivalent for some models, where the basis functions in $\boldsymbol{Z}$ can be derived from the correlation function or matrix $\boldsymbol{R}$. The above was cribbed from sections of Hefley et al (submitted), which is available on arXiv as a preprint. (A third form might be $y \sim \mathcal{N}(\boldsymbol{X\beta}, \sigma_{\epsilon}^2\mathbf{R})$, which is what gamm() with correlation = corFOO() produces.) As to why I mention this, I believe you can achieve what you want with gam() via a first-order form model derived from the spline-equivalent of kriging. For this you would use the following model in R: mod <- gam(y ~ x1 + x2 + s(latitude, longitude, bs = "gp", m = 2), family = betar(link='logit'), data = data) Implicit here is that the splines will be treated as random effects (with the components of any penalty null space as fixed effects) but for none-general-family functions you could request this via method = "REML" or "ML". With m = 2, this selects a power exponential correlation function with range $r$ estimated from the data according to the method of Kammann and Wand (2003): $$\hat{r} = \max_{1 \leq i, j \leq n} \left\lVert x_i - x_j \right\rVert$$ and power = 1. If you want to specify the range and or the power, then you need to supply a vector to m: m = c(2, 100, 1) would be a power exponential function with range parameter 100 and power 1. Other values of the m (or the first element when specified in vector form give different correlation function including spherical and three Matern covariance functions). The assumption now is that given x and y and the random effects $\boldsymbol{Z}$ (given by the Gaussian process spline == kriging) and any model parameters, the residuals are i.i.d. Whether this is the case will depend on how flexible the Guassian process (kriging) part of the model is. With this method I don't think specify a nugget and you have to manually specify the range parameter unless you want it to be taken as the largest separation between any two points in the sample. The detail for the implementation is in ?mgcv:::smooth.construct.gp.smooth.spec You can read more about the first-order and second-order forms in a paper by Hefley et al (submitted). I will also add that in practice, what you've already done using a thin-plate spline for location is also a first-order form model and hence you might not be able to do much or any better with the GP spline I mention above. Information in Hefley et al (submitted) might direct you at alternative ways to approach this model, perhaps using Bayesian methods where you might have more control of exactly how the spatial structure can be specified. Hefley, T. J., Broms, K. M., Brost, B. M., Buderman, F. E., Kay, S. L., Scharf, H. R., … Hooten, M. B. (2016, June 17). The basis function approach for modeling autocorrelation in ecological data. arXiv [stat.AP]. Retrieved from http://arxiv.org/abs/1606.05658 Kammann, E. E., & Wand, M. P. (2003). Geoadditive models. Journal of the Royal Statistical Society. Series C, Applied Statistics, 52(1), 1–18. http://doi.org/10.1111/1467-9876.00385
beta-regression accounting for residual spatial auto-correlation in R
We can think of our observations as arising from some distribution with a mean structure component and a covariance component. Essentially we have $$y = \boldsymbol{X\beta} + \mathbf{Zb} + \epsilon$$
beta-regression accounting for residual spatial auto-correlation in R We can think of our observations as arising from some distribution with a mean structure component and a covariance component. Essentially we have $$y = \boldsymbol{X\beta} + \mathbf{Zb} + \epsilon$$ where $\mathbf{X}$ and $\mathbf{Z}$ are design matrices of fixed and random effects respectively and $\epsilon$ is the unexplained variation. We can model spatial or temporal autocorrelation by including in our model something that accounts for the spatial or temporal separation of the observations. We can do this either in the fixed/random effects part of the model or in the covariance structure of model. For example, in a simple linear regression model assuming independent observations we have $$y \sim \mathcal{N}(\boldsymbol{X\beta}, \sigma_{\epsilon}^2\mathbf{I})$$ where $\mathbf{I}$ is an identity matrix (hence the i.i.d. assumption). We might proceed to include a spatial or temporal correlation effect via $\mathbf{Zb}$, using basis functions, such that our model becomes $$y \sim \mathcal{N}(\boldsymbol{X\beta} + \mathbf{Zb}, \sigma_{\epsilon}^2\mathbf{I})$$ This is known as the first-order form. Alternatively we include the spatial or temporal correlation in the covariance function of the random effects, in that case our model might be $$y = \boldsymbol{X\beta} + \boldsymbol{\eta} + \epsilon$$ where $\boldsymbol{\epsilon} \sim \mathcal{N}(0, \sigma_{\epsilon}^2\mathbf{I})$ and $\boldsymbol{\eta} \sim \mathcal{N}(0, \sigma_{\alpha}^2\mathbf{R})$ where the random effect $\boldsymbol{\eta}$ results in correlated errors, resulting in $$y \sim \mathcal{N}(\mathbf{X\beta}, \sigma_{\epsilon}^2\mathbf{I} + \sigma_{\alpha}^2\mathbf{R})$$ Here $\mathbf{R}$ is specified via a correlation function such as the exponential correlation function you mentions. This is known as the second-order form. The second-order form might be more common, especially in spatial statistics with the ecological and environmental sciences, but the first-order form is useful too. These two forms can be equivalent for some models, where the basis functions in $\boldsymbol{Z}$ can be derived from the correlation function or matrix $\boldsymbol{R}$. The above was cribbed from sections of Hefley et al (submitted), which is available on arXiv as a preprint. (A third form might be $y \sim \mathcal{N}(\boldsymbol{X\beta}, \sigma_{\epsilon}^2\mathbf{R})$, which is what gamm() with correlation = corFOO() produces.) As to why I mention this, I believe you can achieve what you want with gam() via a first-order form model derived from the spline-equivalent of kriging. For this you would use the following model in R: mod <- gam(y ~ x1 + x2 + s(latitude, longitude, bs = "gp", m = 2), family = betar(link='logit'), data = data) Implicit here is that the splines will be treated as random effects (with the components of any penalty null space as fixed effects) but for none-general-family functions you could request this via method = "REML" or "ML". With m = 2, this selects a power exponential correlation function with range $r$ estimated from the data according to the method of Kammann and Wand (2003): $$\hat{r} = \max_{1 \leq i, j \leq n} \left\lVert x_i - x_j \right\rVert$$ and power = 1. If you want to specify the range and or the power, then you need to supply a vector to m: m = c(2, 100, 1) would be a power exponential function with range parameter 100 and power 1. Other values of the m (or the first element when specified in vector form give different correlation function including spherical and three Matern covariance functions). The assumption now is that given x and y and the random effects $\boldsymbol{Z}$ (given by the Gaussian process spline == kriging) and any model parameters, the residuals are i.i.d. Whether this is the case will depend on how flexible the Guassian process (kriging) part of the model is. With this method I don't think specify a nugget and you have to manually specify the range parameter unless you want it to be taken as the largest separation between any two points in the sample. The detail for the implementation is in ?mgcv:::smooth.construct.gp.smooth.spec You can read more about the first-order and second-order forms in a paper by Hefley et al (submitted). I will also add that in practice, what you've already done using a thin-plate spline for location is also a first-order form model and hence you might not be able to do much or any better with the GP spline I mention above. Information in Hefley et al (submitted) might direct you at alternative ways to approach this model, perhaps using Bayesian methods where you might have more control of exactly how the spatial structure can be specified. Hefley, T. J., Broms, K. M., Brost, B. M., Buderman, F. E., Kay, S. L., Scharf, H. R., … Hooten, M. B. (2016, June 17). The basis function approach for modeling autocorrelation in ecological data. arXiv [stat.AP]. Retrieved from http://arxiv.org/abs/1606.05658 Kammann, E. E., & Wand, M. P. (2003). Geoadditive models. Journal of the Royal Statistical Society. Series C, Applied Statistics, 52(1), 1–18. http://doi.org/10.1111/1467-9876.00385
beta-regression accounting for residual spatial auto-correlation in R We can think of our observations as arising from some distribution with a mean structure component and a covariance component. Essentially we have $$y = \boldsymbol{X\beta} + \mathbf{Zb} + \epsilon$$
32,452
Scalable dimension reduction
An interesting option would be exploring neural-based dimensionality reduction. The most commonly used type of network for dimensionality reduction, the autoencoder, can be trained at the cost of $\mathcal{O}(i\cdot n)$, where $i$ represents the training iterations (is an hyper-parameter independent of training data). Therefore, the training complexity simplifies to $\mathcal{O}(n)$. You can start by taking a look at the 2006 seminar work by Hinton and Salakhutdinov [1]. Since then, things have evolved a lot. Now most of the atention is attained by Variational Autoencoders [2], but the basic idea (a network that reconstructs the input at its output layer with a bottleneck layer in-between) remains the same. Note that, as opposed to PCA and RP, autoencoders perform nonlinear dimensionality reduction. Also, as opposed to t-SNE, autoencoders can transform unseen samples without the need to retrain the whole model. On the practical side, I recomend taking a look at this post, which gives details on how to implement different types of autoencoders with the wonderfull library Keras. [1] Hinton, G. E., & Salakhutdinov, R. R. (2006). Reducing the dimensionality of data with neural networks. science, 313(5786), 504-507. [2] Kingma, D. P., & Welling, M. (2013). Auto-encoding variational bayes. arXiv preprint arXiv:1312.6114.
Scalable dimension reduction
An interesting option would be exploring neural-based dimensionality reduction. The most commonly used type of network for dimensionality reduction, the autoencoder, can be trained at the cost of $\ma
Scalable dimension reduction An interesting option would be exploring neural-based dimensionality reduction. The most commonly used type of network for dimensionality reduction, the autoencoder, can be trained at the cost of $\mathcal{O}(i\cdot n)$, where $i$ represents the training iterations (is an hyper-parameter independent of training data). Therefore, the training complexity simplifies to $\mathcal{O}(n)$. You can start by taking a look at the 2006 seminar work by Hinton and Salakhutdinov [1]. Since then, things have evolved a lot. Now most of the atention is attained by Variational Autoencoders [2], but the basic idea (a network that reconstructs the input at its output layer with a bottleneck layer in-between) remains the same. Note that, as opposed to PCA and RP, autoencoders perform nonlinear dimensionality reduction. Also, as opposed to t-SNE, autoencoders can transform unseen samples without the need to retrain the whole model. On the practical side, I recomend taking a look at this post, which gives details on how to implement different types of autoencoders with the wonderfull library Keras. [1] Hinton, G. E., & Salakhutdinov, R. R. (2006). Reducing the dimensionality of data with neural networks. science, 313(5786), 504-507. [2] Kingma, D. P., & Welling, M. (2013). Auto-encoding variational bayes. arXiv preprint arXiv:1312.6114.
Scalable dimension reduction An interesting option would be exploring neural-based dimensionality reduction. The most commonly used type of network for dimensionality reduction, the autoencoder, can be trained at the cost of $\ma
32,453
Scalable dimension reduction
Besides the already mentioned autoencoders, one can try exploiting Johnson-Lindenstrauss' lemma with random projections or random subspace methods. Random projections are $\mathcal{O}(k d N)$, with $N$ the number of samples of dimension $d$ and $k$ the target dimension, cf [1]. A bit of googling will get you some very recent results, in particular for sparse datasets. [1] Random projection in dimensionality reduction: applications to image and text data.
Scalable dimension reduction
Besides the already mentioned autoencoders, one can try exploiting Johnson-Lindenstrauss' lemma with random projections or random subspace methods. Random projections are $\mathcal{O}(k d N)$, with $N
Scalable dimension reduction Besides the already mentioned autoencoders, one can try exploiting Johnson-Lindenstrauss' lemma with random projections or random subspace methods. Random projections are $\mathcal{O}(k d N)$, with $N$ the number of samples of dimension $d$ and $k$ the target dimension, cf [1]. A bit of googling will get you some very recent results, in particular for sparse datasets. [1] Random projection in dimensionality reduction: applications to image and text data.
Scalable dimension reduction Besides the already mentioned autoencoders, one can try exploiting Johnson-Lindenstrauss' lemma with random projections or random subspace methods. Random projections are $\mathcal{O}(k d N)$, with $N
32,454
Bootstrapping test set?
I can't imagine how manipulating with your test set could lead to anything more then cheating yourself that your results are better then in reality. The idea of cross-validation and testing your results on unseen data, is to approximate the situation where your model would be applied to some future, unknown data. This approximation may be better or worse depending on how similar is the data you have to the future data. The idea of bootstrap is that you sample from your data the same way as you'd sample from the population, so to approximate the sampling process and estimate the variability caused by it. First thing to notice is that such procedure does not let you learn anything about possible performance if the data you have is not similar to the future data. Second, the sampling is ought to imitate the sampling process, so rather then resampling your test set, you should instead make multiple random splits to train and test set (i.e. use k-fold cross-validation). Finally, bootstrap is designed for estimating the possible variability, not for correcting it. Bradley Efron himself discouraged from such useage of bootstrap. The completely different story, is to bootstrap resample the train set and then aggregate the results, i.e. use bagging -- this would help to reduce the variance of the predictions.
Bootstrapping test set?
I can't imagine how manipulating with your test set could lead to anything more then cheating yourself that your results are better then in reality. The idea of cross-validation and testing your resul
Bootstrapping test set? I can't imagine how manipulating with your test set could lead to anything more then cheating yourself that your results are better then in reality. The idea of cross-validation and testing your results on unseen data, is to approximate the situation where your model would be applied to some future, unknown data. This approximation may be better or worse depending on how similar is the data you have to the future data. The idea of bootstrap is that you sample from your data the same way as you'd sample from the population, so to approximate the sampling process and estimate the variability caused by it. First thing to notice is that such procedure does not let you learn anything about possible performance if the data you have is not similar to the future data. Second, the sampling is ought to imitate the sampling process, so rather then resampling your test set, you should instead make multiple random splits to train and test set (i.e. use k-fold cross-validation). Finally, bootstrap is designed for estimating the possible variability, not for correcting it. Bradley Efron himself discouraged from such useage of bootstrap. The completely different story, is to bootstrap resample the train set and then aggregate the results, i.e. use bagging -- this would help to reduce the variance of the predictions.
Bootstrapping test set? I can't imagine how manipulating with your test set could lead to anything more then cheating yourself that your results are better then in reality. The idea of cross-validation and testing your resul
32,455
Bootstrapping test set?
I assume that you also have a (bigger) training set, and that the training and test set have the same relation between features and target variable (there is no significant difference). Then: no, bootstrapping your test set and considering the performance over the resulting test sets is most likely not helpful. You use your training data to e.g. select features, train, and evaluate different model types and hyperparameters. From those results you chose one "best suited" model for the job. This is the one you should evaluate on your test set once for reassurance that everything is OK. With this setup, splitting the test set does not bring benefits anymore: if would not reuse samples during bootstrapping, you would just get "subresults", which then would be averaged to one scalar result (and cause less granularity thereby), or you would bootstrap with replacement, which with few partitions would cause better or worse results by chance (and on an infinite amount of rounds would give you very similar results again). If you are really stuck with a very small test set, and test performance is the only thing that counts (why would it be? You aim for generalization, right?), the question boils down to how well test data represents the real application case data - because few samples might just be too less to allow for any good estimate of real world performance. If you think this might be true for your case, getting/asking for more test data might be required anyway.
Bootstrapping test set?
I assume that you also have a (bigger) training set, and that the training and test set have the same relation between features and target variable (there is no significant difference). Then: no, boot
Bootstrapping test set? I assume that you also have a (bigger) training set, and that the training and test set have the same relation between features and target variable (there is no significant difference). Then: no, bootstrapping your test set and considering the performance over the resulting test sets is most likely not helpful. You use your training data to e.g. select features, train, and evaluate different model types and hyperparameters. From those results you chose one "best suited" model for the job. This is the one you should evaluate on your test set once for reassurance that everything is OK. With this setup, splitting the test set does not bring benefits anymore: if would not reuse samples during bootstrapping, you would just get "subresults", which then would be averaged to one scalar result (and cause less granularity thereby), or you would bootstrap with replacement, which with few partitions would cause better or worse results by chance (and on an infinite amount of rounds would give you very similar results again). If you are really stuck with a very small test set, and test performance is the only thing that counts (why would it be? You aim for generalization, right?), the question boils down to how well test data represents the real application case data - because few samples might just be too less to allow for any good estimate of real world performance. If you think this might be true for your case, getting/asking for more test data might be required anyway.
Bootstrapping test set? I assume that you also have a (bigger) training set, and that the training and test set have the same relation between features and target variable (there is no significant difference). Then: no, boot
32,456
Bootstrapping test set?
You are trying to estimate the MSE. You have "n" points, all of which are an unbiased estimate of the MSE. Even if you keep resampling and averaging, you cannot get a more efficient estimator of your MSE than what you already have from the test set. This is analogous to drawing 10 samples and estimating the population mean from the sample average - you cannot make a more (unbiased) efficient estimator than that one.
Bootstrapping test set?
You are trying to estimate the MSE. You have "n" points, all of which are an unbiased estimate of the MSE. Even if you keep resampling and averaging, you cannot get a more efficient estimator of your
Bootstrapping test set? You are trying to estimate the MSE. You have "n" points, all of which are an unbiased estimate of the MSE. Even if you keep resampling and averaging, you cannot get a more efficient estimator of your MSE than what you already have from the test set. This is analogous to drawing 10 samples and estimating the population mean from the sample average - you cannot make a more (unbiased) efficient estimator than that one.
Bootstrapping test set? You are trying to estimate the MSE. You have "n" points, all of which are an unbiased estimate of the MSE. Even if you keep resampling and averaging, you cannot get a more efficient estimator of your
32,457
Was it as valid to perform k-means on a distance matrix as on data matrix (text mining data)?
To understand how the kmeans() function works, you need to read the documentation and/or inspect the underlying code. That said, I am sure it does not take a distance matrix without even bothering. You could write your own function to do k-means clustering from a distance matrix, but it would be an awful hassle. The k-means algorithm is meant to operate over a data matrix, not a distance matrix. It only minimizes squared Euclidean distances (cf. Why does k-means clustering algorithm use only Euclidean distance metric?). It is only sensible when you could have Euclidean distances as a meaningful distance metric. This has always been the case since the algorithm was invented, but few people seem to be aware of this, with the result that k-means is probably the most mis-used algorithm in machine learning. Euclidean distance doesn't make any sense for sparse categorical data (text mining), so I wouldn't even try anything like this. You first need to figure out what distance metric is appropriate for your data (@ttnphns explains some possible measures here: What is the optimal distance function for individuals when attributes are nominal?). Then you can compute the distance matrix and use a clustering algorithm that can operate over one (e.g., k-medians / PAM, various hierarchical algorithms, etc.).
Was it as valid to perform k-means on a distance matrix as on data matrix (text mining data)?
To understand how the kmeans() function works, you need to read the documentation and/or inspect the underlying code. That said, I am sure it does not take a distance matrix without even bothering.
Was it as valid to perform k-means on a distance matrix as on data matrix (text mining data)? To understand how the kmeans() function works, you need to read the documentation and/or inspect the underlying code. That said, I am sure it does not take a distance matrix without even bothering. You could write your own function to do k-means clustering from a distance matrix, but it would be an awful hassle. The k-means algorithm is meant to operate over a data matrix, not a distance matrix. It only minimizes squared Euclidean distances (cf. Why does k-means clustering algorithm use only Euclidean distance metric?). It is only sensible when you could have Euclidean distances as a meaningful distance metric. This has always been the case since the algorithm was invented, but few people seem to be aware of this, with the result that k-means is probably the most mis-used algorithm in machine learning. Euclidean distance doesn't make any sense for sparse categorical data (text mining), so I wouldn't even try anything like this. You first need to figure out what distance metric is appropriate for your data (@ttnphns explains some possible measures here: What is the optimal distance function for individuals when attributes are nominal?). Then you can compute the distance matrix and use a clustering algorithm that can operate over one (e.g., k-medians / PAM, various hierarchical algorithms, etc.).
Was it as valid to perform k-means on a distance matrix as on data matrix (text mining data)? To understand how the kmeans() function works, you need to read the documentation and/or inspect the underlying code. That said, I am sure it does not take a distance matrix without even bothering.
32,458
What is the difference between Stochastic Regressor and Non-Stochastic Regressor in Linear Regression?
In practice the difference is huge. The exogenous assumption that you refer to requires that the errors are not correlated with regressors. If they're correlated then you can't rely on the regressions with stochastic regressors. For instance, in observational studies, such as pretty much all economics, you do not control the regressors. You can not set US GDP to a desired level, you can only observe it. Hence, in the model where GDP is a regressor, you want errors to be independent of GDP, because in this model you can only assume stochastic regressors. When your errors are correlated with regressors you get endogeneity issue. There are ways to handle it, such as using lagged regressors or instrumental variables. In econometrics a textbook example is the impact of the exogenous price on the demand. We're talking about typical demand-supply equations. Here, the problem is that the prices also depend on the supply. Hence, there is an endogeneity issue, which any econometrician will promptly point out. This is to answer your question on feasibility of testing the assumption. Once you figured that endogeneity is here, you may look for a so called instrumental variable. These are regressors which are correlated with the price but not with demand, i.e. something that may impact the supply, for instance. If the demand is for oranges, then maybe a temperature in Florida in Spring would be a suitable instrument, because it's going to impact supply of oranges - and price - but not the demand. So, you plug this instrument into the regression and tease out the impact of the price on demand
What is the difference between Stochastic Regressor and Non-Stochastic Regressor in Linear Regressio
In practice the difference is huge. The exogenous assumption that you refer to requires that the errors are not correlated with regressors. If they're correlated then you can't rely on the regressions
What is the difference between Stochastic Regressor and Non-Stochastic Regressor in Linear Regression? In practice the difference is huge. The exogenous assumption that you refer to requires that the errors are not correlated with regressors. If they're correlated then you can't rely on the regressions with stochastic regressors. For instance, in observational studies, such as pretty much all economics, you do not control the regressors. You can not set US GDP to a desired level, you can only observe it. Hence, in the model where GDP is a regressor, you want errors to be independent of GDP, because in this model you can only assume stochastic regressors. When your errors are correlated with regressors you get endogeneity issue. There are ways to handle it, such as using lagged regressors or instrumental variables. In econometrics a textbook example is the impact of the exogenous price on the demand. We're talking about typical demand-supply equations. Here, the problem is that the prices also depend on the supply. Hence, there is an endogeneity issue, which any econometrician will promptly point out. This is to answer your question on feasibility of testing the assumption. Once you figured that endogeneity is here, you may look for a so called instrumental variable. These are regressors which are correlated with the price but not with demand, i.e. something that may impact the supply, for instance. If the demand is for oranges, then maybe a temperature in Florida in Spring would be a suitable instrument, because it's going to impact supply of oranges - and price - but not the demand. So, you plug this instrument into the regression and tease out the impact of the price on demand
What is the difference between Stochastic Regressor and Non-Stochastic Regressor in Linear Regressio In practice the difference is huge. The exogenous assumption that you refer to requires that the errors are not correlated with regressors. If they're correlated then you can't rely on the regressions
32,459
What is the difference between Stochastic Regressor and Non-Stochastic Regressor in Linear Regression?
Note that we do not require $\epsilon_i$ to be have the same distribution for all $i$. Unequal variance can be handled through weighted least squares or standard errors made robust to heteroskedasticity, while correlations among the error term can be handled using Huber-White standard errors. I agree that we can never assess whether $\epsilon_i$ is correlated with $x_i$. In my current work, the covariate of interest is typically randomly assigned, so we can assert that it is independent of the error term. Other included regressors might not be, but they too are uncorrelated with the regressor of interest and so do not affect the estimate of its coefficient. My formal training is in economics, where observational studies are more common. There we appeal to outside knowledge to assess this assumption. For example, the regression of wages on years of schooling does not estimate the parameters of a conditional expectation because the error term contains things like motivation, which are correlated with years of schooling. A great deal of effort in economics is put into identifying credible variation, though ultimately the credibility of such observational analyses is debatable.
What is the difference between Stochastic Regressor and Non-Stochastic Regressor in Linear Regressio
Note that we do not require $\epsilon_i$ to be have the same distribution for all $i$. Unequal variance can be handled through weighted least squares or standard errors made robust to heteroskedastici
What is the difference between Stochastic Regressor and Non-Stochastic Regressor in Linear Regression? Note that we do not require $\epsilon_i$ to be have the same distribution for all $i$. Unequal variance can be handled through weighted least squares or standard errors made robust to heteroskedasticity, while correlations among the error term can be handled using Huber-White standard errors. I agree that we can never assess whether $\epsilon_i$ is correlated with $x_i$. In my current work, the covariate of interest is typically randomly assigned, so we can assert that it is independent of the error term. Other included regressors might not be, but they too are uncorrelated with the regressor of interest and so do not affect the estimate of its coefficient. My formal training is in economics, where observational studies are more common. There we appeal to outside knowledge to assess this assumption. For example, the regression of wages on years of schooling does not estimate the parameters of a conditional expectation because the error term contains things like motivation, which are correlated with years of schooling. A great deal of effort in economics is put into identifying credible variation, though ultimately the credibility of such observational analyses is debatable.
What is the difference between Stochastic Regressor and Non-Stochastic Regressor in Linear Regressio Note that we do not require $\epsilon_i$ to be have the same distribution for all $i$. Unequal variance can be handled through weighted least squares or standard errors made robust to heteroskedastici
32,460
Power of lady tasting tea experiment
The distribution of the correct number of guesses under the alternative hypothesis follows a non-central hypergeometric distribution, which is parameterized in terms of the odds ratio, that is, how much higher are the odds that the lady will guess "tea first" when in fact tea was really added first as opposed to when in fact milk was added first (or the other way around). If the odds ratio is 1, then we get the central hypergeometric distribution. Let's see if this works. I will use R for illustration purposes, using the MCMCpack package, which has function dnoncenhypergeom() for computing the density of a (non-central) hypergeometric distribution. It has arguments x for the correct number of guesses (careful: this is the correct number of guesses under one of the two conditions, for example, when tea was really added first), arguments n1, n2, and m1 for three of the four margins, and psi for the true odds ratio. Let's compute the density for x equal to 0 to 4 (with all margins equal to 4) when the true odds ratio is 1: install.packages("MCMCpack") library(MCMCpack) sapply(0:4, function(x) dnoncenhypergeom(x, n1=4, n2=4, m1=4, psi=1)) This yields: [1] 0.01428571 0.22857143 0.51428571 0.22857143 0.01428571 So, there is a 1.43% chance that the lady will make 8 correct guesses (i.e., she guesses all 4 cups correctly where tea was added first and hence she also guesses all 4 cups correctly where milk was added first) under the null hypothesis. This is in fact the amount of evidence that Fisher considered sufficient to reject the null hypothesis. The probabilities specified in the question can be used to compute the odds ratio, namely, $(.90/(1-.90)) / (.10/(1-.10)) = 81$ (i.e., $\text{odds}(\text{guess}A|\text{true}A) / \text{odds}(\text{guess}A|\text{true}B)$). What are the chances now that the lady will guess all 8 cups correctly (i.e., she will guess all 4 cups correctly where tea was added first and hence also the 4 cups correctly where milk was added first)? dnoncenhypergeom(4, n1=4, n2=4, m1=4, psi=81) This yields: [1] 0.8312221 So power is about 83% then.
Power of lady tasting tea experiment
The distribution of the correct number of guesses under the alternative hypothesis follows a non-central hypergeometric distribution, which is parameterized in terms of the odds ratio, that is, how mu
Power of lady tasting tea experiment The distribution of the correct number of guesses under the alternative hypothesis follows a non-central hypergeometric distribution, which is parameterized in terms of the odds ratio, that is, how much higher are the odds that the lady will guess "tea first" when in fact tea was really added first as opposed to when in fact milk was added first (or the other way around). If the odds ratio is 1, then we get the central hypergeometric distribution. Let's see if this works. I will use R for illustration purposes, using the MCMCpack package, which has function dnoncenhypergeom() for computing the density of a (non-central) hypergeometric distribution. It has arguments x for the correct number of guesses (careful: this is the correct number of guesses under one of the two conditions, for example, when tea was really added first), arguments n1, n2, and m1 for three of the four margins, and psi for the true odds ratio. Let's compute the density for x equal to 0 to 4 (with all margins equal to 4) when the true odds ratio is 1: install.packages("MCMCpack") library(MCMCpack) sapply(0:4, function(x) dnoncenhypergeom(x, n1=4, n2=4, m1=4, psi=1)) This yields: [1] 0.01428571 0.22857143 0.51428571 0.22857143 0.01428571 So, there is a 1.43% chance that the lady will make 8 correct guesses (i.e., she guesses all 4 cups correctly where tea was added first and hence she also guesses all 4 cups correctly where milk was added first) under the null hypothesis. This is in fact the amount of evidence that Fisher considered sufficient to reject the null hypothesis. The probabilities specified in the question can be used to compute the odds ratio, namely, $(.90/(1-.90)) / (.10/(1-.10)) = 81$ (i.e., $\text{odds}(\text{guess}A|\text{true}A) / \text{odds}(\text{guess}A|\text{true}B)$). What are the chances now that the lady will guess all 8 cups correctly (i.e., she will guess all 4 cups correctly where tea was added first and hence also the 4 cups correctly where milk was added first)? dnoncenhypergeom(4, n1=4, n2=4, m1=4, psi=81) This yields: [1] 0.8312221 So power is about 83% then.
Power of lady tasting tea experiment The distribution of the correct number of guesses under the alternative hypothesis follows a non-central hypergeometric distribution, which is parameterized in terms of the odds ratio, that is, how mu
32,461
Power of lady tasting tea experiment
Under the alternative the lady is not randomly guessing, but "not randomly guessing" covers an infinity of different situations. She might always guess perfectly or she might only do very slightly better than random guessing ... and in the general case there's not even a single-variable "scale" not-random to work along (so we don't even have a power curve unless we restrict the kinds of non-random responses she might give). So in order to compute a power, we must be very specific about how it's non-random (and just how non-random it is in that particular fashion). We could suppose, for example, that she gets a sensation of how much each cup tastes like the milk was added first -- a "milk-firstiness" index which is a random variable on $(-\infty,\infty)$ that has a different (higher) mean when the milk is added first -- e.g. we might suppose that it's say normal or logistic, with mean $\mu_0$ and variance $\sigma^2=1/\omega^2$ ($\omega^2$ is known as "precision") when milk is added last and mean $\mu_1$ and variance $\sigma^2$ when milk is added first (indeed, a simpler but more restrictive presumption might be to set, say, $\mu_1=-\mu_0=1$ so that everything is now a function of one variable, the precision). So for any given values of those parameters, we could compute the probability that she gets all 8 cups correct (that the four smallest "milk-firstiness" values she experiences are associated with the four milk-second cups); if the exact calculation was too hard for us we could simulate it to any desired accuracy. [In the case where the nonrandomness is presumed to be a function of just one variable, we would have a power-curve -- a value for power for each value of the parameter.] That's one specific kind of model for how she might perform "better than random" with which we might specify parameters and obtain a value for power. We could of course suppose many other forms of non-randomness than this.
Power of lady tasting tea experiment
Under the alternative the lady is not randomly guessing, but "not randomly guessing" covers an infinity of different situations. She might always guess perfectly or she might only do very slightly bet
Power of lady tasting tea experiment Under the alternative the lady is not randomly guessing, but "not randomly guessing" covers an infinity of different situations. She might always guess perfectly or she might only do very slightly better than random guessing ... and in the general case there's not even a single-variable "scale" not-random to work along (so we don't even have a power curve unless we restrict the kinds of non-random responses she might give). So in order to compute a power, we must be very specific about how it's non-random (and just how non-random it is in that particular fashion). We could suppose, for example, that she gets a sensation of how much each cup tastes like the milk was added first -- a "milk-firstiness" index which is a random variable on $(-\infty,\infty)$ that has a different (higher) mean when the milk is added first -- e.g. we might suppose that it's say normal or logistic, with mean $\mu_0$ and variance $\sigma^2=1/\omega^2$ ($\omega^2$ is known as "precision") when milk is added last and mean $\mu_1$ and variance $\sigma^2$ when milk is added first (indeed, a simpler but more restrictive presumption might be to set, say, $\mu_1=-\mu_0=1$ so that everything is now a function of one variable, the precision). So for any given values of those parameters, we could compute the probability that she gets all 8 cups correct (that the four smallest "milk-firstiness" values she experiences are associated with the four milk-second cups); if the exact calculation was too hard for us we could simulate it to any desired accuracy. [In the case where the nonrandomness is presumed to be a function of just one variable, we would have a power-curve -- a value for power for each value of the parameter.] That's one specific kind of model for how she might perform "better than random" with which we might specify parameters and obtain a value for power. We could of course suppose many other forms of non-randomness than this.
Power of lady tasting tea experiment Under the alternative the lady is not randomly guessing, but "not randomly guessing" covers an infinity of different situations. She might always guess perfectly or she might only do very slightly bet
32,462
Find data and confidence "ellipses" (regions?) for a bivariate median?
This is a nice question. I'll follow @amoeba's suggestion and bootstrap the spatial medians, using depth::med() with method="Spatial". However, there is a slight complication: med doesn't like it when there are duplicate data points, so we can't do a straightforward bootstrap. Instead, I'll draw a bootstrap sample and then jitter each point by a tiny amount - less than the minimum distances in each of the $x$ and $y$ dimensions in the original data sample - before calculating the spatial median. Finally, I'll calculate the smallest ellipse covering a specified proportion (95%) of bootstrapped medians and plot. library(depth) # for med() library(MASS) # for cov.rob() library(cluster) # for ellipsoidhull() # create data set.seed(1) df <- data.frame(x = rnorm(200, mean = 4, sd = 1.5), y = rnorm(200, mean = 1.4, sd = 2.5)) # find minimum distances in each dimension for later jittering foo <- outer(X=df$x,Y=df$x,FUN=function(xx,yy)abs(xx-yy)) delta.x <- min(foo[upper.tri(foo)])/2 foo <- outer(X=df$y,Y=df$y,FUN=function(xx,yy)abs(xx-yy)) delta.y <- min(foo[upper.tri(foo)])/2 # bootstrap spatial medians, using jittering n.boot <- 1000 pb <- winProgressBar(max=n.boot) boot.med <- matrix(NA,nrow=n.boot,ncol=2) for ( ii in 1:n.boot ) { setWinProgressBar(pb,ii,paste(ii,"of",n.boot)) index <- sample(1:nrow(df),nrow(df),replace=TRUE) bar <- df[index,] + data.frame(x=runif(nrow(df),-delta.x,delta.x), y=runif(nrow(df),-delta.y,delta.y)) boot.med[ii,] <- med(bar,method="Spatial")$median } close(pb) # specify confidence level pp <- 0.95 # find smallest ellipse containing the specified proportion of bootstrapped medians fit <- cov.rob(boot.med, quantile.used = ceiling(pp*n.boot), method = "mve") best_ellipse <- ellipsoidhull( boot.med[fit$best,] ) plot(df) points(boot.med,pch=19,col="grey",cex=0.5) points(df) lines(predict(best_ellipse), col="red") legend("bottomright",bg="white",pch=c(21,19,NA), col=c("black","grey","red"),pt.bg=c("white",NA,NA),lwd=c(0,0,1), legend=c("Observations","Bootstrapped medians","Confidence ellipse")) Finally, note that the bivariate spatial median is asymptotically normally distributed (Brown, 1983, JRSS, Series B), so we could also dispense with the "jittered bootstrap" above and directly calculate the ellipse, trusting that $n=200$ is "asymptotical enough". I may edit this post to include this parametric confidence ellipse if I find the time in the next days.
Find data and confidence "ellipses" (regions?) for a bivariate median?
This is a nice question. I'll follow @amoeba's suggestion and bootstrap the spatial medians, using depth::med() with method="Spatial". However, there is a slight complication: med doesn't like it when
Find data and confidence "ellipses" (regions?) for a bivariate median? This is a nice question. I'll follow @amoeba's suggestion and bootstrap the spatial medians, using depth::med() with method="Spatial". However, there is a slight complication: med doesn't like it when there are duplicate data points, so we can't do a straightforward bootstrap. Instead, I'll draw a bootstrap sample and then jitter each point by a tiny amount - less than the minimum distances in each of the $x$ and $y$ dimensions in the original data sample - before calculating the spatial median. Finally, I'll calculate the smallest ellipse covering a specified proportion (95%) of bootstrapped medians and plot. library(depth) # for med() library(MASS) # for cov.rob() library(cluster) # for ellipsoidhull() # create data set.seed(1) df <- data.frame(x = rnorm(200, mean = 4, sd = 1.5), y = rnorm(200, mean = 1.4, sd = 2.5)) # find minimum distances in each dimension for later jittering foo <- outer(X=df$x,Y=df$x,FUN=function(xx,yy)abs(xx-yy)) delta.x <- min(foo[upper.tri(foo)])/2 foo <- outer(X=df$y,Y=df$y,FUN=function(xx,yy)abs(xx-yy)) delta.y <- min(foo[upper.tri(foo)])/2 # bootstrap spatial medians, using jittering n.boot <- 1000 pb <- winProgressBar(max=n.boot) boot.med <- matrix(NA,nrow=n.boot,ncol=2) for ( ii in 1:n.boot ) { setWinProgressBar(pb,ii,paste(ii,"of",n.boot)) index <- sample(1:nrow(df),nrow(df),replace=TRUE) bar <- df[index,] + data.frame(x=runif(nrow(df),-delta.x,delta.x), y=runif(nrow(df),-delta.y,delta.y)) boot.med[ii,] <- med(bar,method="Spatial")$median } close(pb) # specify confidence level pp <- 0.95 # find smallest ellipse containing the specified proportion of bootstrapped medians fit <- cov.rob(boot.med, quantile.used = ceiling(pp*n.boot), method = "mve") best_ellipse <- ellipsoidhull( boot.med[fit$best,] ) plot(df) points(boot.med,pch=19,col="grey",cex=0.5) points(df) lines(predict(best_ellipse), col="red") legend("bottomright",bg="white",pch=c(21,19,NA), col=c("black","grey","red"),pt.bg=c("white",NA,NA),lwd=c(0,0,1), legend=c("Observations","Bootstrapped medians","Confidence ellipse")) Finally, note that the bivariate spatial median is asymptotically normally distributed (Brown, 1983, JRSS, Series B), so we could also dispense with the "jittered bootstrap" above and directly calculate the ellipse, trusting that $n=200$ is "asymptotical enough". I may edit this post to include this parametric confidence ellipse if I find the time in the next days.
Find data and confidence "ellipses" (regions?) for a bivariate median? This is a nice question. I'll follow @amoeba's suggestion and bootstrap the spatial medians, using depth::med() with method="Spatial". However, there is a slight complication: med doesn't like it when
32,463
Dealing with small batch size in SGD training
With a small batchsize, I believe the SGD descent direction becomes a very noisy estimate of the "true" descent direction (i.e. if we evaluated it on the entire training set). With a small batchsize, I am not sure how much increasing the momentum would help as it would be accumulating momentum in very noisy directions. But I could be wrong, maybe your optimization problem is well-posed enough where this could work. If you aren't gunning for "state of the art" results, one option you have for natural image data is to resize the images. I actually think that modulo chasing down elite benchmarking performance, natural images have a lot of scale invariant properties and a lot of their semantic features are fairly robust under reasonable scaling transformations. This would alleviate some of the GPU memory and allow you to increase your batchsize and your SGD descent directions would be better estimates of the descent directions. If you are dealing with a separable loss function like negative log likelihood, we can exploit the fact that the gradient of a large batch is merely the sum/average of the gradients of its constituent sub-batches. For example if our batchsize is $B$, we can compute gradients of a super batchsize $BK$ by iterating through the batches as usual, computing each batch gradient, but instead of updating the weights, we cache each gradient into a running sum or average. If we average appropriately, we will be computing the exact gradient for the $BK$ sized super batch. We then perform the weight update after each $K$-th batch has been processed. We will be exactly computing the $BK$ batch gradients by serializing the computation as described above. There is minimal extra computational or memory overhead, one only needs to modify the minibatch iterator to include the super batch serialization and gradient cache.
Dealing with small batch size in SGD training
With a small batchsize, I believe the SGD descent direction becomes a very noisy estimate of the "true" descent direction (i.e. if we evaluated it on the entire training set). With a small batchsize,
Dealing with small batch size in SGD training With a small batchsize, I believe the SGD descent direction becomes a very noisy estimate of the "true" descent direction (i.e. if we evaluated it on the entire training set). With a small batchsize, I am not sure how much increasing the momentum would help as it would be accumulating momentum in very noisy directions. But I could be wrong, maybe your optimization problem is well-posed enough where this could work. If you aren't gunning for "state of the art" results, one option you have for natural image data is to resize the images. I actually think that modulo chasing down elite benchmarking performance, natural images have a lot of scale invariant properties and a lot of their semantic features are fairly robust under reasonable scaling transformations. This would alleviate some of the GPU memory and allow you to increase your batchsize and your SGD descent directions would be better estimates of the descent directions. If you are dealing with a separable loss function like negative log likelihood, we can exploit the fact that the gradient of a large batch is merely the sum/average of the gradients of its constituent sub-batches. For example if our batchsize is $B$, we can compute gradients of a super batchsize $BK$ by iterating through the batches as usual, computing each batch gradient, but instead of updating the weights, we cache each gradient into a running sum or average. If we average appropriately, we will be computing the exact gradient for the $BK$ sized super batch. We then perform the weight update after each $K$-th batch has been processed. We will be exactly computing the $BK$ batch gradients by serializing the computation as described above. There is minimal extra computational or memory overhead, one only needs to modify the minibatch iterator to include the super batch serialization and gradient cache.
Dealing with small batch size in SGD training With a small batchsize, I believe the SGD descent direction becomes a very noisy estimate of the "true" descent direction (i.e. if we evaluated it on the entire training set). With a small batchsize,
32,464
Dealing with small batch size in SGD training
Recently I came across an interesting work: Samuel L. Smith, Pieter-Jan Kindermans, Chris Ying, Quoc V. Le, Don't Decay the Learning Rate, Increase the Batch Size (ICLR 2018). This works shows a direct link between batch size and learning rate. Specifically, decreasing learning rate has the same effect as increasing batch size and vice versa. Taking their conclusion to extreme, one might consider decreasing the batch size and compensating for it by increasing the learning rate. I haven't actually tried it yet, though.
Dealing with small batch size in SGD training
Recently I came across an interesting work: Samuel L. Smith, Pieter-Jan Kindermans, Chris Ying, Quoc V. Le, Don't Decay the Learning Rate, Increase the Batch Size (ICLR 2018). This works shows a dire
Dealing with small batch size in SGD training Recently I came across an interesting work: Samuel L. Smith, Pieter-Jan Kindermans, Chris Ying, Quoc V. Le, Don't Decay the Learning Rate, Increase the Batch Size (ICLR 2018). This works shows a direct link between batch size and learning rate. Specifically, decreasing learning rate has the same effect as increasing batch size and vice versa. Taking their conclusion to extreme, one might consider decreasing the batch size and compensating for it by increasing the learning rate. I haven't actually tried it yet, though.
Dealing with small batch size in SGD training Recently I came across an interesting work: Samuel L. Smith, Pieter-Jan Kindermans, Chris Ying, Quoc V. Le, Don't Decay the Learning Rate, Increase the Batch Size (ICLR 2018). This works shows a dire
32,465
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel trick
This answer also adds points from pAt84's answer Dimensionality reduction. I don't think reducing dimension can make your data more separable actually but it has some other benefits. First, as the dimension of your space grows, you often need more samples to be able to catch patterns, this is just a question of volume. Of course this all depends on how corrolated your data is (if you add a duplicate column it won't change). So reducing your dimension can be a necessity when you have feature vectors that has too many components, e.g. if you work with text and have a sort of TF-IDF, it would create one dimension per word (or lemma). Moreover, it prevents you from the curse of dimensionnality (e.g. if you need to perform some sort of KNN afterwards). And obviously it also fastens a lot the algorithm you run in the reduced space - though the cost of reducing dimension can be higher than the gain of running algorithms in reduced dimension. One thing is sure: dimensionnality reduction decreases information. Most of the time it does so by discarding correlations in the input data. Kernel trick. That being said, the kernel trick is an entirely different idea. Some data that are not separable in the original space can become in a higher one: imagine two circles of radius $.5$ and $1$ sampled, those points are not separable, but if you add the distance to $0$ they become. So the idea is that the way we use a dot-product in the original space is not sufficient enough, we ought to use the dot-product in that mapped space with distance to the origine, and that's the core idea to kernels: find functions that can "scatter" our data as we want into a hilbert space. But the way I prefer to see it is that using a kernel is using a prior information on your data: how they can be compared. Roughly, a kernel is more or less a similarity matrix, and a kernel-based method is a method where you've switch the naive way of comparison (regular dot-product in the original space) to one that fits your data best (your kernel). Then, indeed, it can correspond in a mathematical way, to increasing the dimension of the space comparison happens in. Precisely: your data still lives on the same-dimensional space, but the kernel you provided acts as if you mapped your data in a higher dimensional space (RKHS), that can have an infinite dimension (e.g. with an RBF), and you used a dot-product in that space. The main trick of kernel-based method is that you actualy never explicitly map your data into the RKHS - that's why it can work! All the work is done by applying your kernel on two samples. Eventually, you haven't gained any information, meaning that it helps give a mathematical frame to explain how it works, but intuitively the idea is just that you've provided a better way to compare your data: no dimension were really explicitly added to your data (computationaly), you simply found a more suitable way to compare them. Now nothing prevents you from doing both: you could try to categorize texts by doing a TF-IDF, then a PCA and then an RBF-SVM (though a linear one is most of the time OK with texts but nonetheless that would make perfect sense).
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel
This answer also adds points from pAt84's answer Dimensionality reduction. I don't think reducing dimension can make your data more separable actually but it has some other benefits. First, as the dim
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel trick This answer also adds points from pAt84's answer Dimensionality reduction. I don't think reducing dimension can make your data more separable actually but it has some other benefits. First, as the dimension of your space grows, you often need more samples to be able to catch patterns, this is just a question of volume. Of course this all depends on how corrolated your data is (if you add a duplicate column it won't change). So reducing your dimension can be a necessity when you have feature vectors that has too many components, e.g. if you work with text and have a sort of TF-IDF, it would create one dimension per word (or lemma). Moreover, it prevents you from the curse of dimensionnality (e.g. if you need to perform some sort of KNN afterwards). And obviously it also fastens a lot the algorithm you run in the reduced space - though the cost of reducing dimension can be higher than the gain of running algorithms in reduced dimension. One thing is sure: dimensionnality reduction decreases information. Most of the time it does so by discarding correlations in the input data. Kernel trick. That being said, the kernel trick is an entirely different idea. Some data that are not separable in the original space can become in a higher one: imagine two circles of radius $.5$ and $1$ sampled, those points are not separable, but if you add the distance to $0$ they become. So the idea is that the way we use a dot-product in the original space is not sufficient enough, we ought to use the dot-product in that mapped space with distance to the origine, and that's the core idea to kernels: find functions that can "scatter" our data as we want into a hilbert space. But the way I prefer to see it is that using a kernel is using a prior information on your data: how they can be compared. Roughly, a kernel is more or less a similarity matrix, and a kernel-based method is a method where you've switch the naive way of comparison (regular dot-product in the original space) to one that fits your data best (your kernel). Then, indeed, it can correspond in a mathematical way, to increasing the dimension of the space comparison happens in. Precisely: your data still lives on the same-dimensional space, but the kernel you provided acts as if you mapped your data in a higher dimensional space (RKHS), that can have an infinite dimension (e.g. with an RBF), and you used a dot-product in that space. The main trick of kernel-based method is that you actualy never explicitly map your data into the RKHS - that's why it can work! All the work is done by applying your kernel on two samples. Eventually, you haven't gained any information, meaning that it helps give a mathematical frame to explain how it works, but intuitively the idea is just that you've provided a better way to compare your data: no dimension were really explicitly added to your data (computationaly), you simply found a more suitable way to compare them. Now nothing prevents you from doing both: you could try to categorize texts by doing a TF-IDF, then a PCA and then an RBF-SVM (though a linear one is most of the time OK with texts but nonetheless that would make perfect sense).
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel This answer also adds points from pAt84's answer Dimensionality reduction. I don't think reducing dimension can make your data more separable actually but it has some other benefits. First, as the dim
32,466
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel trick
I won't have enough space in the comments to give my thoughts on Vinces answer, which is certainly very good but lacking some additional insight. Can answers be merged? Dimensionality reduction would not make the data more separable during training: you are giving away information. However, this information drain might be useful for the generalization of the learned model, i.e. its performance on unseen data will increase. You do not always need more samples to catch patterns in a high(er)-dimensional space although in general this might actually be the case. It also depends on the correlation of the features. If you just double a feature vector, i.e. two feature vectors will be the same, the increase in dimensionality will obviously not have significant consequences other than probably upsetting your regularization scheme of the learner. It is quite important to see how much the data correlates, the rank of the feature matrix can be a very good inside. Vince makes a very good point when he says that dimensionality reduction can fasten your algorithm during training and testing. However, keep in mind that the reduction itself also has a computational complexity, so performing PCA and adding an SVM might not give you much of a speedup (and can be absorbed into one weight vector I think). However, if you keep the dimensionality reduction simple enough, then this will really work in your favor. A good example of that are HOG features in object detection (http://cs.brown.edu/~pff/papers/lsvm-pami.pdf). In the paper PCA is performed on the HOG feature vector. A closer look at the eigenvectors reveals that a simple dimensionlity reduction, which just sums up different groups of features, will be enough and it indeed is. This gave a 2 to 3 times speedup. As for the kernel trick: the function that `lifts' your data into a higher dimensional space does not necessarily have to map into euclidean space but into a Reproducing Kernel Hilbert Space (RKHS). This gives you a bit more freedom in designing such functions. The Gram matrix of the kernel function, i.e. the dot-product in higher-dimensional space for all combinations of training examples can vaguely be seen as a similarity/dissimilarity matrix. However, I would not really push this thought too far. For an RBF kernel this is certainly true but a polynomial kernel is very hard to interpret in this way. Actually additional components are added to your feature vector when using kernels, i.e. the dimensionality increases. It does so implicitly in the RKHS. For many kernels, e.g. polynomial kernels, the dimensionality increases massively. For the RBF kernel it is even infinite under some conditions. Doing both (PCA + kernel-based learning) is called kernel pca and essentially fuses both methods. Keep in mind though: just as a dimensionlity reduction may speed up your algorithms, kernel functions will almost always slow them down due to its increased computational complexity at test time c.f. a linear classifier. This can partially be circumvented by explicit feature mapping, i.e. actually executing the mapping function from original to high-dimensional space and keeping an eye on the dimensionality. See, for example, this paper: http://www.robots.ox.ac.uk/~vedaldi/assets/pubs/vedaldi11efficient.pdf This trick is quite nice as it gives you an intuition of the higher dimensional space while not making it too large in the sense of having too many components. Once your feature vectors are explicitely mapped into the higher-dimensional space, you may apply a linear classifier. There is certainly more out there (e.g. low-rank expansion) but I think these two answers should give you a good and somewhat detailed overview. Vinces answer should be upvoted and chosen as best answer if you are happy with the information we gave you.
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel
I won't have enough space in the comments to give my thoughts on Vinces answer, which is certainly very good but lacking some additional insight. Can answers be merged? Dimensionality reduction would
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel trick I won't have enough space in the comments to give my thoughts on Vinces answer, which is certainly very good but lacking some additional insight. Can answers be merged? Dimensionality reduction would not make the data more separable during training: you are giving away information. However, this information drain might be useful for the generalization of the learned model, i.e. its performance on unseen data will increase. You do not always need more samples to catch patterns in a high(er)-dimensional space although in general this might actually be the case. It also depends on the correlation of the features. If you just double a feature vector, i.e. two feature vectors will be the same, the increase in dimensionality will obviously not have significant consequences other than probably upsetting your regularization scheme of the learner. It is quite important to see how much the data correlates, the rank of the feature matrix can be a very good inside. Vince makes a very good point when he says that dimensionality reduction can fasten your algorithm during training and testing. However, keep in mind that the reduction itself also has a computational complexity, so performing PCA and adding an SVM might not give you much of a speedup (and can be absorbed into one weight vector I think). However, if you keep the dimensionality reduction simple enough, then this will really work in your favor. A good example of that are HOG features in object detection (http://cs.brown.edu/~pff/papers/lsvm-pami.pdf). In the paper PCA is performed on the HOG feature vector. A closer look at the eigenvectors reveals that a simple dimensionlity reduction, which just sums up different groups of features, will be enough and it indeed is. This gave a 2 to 3 times speedup. As for the kernel trick: the function that `lifts' your data into a higher dimensional space does not necessarily have to map into euclidean space but into a Reproducing Kernel Hilbert Space (RKHS). This gives you a bit more freedom in designing such functions. The Gram matrix of the kernel function, i.e. the dot-product in higher-dimensional space for all combinations of training examples can vaguely be seen as a similarity/dissimilarity matrix. However, I would not really push this thought too far. For an RBF kernel this is certainly true but a polynomial kernel is very hard to interpret in this way. Actually additional components are added to your feature vector when using kernels, i.e. the dimensionality increases. It does so implicitly in the RKHS. For many kernels, e.g. polynomial kernels, the dimensionality increases massively. For the RBF kernel it is even infinite under some conditions. Doing both (PCA + kernel-based learning) is called kernel pca and essentially fuses both methods. Keep in mind though: just as a dimensionlity reduction may speed up your algorithms, kernel functions will almost always slow them down due to its increased computational complexity at test time c.f. a linear classifier. This can partially be circumvented by explicit feature mapping, i.e. actually executing the mapping function from original to high-dimensional space and keeping an eye on the dimensionality. See, for example, this paper: http://www.robots.ox.ac.uk/~vedaldi/assets/pubs/vedaldi11efficient.pdf This trick is quite nice as it gives you an intuition of the higher dimensional space while not making it too large in the sense of having too many components. Once your feature vectors are explicitely mapped into the higher-dimensional space, you may apply a linear classifier. There is certainly more out there (e.g. low-rank expansion) but I think these two answers should give you a good and somewhat detailed overview. Vinces answer should be upvoted and chosen as best answer if you are happy with the information we gave you.
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel I won't have enough space in the comments to give my thoughts on Vinces answer, which is certainly very good but lacking some additional insight. Can answers be merged? Dimensionality reduction would
32,467
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel trick
Dimensionality Reduction: this is a way of reducing the features of your dataset which may not really contribute much to the model development. Putting it in another way, dimensionality reduction helps to remove "noice" from our dataset thus avoiding overfitting of our model. However, Kernel Trick helps us to make a linearly inseparable dataset to become linearly separable by projecting it into higher dimensionality which may otherwise improve the precision of our model. With Kernel Trick, you can make a nonlinear dataset linear.
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel
Dimensionality Reduction: this is a way of reducing the features of your dataset which may not really contribute much to the model development. Putting it in another way, dimensionality reduction help
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel trick Dimensionality Reduction: this is a way of reducing the features of your dataset which may not really contribute much to the model development. Putting it in another way, dimensionality reduction helps to remove "noice" from our dataset thus avoiding overfitting of our model. However, Kernel Trick helps us to make a linearly inseparable dataset to become linearly separable by projecting it into higher dimensionality which may otherwise improve the precision of our model. With Kernel Trick, you can make a nonlinear dataset linear.
Projecting to lower/higher-dimensional space for classification: dimensionality reduction vs kernel Dimensionality Reduction: this is a way of reducing the features of your dataset which may not really contribute much to the model development. Putting it in another way, dimensionality reduction help
32,468
Real life examples of an inefficient Random Number Generator
A lottery scheme in Ontario used poorly designed random generation, which was spotted by a statistician, Mohan Srivastava of Toronto, Canada, who notified the Ontario Lottery and Gaming Corporation of the issue, rather than making a hefty profit out of this loophole.
Real life examples of an inefficient Random Number Generator
A lottery scheme in Ontario used poorly designed random generation, which was spotted by a statistician, Mohan Srivastava of Toronto, Canada, who notified the Ontario Lottery and Gaming Corporation of
Real life examples of an inefficient Random Number Generator A lottery scheme in Ontario used poorly designed random generation, which was spotted by a statistician, Mohan Srivastava of Toronto, Canada, who notified the Ontario Lottery and Gaming Corporation of the issue, rather than making a hefty profit out of this loophole.
Real life examples of an inefficient Random Number Generator A lottery scheme in Ontario used poorly designed random generation, which was spotted by a statistician, Mohan Srivastava of Toronto, Canada, who notified the Ontario Lottery and Gaming Corporation of
32,469
Expected value and variance of sample correlation
I cannot give you one expression, but here are several articles that cover some non-normal cases: Browne, M. W., & Shapiro, A. (1986). The asymptotic covariance matrix of sample correlation coefficients under general conditions. Linear Algebra and its Applications, 82, 169-176. Gayen, A. K. (1951). The frequency distribution of the product-moment correlation coefficient in random samples of any size drawn from non-normal universes. Biometrika, 38, 219-247. Kowalski, C. (1972). On the effects of non-normality on the distribution of the sample product-moment correlation coefficient. Applied Statistics, 21, 1-12. Subrahmaniam, K., & Gajjar, A. V. (1980). Robustness to nonnormality of some transformations of the sample correlation coefficient. Journal of Multivariate Analysis, 10, 60-77. Yuan, K.-H., & Bentler, P. M. (2000). Inferences on correlation coefficients in some classes of nonnormal distributions. Journal of Multivariate Analysis, 72, 230-248.
Expected value and variance of sample correlation
I cannot give you one expression, but here are several articles that cover some non-normal cases: Browne, M. W., & Shapiro, A. (1986). The asymptotic covariance matrix of sample correlation coefficien
Expected value and variance of sample correlation I cannot give you one expression, but here are several articles that cover some non-normal cases: Browne, M. W., & Shapiro, A. (1986). The asymptotic covariance matrix of sample correlation coefficients under general conditions. Linear Algebra and its Applications, 82, 169-176. Gayen, A. K. (1951). The frequency distribution of the product-moment correlation coefficient in random samples of any size drawn from non-normal universes. Biometrika, 38, 219-247. Kowalski, C. (1972). On the effects of non-normality on the distribution of the sample product-moment correlation coefficient. Applied Statistics, 21, 1-12. Subrahmaniam, K., & Gajjar, A. V. (1980). Robustness to nonnormality of some transformations of the sample correlation coefficient. Journal of Multivariate Analysis, 10, 60-77. Yuan, K.-H., & Bentler, P. M. (2000). Inferences on correlation coefficients in some classes of nonnormal distributions. Journal of Multivariate Analysis, 72, 230-248.
Expected value and variance of sample correlation I cannot give you one expression, but here are several articles that cover some non-normal cases: Browne, M. W., & Shapiro, A. (1986). The asymptotic covariance matrix of sample correlation coefficien
32,470
Standard error for the sum of regression coefficients when the covariance is negative
To elaborate on (and in fact, make more precise my part of) the discussion in the comments a bit: Variance-covariance matrices are positive semi-definite, as discussed for example in @DilipSarwate's answer here: The variance of a weighted sum $\sum_i a_i X_i$ of random variables must be nonnegative for all choices of real numbers $a_i$. Since the variance can be expressed as $$\operatorname{var}\left(\sum_i a_i X_i\right) = \sum_i \sum_j a_ia_j \operatorname{cov}(X_i,X_j) = \sum_i \sum_j a_ia_j \Sigma_{i,j},$$ we have that the covariance matrix $\Sigma = [\Sigma_{i,j}]$ must be positive semidefinite (which is sometimes called nonnegative definite). (As the general notation suggests, this issue therefore also has nothing to do with coefficient estimates, but applies for all random variables.) If you specialize this to your problem $a_1=a_2=1$, you obtain the well-known result that $$ \operatorname{var}\left(X_1+X_2\right) = \operatorname{var}\left(X_1\right) +\operatorname{var}\left(X_2\right) +2\operatorname{cov}(X_i,X_j)\geq0 $$ Thus, the smallest possible covariance is $$ \operatorname{cov}(X_i,X_j)=-\frac{\operatorname{var}\left(X_1\right) +\operatorname{var}\left(X_2\right) }{2} $$
Standard error for the sum of regression coefficients when the covariance is negative
To elaborate on (and in fact, make more precise my part of) the discussion in the comments a bit: Variance-covariance matrices are positive semi-definite, as discussed for example in @DilipSarwate's a
Standard error for the sum of regression coefficients when the covariance is negative To elaborate on (and in fact, make more precise my part of) the discussion in the comments a bit: Variance-covariance matrices are positive semi-definite, as discussed for example in @DilipSarwate's answer here: The variance of a weighted sum $\sum_i a_i X_i$ of random variables must be nonnegative for all choices of real numbers $a_i$. Since the variance can be expressed as $$\operatorname{var}\left(\sum_i a_i X_i\right) = \sum_i \sum_j a_ia_j \operatorname{cov}(X_i,X_j) = \sum_i \sum_j a_ia_j \Sigma_{i,j},$$ we have that the covariance matrix $\Sigma = [\Sigma_{i,j}]$ must be positive semidefinite (which is sometimes called nonnegative definite). (As the general notation suggests, this issue therefore also has nothing to do with coefficient estimates, but applies for all random variables.) If you specialize this to your problem $a_1=a_2=1$, you obtain the well-known result that $$ \operatorname{var}\left(X_1+X_2\right) = \operatorname{var}\left(X_1\right) +\operatorname{var}\left(X_2\right) +2\operatorname{cov}(X_i,X_j)\geq0 $$ Thus, the smallest possible covariance is $$ \operatorname{cov}(X_i,X_j)=-\frac{\operatorname{var}\left(X_1\right) +\operatorname{var}\left(X_2\right) }{2} $$
Standard error for the sum of regression coefficients when the covariance is negative To elaborate on (and in fact, make more precise my part of) the discussion in the comments a bit: Variance-covariance matrices are positive semi-definite, as discussed for example in @DilipSarwate's a
32,471
Transforming Order Statistics
This problem can be solved from the definitions alone: the only advanced calculation is the integral of a monomial. Preliminary observations Let's work with the variables $X_i/a$ and $Y_i/a$ throughout: this does not change $Z_n$ but it makes $(X_1, \ldots, Y_n)$ iid with Uniform$(0,1)$ distributions, eliminating all distracting appearances of $a$ in the calculations. Thus we may assume $a=1$ without any loss of generality. Note that the independence of the $Y_i$ and their uniform distribution imply that for any number $y$ for which $0\le y \le 1$, $$\Pr(y \ge Y_{(n)}) = \Pr(y \ge Y_1 , \ldots, y \ge Y_n) = \Pr(y \ge Y_1)\cdots \Pr(y \ge Y_n) = y^n,$$ with an identical result holding for $X_{(n)}$. For future reference, this allows us to compute $$\mathbb{E}(2X_{(n)}^n) = \int_0^1 2x^n\mathrm{d}(x^n) = \int_0^1 2nx^{2n-1}\mathrm{d}x = 1.$$ Solution Let $t$ be a positive real number. To find the distribution of $Z_n$, substitute its definition and simplify the resulting inequality: $$\eqalign{ \Pr(Z_n \gt t) &= \Pr(Z_n / n \gt t/n) = \Pr\left(\exp(Z_n/n) \gt e^{t/n}\right) \\ &=\Pr\left(\frac{\max(X_{(n)}, Y_{(n)})}{\min(X_{(n)}, Y_{(n)})} \gt e^{t/n}\right) \\ &= \Pr\left(e^{-t/n}{\max(X_{(n)}, Y_{(n)})} \gt {\min(X_{(n)}, Y_{(n)})}\right). }$$ This event breaks into two equiprobable cases, depending on whether $X_{(n)}$ or $Y_{(n)}$ is the smaller of the two (and their intersection, with zero probability, can be ignored). Thus we need only compute the chance of one of these cases (say where $Y_{(n)}$ is the smaller) and double it. Since $t\ge 0$, $0 \le e^{-t/n}X_{(n)} \le 1$, allowing us (upon letting $e^{-t/n}X_{(n)}$ to play the role of $y$) to apply the computations in the preliminary section: $$\Pr(Z_n \gt t) =2\Pr\left(e^{-t/n}X_{(n)} \gt {Y_{(n)}}\right) =2 \mathbb{E}\left[\left(e^{-t/n}{X_{(n)}}\right)^n\right] = e^{-t} \mathbb{E}\left[2{X_{(n)}^n}\right] = e^{-t}. $$ That's what it means for $Z_n$ to have an Exp$(1)$ distribution.
Transforming Order Statistics
This problem can be solved from the definitions alone: the only advanced calculation is the integral of a monomial. Preliminary observations Let's work with the variables $X_i/a$ and $Y_i/a$ througho
Transforming Order Statistics This problem can be solved from the definitions alone: the only advanced calculation is the integral of a monomial. Preliminary observations Let's work with the variables $X_i/a$ and $Y_i/a$ throughout: this does not change $Z_n$ but it makes $(X_1, \ldots, Y_n)$ iid with Uniform$(0,1)$ distributions, eliminating all distracting appearances of $a$ in the calculations. Thus we may assume $a=1$ without any loss of generality. Note that the independence of the $Y_i$ and their uniform distribution imply that for any number $y$ for which $0\le y \le 1$, $$\Pr(y \ge Y_{(n)}) = \Pr(y \ge Y_1 , \ldots, y \ge Y_n) = \Pr(y \ge Y_1)\cdots \Pr(y \ge Y_n) = y^n,$$ with an identical result holding for $X_{(n)}$. For future reference, this allows us to compute $$\mathbb{E}(2X_{(n)}^n) = \int_0^1 2x^n\mathrm{d}(x^n) = \int_0^1 2nx^{2n-1}\mathrm{d}x = 1.$$ Solution Let $t$ be a positive real number. To find the distribution of $Z_n$, substitute its definition and simplify the resulting inequality: $$\eqalign{ \Pr(Z_n \gt t) &= \Pr(Z_n / n \gt t/n) = \Pr\left(\exp(Z_n/n) \gt e^{t/n}\right) \\ &=\Pr\left(\frac{\max(X_{(n)}, Y_{(n)})}{\min(X_{(n)}, Y_{(n)})} \gt e^{t/n}\right) \\ &= \Pr\left(e^{-t/n}{\max(X_{(n)}, Y_{(n)})} \gt {\min(X_{(n)}, Y_{(n)})}\right). }$$ This event breaks into two equiprobable cases, depending on whether $X_{(n)}$ or $Y_{(n)}$ is the smaller of the two (and their intersection, with zero probability, can be ignored). Thus we need only compute the chance of one of these cases (say where $Y_{(n)}$ is the smaller) and double it. Since $t\ge 0$, $0 \le e^{-t/n}X_{(n)} \le 1$, allowing us (upon letting $e^{-t/n}X_{(n)}$ to play the role of $y$) to apply the computations in the preliminary section: $$\Pr(Z_n \gt t) =2\Pr\left(e^{-t/n}X_{(n)} \gt {Y_{(n)}}\right) =2 \mathbb{E}\left[\left(e^{-t/n}{X_{(n)}}\right)^n\right] = e^{-t} \mathbb{E}\left[2{X_{(n)}^n}\right] = e^{-t}. $$ That's what it means for $Z_n$ to have an Exp$(1)$ distribution.
Transforming Order Statistics This problem can be solved from the definitions alone: the only advanced calculation is the integral of a monomial. Preliminary observations Let's work with the variables $X_i/a$ and $Y_i/a$ througho
32,472
Transforming Order Statistics
I will sketch the solution, here using a computer algebra system to do the nitty gritties ... Solution If $X_1, ... , X_n$ is a sample of size $n$ on parent $X \sim \text{Uniform}(0,a)$, then the pdf of the sample maximum is: $$f_{n}(x) = \frac{n}{a^n} x^{n-1}$$ and similarly for $Y$. Approach 1: Find the joint pdf of $(X_{(n)},Y_{(n)})$ Since $X$ and $Y$ are independent, the joint pdf of the 2 sample maximums $(X_{(n)},Y_{(n)})$ is simply the product of the 2 pdf's, say $f_{(n)}(x,y)$: Given $Z_n= n\log\frac{\max(Y_{(n)},X_{(n)})}{\min(Y_{(n)},X_{(n)})}$. Then, the cdf of $Z_n$ is $P(Z_n < z)$ is: where I am using the Prob function from the mathStatica package for Mathematica to automate. Differentiating the cdf wrt $z$ yields the pdf of $Z_n$ as standard Exponential. Approach 2: Order statistics We can use order statistics to 'by-pass' the mechanics of having to deal with the Max and Min functions. Once again: If $X_1, ... , X_n$ is a sample of size $n$ on parent $X \sim \text{Uniform}(0,a)$, then the pdf of the sample maximum $W = X_{(n)}$ is, say, $f_n(w)$: The sample maximums $X_{(n)}$ and $Y_{(n)}$ are just two independent drawings from this distribution of $W$; i.e. the $1^{st}$ and $2^{nd}$ order statistics of $W$ (in a sample of size 2) are just what we are looking for: $W_{(1)} = \min(Y_{(n)},X_{(n)})$ $W_{(2)} = \max(Y_{(n)},X_{(n)})$ The joint pdf of $(W_{(1)}, W_{(2)})$, in a sample of size 2, say $g(.,.)$, is: Given $Z_n= n\log\frac{\max(Y_{(n)},X_{(n)})}{\min(Y_{(n)},X_{(n)})}$. Then, the cdf of $Z_n$ is $P(Z_n < z)$ is: The advantage of this approach is that the probability calculation no longer involves the max/min functions, which may make the derivation (especially by hand) somewhat easier to express. Other As per my comment above, it appears you have misinterpreted the question ... We are asked to find: $$Z_n= n\log\frac{\max(Y_{(n)},X_{(n)})}{\min(Y_{(n)},X_{(n)})}$$ where the denominator is min(xMax, yMax), ... not the minimum of all the $X$'s and $Y$'s.
Transforming Order Statistics
I will sketch the solution, here using a computer algebra system to do the nitty gritties ... Solution If $X_1, ... , X_n$ is a sample of size $n$ on parent $X \sim \text{Uniform}(0,a)$, then the pdf
Transforming Order Statistics I will sketch the solution, here using a computer algebra system to do the nitty gritties ... Solution If $X_1, ... , X_n$ is a sample of size $n$ on parent $X \sim \text{Uniform}(0,a)$, then the pdf of the sample maximum is: $$f_{n}(x) = \frac{n}{a^n} x^{n-1}$$ and similarly for $Y$. Approach 1: Find the joint pdf of $(X_{(n)},Y_{(n)})$ Since $X$ and $Y$ are independent, the joint pdf of the 2 sample maximums $(X_{(n)},Y_{(n)})$ is simply the product of the 2 pdf's, say $f_{(n)}(x,y)$: Given $Z_n= n\log\frac{\max(Y_{(n)},X_{(n)})}{\min(Y_{(n)},X_{(n)})}$. Then, the cdf of $Z_n$ is $P(Z_n < z)$ is: where I am using the Prob function from the mathStatica package for Mathematica to automate. Differentiating the cdf wrt $z$ yields the pdf of $Z_n$ as standard Exponential. Approach 2: Order statistics We can use order statistics to 'by-pass' the mechanics of having to deal with the Max and Min functions. Once again: If $X_1, ... , X_n$ is a sample of size $n$ on parent $X \sim \text{Uniform}(0,a)$, then the pdf of the sample maximum $W = X_{(n)}$ is, say, $f_n(w)$: The sample maximums $X_{(n)}$ and $Y_{(n)}$ are just two independent drawings from this distribution of $W$; i.e. the $1^{st}$ and $2^{nd}$ order statistics of $W$ (in a sample of size 2) are just what we are looking for: $W_{(1)} = \min(Y_{(n)},X_{(n)})$ $W_{(2)} = \max(Y_{(n)},X_{(n)})$ The joint pdf of $(W_{(1)}, W_{(2)})$, in a sample of size 2, say $g(.,.)$, is: Given $Z_n= n\log\frac{\max(Y_{(n)},X_{(n)})}{\min(Y_{(n)},X_{(n)})}$. Then, the cdf of $Z_n$ is $P(Z_n < z)$ is: The advantage of this approach is that the probability calculation no longer involves the max/min functions, which may make the derivation (especially by hand) somewhat easier to express. Other As per my comment above, it appears you have misinterpreted the question ... We are asked to find: $$Z_n= n\log\frac{\max(Y_{(n)},X_{(n)})}{\min(Y_{(n)},X_{(n)})}$$ where the denominator is min(xMax, yMax), ... not the minimum of all the $X$'s and $Y$'s.
Transforming Order Statistics I will sketch the solution, here using a computer algebra system to do the nitty gritties ... Solution If $X_1, ... , X_n$ is a sample of size $n$ on parent $X \sim \text{Uniform}(0,a)$, then the pdf
32,473
Why is lasso in matlab much slower than glmnet in R (10 min versus ~1 s)?
glmnet in R is fast because it uses what's called regularization paths. Basically, you select a ordered sequence of penalization parameters $\lambda_1, \ldots \lambda_m$. The solution for $\lambda_1$ is used as a warm start for $\lambda_{2}$, the solution for $\lambda_2$ used as a warm start for $\lambda_3$, and so on. This is because the solutions should be close to one another. So fitting the model for the $(n+1)$th penalization parameter, you don't start the coordinate descent from a completely random place in the parameter space. Instead you start from somewhere that's already close to the solution: the parameters for the $n$th model. If you run separate glmnet calls for each $\lambda$, it's considerably slower, and indeed the documentation in ?glmnet states the following about the lambda parameter: WARNING: use with care. Do not supply a single value for lambda [...] Supply instead a decreasing sequence of lambda values. glmnet relies on its warms starts for speed, and its often faster to fit a whole path than compute a single fit. Emphasis mine. So in the time a non-regularization-path approach computes the solution for one $\lambda$ the regularization-path-based one has already done all of the $\lambda$s and started on the next fold. See also the comment to this answer from Chris Haug. Apparently he has access to MATLAB, which I don't. His findings seem to confirm my suspicion that the difference in speed comes from the use of the regularization path.
Why is lasso in matlab much slower than glmnet in R (10 min versus ~1 s)?
glmnet in R is fast because it uses what's called regularization paths. Basically, you select a ordered sequence of penalization parameters $\lambda_1, \ldots \lambda_m$. The solution for $\lambda_1$
Why is lasso in matlab much slower than glmnet in R (10 min versus ~1 s)? glmnet in R is fast because it uses what's called regularization paths. Basically, you select a ordered sequence of penalization parameters $\lambda_1, \ldots \lambda_m$. The solution for $\lambda_1$ is used as a warm start for $\lambda_{2}$, the solution for $\lambda_2$ used as a warm start for $\lambda_3$, and so on. This is because the solutions should be close to one another. So fitting the model for the $(n+1)$th penalization parameter, you don't start the coordinate descent from a completely random place in the parameter space. Instead you start from somewhere that's already close to the solution: the parameters for the $n$th model. If you run separate glmnet calls for each $\lambda$, it's considerably slower, and indeed the documentation in ?glmnet states the following about the lambda parameter: WARNING: use with care. Do not supply a single value for lambda [...] Supply instead a decreasing sequence of lambda values. glmnet relies on its warms starts for speed, and its often faster to fit a whole path than compute a single fit. Emphasis mine. So in the time a non-regularization-path approach computes the solution for one $\lambda$ the regularization-path-based one has already done all of the $\lambda$s and started on the next fold. See also the comment to this answer from Chris Haug. Apparently he has access to MATLAB, which I don't. His findings seem to confirm my suspicion that the difference in speed comes from the use of the regularization path.
Why is lasso in matlab much slower than glmnet in R (10 min versus ~1 s)? glmnet in R is fast because it uses what's called regularization paths. Basically, you select a ordered sequence of penalization parameters $\lambda_1, \ldots \lambda_m$. The solution for $\lambda_1$
32,474
Python Lasagne tutorial: validation error lower than training error
Here is a possible explanation (could very well be wrong however), maybe you could try modifying their tutorial code to see if this works or not? For minibatch descent methods the parameters of our model get updated after each minibatch. It's important to note that in the code you posted the training error of each minibatch is computed using a different set of weights. On the other hand, note that for the validation error, it is being computed with the same set of weights. And perhaps more importantly, the MLP is being trained with Dropout. When we are computing training error, again, unlike validation error, we do not turn off Dropout. In particular, note that in the code for the validation function we have Deterministic = True while this is absent from the training function. In particular note that the very purpose of using Dropout is to prevent overfitting, i.e. lower training error than validation error. And to this end, we see that Dropout is doing a good job as it is very easy for even relatively shallow models to overfit the MNIST dataset these days. So here's what you can try: after each epoch of training, run the val_fn on the training set as well as the validation set. This will come at the cost of an additional full forward pass through the training set. But for MNIST and a simple model like MLP, it isn't going to cost too much in terms of computation and it might be worth it to get your hands dirty modifying some Lasagne code as well as building some general intuition about minibatch + Dropout training.
Python Lasagne tutorial: validation error lower than training error
Here is a possible explanation (could very well be wrong however), maybe you could try modifying their tutorial code to see if this works or not? For minibatch descent methods the parameters of our m
Python Lasagne tutorial: validation error lower than training error Here is a possible explanation (could very well be wrong however), maybe you could try modifying their tutorial code to see if this works or not? For minibatch descent methods the parameters of our model get updated after each minibatch. It's important to note that in the code you posted the training error of each minibatch is computed using a different set of weights. On the other hand, note that for the validation error, it is being computed with the same set of weights. And perhaps more importantly, the MLP is being trained with Dropout. When we are computing training error, again, unlike validation error, we do not turn off Dropout. In particular, note that in the code for the validation function we have Deterministic = True while this is absent from the training function. In particular note that the very purpose of using Dropout is to prevent overfitting, i.e. lower training error than validation error. And to this end, we see that Dropout is doing a good job as it is very easy for even relatively shallow models to overfit the MNIST dataset these days. So here's what you can try: after each epoch of training, run the val_fn on the training set as well as the validation set. This will come at the cost of an additional full forward pass through the training set. But for MNIST and a simple model like MLP, it isn't going to cost too much in terms of computation and it might be worth it to get your hands dirty modifying some Lasagne code as well as building some general intuition about minibatch + Dropout training.
Python Lasagne tutorial: validation error lower than training error Here is a possible explanation (could very well be wrong however), maybe you could try modifying their tutorial code to see if this works or not? For minibatch descent methods the parameters of our m
32,475
Are any processes in nature distributed exactly normal?
If you mean "exactly" precisely enough, then I think the answer is "no" because any natural event has a limited population (even if the population is very large) so no probability will be exactly correct. Also the normal distribution applies to continuous variables and nothing is really continuous. Even weight, if you get down to the subatomic level, is a count (how much does Peter weigh? Please answer in terms of protons). Perhaps more interesting, many variables that are assumed to be normally distributed may not even be roughly normal, in typical populations.
Are any processes in nature distributed exactly normal?
If you mean "exactly" precisely enough, then I think the answer is "no" because any natural event has a limited population (even if the population is very large) so no probability will be exactly corr
Are any processes in nature distributed exactly normal? If you mean "exactly" precisely enough, then I think the answer is "no" because any natural event has a limited population (even if the population is very large) so no probability will be exactly correct. Also the normal distribution applies to continuous variables and nothing is really continuous. Even weight, if you get down to the subatomic level, is a count (how much does Peter weigh? Please answer in terms of protons). Perhaps more interesting, many variables that are assumed to be normally distributed may not even be roughly normal, in typical populations.
Are any processes in nature distributed exactly normal? If you mean "exactly" precisely enough, then I think the answer is "no" because any natural event has a limited population (even if the population is very large) so no probability will be exactly corr
32,476
How many sides does a die have? Bayesian inference in JAGS
This an interesting problem termed 'species-sampling', that has received a lot of attention over the years, and encompasses many other estimation problems (such as mark-recapture). Suffice it to say, JAGS will not help you in this case--JAGS cannot handle Markov chains with a variable dimension across iterations. One must recourse to an MCMC scheme designed for such problems, such as reversible jump MCMC. Here's one approach that's suitable for the specific model you are describing, which I first encountered in the work of Jeff Miller (arxived). Part I (Original question) One assumption I'll make is that an observation a given category implies the existence of categories of a lesser rank. That is, observing a die roll on side 9 implies the existence of sides 1-8. It doesn't have to be this way--the categories could be arbitrary--but I'll assume so in my example. This means that 0 values are observable, in contrast to other species-estimation problems. Let's say we have a multinomial sample, $$ Y = \{y_1, y_2, \dots, y_m, y_{m+1}, \dots, y_{n} \} \sim \mathcal{M}(\{p_1, p_2, \dots, p_m, p_{m+1}, \dots, p_n\}) $$ where $m$ is the maximum category observed, $n$ is the (unknown) number of categories, and all $\{y_{m+1},\dots,y_{n}\}$ equal 0. The parameter $n$ is finite, and we need a prior for it. Any discrete, proper prior with support on $[1, \infty)$ will work; take for example a zero-truncated Poisson: $$n \sim \mathcal{P}(\lambda), n > 0$$ A convenient prior for the multinomial probabilities is the Dirichlet, $$ P = \{ p_1, \dots, p_n \} \sim \mathcal{D}(\{ \alpha_1, \dots, \alpha_n \}) $$ And for simplicitly assume $\alpha_1 = \alpha_2 = \dots = \alpha_n = \tilde{\alpha}$. To make the problem more tractable, we marginalize out the weights: $$ p(Y|\tilde{\alpha}, n) = \int_P p(Y|P, n)p(P|\tilde{\alpha}, n) dP $$ Which in this case leads the well-studied Dirichlet-multinomial distribution. The goal is then to estimate the conditional posterior, $$ p(n|Y, \tilde{\alpha}, \lambda) = \frac{ p(Y|n, \tilde{\alpha}) p(n|\lambda) }{ p(Y|\tilde{\alpha}, \lambda) } $$ Where I'm explicitly assuming $\tilde{\alpha}$ and $\lambda$ are fixed hyperparameters. It is easy to see that: $$ p(Y|\tilde{\alpha}, \lambda) = \sum_{n=1}^\infty p(Y|n, \tilde{\alpha}) p(n|\lambda) $$ Where $p(Y|n, \tilde{\alpha}) = 0$ where $n < m$. This infinite series should converge rather quickly (as long as the tail on the prior isn't too heavy), and so is easy to approximate. For the truncated Poisson, it has the form: $$ p(Y|\tilde{\alpha}, \lambda) = \frac{1}{(e^\lambda - 1)} \sum_{n=m}^\infty \frac{\Gamma(n\tilde{\alpha})\prod_{i=1}^n \Gamma(y_i + \tilde{\alpha})}{\Gamma(n\tilde{\alpha} + \sum_{i=1}^n y_i) \Gamma(\tilde{\alpha})^n} \cdot \frac{\lambda^n}{n!} $$ Leading to: $$ p(n|Y,\tilde{\alpha}, \lambda) = \frac{\Gamma(n\tilde{\alpha})\prod_{i=1}^n \Gamma(y_i + \tilde{\alpha})}{\Gamma(n\tilde{\alpha} + \sum_{i=1}^n y_i) \Gamma(\tilde{\alpha})^n} \cdot \frac{\lambda^n}{n!} \cdot \left(\sum_{j=m}^\infty \frac{\Gamma(j\tilde{\alpha})\prod_{i=1}^j \Gamma(y_i + \tilde{\alpha})}{\Gamma(j\tilde{\alpha} + \sum_{i=1}^j y_i) \Gamma(\tilde{\alpha})^j} \cdot \frac{\lambda^j}{j!}\right)^{-1} $$ Which has support on $[m, \infty)$. There isn't a need for MCMC in this case as the infinite series in the denominator of Bayes' rule can be approximated without too much effort. Here's a sloppy example in R: logPosteriorN <- function(max, Y, lambda, alpha){ m <- length(Y) sumy <- sum(Y) pp <- sapply(1:max, function(j){ prior <- log(lambda)*j - log(exp(lambda)-1) - lgamma(j+1) posterior <- lgamma(alpha*j) + sum(lgamma(Y + alpha)) - j*lgamma(alpha) - lgamma(sumy + j*alpha) if( j > m ) { posterior <- posterior + (j-m)*lgamma(alpha) } else if( j < m ) { posterior = -Inf } prior + posterior }) evidence <- log(sum(exp(pp))) # there's no check that this converges pp - evidence } ## with even representation of sides Y <- c(10, 10, 10, 10) post <- logPosteriorN(30, Y, 10, 1.2) plot(1:30, exp(post), pch=19, type="b") ## with uneven representation of sides Y <- c(1, 2, 1, 0, 0, 2, 1, 0, 1) post <- logPosteriorN(30, Y, 10, 1.2) plot(1:30, exp(post), pch=19, type="b") Your intuition is correct: sparse sampling across categories leads to greater uncertainty about the total number of categories. If you wished to treat $\tilde{\alpha}$ as an unknown parameter, you would need to use MCMC and alternate updates of $n$ and $\tilde{\alpha}$. Of course, this is one approach to estimation. You will readily find others (of Bayesian and non-Bayesian flavors) with a little searching. Part II (Answer to comment) $Y = \{y_1, \dots, y_m, y_{m+1}, \dots, y_n \}$ is a partially-observed multinomial vector with corresponding probabilities $\Omega = \{\omega_1, \dots, \omega_m, \omega_{m+1}, \dots, \omega_n\}$: $$ \mathrm{Pr}(Y|\Omega, n) = \frac{\Gamma(\sum_{i=1}^n y_i + 1)}{\prod_{i=1}^n \Gamma(y_i + 1) } \prod_{i=1}^n \omega_i^{y_i} $$ Where $y \in \mathbb{N}$, $y_1 \dots y_m > 0$ and $y_{m+1} \dots y_n = 0$ but otherwise the indices are abitrary. As before, the problem is to infer the true number of categories $n$, and we start with a prior on $n$ such as a zero-truncated Poisson: $$ \mathrm{Pr}(n|\lambda) = \frac{\lambda^{n}}{(\exp\{\lambda\} - 1)n!},~n \in \mathbb{Z}^+ $$ Also as before, we treat the multinomial probabilities $\Omega$ as Dirichlet distributed with a symmetric hyperparameter $\tilde{\alpha}$, i.e. for a given $n$, $$ \mathrm{Pr}(\Omega|\tilde{\alpha}, n) = \frac{\Gamma(n\tilde{\alpha})}{\Gamma(\tilde{\alpha})^n} \prod_{i=1}^n \omega_i^{\tilde{\alpha}-1} $$ Integrating (marginalizing) over the vector of probabilities gives the multinomial Dirichlet: $$ \mathrm{Pr}(Y|\tilde{\alpha}, n) = \int \mathrm{Pr}(Y|\Omega, n) \mathrm{Pr}(\Omega|\tilde{\alpha}, n) = \frac{\Gamma(n \tilde{\alpha})} {\Gamma(\sum_{i=1}^n y_i + n \tilde{\alpha}) \Gamma(\tilde{\alpha})^n} \prod_{i=1}^n \Gamma(y_i + \tilde{\alpha}) $$ Here is where we diverge from the model in Part I above. In Part I, there was an implicit ordering to categories: for example, in an $n$-sided die, the categories (sides) have an implicit ordering and the observation of any category $i \in \{1 \dots n\}$ implies the existence of lesser categories $j < i$. In Part II, we have a partially-observed multinomial random vector which has no implicit ordering. In other words, the data represent an unordered partition of the data points into $m \leq n$ observed categories. I'll denote the unordered partition that results from $Y$ augmented by $n-m$ unobserved categories, as $\mathcal{P}[Y]$. The probability of the unordered partition conditional on a true number of categories $n$, can be found by considering the number of permutations of categories which result in the same partition: $$ \mathrm{Pr}(\mathcal{P}[Y]|\tilde{\alpha}, n) = \frac{n!}{(n-m)!} \mathrm{Pr}(Y|\tilde{\alpha}, n) $$ And this can be integrated over $n$ to give: $$ \mathrm{Pr}(\mathcal{P}[Y]|\tilde{\alpha}, \lambda) = \sum_{j=m}^{\infty} \mathrm{Pr}(\mathcal{P}[Y]|\tilde{\alpha}, n) \mathrm{Pr}(n|\lambda) $$ Using Bayes' rule to retrieve the posterior: $$ \mathrm{Pr}(n|\mathcal{P}[Y], \tilde{\alpha}, \lambda) = \frac{\mathrm{Pr}(\mathcal{P}[Y]|n, \tilde{\alpha}) \mathrm{Pr}(n|\lambda)}{\mathrm{Pr}(\mathcal{P}[Y]|\tilde{\alpha}, \lambda)} $$ Just plug in from the definitions above. Again, the denominator is an infinite series that will converge quickly: in this simple model, there is no need for MCMC to give an adequate approximation. By modifying the R code from Part I: logPosteriorN_2 <- function(max, Y, lambda, alpha){ m <- length(Y) sumy <- sum(Y) pp <- sapply(1:max, function(j){ prior <- log(lambda)*j - log(exp(lambda)-1) - lgamma(j+1) likelihood <- lchoose(j, m) + lgamma(m + 1) + lgamma(alpha*j) + sum(lgamma(Y + alpha)) - j*lgamma(alpha) - lgamma(sumy + j*alpha) if( j > m ) { likelihood <- likelihood + (j-m)*lgamma(alpha) } else if( j < m ) { likelihood = -Inf } prior + likelihood }) evidence <- log(sum(exp(pp))) # there's no check that this converges pp - evidence } Y_1 <- rep(10, 15) pos_1 <- logPosteriorN_2(50, Y_1, 6, 1) plot(1:50, exp(pos_1))
How many sides does a die have? Bayesian inference in JAGS
This an interesting problem termed 'species-sampling', that has received a lot of attention over the years, and encompasses many other estimation problems (such as mark-recapture). Suffice it to say,
How many sides does a die have? Bayesian inference in JAGS This an interesting problem termed 'species-sampling', that has received a lot of attention over the years, and encompasses many other estimation problems (such as mark-recapture). Suffice it to say, JAGS will not help you in this case--JAGS cannot handle Markov chains with a variable dimension across iterations. One must recourse to an MCMC scheme designed for such problems, such as reversible jump MCMC. Here's one approach that's suitable for the specific model you are describing, which I first encountered in the work of Jeff Miller (arxived). Part I (Original question) One assumption I'll make is that an observation a given category implies the existence of categories of a lesser rank. That is, observing a die roll on side 9 implies the existence of sides 1-8. It doesn't have to be this way--the categories could be arbitrary--but I'll assume so in my example. This means that 0 values are observable, in contrast to other species-estimation problems. Let's say we have a multinomial sample, $$ Y = \{y_1, y_2, \dots, y_m, y_{m+1}, \dots, y_{n} \} \sim \mathcal{M}(\{p_1, p_2, \dots, p_m, p_{m+1}, \dots, p_n\}) $$ where $m$ is the maximum category observed, $n$ is the (unknown) number of categories, and all $\{y_{m+1},\dots,y_{n}\}$ equal 0. The parameter $n$ is finite, and we need a prior for it. Any discrete, proper prior with support on $[1, \infty)$ will work; take for example a zero-truncated Poisson: $$n \sim \mathcal{P}(\lambda), n > 0$$ A convenient prior for the multinomial probabilities is the Dirichlet, $$ P = \{ p_1, \dots, p_n \} \sim \mathcal{D}(\{ \alpha_1, \dots, \alpha_n \}) $$ And for simplicitly assume $\alpha_1 = \alpha_2 = \dots = \alpha_n = \tilde{\alpha}$. To make the problem more tractable, we marginalize out the weights: $$ p(Y|\tilde{\alpha}, n) = \int_P p(Y|P, n)p(P|\tilde{\alpha}, n) dP $$ Which in this case leads the well-studied Dirichlet-multinomial distribution. The goal is then to estimate the conditional posterior, $$ p(n|Y, \tilde{\alpha}, \lambda) = \frac{ p(Y|n, \tilde{\alpha}) p(n|\lambda) }{ p(Y|\tilde{\alpha}, \lambda) } $$ Where I'm explicitly assuming $\tilde{\alpha}$ and $\lambda$ are fixed hyperparameters. It is easy to see that: $$ p(Y|\tilde{\alpha}, \lambda) = \sum_{n=1}^\infty p(Y|n, \tilde{\alpha}) p(n|\lambda) $$ Where $p(Y|n, \tilde{\alpha}) = 0$ where $n < m$. This infinite series should converge rather quickly (as long as the tail on the prior isn't too heavy), and so is easy to approximate. For the truncated Poisson, it has the form: $$ p(Y|\tilde{\alpha}, \lambda) = \frac{1}{(e^\lambda - 1)} \sum_{n=m}^\infty \frac{\Gamma(n\tilde{\alpha})\prod_{i=1}^n \Gamma(y_i + \tilde{\alpha})}{\Gamma(n\tilde{\alpha} + \sum_{i=1}^n y_i) \Gamma(\tilde{\alpha})^n} \cdot \frac{\lambda^n}{n!} $$ Leading to: $$ p(n|Y,\tilde{\alpha}, \lambda) = \frac{\Gamma(n\tilde{\alpha})\prod_{i=1}^n \Gamma(y_i + \tilde{\alpha})}{\Gamma(n\tilde{\alpha} + \sum_{i=1}^n y_i) \Gamma(\tilde{\alpha})^n} \cdot \frac{\lambda^n}{n!} \cdot \left(\sum_{j=m}^\infty \frac{\Gamma(j\tilde{\alpha})\prod_{i=1}^j \Gamma(y_i + \tilde{\alpha})}{\Gamma(j\tilde{\alpha} + \sum_{i=1}^j y_i) \Gamma(\tilde{\alpha})^j} \cdot \frac{\lambda^j}{j!}\right)^{-1} $$ Which has support on $[m, \infty)$. There isn't a need for MCMC in this case as the infinite series in the denominator of Bayes' rule can be approximated without too much effort. Here's a sloppy example in R: logPosteriorN <- function(max, Y, lambda, alpha){ m <- length(Y) sumy <- sum(Y) pp <- sapply(1:max, function(j){ prior <- log(lambda)*j - log(exp(lambda)-1) - lgamma(j+1) posterior <- lgamma(alpha*j) + sum(lgamma(Y + alpha)) - j*lgamma(alpha) - lgamma(sumy + j*alpha) if( j > m ) { posterior <- posterior + (j-m)*lgamma(alpha) } else if( j < m ) { posterior = -Inf } prior + posterior }) evidence <- log(sum(exp(pp))) # there's no check that this converges pp - evidence } ## with even representation of sides Y <- c(10, 10, 10, 10) post <- logPosteriorN(30, Y, 10, 1.2) plot(1:30, exp(post), pch=19, type="b") ## with uneven representation of sides Y <- c(1, 2, 1, 0, 0, 2, 1, 0, 1) post <- logPosteriorN(30, Y, 10, 1.2) plot(1:30, exp(post), pch=19, type="b") Your intuition is correct: sparse sampling across categories leads to greater uncertainty about the total number of categories. If you wished to treat $\tilde{\alpha}$ as an unknown parameter, you would need to use MCMC and alternate updates of $n$ and $\tilde{\alpha}$. Of course, this is one approach to estimation. You will readily find others (of Bayesian and non-Bayesian flavors) with a little searching. Part II (Answer to comment) $Y = \{y_1, \dots, y_m, y_{m+1}, \dots, y_n \}$ is a partially-observed multinomial vector with corresponding probabilities $\Omega = \{\omega_1, \dots, \omega_m, \omega_{m+1}, \dots, \omega_n\}$: $$ \mathrm{Pr}(Y|\Omega, n) = \frac{\Gamma(\sum_{i=1}^n y_i + 1)}{\prod_{i=1}^n \Gamma(y_i + 1) } \prod_{i=1}^n \omega_i^{y_i} $$ Where $y \in \mathbb{N}$, $y_1 \dots y_m > 0$ and $y_{m+1} \dots y_n = 0$ but otherwise the indices are abitrary. As before, the problem is to infer the true number of categories $n$, and we start with a prior on $n$ such as a zero-truncated Poisson: $$ \mathrm{Pr}(n|\lambda) = \frac{\lambda^{n}}{(\exp\{\lambda\} - 1)n!},~n \in \mathbb{Z}^+ $$ Also as before, we treat the multinomial probabilities $\Omega$ as Dirichlet distributed with a symmetric hyperparameter $\tilde{\alpha}$, i.e. for a given $n$, $$ \mathrm{Pr}(\Omega|\tilde{\alpha}, n) = \frac{\Gamma(n\tilde{\alpha})}{\Gamma(\tilde{\alpha})^n} \prod_{i=1}^n \omega_i^{\tilde{\alpha}-1} $$ Integrating (marginalizing) over the vector of probabilities gives the multinomial Dirichlet: $$ \mathrm{Pr}(Y|\tilde{\alpha}, n) = \int \mathrm{Pr}(Y|\Omega, n) \mathrm{Pr}(\Omega|\tilde{\alpha}, n) = \frac{\Gamma(n \tilde{\alpha})} {\Gamma(\sum_{i=1}^n y_i + n \tilde{\alpha}) \Gamma(\tilde{\alpha})^n} \prod_{i=1}^n \Gamma(y_i + \tilde{\alpha}) $$ Here is where we diverge from the model in Part I above. In Part I, there was an implicit ordering to categories: for example, in an $n$-sided die, the categories (sides) have an implicit ordering and the observation of any category $i \in \{1 \dots n\}$ implies the existence of lesser categories $j < i$. In Part II, we have a partially-observed multinomial random vector which has no implicit ordering. In other words, the data represent an unordered partition of the data points into $m \leq n$ observed categories. I'll denote the unordered partition that results from $Y$ augmented by $n-m$ unobserved categories, as $\mathcal{P}[Y]$. The probability of the unordered partition conditional on a true number of categories $n$, can be found by considering the number of permutations of categories which result in the same partition: $$ \mathrm{Pr}(\mathcal{P}[Y]|\tilde{\alpha}, n) = \frac{n!}{(n-m)!} \mathrm{Pr}(Y|\tilde{\alpha}, n) $$ And this can be integrated over $n$ to give: $$ \mathrm{Pr}(\mathcal{P}[Y]|\tilde{\alpha}, \lambda) = \sum_{j=m}^{\infty} \mathrm{Pr}(\mathcal{P}[Y]|\tilde{\alpha}, n) \mathrm{Pr}(n|\lambda) $$ Using Bayes' rule to retrieve the posterior: $$ \mathrm{Pr}(n|\mathcal{P}[Y], \tilde{\alpha}, \lambda) = \frac{\mathrm{Pr}(\mathcal{P}[Y]|n, \tilde{\alpha}) \mathrm{Pr}(n|\lambda)}{\mathrm{Pr}(\mathcal{P}[Y]|\tilde{\alpha}, \lambda)} $$ Just plug in from the definitions above. Again, the denominator is an infinite series that will converge quickly: in this simple model, there is no need for MCMC to give an adequate approximation. By modifying the R code from Part I: logPosteriorN_2 <- function(max, Y, lambda, alpha){ m <- length(Y) sumy <- sum(Y) pp <- sapply(1:max, function(j){ prior <- log(lambda)*j - log(exp(lambda)-1) - lgamma(j+1) likelihood <- lchoose(j, m) + lgamma(m + 1) + lgamma(alpha*j) + sum(lgamma(Y + alpha)) - j*lgamma(alpha) - lgamma(sumy + j*alpha) if( j > m ) { likelihood <- likelihood + (j-m)*lgamma(alpha) } else if( j < m ) { likelihood = -Inf } prior + likelihood }) evidence <- log(sum(exp(pp))) # there's no check that this converges pp - evidence } Y_1 <- rep(10, 15) pos_1 <- logPosteriorN_2(50, Y_1, 6, 1) plot(1:50, exp(pos_1))
How many sides does a die have? Bayesian inference in JAGS This an interesting problem termed 'species-sampling', that has received a lot of attention over the years, and encompasses many other estimation problems (such as mark-recapture). Suffice it to say,
32,477
Multiple logistic regression power analysis
The problem is that there isn't really a $R^2$ for logistic regression. Instead there are many different "pseudo-$R^2$s" that may be similar to the $R^2$ from a linear model in different ways. You can get a list of some at UCLA's statistics help website here. In addition, the effect (e.g., odds ratio) of the added variable, $x_2$, isn't sufficient to determine your power to detect that effect. It matters how $x_2$ is distributed: The more widely spread the values are, the more powerful your test, even if the odds ratio is held constant. It further matters what the correlation between $x_2$ and $x_1$ is: The more correlated they are, the more data would be required to achieve the same power. As a result of these facts, the way I try to calculate the power in these more complicated situations is to simulate. In that vein, it may help you to read my answer here: Simulation of logistic regression power analysis - designed experiments. Looking at G*Power's documentation, they use a method based on Hsieh, Bloch, & Larsen (1998). The idea is that you first regress $x_2$ on $x_1$ (or whatever predictor variables went into the first model) using a linear regression. You use the regular $R^2$ for that. (That value should lie in the interval $[0,\ 1]$.) It goes in the R² other X field you are referring to. Then you specify the distribution of $x_2$ in the next couple of fields (X distribution, X parm μ, and Z parm σ). Hsieh, F.Y., Bloch, D.A., & Larsen, M.D. (1998). A simple method of sample size calculation for linear and logistic regression. Statistics in Medicine, 17, 1623-1634.
Multiple logistic regression power analysis
The problem is that there isn't really a $R^2$ for logistic regression. Instead there are many different "pseudo-$R^2$s" that may be similar to the $R^2$ from a linear model in different ways. You c
Multiple logistic regression power analysis The problem is that there isn't really a $R^2$ for logistic regression. Instead there are many different "pseudo-$R^2$s" that may be similar to the $R^2$ from a linear model in different ways. You can get a list of some at UCLA's statistics help website here. In addition, the effect (e.g., odds ratio) of the added variable, $x_2$, isn't sufficient to determine your power to detect that effect. It matters how $x_2$ is distributed: The more widely spread the values are, the more powerful your test, even if the odds ratio is held constant. It further matters what the correlation between $x_2$ and $x_1$ is: The more correlated they are, the more data would be required to achieve the same power. As a result of these facts, the way I try to calculate the power in these more complicated situations is to simulate. In that vein, it may help you to read my answer here: Simulation of logistic regression power analysis - designed experiments. Looking at G*Power's documentation, they use a method based on Hsieh, Bloch, & Larsen (1998). The idea is that you first regress $x_2$ on $x_1$ (or whatever predictor variables went into the first model) using a linear regression. You use the regular $R^2$ for that. (That value should lie in the interval $[0,\ 1]$.) It goes in the R² other X field you are referring to. Then you specify the distribution of $x_2$ in the next couple of fields (X distribution, X parm μ, and Z parm σ). Hsieh, F.Y., Bloch, D.A., & Larsen, M.D. (1998). A simple method of sample size calculation for linear and logistic regression. Statistics in Medicine, 17, 1623-1634.
Multiple logistic regression power analysis The problem is that there isn't really a $R^2$ for logistic regression. Instead there are many different "pseudo-$R^2$s" that may be similar to the $R^2$ from a linear model in different ways. You c
32,478
Multiple logistic regression power analysis
The excellent book Regression Methods in Biostatistics: Linear, Logistic, Survival, and Repeated Measures Models have a treatment of power analysis for logistic regression, with some simple useful (approximate) formulas, very possibly the formulas used by GPower referred in another answer (in section 5.7.) If those approximations are not good enough, probably simulation will be needed. Two-sided testing of $H_0\colon \beta_j=0$ (log-odds scale) versus $H_1\colon \beta_j=\beta_j^a$ with level $\alpha$ and power $\gamma$, standard deviation of predictor $x_j$ is $\sigma_{x_j}$, $p$ the marginal prevalence of the outcome and $\rho_j^2$ is the multiple correlation of $x_j$ with all the other predictors (this is the R-squared reported by a linear multiple regression of $X_j$ as response on all the other predictors, and do not involve the response in the logistic regression at all.) The minimum sample size is then $$ n=\frac{(z_{1-\alpha/2}+z_\gamma)^2}{(\beta_j^a \sigma_{x_j})^2 p(1-p) (1-\rho_j^2)} $$ where $z_{1-\alpha/2}$ and $z_\gamma$ are quantiles of the standard normal distribution corresponding to level and power. Note the use in this formula of the variance inflation factor $\text{vif}_j=\frac1{1-\rho_j^2}$. A graph showing minimum sample size as function of alternative coefficient $\beta_j^a$: For completeness some related formulas from the same source: If sample size $n$ is decided then power is $$ \gamma=1-\Phi\left(z_{1-\alpha/2}-|\beta_j^a| \sigma_x\sqrt{np(1-p)(1-\rho_j^2)}\right)$$ where $\Phi$ is the standard normal cumulative distribution function. The minimum detectable effect (on log-odds scale) is $$ \pm \beta_j^a = \frac{z_{1-\alpha/2}+z_\gamma}{\sigma_{x_j}\sqrt{np(1-p)(1-\rho_j^2)}} $$ The references given for this approximate formulas is A SIMPLE METHOD OF SAMPLE SIZE CALCULATION FOR LINEAR AND LOGISTIC REGRESSION which in turn for much of the theory refers to Sample Size for Logistic Regression With Small Response Probability which bases its result on approximations to the Fisher information matrix, so this is really based on normal approximations. It is known that normal approximations can be bad for logistic regression, so the results from this formulas should probably be checked by simulation. Code in R: min_n <- function(alpha=0.05, power=0.8, beta_a, sigma_x, p, R2) { z1 <- qnorm(1-alpha/2); z2 <- qnorm(power) n <- (z1 + z2)^2 / ( (beta_a*sigma_x)^2 * p*(1-p) * (1-R2) ) ceiling(n) } A simple test: min_n(beta_a=0.2, sigma_x=1, p=0.5, R2=0.5) [1] 1570 Code for the plot: ypos <- c(30, 100, 300, 1000, 3000, 10000, 30000, 100000) plot(function(b) min_n(beta_a=b, sigma_x=1, p=0.5, R2=0.5), from=0.0, to=1.0, n=101, log="y", xlab="alternativ coefficient", ylab="n", yaxt="n", lwd=3) axis(2, at=ypos, labels=sprintf("%i", ypos), las=1) plot(function(b) min_n(beta_a=b, sigma_x=1, p=0.1, R2=0.5), from=0.0, to=1.0, n=101, log="y", add=TRUE, col="blue", lwd=3) legend("topright", legend=c("p=0.5", "p=0.1"), col=c("black", "blue"), lwd=3) title(expression(paste("Sample size for logistic regression ", "with ", sigma[x]==1, " and ", "R2=0.5")))
Multiple logistic regression power analysis
The excellent book Regression Methods in Biostatistics: Linear, Logistic, Survival, and Repeated Measures Models have a treatment of power analysis for logistic regression, with some simple useful (ap
Multiple logistic regression power analysis The excellent book Regression Methods in Biostatistics: Linear, Logistic, Survival, and Repeated Measures Models have a treatment of power analysis for logistic regression, with some simple useful (approximate) formulas, very possibly the formulas used by GPower referred in another answer (in section 5.7.) If those approximations are not good enough, probably simulation will be needed. Two-sided testing of $H_0\colon \beta_j=0$ (log-odds scale) versus $H_1\colon \beta_j=\beta_j^a$ with level $\alpha$ and power $\gamma$, standard deviation of predictor $x_j$ is $\sigma_{x_j}$, $p$ the marginal prevalence of the outcome and $\rho_j^2$ is the multiple correlation of $x_j$ with all the other predictors (this is the R-squared reported by a linear multiple regression of $X_j$ as response on all the other predictors, and do not involve the response in the logistic regression at all.) The minimum sample size is then $$ n=\frac{(z_{1-\alpha/2}+z_\gamma)^2}{(\beta_j^a \sigma_{x_j})^2 p(1-p) (1-\rho_j^2)} $$ where $z_{1-\alpha/2}$ and $z_\gamma$ are quantiles of the standard normal distribution corresponding to level and power. Note the use in this formula of the variance inflation factor $\text{vif}_j=\frac1{1-\rho_j^2}$. A graph showing minimum sample size as function of alternative coefficient $\beta_j^a$: For completeness some related formulas from the same source: If sample size $n$ is decided then power is $$ \gamma=1-\Phi\left(z_{1-\alpha/2}-|\beta_j^a| \sigma_x\sqrt{np(1-p)(1-\rho_j^2)}\right)$$ where $\Phi$ is the standard normal cumulative distribution function. The minimum detectable effect (on log-odds scale) is $$ \pm \beta_j^a = \frac{z_{1-\alpha/2}+z_\gamma}{\sigma_{x_j}\sqrt{np(1-p)(1-\rho_j^2)}} $$ The references given for this approximate formulas is A SIMPLE METHOD OF SAMPLE SIZE CALCULATION FOR LINEAR AND LOGISTIC REGRESSION which in turn for much of the theory refers to Sample Size for Logistic Regression With Small Response Probability which bases its result on approximations to the Fisher information matrix, so this is really based on normal approximations. It is known that normal approximations can be bad for logistic regression, so the results from this formulas should probably be checked by simulation. Code in R: min_n <- function(alpha=0.05, power=0.8, beta_a, sigma_x, p, R2) { z1 <- qnorm(1-alpha/2); z2 <- qnorm(power) n <- (z1 + z2)^2 / ( (beta_a*sigma_x)^2 * p*(1-p) * (1-R2) ) ceiling(n) } A simple test: min_n(beta_a=0.2, sigma_x=1, p=0.5, R2=0.5) [1] 1570 Code for the plot: ypos <- c(30, 100, 300, 1000, 3000, 10000, 30000, 100000) plot(function(b) min_n(beta_a=b, sigma_x=1, p=0.5, R2=0.5), from=0.0, to=1.0, n=101, log="y", xlab="alternativ coefficient", ylab="n", yaxt="n", lwd=3) axis(2, at=ypos, labels=sprintf("%i", ypos), las=1) plot(function(b) min_n(beta_a=b, sigma_x=1, p=0.1, R2=0.5), from=0.0, to=1.0, n=101, log="y", add=TRUE, col="blue", lwd=3) legend("topright", legend=c("p=0.5", "p=0.1"), col=c("black", "blue"), lwd=3) title(expression(paste("Sample size for logistic regression ", "with ", sigma[x]==1, " and ", "R2=0.5")))
Multiple logistic regression power analysis The excellent book Regression Methods in Biostatistics: Linear, Logistic, Survival, and Repeated Measures Models have a treatment of power analysis for logistic regression, with some simple useful (ap
32,479
Multiple logistic regression power analysis
I dig a little and found that GPower does have a section on logistic regression in the supporting manual (GPower 3.1 Correlation & Regression, 2009)) Here are explanations for the parameters based on that manual. This will help to get the conceptual part but you may still struggle with specific numbers to enter. Odds ratio & Pr(Y=1 | X=1)H0: These two are to calculate the effect size. "Given the conditional probability p1=p(Y=1|X=1) under H0, we may define the effect size either by specifying p2=(Y=1|X=1)under H1 or by specifying the odds ratio OR=[p2/(1-p2)]/[p1(1-p1)]." R2 other X: "The sample size N is multiplied by (1-R2), where R2 is the squared multiple correlation coefficient when the predictor of interest is regressed on the other predictors," i.e., "The proportion of variance of Xj explained by additional predictors in the model (R2 other X)." X distribution, X parm mu, & X parm sigma: These are about the predictor distribution. "The power of the test also depends on the distribution of the predictor X, the 'X distribution' and its parameters need to be specified. Users may choose between six predefined distributions or select a manual imput mode. Depending on this selection, additional parameters must be specified" (see the original manual for details). (p.1157, Faul, Erdfelder, Buchner, & Lang, 2009)
Multiple logistic regression power analysis
I dig a little and found that GPower does have a section on logistic regression in the supporting manual (GPower 3.1 Correlation & Regression, 2009)) Here are explanations for the parameters based on
Multiple logistic regression power analysis I dig a little and found that GPower does have a section on logistic regression in the supporting manual (GPower 3.1 Correlation & Regression, 2009)) Here are explanations for the parameters based on that manual. This will help to get the conceptual part but you may still struggle with specific numbers to enter. Odds ratio & Pr(Y=1 | X=1)H0: These two are to calculate the effect size. "Given the conditional probability p1=p(Y=1|X=1) under H0, we may define the effect size either by specifying p2=(Y=1|X=1)under H1 or by specifying the odds ratio OR=[p2/(1-p2)]/[p1(1-p1)]." R2 other X: "The sample size N is multiplied by (1-R2), where R2 is the squared multiple correlation coefficient when the predictor of interest is regressed on the other predictors," i.e., "The proportion of variance of Xj explained by additional predictors in the model (R2 other X)." X distribution, X parm mu, & X parm sigma: These are about the predictor distribution. "The power of the test also depends on the distribution of the predictor X, the 'X distribution' and its parameters need to be specified. Users may choose between six predefined distributions or select a manual imput mode. Depending on this selection, additional parameters must be specified" (see the original manual for details). (p.1157, Faul, Erdfelder, Buchner, & Lang, 2009)
Multiple logistic regression power analysis I dig a little and found that GPower does have a section on logistic regression in the supporting manual (GPower 3.1 Correlation & Regression, 2009)) Here are explanations for the parameters based on
32,480
Sequential pattern mining on single sequence
Calculate a histogram of N-grams and threshold at an appropriate level. In Python: from scipy.stats import itemfreq s = '36127389722027284897241032720389720' N = 2 # bi-grams grams = [s[i:i+N] for i in xrange(len(s)-N)] print itemfreq(grams) The N-gram calculation (lines three and four) are from this answer. The example output is [['02' '1'] ['03' '2'] ['10' '1'] ['12' '1'] ['20' '2'] ['22' '1'] ['24' '1'] ['27' '3'] ['28' '1'] ['32' '1'] ['36' '1'] ['38' '2'] ['41' '1'] ['48' '1'] ['61' '1'] ['72' '5'] ['73' '1'] ['84' '1'] ['89' '3'] ['97' '3']] So 72 is the most frequent two-digit subsequence in your example, occurring a total of five times. You can run the code for all $N$ you are interested about.
Sequential pattern mining on single sequence
Calculate a histogram of N-grams and threshold at an appropriate level. In Python: from scipy.stats import itemfreq s = '36127389722027284897241032720389720' N = 2 # bi-grams grams = [s[i:i+N] for i i
Sequential pattern mining on single sequence Calculate a histogram of N-grams and threshold at an appropriate level. In Python: from scipy.stats import itemfreq s = '36127389722027284897241032720389720' N = 2 # bi-grams grams = [s[i:i+N] for i in xrange(len(s)-N)] print itemfreq(grams) The N-gram calculation (lines three and four) are from this answer. The example output is [['02' '1'] ['03' '2'] ['10' '1'] ['12' '1'] ['20' '2'] ['22' '1'] ['24' '1'] ['27' '3'] ['28' '1'] ['32' '1'] ['36' '1'] ['38' '2'] ['41' '1'] ['48' '1'] ['61' '1'] ['72' '5'] ['73' '1'] ['84' '1'] ['89' '3'] ['97' '3']] So 72 is the most frequent two-digit subsequence in your example, occurring a total of five times. You can run the code for all $N$ you are interested about.
Sequential pattern mining on single sequence Calculate a histogram of N-grams and threshold at an appropriate level. In Python: from scipy.stats import itemfreq s = '36127389722027284897241032720389720' N = 2 # bi-grams grams = [s[i:i+N] for i i
32,481
Sequential pattern mining on single sequence
I think you can use the Apriori algorithm. Count the number each single element occurs in the sequence. If the count is greater than some threshold $\varepsilon$ then the item is frequent. Then count the number of pairs of frequent items. Continue with the number of frequent $4$-tuples, etc.
Sequential pattern mining on single sequence
I think you can use the Apriori algorithm. Count the number each single element occurs in the sequence. If the count is greater than some threshold $\varepsilon$ then the item is frequent. Then count
Sequential pattern mining on single sequence I think you can use the Apriori algorithm. Count the number each single element occurs in the sequence. If the count is greater than some threshold $\varepsilon$ then the item is frequent. Then count the number of pairs of frequent items. Continue with the number of frequent $4$-tuples, etc.
Sequential pattern mining on single sequence I think you can use the Apriori algorithm. Count the number each single element occurs in the sequence. If the count is greater than some threshold $\varepsilon$ then the item is frequent. Then count
32,482
Sequential pattern mining on single sequence
You could use something like the following. As far as I know SPADE uses something similar too for multiple sequences. 36127389722027284897241032720389720 First you need to gather the positions of every item in your sequence. length: 1 { 0: [11,23,28,34], //4 1: [2,22], //2 2: [3,9,10,12,14,20,25,27,33], //9 3: [0,5,24,29], //4 4: [16,21], //2 5: [], //0 6: [1], //1 7: [4,8,13,19,26,32], //6 8: [6,15,17,30], //4 9: [7,18,31] //3 } Then check the support of these items against the minimum support you choose for frequent sequences. min_sup: 3 { 0: [11,23,28,34], //4 2: [3,9,10,12,14,20,25,27,33], //9 3: [0,5,24,29], //4 7: [4,8,13,19,26,32], //6 8: [6,15,17,30], //4 9: [7,18,31] //3 } In your case you need to find the items with consecutive positions. You can use wildcards too, but in that case the position difference will be more than 1 and you will find a lot more candidates. length: 2 { 00: [], //0 02: [[11,12]], //1 03: [[23,24],[28,29]], //2 07: [], //0 08: [], //0 09: [], //0 20: [[33,34]], //1 22: [[9,10]], //1 23: [], //0 27: [[3,4],[12,13],[25,26]], //3 28: [], //0 29: [], //0 30: [], //0 32: [[24,25]], //1 33: [], //0 37: [], //0 38: [[5,6],[29,30]], //2 39: [], //0 70: [], //0 72: [[8,9],[13,14],[19,20],[26,27],[32,33]], //5 73: [[4,5]], //1 77: [], //0 78: [], //0 79: [], //0 80: [], //0 82: [], //0 83: [], //0 87: [], //0 88: [], //0 89: [[6,7],[17,18],[30,31]], //3 90: [], //0 92: [], //0 93: [], //0 97: [[7,8],[18,19],[31,32]], //3 98: [], //0 99: [] //0 } min_sup: 3 { 27: [[3,4],[12,13],[25,26]], //3 72: [[8,9],[13,14],[19,20],[26,27],[32,33]], //5 89: [[6,7],[17,18],[30,31]], //3 97: [[7,8],[18,19],[31,32]], //3 } You can try to combine the upper sequences based on the ending, or you can just check the positions. length: 3 { 272: [[12,13,14],[25,26,27]], //2 727: [], //0 897: [[6,7,8],[17,18,19],[30,31,32]], //3 972: [[7,8,9],[18,19,20],[31,32,33]] //3 } min_sup: 3 { 897: [[6,7,8],[17,18,19],[30,31,32]], //3 972: [[7,8,9],[18,19,20],[31,32,33]] //3 } length: 4 { 8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3 } min_sup: 3 { 8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3 } There is only one pattern and you cannot combine it with itself, so the mining is complete. { 27: [[3,4],[12,13],[25,26]], //3 72: [[8,9],[13,14],[19,20],[26,27],[32,33]], //5 89: [[6,7],[17,18],[30,31]], //3 97: [[7,8],[18,19],[31,32]], //3 897: [[6,7,8],[17,18,19],[30,31,32]], //3 972: [[7,8,9],[18,19,20],[31,32,33]] //3 8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3 } If we exclude the sub-patterns of 8972. { 27: [[3,4],[12,13],[25,26]], //3 72: [[13,14],[26,27]], //2 8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3 } min_sup: 3 { 27: [[3,4],[12,13],[25,26]], //3 8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3 } I think it is the same as the patterns you have found. 361[27]3[8972]20[27]284[8972]4103[27]203[8972]0 Another option to keep the 72 too, because it occurs 3 times as a sub-sequence of 8972 and 2 other times independently from 8972. I think this should depend on whether you allow overlapping. 361[27]3[89(72)]202(72)84[89(72)]4103[2(7]2)03[89(72)]0 Note: I don't think sequential pattern mining is considered machine learning.
Sequential pattern mining on single sequence
You could use something like the following. As far as I know SPADE uses something similar too for multiple sequences. 36127389722027284897241032720389720 First you need to gather the positions of eve
Sequential pattern mining on single sequence You could use something like the following. As far as I know SPADE uses something similar too for multiple sequences. 36127389722027284897241032720389720 First you need to gather the positions of every item in your sequence. length: 1 { 0: [11,23,28,34], //4 1: [2,22], //2 2: [3,9,10,12,14,20,25,27,33], //9 3: [0,5,24,29], //4 4: [16,21], //2 5: [], //0 6: [1], //1 7: [4,8,13,19,26,32], //6 8: [6,15,17,30], //4 9: [7,18,31] //3 } Then check the support of these items against the minimum support you choose for frequent sequences. min_sup: 3 { 0: [11,23,28,34], //4 2: [3,9,10,12,14,20,25,27,33], //9 3: [0,5,24,29], //4 7: [4,8,13,19,26,32], //6 8: [6,15,17,30], //4 9: [7,18,31] //3 } In your case you need to find the items with consecutive positions. You can use wildcards too, but in that case the position difference will be more than 1 and you will find a lot more candidates. length: 2 { 00: [], //0 02: [[11,12]], //1 03: [[23,24],[28,29]], //2 07: [], //0 08: [], //0 09: [], //0 20: [[33,34]], //1 22: [[9,10]], //1 23: [], //0 27: [[3,4],[12,13],[25,26]], //3 28: [], //0 29: [], //0 30: [], //0 32: [[24,25]], //1 33: [], //0 37: [], //0 38: [[5,6],[29,30]], //2 39: [], //0 70: [], //0 72: [[8,9],[13,14],[19,20],[26,27],[32,33]], //5 73: [[4,5]], //1 77: [], //0 78: [], //0 79: [], //0 80: [], //0 82: [], //0 83: [], //0 87: [], //0 88: [], //0 89: [[6,7],[17,18],[30,31]], //3 90: [], //0 92: [], //0 93: [], //0 97: [[7,8],[18,19],[31,32]], //3 98: [], //0 99: [] //0 } min_sup: 3 { 27: [[3,4],[12,13],[25,26]], //3 72: [[8,9],[13,14],[19,20],[26,27],[32,33]], //5 89: [[6,7],[17,18],[30,31]], //3 97: [[7,8],[18,19],[31,32]], //3 } You can try to combine the upper sequences based on the ending, or you can just check the positions. length: 3 { 272: [[12,13,14],[25,26,27]], //2 727: [], //0 897: [[6,7,8],[17,18,19],[30,31,32]], //3 972: [[7,8,9],[18,19,20],[31,32,33]] //3 } min_sup: 3 { 897: [[6,7,8],[17,18,19],[30,31,32]], //3 972: [[7,8,9],[18,19,20],[31,32,33]] //3 } length: 4 { 8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3 } min_sup: 3 { 8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3 } There is only one pattern and you cannot combine it with itself, so the mining is complete. { 27: [[3,4],[12,13],[25,26]], //3 72: [[8,9],[13,14],[19,20],[26,27],[32,33]], //5 89: [[6,7],[17,18],[30,31]], //3 97: [[7,8],[18,19],[31,32]], //3 897: [[6,7,8],[17,18,19],[30,31,32]], //3 972: [[7,8,9],[18,19,20],[31,32,33]] //3 8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3 } If we exclude the sub-patterns of 8972. { 27: [[3,4],[12,13],[25,26]], //3 72: [[13,14],[26,27]], //2 8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3 } min_sup: 3 { 27: [[3,4],[12,13],[25,26]], //3 8972: [[6,7,8,9],[17,18,19,20],[30,31,32,33]] //3 } I think it is the same as the patterns you have found. 361[27]3[8972]20[27]284[8972]4103[27]203[8972]0 Another option to keep the 72 too, because it occurs 3 times as a sub-sequence of 8972 and 2 other times independently from 8972. I think this should depend on whether you allow overlapping. 361[27]3[89(72)]202(72)84[89(72)]4103[2(7]2)03[89(72)]0 Note: I don't think sequential pattern mining is considered machine learning.
Sequential pattern mining on single sequence You could use something like the following. As far as I know SPADE uses something similar too for multiple sequences. 36127389722027284897241032720389720 First you need to gather the positions of eve
32,483
Sequential pattern mining on single sequence
When it comes to a single sequence, episode mining fits the need. When you want to know the probability of one element following another, sequential association analysis, such as lag-sequential analysis (Bakeman & Gottman, 1997: Observing interaction: An introduction to sequential analysis) serves the need.
Sequential pattern mining on single sequence
When it comes to a single sequence, episode mining fits the need. When you want to know the probability of one element following another, sequential association analysis, such as lag-sequential analys
Sequential pattern mining on single sequence When it comes to a single sequence, episode mining fits the need. When you want to know the probability of one element following another, sequential association analysis, such as lag-sequential analysis (Bakeman & Gottman, 1997: Observing interaction: An introduction to sequential analysis) serves the need.
Sequential pattern mining on single sequence When it comes to a single sequence, episode mining fits the need. When you want to know the probability of one element following another, sequential association analysis, such as lag-sequential analys
32,484
How to calculate the relative risk based on two independent confidence intervals
You can use the Delta method to obtain an approximate distribution of your relative risk, as shown by that link. Then you can define a pivot and use this to obtain a CI. I understand that there might be some confusion regarding the use of the Delta method, so here are a few simple steps that show how to construct an approximate CI for the relative risk. Estimate the RR from the data Find the natural log of RR: $\log(RR)$ The confidence coefficient is from the standard normal distribution: 1.96 for a 95% confidence interval Now you need the standard error. Using the Delta method for sample sizes $n$ and $m$ with probabilities $p$ and $q$ respectively, this is found to be $$SE=\sqrt{\frac{1-p}{pn}+\frac{1-q}{qm}}$$ Of course you need to replace the unknown quantities with your estimates, let's denote them by $\widehat{p}$ and $\widehat{q}$. You might notice that this is the second approximation we are using. Now that you have the formula, compute the standard error: $SE$ Calculate the lower and upper limits on the log scale: $\log(RR) scale: \log(RR) ± 1.96 \times SE \log(RR)$ Exponentiate! You can find plenty such information throughout the internet and the above steps are taken from here. We all have Fisher to thank for these approximations!
How to calculate the relative risk based on two independent confidence intervals
You can use the Delta method to obtain an approximate distribution of your relative risk, as shown by that link. Then you can define a pivot and use this to obtain a CI. I understand that there might
How to calculate the relative risk based on two independent confidence intervals You can use the Delta method to obtain an approximate distribution of your relative risk, as shown by that link. Then you can define a pivot and use this to obtain a CI. I understand that there might be some confusion regarding the use of the Delta method, so here are a few simple steps that show how to construct an approximate CI for the relative risk. Estimate the RR from the data Find the natural log of RR: $\log(RR)$ The confidence coefficient is from the standard normal distribution: 1.96 for a 95% confidence interval Now you need the standard error. Using the Delta method for sample sizes $n$ and $m$ with probabilities $p$ and $q$ respectively, this is found to be $$SE=\sqrt{\frac{1-p}{pn}+\frac{1-q}{qm}}$$ Of course you need to replace the unknown quantities with your estimates, let's denote them by $\widehat{p}$ and $\widehat{q}$. You might notice that this is the second approximation we are using. Now that you have the formula, compute the standard error: $SE$ Calculate the lower and upper limits on the log scale: $\log(RR) scale: \log(RR) ± 1.96 \times SE \log(RR)$ Exponentiate! You can find plenty such information throughout the internet and the above steps are taken from here. We all have Fisher to thank for these approximations!
How to calculate the relative risk based on two independent confidence intervals You can use the Delta method to obtain an approximate distribution of your relative risk, as shown by that link. Then you can define a pivot and use this to obtain a CI. I understand that there might
32,485
Why pglm fails for within model?
There is a good reason for that. Within model for probit regression suffers from incidental parameters problem. Within model for logit regression can be estimated, but requires quite strong assumptions. This is discussed in J. Wooldridge's "Econometric analysis of cross-section and panel data", chapter 15. If you look at the code for pglm, you can see that starting values are calculated with function starting.values. For family binomial the code calculates starting values only for model random and pooling, there is no variant for within. Hence the error. If you supply the starting values, the error is given in the function lnl.binomial. Looking at the code it is clear that model within is not supported. The author of package pglm could add explicit error message for the case of within model. I would advise you to write to him.
Why pglm fails for within model?
There is a good reason for that. Within model for probit regression suffers from incidental parameters problem. Within model for logit regression can be estimated, but requires quite strong assumption
Why pglm fails for within model? There is a good reason for that. Within model for probit regression suffers from incidental parameters problem. Within model for logit regression can be estimated, but requires quite strong assumptions. This is discussed in J. Wooldridge's "Econometric analysis of cross-section and panel data", chapter 15. If you look at the code for pglm, you can see that starting values are calculated with function starting.values. For family binomial the code calculates starting values only for model random and pooling, there is no variant for within. Hence the error. If you supply the starting values, the error is given in the function lnl.binomial. Looking at the code it is clear that model within is not supported. The author of package pglm could add explicit error message for the case of within model. I would advise you to write to him.
Why pglm fails for within model? There is a good reason for that. Within model for probit regression suffers from incidental parameters problem. Within model for logit regression can be estimated, but requires quite strong assumption
32,486
Probability of a consecutive pair of values
Run a Markov chain. Let a "flip" (at index $i$) be the event that $X_{i-1}$ and $X_{i}$ are of opposite signs and both exceed $1.5$ in size. As we scan across any realization of $(X_i)$ looking for flips, we can exploit the symmetry of the standard Normal distribution to describe the process with just four states: The Start, before $X_1$ is observed. Zero, where $-1.5 \le X_{i-1} \le 1.5$. One, where $|X_{i-1}| \gt 1.5$. Flipped, where a flip occurs at $i$. Start transitions into the (mixed) state $$\mu = (1-2p, 2p, 0)$$ (corresponding to the chances of being in states (Zero, One, Flipped)) where $$p = \Pr(X_1 \lt -1.5) = \Pr(X_1 \gt 1.5) \approx 0.0668072.$$ Because Start is never seen again, let's not bother to track it any further. Zero transitions into One with probability $2p$ (when $|X_i|\gt 1.5$) and otherwise stays at Zero. One transitions into Flipped with probability $p$: this occurs when $|X_i| \gt 1.5$ and $X_i$ has the opposite sign of $X_{i-1}$. It also transitions back to One with probability $p$ when $|X_i| \gt 1.5$ and $X_i$ has the same sign as $X_{i-1}$. Otherwise it transitions to Zero. Flipped is an absorbing state: once there, nothing changes regardless of the value of $X_i$. Thus the transition matrix (ignoring the transient Start) for (Zero, One, Flipped) is therefore $$\mathbb{P} = \left( \begin{array}{ccc} 1-2 p & 2 p & 0 \\ 1-2 p & p & p \\ 0 & 0 & 1 \\ \end{array} \right)$$ After leaving the start state (and entering the mixed state $\mu$), $20-1$ transitions will be made in the scan for a flip. The desired probability therefore is the third entry (corresponding to Flipped) in $$\mu \cdot \mathbb{P}^{20-1} \approx 0.149045.$$ Computational Details We don't need to do $18$ matrix multiplications to obtain $\mathbb{P}^{19}$. Instead, after diagonalizing $$\mathbb{P} = \mathbb{Q}^{-1} \mathbb{E} \mathbb{Q},$$ the answer for any exponent $n$ (even huge ones) can be computed via just one matrix multiplication as $$\mu\cdot\mathbb{P}^n = \left(\mu\cdot\mathbb{Q}^{-1}\right) \mathbb{E}^n \mathbb{Q}$$ with $$\mu \cdot \mathbb{Q}^{-1} = \left(1,\frac{-4 p^2+p+1-\sqrt{(2-7 p) p+1}}{2 \sqrt{(2-7 p) p+1}},-\frac{-4 p^2+p+1+\sqrt{(2-7 p) p+1}}{2 \sqrt{(2-7 p) p+1}}\right),$$ $$\mathbb{Q} = \left( \begin{array}{ccc} 0 & 0 & 1 \\ \frac{\left(1+p+\sqrt{-7 p^2+2 p+1}\right) \left(3 p-1+\sqrt{-7 p^2+2 p+1}\right)}{8 p^2} & -\frac{1+p+\sqrt{-7 p^2+2 p+1}}{2 p} & 1 \\ \frac{\left(1+p-\sqrt{-7 p^2+2 p+1}\right) \left(3 p-1-\sqrt{-7 p^2+2 p+1}\right)}{8 p^2} & -\frac{1+p-\sqrt{-7 p^2+2 p+1}}{2 p} & 1 \\ \end{array} \right) $$ and $$\mathbb{E}^n = \left( \begin{array}{ccc} 1 & 0 & 0 \\ 0 & \left(\frac{1}{2} \left(1-p-\sqrt{-7 p^2+2 p+1}\right)\right)^n & 0 \\ 0 & 0 & \left(\frac{1}{2} \left(1-p+\sqrt{-7 p^2+2 p+1}\right)\right)^n \\ \end{array} \right)$$ A million-iteration simulation (using R) supports this result. Its output, Mean LCL UCL 0.1488040 0.1477363 0.1498717 estimates the answer as $0.1488$ with a confidence interval $[0.1477, 0.1499]$ that includes $0.149045$. n <- 20 # Length of the sequence n.iter <- 1e6 # Length of the simulation set.seed(17) # Start at a reproducible point x <- rnorm(n.iter*n) # The X_i y <- matrix(sign(x) * (abs(x) > 3/2), n, n.iter) flips <- colSums(y[-1, ] * y[-n, ] == -1) # Flip indicators x.bar <- mean(flips >= 1) # Mean no. of flipped sequences s <- sqrt(x.bar * (1-x.bar) / n.iter) # Standard error of the mean (c(Mean=x.bar, x.bar + c(LCL=-3,UCL=3) * s)) # The results
Probability of a consecutive pair of values
Run a Markov chain. Let a "flip" (at index $i$) be the event that $X_{i-1}$ and $X_{i}$ are of opposite signs and both exceed $1.5$ in size. As we scan across any realization of $(X_i)$ looking for f
Probability of a consecutive pair of values Run a Markov chain. Let a "flip" (at index $i$) be the event that $X_{i-1}$ and $X_{i}$ are of opposite signs and both exceed $1.5$ in size. As we scan across any realization of $(X_i)$ looking for flips, we can exploit the symmetry of the standard Normal distribution to describe the process with just four states: The Start, before $X_1$ is observed. Zero, where $-1.5 \le X_{i-1} \le 1.5$. One, where $|X_{i-1}| \gt 1.5$. Flipped, where a flip occurs at $i$. Start transitions into the (mixed) state $$\mu = (1-2p, 2p, 0)$$ (corresponding to the chances of being in states (Zero, One, Flipped)) where $$p = \Pr(X_1 \lt -1.5) = \Pr(X_1 \gt 1.5) \approx 0.0668072.$$ Because Start is never seen again, let's not bother to track it any further. Zero transitions into One with probability $2p$ (when $|X_i|\gt 1.5$) and otherwise stays at Zero. One transitions into Flipped with probability $p$: this occurs when $|X_i| \gt 1.5$ and $X_i$ has the opposite sign of $X_{i-1}$. It also transitions back to One with probability $p$ when $|X_i| \gt 1.5$ and $X_i$ has the same sign as $X_{i-1}$. Otherwise it transitions to Zero. Flipped is an absorbing state: once there, nothing changes regardless of the value of $X_i$. Thus the transition matrix (ignoring the transient Start) for (Zero, One, Flipped) is therefore $$\mathbb{P} = \left( \begin{array}{ccc} 1-2 p & 2 p & 0 \\ 1-2 p & p & p \\ 0 & 0 & 1 \\ \end{array} \right)$$ After leaving the start state (and entering the mixed state $\mu$), $20-1$ transitions will be made in the scan for a flip. The desired probability therefore is the third entry (corresponding to Flipped) in $$\mu \cdot \mathbb{P}^{20-1} \approx 0.149045.$$ Computational Details We don't need to do $18$ matrix multiplications to obtain $\mathbb{P}^{19}$. Instead, after diagonalizing $$\mathbb{P} = \mathbb{Q}^{-1} \mathbb{E} \mathbb{Q},$$ the answer for any exponent $n$ (even huge ones) can be computed via just one matrix multiplication as $$\mu\cdot\mathbb{P}^n = \left(\mu\cdot\mathbb{Q}^{-1}\right) \mathbb{E}^n \mathbb{Q}$$ with $$\mu \cdot \mathbb{Q}^{-1} = \left(1,\frac{-4 p^2+p+1-\sqrt{(2-7 p) p+1}}{2 \sqrt{(2-7 p) p+1}},-\frac{-4 p^2+p+1+\sqrt{(2-7 p) p+1}}{2 \sqrt{(2-7 p) p+1}}\right),$$ $$\mathbb{Q} = \left( \begin{array}{ccc} 0 & 0 & 1 \\ \frac{\left(1+p+\sqrt{-7 p^2+2 p+1}\right) \left(3 p-1+\sqrt{-7 p^2+2 p+1}\right)}{8 p^2} & -\frac{1+p+\sqrt{-7 p^2+2 p+1}}{2 p} & 1 \\ \frac{\left(1+p-\sqrt{-7 p^2+2 p+1}\right) \left(3 p-1-\sqrt{-7 p^2+2 p+1}\right)}{8 p^2} & -\frac{1+p-\sqrt{-7 p^2+2 p+1}}{2 p} & 1 \\ \end{array} \right) $$ and $$\mathbb{E}^n = \left( \begin{array}{ccc} 1 & 0 & 0 \\ 0 & \left(\frac{1}{2} \left(1-p-\sqrt{-7 p^2+2 p+1}\right)\right)^n & 0 \\ 0 & 0 & \left(\frac{1}{2} \left(1-p+\sqrt{-7 p^2+2 p+1}\right)\right)^n \\ \end{array} \right)$$ A million-iteration simulation (using R) supports this result. Its output, Mean LCL UCL 0.1488040 0.1477363 0.1498717 estimates the answer as $0.1488$ with a confidence interval $[0.1477, 0.1499]$ that includes $0.149045$. n <- 20 # Length of the sequence n.iter <- 1e6 # Length of the simulation set.seed(17) # Start at a reproducible point x <- rnorm(n.iter*n) # The X_i y <- matrix(sign(x) * (abs(x) > 3/2), n, n.iter) flips <- colSums(y[-1, ] * y[-n, ] == -1) # Flip indicators x.bar <- mean(flips >= 1) # Mean no. of flipped sequences s <- sqrt(x.bar * (1-x.bar) / n.iter) # Standard error of the mean (c(Mean=x.bar, x.bar + c(LCL=-3,UCL=3) * s)) # The results
Probability of a consecutive pair of values Run a Markov chain. Let a "flip" (at index $i$) be the event that $X_{i-1}$ and $X_{i}$ are of opposite signs and both exceed $1.5$ in size. As we scan across any realization of $(X_i)$ looking for f
32,487
What's the minimum of $\mu (1-\mu)/ \sigma^2$ over all continuous unimodal distributions on a bounded interval $[0,1]$?
A minimum does not exist. However, an infimum does. It follows from the fact that The supremum of the variance of unimodal distributions defined on $[0,1]$ having mean $\mu$ is $\mu(2 - 3\mu)/3$ ($0 \le \mu \le 1/2$) or $(1-\mu)(3\mu-1)/3$ ($1/2\le \mu \le 1$). The supremum is actually attained by a distribution that--although it does not have a density function--can still (in a generalized sense) be thought of as "unimodal"; it will have an atom at $0$ (when $\mu \lt 1/2$) or an atom at $1$ (when $\mu \gt 1/2$) but otherwise be uniform. I will sketch the argument. The question asks us to optimize a linear functional $$\mathcal{L_{x^2}}: D[0,1] \to \mathbb{R}$$ subject to various equality and inequality constraints, where $D[0,1]$ is the set of (signed) measures on the interval $[0,1]$. For differentiable $F:[0,1]\to\mathbb{R}$ and $g:[0,1]\to\mathbb{R}$ any continuous function, define $$\mathcal{L}_g[F] = \int_0^1 g(x) dF(x),$$ and extend $\mathcal{L}$ to all of $D[0,1]$ by continuity. The equality constraints are $$\mathcal{L}_1[F] = 1$$ and $$\mathcal{L}_x[F] = \mu.$$ The inequality constraints are that $$f(x) \ge 0$$ and there exists $\lambda \in [0,1]$ (a "mode") such that for all $0\le x \le y \le \lambda$ and all $\lambda \le y \le x \le 1$, $$f(x) \le f(y).$$ These constraints determine a convex domain $\mathcal{X}\subset D[0,1]$ over which $\mathcal{L}_{x^2}$ is to be optimized. As with any linear program in a finite dimensional space, the extrema of $\mathcal{L}_g$ will be attained at vertices of $\mathcal{X}$. These evidently are the measures, absolutely continuous with respect to Lebesgue measure, that are piecewise constant, because the vertices are where almost all the inequalities become equalities: and most of those inequalities are associated with the unimodality of $F$ (non-increasing tail behavior). In order to satisfy the two equality constraints we need make only a single break in the graph of $f$, say at a number $0\lt \lambda \lt 1$. Letting the constant value on the interval $[0,\lambda)$ be $a$ and the constant value on $(\lambda, 1]$ be $b$, an easy calculation based on the equality constraints yields $$a = \frac{1+\lambda-2\mu}{\lambda},\ b = \frac{2\mu-\lambda}{1-\lambda}.$$ This figure says it all: it graphs the locally constant distribution function of mean $\mu$ with at most a single break at $\lambda$. (The plot of $f_{(\lambda,\mu)}$ for $\mu \gt 1/2$ looks like the reversal of this one.) The value of $\mathcal{L}_{x^2}$ at such measures (which I will denote $f_{(\lambda, \mu)}$, the density of a distribution $F_{(\lambda, \mu)}$) is just as readily computed to be $$\mathcal{L}_{x^2}[f_{(\lambda, \mu)}] = \frac{1}{3}\left(2\mu + (2\mu - 1)\lambda\right).$$ This expression is linear in $\lambda$, implying it is maximized at $0$ (when $\mu \lt 1/2$), $1$ (when $\mu \gt 1/2$), or at any value (when $\mu = 1/2$). However, except when $\mu=1/2$, the limiting values of the measures $f_{(\lambda, \mu)}$ are no longer continuous: the corresponding distribution $F = \lim_{\lambda\to 0} F_{(\lambda, \mu)}$ or $F = \lim_{\lambda\to 1} F_{(\lambda, \mu)}$ has a jump discontinuity at $0$ or $1$ (but not both). This figure graphs the optimal $F$ for a mean of $\mu \approx 2/5$. Regardless, the optimum value is $$\sigma^2_\mu = \sup_\lambda \mathcal{L}_{x^2}[f_{(\lambda, \mu)}] = \frac{1}{3}\mu(2 - 3\mu).$$ Consequently, the infimum of $\mu(1-\mu)/\sigma^2$ for $0\le \mu \lt 1/2$ is $$\mu(1-\mu)/\sigma^2_\mu = \frac{3-3\mu}{2-3\mu},$$ with a comparable expression when $1/2\lt \mu \le 1$ (obtained by replacing $\mu$ by $1-\mu$). This figure plots the supremum $\mu(1-\mu)/\sigma^2_\mu$ versus $\mu$.
What's the minimum of $\mu (1-\mu)/ \sigma^2$ over all continuous unimodal distributions on a bounde
A minimum does not exist. However, an infimum does. It follows from the fact that The supremum of the variance of unimodal distributions defined on $[0,1]$ having mean $\mu$ is $\mu(2 - 3\mu)/3$ ($0
What's the minimum of $\mu (1-\mu)/ \sigma^2$ over all continuous unimodal distributions on a bounded interval $[0,1]$? A minimum does not exist. However, an infimum does. It follows from the fact that The supremum of the variance of unimodal distributions defined on $[0,1]$ having mean $\mu$ is $\mu(2 - 3\mu)/3$ ($0 \le \mu \le 1/2$) or $(1-\mu)(3\mu-1)/3$ ($1/2\le \mu \le 1$). The supremum is actually attained by a distribution that--although it does not have a density function--can still (in a generalized sense) be thought of as "unimodal"; it will have an atom at $0$ (when $\mu \lt 1/2$) or an atom at $1$ (when $\mu \gt 1/2$) but otherwise be uniform. I will sketch the argument. The question asks us to optimize a linear functional $$\mathcal{L_{x^2}}: D[0,1] \to \mathbb{R}$$ subject to various equality and inequality constraints, where $D[0,1]$ is the set of (signed) measures on the interval $[0,1]$. For differentiable $F:[0,1]\to\mathbb{R}$ and $g:[0,1]\to\mathbb{R}$ any continuous function, define $$\mathcal{L}_g[F] = \int_0^1 g(x) dF(x),$$ and extend $\mathcal{L}$ to all of $D[0,1]$ by continuity. The equality constraints are $$\mathcal{L}_1[F] = 1$$ and $$\mathcal{L}_x[F] = \mu.$$ The inequality constraints are that $$f(x) \ge 0$$ and there exists $\lambda \in [0,1]$ (a "mode") such that for all $0\le x \le y \le \lambda$ and all $\lambda \le y \le x \le 1$, $$f(x) \le f(y).$$ These constraints determine a convex domain $\mathcal{X}\subset D[0,1]$ over which $\mathcal{L}_{x^2}$ is to be optimized. As with any linear program in a finite dimensional space, the extrema of $\mathcal{L}_g$ will be attained at vertices of $\mathcal{X}$. These evidently are the measures, absolutely continuous with respect to Lebesgue measure, that are piecewise constant, because the vertices are where almost all the inequalities become equalities: and most of those inequalities are associated with the unimodality of $F$ (non-increasing tail behavior). In order to satisfy the two equality constraints we need make only a single break in the graph of $f$, say at a number $0\lt \lambda \lt 1$. Letting the constant value on the interval $[0,\lambda)$ be $a$ and the constant value on $(\lambda, 1]$ be $b$, an easy calculation based on the equality constraints yields $$a = \frac{1+\lambda-2\mu}{\lambda},\ b = \frac{2\mu-\lambda}{1-\lambda}.$$ This figure says it all: it graphs the locally constant distribution function of mean $\mu$ with at most a single break at $\lambda$. (The plot of $f_{(\lambda,\mu)}$ for $\mu \gt 1/2$ looks like the reversal of this one.) The value of $\mathcal{L}_{x^2}$ at such measures (which I will denote $f_{(\lambda, \mu)}$, the density of a distribution $F_{(\lambda, \mu)}$) is just as readily computed to be $$\mathcal{L}_{x^2}[f_{(\lambda, \mu)}] = \frac{1}{3}\left(2\mu + (2\mu - 1)\lambda\right).$$ This expression is linear in $\lambda$, implying it is maximized at $0$ (when $\mu \lt 1/2$), $1$ (when $\mu \gt 1/2$), or at any value (when $\mu = 1/2$). However, except when $\mu=1/2$, the limiting values of the measures $f_{(\lambda, \mu)}$ are no longer continuous: the corresponding distribution $F = \lim_{\lambda\to 0} F_{(\lambda, \mu)}$ or $F = \lim_{\lambda\to 1} F_{(\lambda, \mu)}$ has a jump discontinuity at $0$ or $1$ (but not both). This figure graphs the optimal $F$ for a mean of $\mu \approx 2/5$. Regardless, the optimum value is $$\sigma^2_\mu = \sup_\lambda \mathcal{L}_{x^2}[f_{(\lambda, \mu)}] = \frac{1}{3}\mu(2 - 3\mu).$$ Consequently, the infimum of $\mu(1-\mu)/\sigma^2$ for $0\le \mu \lt 1/2$ is $$\mu(1-\mu)/\sigma^2_\mu = \frac{3-3\mu}{2-3\mu},$$ with a comparable expression when $1/2\lt \mu \le 1$ (obtained by replacing $\mu$ by $1-\mu$). This figure plots the supremum $\mu(1-\mu)/\sigma^2_\mu$ versus $\mu$.
What's the minimum of $\mu (1-\mu)/ \sigma^2$ over all continuous unimodal distributions on a bounde A minimum does not exist. However, an infimum does. It follows from the fact that The supremum of the variance of unimodal distributions defined on $[0,1]$ having mean $\mu$ is $\mu(2 - 3\mu)/3$ ($0
32,488
Gibbs Sampler transition kernel
If you write down the transition of the systematic Gibbs sampler kernel, you get $$\mathbb{P}(X'\in A_1\times\cdots\times A_d|X=x)=\int_{A_1} \pi_1(x'_1|x_{-1})\Big\{\int_{A_2} \pi_2(x'_2|x'_1,x_{-1:2})\cdots \left\{\int_{A_d} \pi_d(x'_1|x_{-d}')\lambda(\text{d}x_d')\right\} \cdots\lambda(\text{d}x_2')\Big\}\lambda(\text{d}x_1')$$ for any product set $A_1\times\cdots\times A_d\in\mathcal{B}(\mathbb{R^d})$ and therefore $$K(x,x')=\pi_1(x'_1|x_{-1})\times\pi_2(x'_2|x'_1,x_{-1:2})\times\cdots\times\pi_d(x'_d|x_{-d}')$$ is the density of a probability measure that is absolutely continuous against the Lebesgue measure on $(\mathbb{R}^d,\mathcal{B}(\mathbb{R^d}))$.
Gibbs Sampler transition kernel
If you write down the transition of the systematic Gibbs sampler kernel, you get $$\mathbb{P}(X'\in A_1\times\cdots\times A_d|X=x)=\int_{A_1} \pi_1(x'_1|x_{-1})\Big\{\int_{A_2} \pi_2(x'_2|x'_1,x_{-1:2
Gibbs Sampler transition kernel If you write down the transition of the systematic Gibbs sampler kernel, you get $$\mathbb{P}(X'\in A_1\times\cdots\times A_d|X=x)=\int_{A_1} \pi_1(x'_1|x_{-1})\Big\{\int_{A_2} \pi_2(x'_2|x'_1,x_{-1:2})\cdots \left\{\int_{A_d} \pi_d(x'_1|x_{-d}')\lambda(\text{d}x_d')\right\} \cdots\lambda(\text{d}x_2')\Big\}\lambda(\text{d}x_1')$$ for any product set $A_1\times\cdots\times A_d\in\mathcal{B}(\mathbb{R^d})$ and therefore $$K(x,x')=\pi_1(x'_1|x_{-1})\times\pi_2(x'_2|x'_1,x_{-1:2})\times\cdots\times\pi_d(x'_d|x_{-d}')$$ is the density of a probability measure that is absolutely continuous against the Lebesgue measure on $(\mathbb{R}^d,\mathcal{B}(\mathbb{R^d}))$.
Gibbs Sampler transition kernel If you write down the transition of the systematic Gibbs sampler kernel, you get $$\mathbb{P}(X'\in A_1\times\cdots\times A_d|X=x)=\int_{A_1} \pi_1(x'_1|x_{-1})\Big\{\int_{A_2} \pi_2(x'_2|x'_1,x_{-1:2
32,489
Prior for the coefficients of a linear regression model
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. A nice document with general advice on choosing priors (with links to papers with more detail) is here: https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations.
Prior for the coefficients of a linear regression model
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Prior for the coefficients of a linear regression model Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. A nice document with general advice on choosing priors (with links to papers with more detail) is here: https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations.
Prior for the coefficients of a linear regression model Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
32,490
Prior for the coefficients of a linear regression model
In practice, the prior that you select should come from domain expertise. Furthermore, a common practice is to select the prior based on your knowledge of the mean and then determining the variance based on your certainty. For example, if your variables are economic variables for individuals (e.g. unemployed, level of education, GDP of country of residence, age) you might take hints from economic theory for predicting, for example, annual income; at the very least, you would at least have guidance for the signs of the means of the components of the $ \beta $ vector. As for the variance, you would choose a higher variance for your prior if you're less sure about the effect of each component. You may also want to think about possible interaction effects between your variables (which would manifest in covariance between different $ \beta_i $ coefficients). Here it could be beneficial to impose additional assumptions, such as constant variance or a diagonal covariance matrix for your $ \beta $ prior, for computational simplicity. At the end of the day it's kind of an art, but there are some cases for which you can obtain reasonable conjugate priors on $ \beta $ if you assume, for example that $ \beta $ has a multivariate Normal prior, and $ \epsilon $ is also some flavour of multivariate normal. I would recommend Bayesian Data Analysis for more details on Bayesian Linear Regression.
Prior for the coefficients of a linear regression model
In practice, the prior that you select should come from domain expertise. Furthermore, a common practice is to select the prior based on your knowledge of the mean and then determining the variance ba
Prior for the coefficients of a linear regression model In practice, the prior that you select should come from domain expertise. Furthermore, a common practice is to select the prior based on your knowledge of the mean and then determining the variance based on your certainty. For example, if your variables are economic variables for individuals (e.g. unemployed, level of education, GDP of country of residence, age) you might take hints from economic theory for predicting, for example, annual income; at the very least, you would at least have guidance for the signs of the means of the components of the $ \beta $ vector. As for the variance, you would choose a higher variance for your prior if you're less sure about the effect of each component. You may also want to think about possible interaction effects between your variables (which would manifest in covariance between different $ \beta_i $ coefficients). Here it could be beneficial to impose additional assumptions, such as constant variance or a diagonal covariance matrix for your $ \beta $ prior, for computational simplicity. At the end of the day it's kind of an art, but there are some cases for which you can obtain reasonable conjugate priors on $ \beta $ if you assume, for example that $ \beta $ has a multivariate Normal prior, and $ \epsilon $ is also some flavour of multivariate normal. I would recommend Bayesian Data Analysis for more details on Bayesian Linear Regression.
Prior for the coefficients of a linear regression model In practice, the prior that you select should come from domain expertise. Furthermore, a common practice is to select the prior based on your knowledge of the mean and then determining the variance ba
32,491
How can I generate random numbers from any given copula?
For a copula that corresponds to a known multivariate distribution, you can simulate from that distribution and then make the margins uniform (e.g. Gaussian copula, t-copula). More generally if you can work out the conditional (either $C(u|v)$ or $c(u|v)$), you can simulate from a uniform for $V$ and then from the conditional, perhaps via inverse-cdf (if you know $C(u|v)$) or perhaps via say accept-reject (maybe an adaptive accept-reject, some version of ziggurat, etc, if you know $c(u|v)$). In the case of bivariate Archimedean copulas, following Nelsen (1999) or Embrechts et al., (2001), we have a mechanism for then generating from them as follows. Suppose $(U_1,U_2)$ has a two-dimensional Archimedean copula with generator $\phi$. Then: Simulate two independent $U(0,1)$ random variables, $v_1$ and $v_2$ Set $t=K_C^{-1}(v_2)\,$, where $K_C(t)=t-\phi(t)/\phi'(t)$ The desired simulated values are $u_1=\phi^{-1}(v_1\,\phi(t))$ and $u_2=\phi^{-1}((1-v_1)\phi(t))$. There are other methods; for example in some cases it might sometimes be practical to do some version of bivariate accept-reject, say, or via transformation to some convenient bivariate distribution on which accept-reject might be applied.
How can I generate random numbers from any given copula?
For a copula that corresponds to a known multivariate distribution, you can simulate from that distribution and then make the margins uniform (e.g. Gaussian copula, t-copula). More generally if you ca
How can I generate random numbers from any given copula? For a copula that corresponds to a known multivariate distribution, you can simulate from that distribution and then make the margins uniform (e.g. Gaussian copula, t-copula). More generally if you can work out the conditional (either $C(u|v)$ or $c(u|v)$), you can simulate from a uniform for $V$ and then from the conditional, perhaps via inverse-cdf (if you know $C(u|v)$) or perhaps via say accept-reject (maybe an adaptive accept-reject, some version of ziggurat, etc, if you know $c(u|v)$). In the case of bivariate Archimedean copulas, following Nelsen (1999) or Embrechts et al., (2001), we have a mechanism for then generating from them as follows. Suppose $(U_1,U_2)$ has a two-dimensional Archimedean copula with generator $\phi$. Then: Simulate two independent $U(0,1)$ random variables, $v_1$ and $v_2$ Set $t=K_C^{-1}(v_2)\,$, where $K_C(t)=t-\phi(t)/\phi'(t)$ The desired simulated values are $u_1=\phi^{-1}(v_1\,\phi(t))$ and $u_2=\phi^{-1}((1-v_1)\phi(t))$. There are other methods; for example in some cases it might sometimes be practical to do some version of bivariate accept-reject, say, or via transformation to some convenient bivariate distribution on which accept-reject might be applied.
How can I generate random numbers from any given copula? For a copula that corresponds to a known multivariate distribution, you can simulate from that distribution and then make the margins uniform (e.g. Gaussian copula, t-copula). More generally if you ca
32,492
How can I generate random numbers from any given copula?
" require(mvtnorm) S <- matrix(c(1,.8,.8,1),2,2) #Correlation matrix AB <- rmvnorm(mean=c(0,0),sig=S,n=1000) #Our gaussian variables U <- pnorm(AB) #Now U is uniform - check using hist(U[,1]) or hist(U[,2]) x <- qgamma(U[,1],2) #x is gamma distributed y <- qbeta(U[,2],1,2) #y is beta distributed plot(x,y) #They correlate! " Source: Copulas made easy
How can I generate random numbers from any given copula?
" require(mvtnorm) S <- matrix(c(1,.8,.8,1),2,2) #Correlation matrix AB <- rmvnorm(mean=c(0,0),sig=S,n=1000) #Our gaussian variables U <- pnorm(AB) #Now U is uniform - check using hist(U[,1]) or hist(
How can I generate random numbers from any given copula? " require(mvtnorm) S <- matrix(c(1,.8,.8,1),2,2) #Correlation matrix AB <- rmvnorm(mean=c(0,0),sig=S,n=1000) #Our gaussian variables U <- pnorm(AB) #Now U is uniform - check using hist(U[,1]) or hist(U[,2]) x <- qgamma(U[,1],2) #x is gamma distributed y <- qbeta(U[,2],1,2) #y is beta distributed plot(x,y) #They correlate! " Source: Copulas made easy
How can I generate random numbers from any given copula? " require(mvtnorm) S <- matrix(c(1,.8,.8,1),2,2) #Correlation matrix AB <- rmvnorm(mean=c(0,0),sig=S,n=1000) #Our gaussian variables U <- pnorm(AB) #Now U is uniform - check using hist(U[,1]) or hist(
32,493
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution?
Intuitively, it's because the variance is defined in terms of the mean. So if the experimental mean $\bar x$ is found to be a long way from $\mu_0$, then that increases the posterior estimate of $\sigma^2$. A bit more rigorously - and I'm taking this from MLAPP 4.6.3.7 - suppose you have a $\text{NI}\chi^2(\mu_0, \kappa_0, \sigma_0, \nu_0)$ prior (which is just a reparameterization of a NIG prior), where $\kappa_0, \nu_0$ encode the strengths of the prior mean and variance, respectively. Then the posterior hyperparameter for $\sigma^2$ is $$ \sigma^2_N = \frac{1}{\nu_0 + N} \left(\nu_0\sigma^2_0 + Ns^2 + \frac{N\kappa_0}{\kappa_0 + N}(\mu_0 - \bar x)^2\right)$$ where $s^2$ is the experimental variance. We can loosely rewrite this as $$ \begin{align} \sigma^2_N = \frac{1}{\nu_0 + N} \left(\nu_0 \times \text{contribution from the prior} \\ + N\times \text{contribution from the experiment} \\ + \frac{N\kappa_0}{\kappa_0 + N}\times \text{uncertainty in $\mu$}\right) \end{align}$$
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution
Intuitively, it's because the variance is defined in terms of the mean. So if the experimental mean $\bar x$ is found to be a long way from $\mu_0$, then that increases the posterior estimate of $\sig
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution? Intuitively, it's because the variance is defined in terms of the mean. So if the experimental mean $\bar x$ is found to be a long way from $\mu_0$, then that increases the posterior estimate of $\sigma^2$. A bit more rigorously - and I'm taking this from MLAPP 4.6.3.7 - suppose you have a $\text{NI}\chi^2(\mu_0, \kappa_0, \sigma_0, \nu_0)$ prior (which is just a reparameterization of a NIG prior), where $\kappa_0, \nu_0$ encode the strengths of the prior mean and variance, respectively. Then the posterior hyperparameter for $\sigma^2$ is $$ \sigma^2_N = \frac{1}{\nu_0 + N} \left(\nu_0\sigma^2_0 + Ns^2 + \frac{N\kappa_0}{\kappa_0 + N}(\mu_0 - \bar x)^2\right)$$ where $s^2$ is the experimental variance. We can loosely rewrite this as $$ \begin{align} \sigma^2_N = \frac{1}{\nu_0 + N} \left(\nu_0 \times \text{contribution from the prior} \\ + N\times \text{contribution from the experiment} \\ + \frac{N\kappa_0}{\kappa_0 + N}\times \text{uncertainty in $\mu$}\right) \end{align}$$
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution Intuitively, it's because the variance is defined in terms of the mean. So if the experimental mean $\bar x$ is found to be a long way from $\mu_0$, then that increases the posterior estimate of $\sig
32,494
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution?
I do not understand the issue: for the model as described, there is a joint posterior distribution \begin{align} p(\mu, \sigma^2 | x,\mu_0, \sigma_0,\alpha, \beta) \propto \overbrace{p(\mu | \mu_0, \sigma_0)}^\text{Normal} \underbrace{p(\sigma^2 | \alpha, \beta)}_\text{inverse Gamma} \overbrace{p (x | \mu, \sigma^2)}^\text{Normal} \end{align} that is non-standard in the sense that the marginal posterior distributions of both $\mu$ and $\sigma^2$ are not traditional distributions and are not from exponential families. But this distribution on $(\mu, \sigma^2)$ can be computed at any value of $(\mu, \sigma^2,x,\mu_0, \sigma_0,\alpha, \beta)$ and hence can be simulated by all sorts of Monte Carlo approaches, including the or rather a Gibbs sampler. Therefore, the lack of conjugacy does not prevent one from using a Gibbs sampler or another Markov Chain Monte Carlo method. They both produce simulations from the joint posterior $$p(\mu, \sigma^2 | x,\mu_0, \sigma_0,\alpha, \beta)$$ and not solely from the two marginal posteriors $$p(\mu | x,\mu_0, \sigma_0,\alpha, \beta)\quad\text{and}\quad p(\sigma^2 | x,\mu_0, \sigma_0,\alpha, \beta)$$
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution
I do not understand the issue: for the model as described, there is a joint posterior distribution \begin{align} p(\mu, \sigma^2 | x,\mu_0, \sigma_0,\alpha, \beta) \propto \overbrace{p(\mu | \mu_0, \
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution? I do not understand the issue: for the model as described, there is a joint posterior distribution \begin{align} p(\mu, \sigma^2 | x,\mu_0, \sigma_0,\alpha, \beta) \propto \overbrace{p(\mu | \mu_0, \sigma_0)}^\text{Normal} \underbrace{p(\sigma^2 | \alpha, \beta)}_\text{inverse Gamma} \overbrace{p (x | \mu, \sigma^2)}^\text{Normal} \end{align} that is non-standard in the sense that the marginal posterior distributions of both $\mu$ and $\sigma^2$ are not traditional distributions and are not from exponential families. But this distribution on $(\mu, \sigma^2)$ can be computed at any value of $(\mu, \sigma^2,x,\mu_0, \sigma_0,\alpha, \beta)$ and hence can be simulated by all sorts of Monte Carlo approaches, including the or rather a Gibbs sampler. Therefore, the lack of conjugacy does not prevent one from using a Gibbs sampler or another Markov Chain Monte Carlo method. They both produce simulations from the joint posterior $$p(\mu, \sigma^2 | x,\mu_0, \sigma_0,\alpha, \beta)$$ and not solely from the two marginal posteriors $$p(\mu | x,\mu_0, \sigma_0,\alpha, \beta)\quad\text{and}\quad p(\sigma^2 | x,\mu_0, \sigma_0,\alpha, \beta)$$
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution I do not understand the issue: for the model as described, there is a joint posterior distribution \begin{align} p(\mu, \sigma^2 | x,\mu_0, \sigma_0,\alpha, \beta) \propto \overbrace{p(\mu | \mu_0, \
32,495
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution?
Stéphane is right that there's a semi-conjugacy, but you wouldn't lose conjugacy at all if you just expressed the prior and likelihood as distribution having three parameters that work out to be the mean, variance, and number of samples.
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution
Stéphane is right that there's a semi-conjugacy, but you wouldn't lose conjugacy at all if you just expressed the prior and likelihood as distribution having three parameters that work out to be the m
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution? Stéphane is right that there's a semi-conjugacy, but you wouldn't lose conjugacy at all if you just expressed the prior and likelihood as distribution having three parameters that work out to be the mean, variance, and number of samples.
Why do we lose conjugacy when assuming unknown $\mu$ and unknown $\sigma^2$ in a normal distribution Stéphane is right that there's a semi-conjugacy, but you wouldn't lose conjugacy at all if you just expressed the prior and likelihood as distribution having three parameters that work out to be the m
32,496
Can a CDF from data cross with another CDF
The empirical cdf, $\hat{F}(t)$ is the proportion of the sample at or below $t$. Consider ordering your rows by increasing $y$ (and at a fixed value of $y$, ordering by increasing $x$). Then for each such row (row $i$, say), the height of each cdf is $i/n$*, and the corresponding abscissa for the x-sample is always to the right of the abscissa for the y-sample. The step-functions can coincide, but the x-sample ecdf will never be above/left of the y-sample ecdf. Indeed, imagine we "draw on the plot" all the vertical jumps in the ecdf. Then a horizontal line drawn across the plot at some value of $F$ will strike the ecdf steps at a particular value of $y$ and $x$ that appears in our table listing the sample values in order (indeed, for a given value of $F$, it's easy to work out which row it will be$^\dagger$), which always has $y_i\leq x_i$. *(it's slightly more complicated when there are duplicate values, but not in a way that changes the argument substantively) $\dagger$ For the grey horizontal line in the plot ($F\approx 0.481$), it strikes the vertical jumps of the ecdf at $t_y=194.4503$ and $t_x=200.0431$ which occur in the 73rd row of the data table when sorted as indicated earlier.
Can a CDF from data cross with another CDF
The empirical cdf, $\hat{F}(t)$ is the proportion of the sample at or below $t$. Consider ordering your rows by increasing $y$ (and at a fixed value of $y$, ordering by increasing $x$). Then for each
Can a CDF from data cross with another CDF The empirical cdf, $\hat{F}(t)$ is the proportion of the sample at or below $t$. Consider ordering your rows by increasing $y$ (and at a fixed value of $y$, ordering by increasing $x$). Then for each such row (row $i$, say), the height of each cdf is $i/n$*, and the corresponding abscissa for the x-sample is always to the right of the abscissa for the y-sample. The step-functions can coincide, but the x-sample ecdf will never be above/left of the y-sample ecdf. Indeed, imagine we "draw on the plot" all the vertical jumps in the ecdf. Then a horizontal line drawn across the plot at some value of $F$ will strike the ecdf steps at a particular value of $y$ and $x$ that appears in our table listing the sample values in order (indeed, for a given value of $F$, it's easy to work out which row it will be$^\dagger$), which always has $y_i\leq x_i$. *(it's slightly more complicated when there are duplicate values, but not in a way that changes the argument substantively) $\dagger$ For the grey horizontal line in the plot ($F\approx 0.481$), it strikes the vertical jumps of the ecdf at $t_y=194.4503$ and $t_x=200.0431$ which occur in the 73rd row of the data table when sorted as indicated earlier.
Can a CDF from data cross with another CDF The empirical cdf, $\hat{F}(t)$ is the proportion of the sample at or below $t$. Consider ordering your rows by increasing $y$ (and at a fixed value of $y$, ordering by increasing $x$). Then for each
32,497
Can a CDF from data cross with another CDF
Glen_b's answer is correct, but I think there's an even simpler way to demonstrate this. The eCDF is a plot of ($x$, proportion of values at or below $x$). We start by sorting the values in ascending order: call them $x_1, x_2, \ldots, x_n$ and $y_1, y_2, \ldots, y_n$. Furthermore, from your question, we know that the two vectors are the same length and $y_i \ge x_i$ for every index $i$. Since $y_1$ is greater than or equal to $x_1$, $y_1$ must be located at or to the right of $x_1$ and, since they're the smallest points in the list, they both have a height/y-coordinate of $\frac{1}{n}$. Both curves move upwards at the same rate ($\frac{1}{n}$ per step) and to the right. However, since $y_i > x_i$, the $Y$ curve moves at least as far to the right as the $X$ curve on each step. Since the $Y$ curve started at or out to the right of the $X$ curve and each subsquent update pushes $Y$ at least as far rightwards as $X$, the curves never cross.
Can a CDF from data cross with another CDF
Glen_b's answer is correct, but I think there's an even simpler way to demonstrate this. The eCDF is a plot of ($x$, proportion of values at or below $x$). We start by sorting the values in ascending
Can a CDF from data cross with another CDF Glen_b's answer is correct, but I think there's an even simpler way to demonstrate this. The eCDF is a plot of ($x$, proportion of values at or below $x$). We start by sorting the values in ascending order: call them $x_1, x_2, \ldots, x_n$ and $y_1, y_2, \ldots, y_n$. Furthermore, from your question, we know that the two vectors are the same length and $y_i \ge x_i$ for every index $i$. Since $y_1$ is greater than or equal to $x_1$, $y_1$ must be located at or to the right of $x_1$ and, since they're the smallest points in the list, they both have a height/y-coordinate of $\frac{1}{n}$. Both curves move upwards at the same rate ($\frac{1}{n}$ per step) and to the right. However, since $y_i > x_i$, the $Y$ curve moves at least as far to the right as the $X$ curve on each step. Since the $Y$ curve started at or out to the right of the $X$ curve and each subsquent update pushes $Y$ at least as far rightwards as $X$, the curves never cross.
Can a CDF from data cross with another CDF Glen_b's answer is correct, but I think there's an even simpler way to demonstrate this. The eCDF is a plot of ($x$, proportion of values at or below $x$). We start by sorting the values in ascending
32,498
Can a CDF from data cross with another CDF
Just formalise what was written above: If the emperical CDFs are written as $F_X$ and $F_Y$ respectively, then $F_X(x) = \frac{1}{n} \sum_{x_i} I(x_i \leq x)$ and likewise $F_Y(x) = \frac{1}{n} \sum_{y_i} I(y_i \leq x)$. Now, for any $x$, we can show that $I(x_i \leq x) \leq I(y_i \leq x)$. Prove this by contradiction - Suppose there was an $x$ where this didn't hold and show that there must be a pair $(x_i, y_i)$ for which $y_i > x_i$. Thus, $F_X(x) \leq F_Y(x)$ for all $x$. Note: There are some implicit assumptions in this demonstration that the number of data points are finite. I guess it is possible to have infinite data sets of the same size (ie cardinality). I'm fairly certain the result holds, but far less certain about the proof of such a result.
Can a CDF from data cross with another CDF
Just formalise what was written above: If the emperical CDFs are written as $F_X$ and $F_Y$ respectively, then $F_X(x) = \frac{1}{n} \sum_{x_i} I(x_i \leq x)$ and likewise $F_Y(x) = \frac{1}{n} \sum_{
Can a CDF from data cross with another CDF Just formalise what was written above: If the emperical CDFs are written as $F_X$ and $F_Y$ respectively, then $F_X(x) = \frac{1}{n} \sum_{x_i} I(x_i \leq x)$ and likewise $F_Y(x) = \frac{1}{n} \sum_{y_i} I(y_i \leq x)$. Now, for any $x$, we can show that $I(x_i \leq x) \leq I(y_i \leq x)$. Prove this by contradiction - Suppose there was an $x$ where this didn't hold and show that there must be a pair $(x_i, y_i)$ for which $y_i > x_i$. Thus, $F_X(x) \leq F_Y(x)$ for all $x$. Note: There are some implicit assumptions in this demonstration that the number of data points are finite. I guess it is possible to have infinite data sets of the same size (ie cardinality). I'm fairly certain the result holds, but far less certain about the proof of such a result.
Can a CDF from data cross with another CDF Just formalise what was written above: If the emperical CDFs are written as $F_X$ and $F_Y$ respectively, then $F_X(x) = \frac{1}{n} \sum_{x_i} I(x_i \leq x)$ and likewise $F_Y(x) = \frac{1}{n} \sum_{
32,499
Interpretation of interaction term
$b_3$ is the difference between white females and the sum of $a+b_1+b_2$. That is, the difference between white females and the sum of non-white males plus the difference between non-white females and non-white males plus the difference between white males and non-white males. \begin{align} b_3 = \bar x_\text{white female} - \big[&\ \ \bar x_\text{non-white male}\quad\quad\quad\quad\quad\quad\quad\ \ + \\ &(\bar x_\text{non-white female} - \bar x_\text{non-white male}) + \\ &(\bar x_\text{white male}\quad\quad\! - \bar x_\text{non-white male})\quad\ \big] \end{align} Honestly, it's a bit of a mess to interpret in this way. More typically, we interpret the test of $b_3$ as a test of the additivity of the effects of ${\rm white}$ and ${\rm female}$. (The expression within the square brackets $[]$ is the additive effect of ${\rm white}$ and ${\rm female}$.) Then we make more substantive interpretations only of simple effects (i.e., the effect of one factor within a pre-specified level of the other factor). People rarely try to interpret the interaction effect / coefficient in isolation. It may also help you to read my answer here: Interpretation of betas when there are multiple categorical variables, which covers an analogous, but simpler, situation without the interaction.
Interpretation of interaction term
$b_3$ is the difference between white females and the sum of $a+b_1+b_2$. That is, the difference between white females and the sum of non-white males plus the difference between non-white females an
Interpretation of interaction term $b_3$ is the difference between white females and the sum of $a+b_1+b_2$. That is, the difference between white females and the sum of non-white males plus the difference between non-white females and non-white males plus the difference between white males and non-white males. \begin{align} b_3 = \bar x_\text{white female} - \big[&\ \ \bar x_\text{non-white male}\quad\quad\quad\quad\quad\quad\quad\ \ + \\ &(\bar x_\text{non-white female} - \bar x_\text{non-white male}) + \\ &(\bar x_\text{white male}\quad\quad\! - \bar x_\text{non-white male})\quad\ \big] \end{align} Honestly, it's a bit of a mess to interpret in this way. More typically, we interpret the test of $b_3$ as a test of the additivity of the effects of ${\rm white}$ and ${\rm female}$. (The expression within the square brackets $[]$ is the additive effect of ${\rm white}$ and ${\rm female}$.) Then we make more substantive interpretations only of simple effects (i.e., the effect of one factor within a pre-specified level of the other factor). People rarely try to interpret the interaction effect / coefficient in isolation. It may also help you to read my answer here: Interpretation of betas when there are multiple categorical variables, which covers an analogous, but simpler, situation without the interaction.
Interpretation of interaction term $b_3$ is the difference between white females and the sum of $a+b_1+b_2$. That is, the difference between white females and the sum of non-white males plus the difference between non-white females an
32,500
Kernel density estimation on bounded support?
Several methods to deal with density estimation on bounded support (including the estimation method proposed by Chen) are implemented in the bde package available from the CRAN repository. You may be interested in using it.
Kernel density estimation on bounded support?
Several methods to deal with density estimation on bounded support (including the estimation method proposed by Chen) are implemented in the bde package available from the CRAN repository. You may be
Kernel density estimation on bounded support? Several methods to deal with density estimation on bounded support (including the estimation method proposed by Chen) are implemented in the bde package available from the CRAN repository. You may be interested in using it.
Kernel density estimation on bounded support? Several methods to deal with density estimation on bounded support (including the estimation method proposed by Chen) are implemented in the bde package available from the CRAN repository. You may be