idx
int64
1
56k
question
stringlengths
15
155
answer
stringlengths
2
29.2k
question_cut
stringlengths
15
100
answer_cut
stringlengths
2
200
conversation
stringlengths
47
29.3k
conversation_cut
stringlengths
47
301
36,901
Are there two definitions of the word bias?
I agree that this terminology is confusing. Bias has one meaning in both of these contexts: distance from ideal or target values, but the interpretation depends on which space we are talking about. I'll explain what I mean with regard to the two quotes in your question. By using mean-wise imputation, we are adding bias to our estimate. This refers to bias in the data space. Mean-wise imputation influences the position of your estimates relative to the target values. The bias-variance trade-off is an important subject when picking models. This refers to bias and variance in the parameter space of models. That is, if you trained a stochastic model 1000 times, you could observe bias or variance of the parameter values. A high bias model has consistent parameters, but they differ from an 'optimal' solution. A high variance model will get different values for the parameters each time it's trained.
Are there two definitions of the word bias?
I agree that this terminology is confusing. Bias has one meaning in both of these contexts: distance from ideal or target values, but the interpretation depends on which space we are talking about.
Are there two definitions of the word bias? I agree that this terminology is confusing. Bias has one meaning in both of these contexts: distance from ideal or target values, but the interpretation depends on which space we are talking about. I'll explain what I mean with regard to the two quotes in your question. By using mean-wise imputation, we are adding bias to our estimate. This refers to bias in the data space. Mean-wise imputation influences the position of your estimates relative to the target values. The bias-variance trade-off is an important subject when picking models. This refers to bias and variance in the parameter space of models. That is, if you trained a stochastic model 1000 times, you could observe bias or variance of the parameter values. A high bias model has consistent parameters, but they differ from an 'optimal' solution. A high variance model will get different values for the parameters each time it's trained.
Are there two definitions of the word bias? I agree that this terminology is confusing. Bias has one meaning in both of these contexts: distance from ideal or target values, but the interpretation depends on which space we are talking about.
36,902
Gradients of cross-entropy error in neural network
Use the chain rule, $$ \frac{\partial C}{\partial W_1} = \frac{\partial C}{\partial z} \frac{\partial z}{\partial h} \frac{\partial h}{\partial a} \frac{\partial a}{\partial W_1} , $$ where $$ a = W_1x+b_1 . $$ $$ \frac{\partial C}{\partial z} = y-\hat{y}, $$ $$ \frac{\partial z}{\partial h} = W_2, $$ $$ \frac{\partial h}{\partial a} = \sigma(a)(1 - \sigma(a)), $$ $$ \frac{\partial a}{\partial W_1} = x, $$ so $$ \frac{\partial C}{\partial W_1} = (y-\hat{y})W_2\sigma(a)(1 - \sigma(a))x = (y-\hat{y})W_2h(1 - h)x. $$ You could take a look at Pattern Recognition and Machine Learning Section 5.3 for details.
Gradients of cross-entropy error in neural network
Use the chain rule, $$ \frac{\partial C}{\partial W_1} = \frac{\partial C}{\partial z} \frac{\partial z}{\partial h} \frac{\partial h}{\partial a} \frac{\partial a}{\partial W_1} , $$ where $$ a = W
Gradients of cross-entropy error in neural network Use the chain rule, $$ \frac{\partial C}{\partial W_1} = \frac{\partial C}{\partial z} \frac{\partial z}{\partial h} \frac{\partial h}{\partial a} \frac{\partial a}{\partial W_1} , $$ where $$ a = W_1x+b_1 . $$ $$ \frac{\partial C}{\partial z} = y-\hat{y}, $$ $$ \frac{\partial z}{\partial h} = W_2, $$ $$ \frac{\partial h}{\partial a} = \sigma(a)(1 - \sigma(a)), $$ $$ \frac{\partial a}{\partial W_1} = x, $$ so $$ \frac{\partial C}{\partial W_1} = (y-\hat{y})W_2\sigma(a)(1 - \sigma(a))x = (y-\hat{y})W_2h(1 - h)x. $$ You could take a look at Pattern Recognition and Machine Learning Section 5.3 for details.
Gradients of cross-entropy error in neural network Use the chain rule, $$ \frac{\partial C}{\partial W_1} = \frac{\partial C}{\partial z} \frac{\partial z}{\partial h} \frac{\partial h}{\partial a} \frac{\partial a}{\partial W_1} , $$ where $$ a = W
36,903
Help explaining (offering intuition/examples of) the score function and fisher's information to students
Buse, A (1982). The Likelihood Ratio, Wald, and Lagrange Multiplier Tests: An Expository Note. The American Statistician, 36:3a, 153-157 is an excellent reference with one major reservation: Lagrange multiplier test should have been called Rao's efficient score test. I wrote Prof. Rao about this when the paper came out to let him know my frustration that incorrect terminology was being used and he was thankful. Other than that it's an excellent article. I've sent you a personal email with the pdf. Another article by Linda Pickle is also excellent - Stat Comp & Stat Graphics Newsletter Nov. 1991 which I'm sending to you.
Help explaining (offering intuition/examples of) the score function and fisher's information to stud
Buse, A (1982). The Likelihood Ratio, Wald, and Lagrange Multiplier Tests: An Expository Note. The American Statistician, 36:3a, 153-157 is an excellent reference with one major reservation: Lagrange
Help explaining (offering intuition/examples of) the score function and fisher's information to students Buse, A (1982). The Likelihood Ratio, Wald, and Lagrange Multiplier Tests: An Expository Note. The American Statistician, 36:3a, 153-157 is an excellent reference with one major reservation: Lagrange multiplier test should have been called Rao's efficient score test. I wrote Prof. Rao about this when the paper came out to let him know my frustration that incorrect terminology was being used and he was thankful. Other than that it's an excellent article. I've sent you a personal email with the pdf. Another article by Linda Pickle is also excellent - Stat Comp & Stat Graphics Newsletter Nov. 1991 which I'm sending to you.
Help explaining (offering intuition/examples of) the score function and fisher's information to stud Buse, A (1982). The Likelihood Ratio, Wald, and Lagrange Multiplier Tests: An Expository Note. The American Statistician, 36:3a, 153-157 is an excellent reference with one major reservation: Lagrange
36,904
Can BIC be Used for Hypothesis Testing
You can construct just such an asymptotic approximation, but note that you can rewrite it in terms of the difference from (say) $BIC_0$ (or indeed any convenient constant). This can help avoid problems with underflow or overflow when exponentiating numbers which might be very far from 0. Note further that (using a similar approach to the one you used) it generalizes to a larger collection of alternative models than just two. I wouldn't call it "hypothesis testing", though; to my mind it's nearer to Bayesian model selection, but it occurs more often in a related but slightly different context. (Don't mind me, though, other people have referred to it or something very like it as hypothesis testing, you can probably find several examples among the references in the links below, and elsewhere.) It (or a slightly re-written form of it) is an approximation I've seen often (I guess it depends on which things you read), and does produce an approximate posterior probability of the models under consideration (under a particular set of assumptions). It occurs particularly often in the context of discussions of model averaging or model uncertainty, where rather than choosing a particular model and conditioning on that choice, all* of the models are weighted by their posterior probability, in order (for example) to produce a distribution of predictions. * or sometimes just a subset of the models with the highest posterior probabilities, often as an approximation of an overall, but sometimes extremely large set. (see also Occam's window) If you search on Bayesian model averaging and BIC you should be able to turn up quite a few references (names like Hoeting, Raftery or Madigan are on quite a few of the papers, but many other authors write on this stuff); if you can't find any I can point some out. Just as one example, in Raftery [1], equation 35, he uses just such an expression as you have above but generalized to $k$ models. Try these links, which have a number of papers that do something along the lines of what you describe (for the first link, I can't get the original to load so I have gone to the last version at archive.org): https://web.archive.org/web/20150925053749/http://www2.research.att.com/~volinsky/bma.html http://www.stat.washington.edu/raftery/Research/bma.html (not all links at those pages will necessarily be what you're after, but each will have many papers that relate to it.) [1] Raftery, A.E. (1995). "Bayesian model selection in social research (with Discussion)." Sociological Methodology, 25, 111-196.
Can BIC be Used for Hypothesis Testing
You can construct just such an asymptotic approximation, but note that you can rewrite it in terms of the difference from (say) $BIC_0$ (or indeed any convenient constant). This can help avoid problem
Can BIC be Used for Hypothesis Testing You can construct just such an asymptotic approximation, but note that you can rewrite it in terms of the difference from (say) $BIC_0$ (or indeed any convenient constant). This can help avoid problems with underflow or overflow when exponentiating numbers which might be very far from 0. Note further that (using a similar approach to the one you used) it generalizes to a larger collection of alternative models than just two. I wouldn't call it "hypothesis testing", though; to my mind it's nearer to Bayesian model selection, but it occurs more often in a related but slightly different context. (Don't mind me, though, other people have referred to it or something very like it as hypothesis testing, you can probably find several examples among the references in the links below, and elsewhere.) It (or a slightly re-written form of it) is an approximation I've seen often (I guess it depends on which things you read), and does produce an approximate posterior probability of the models under consideration (under a particular set of assumptions). It occurs particularly often in the context of discussions of model averaging or model uncertainty, where rather than choosing a particular model and conditioning on that choice, all* of the models are weighted by their posterior probability, in order (for example) to produce a distribution of predictions. * or sometimes just a subset of the models with the highest posterior probabilities, often as an approximation of an overall, but sometimes extremely large set. (see also Occam's window) If you search on Bayesian model averaging and BIC you should be able to turn up quite a few references (names like Hoeting, Raftery or Madigan are on quite a few of the papers, but many other authors write on this stuff); if you can't find any I can point some out. Just as one example, in Raftery [1], equation 35, he uses just such an expression as you have above but generalized to $k$ models. Try these links, which have a number of papers that do something along the lines of what you describe (for the first link, I can't get the original to load so I have gone to the last version at archive.org): https://web.archive.org/web/20150925053749/http://www2.research.att.com/~volinsky/bma.html http://www.stat.washington.edu/raftery/Research/bma.html (not all links at those pages will necessarily be what you're after, but each will have many papers that relate to it.) [1] Raftery, A.E. (1995). "Bayesian model selection in social research (with Discussion)." Sociological Methodology, 25, 111-196.
Can BIC be Used for Hypothesis Testing You can construct just such an asymptotic approximation, but note that you can rewrite it in terms of the difference from (say) $BIC_0$ (or indeed any convenient constant). This can help avoid problem
36,905
Why do we deseasonalize data?
You deaseasonalize when the focus is on the secular trends. For instance, you're interested where the sales are going as opposed to what will be the sales in the next month. Sales are usually highly seasonal, e.g. home sales are up in summer and down in winter. So, if your focus is on figuring out whether the general trend of sales is up, you deseasonalize, and possibly forget about the seasonal component. However, if you need to forecast the sales in next quarter, then you need take into account both the secular trend and seasonality. You could do this by analyzing the components separately, or aggregated. In the latter case you don't bother deseasonalizing. see also "WHY ADJUST?" section in "Seasonality: Causation, Interpretation, and Implications," Granger, URL: http://www.nber.org/chapters/c4321
Why do we deseasonalize data?
You deaseasonalize when the focus is on the secular trends. For instance, you're interested where the sales are going as opposed to what will be the sales in the next month. Sales are usually highly s
Why do we deseasonalize data? You deaseasonalize when the focus is on the secular trends. For instance, you're interested where the sales are going as opposed to what will be the sales in the next month. Sales are usually highly seasonal, e.g. home sales are up in summer and down in winter. So, if your focus is on figuring out whether the general trend of sales is up, you deseasonalize, and possibly forget about the seasonal component. However, if you need to forecast the sales in next quarter, then you need take into account both the secular trend and seasonality. You could do this by analyzing the components separately, or aggregated. In the latter case you don't bother deseasonalizing. see also "WHY ADJUST?" section in "Seasonality: Causation, Interpretation, and Implications," Granger, URL: http://www.nber.org/chapters/c4321
Why do we deseasonalize data? You deaseasonalize when the focus is on the secular trends. For instance, you're interested where the sales are going as opposed to what will be the sales in the next month. Sales are usually highly s
36,906
Why do we deseasonalize data?
You can only make a regression line using deseasonalised data. The Regression line equation can then be used to make deseasonalised future predictions. From this you can find the seasonalised future values. So perhaps this was done to forcast future values? Though, i'm not too certain on how this correlates to stationary and non-stationary data.
Why do we deseasonalize data?
You can only make a regression line using deseasonalised data. The Regression line equation can then be used to make deseasonalised future predictions. From this you can find the seasonalised future v
Why do we deseasonalize data? You can only make a regression line using deseasonalised data. The Regression line equation can then be used to make deseasonalised future predictions. From this you can find the seasonalised future values. So perhaps this was done to forcast future values? Though, i'm not too certain on how this correlates to stationary and non-stationary data.
Why do we deseasonalize data? You can only make a regression line using deseasonalised data. The Regression line equation can then be used to make deseasonalised future predictions. From this you can find the seasonalised future v
36,907
Regression Mixture in PYMC3
An alternative is to use the marginalized mixture model (see also this SO answer). This utilizes the NUTS using ADVI and converges within 6000 samples. import theano.tensore as tt ncls = 2 with pm.Model() as basic_model: w = pm.Dirichlet('w', np.ones(ncls)) alpha = pm.Normal('alpha', mu=0, sd=10) beta = pm.Normal('beta', mu=0, sd=100, shape=ncls) sigma = pm.Uniform('sigma', 0, 20) mu = tt.stack([alpha + beta[0]*X1, alpha + beta[1]*X1], axis=1) y_obs = pm.NormalMixture('y_obs', w, mu, tau=sigma, observed=Y) with basic_model: trace = pm.sample(5000, n_init=10000, tune=1000)[1000:]
Regression Mixture in PYMC3
An alternative is to use the marginalized mixture model (see also this SO answer). This utilizes the NUTS using ADVI and converges within 6000 samples. import theano.tensore as tt ncls = 2 with pm.Mo
Regression Mixture in PYMC3 An alternative is to use the marginalized mixture model (see also this SO answer). This utilizes the NUTS using ADVI and converges within 6000 samples. import theano.tensore as tt ncls = 2 with pm.Model() as basic_model: w = pm.Dirichlet('w', np.ones(ncls)) alpha = pm.Normal('alpha', mu=0, sd=10) beta = pm.Normal('beta', mu=0, sd=100, shape=ncls) sigma = pm.Uniform('sigma', 0, 20) mu = tt.stack([alpha + beta[0]*X1, alpha + beta[1]*X1], axis=1) y_obs = pm.NormalMixture('y_obs', w, mu, tau=sigma, observed=Y) with basic_model: trace = pm.sample(5000, n_init=10000, tune=1000)[1000:]
Regression Mixture in PYMC3 An alternative is to use the marginalized mixture model (see also this SO answer). This utilizes the NUTS using ADVI and converges within 6000 samples. import theano.tensore as tt ncls = 2 with pm.Mo
36,908
Regression Mixture in PYMC3
So the problem with this was actually with the BinaryMetropolis sampler, a problem I only discovered by stumbling on this post. I adjusted the scaling parameter of the sampler and after about 35k samples, it converged on the parameters. with basic_model: step1 = pm.Metropolis([p, alpha, beta_1, sigma]) step2 = pm.BinaryMetropolis([category], scaling=.01) trace = pm.sample(50000, [step1, step2], progressbar=True)
Regression Mixture in PYMC3
So the problem with this was actually with the BinaryMetropolis sampler, a problem I only discovered by stumbling on this post. I adjusted the scaling parameter of the sampler and after about 35k samp
Regression Mixture in PYMC3 So the problem with this was actually with the BinaryMetropolis sampler, a problem I only discovered by stumbling on this post. I adjusted the scaling parameter of the sampler and after about 35k samples, it converged on the parameters. with basic_model: step1 = pm.Metropolis([p, alpha, beta_1, sigma]) step2 = pm.BinaryMetropolis([category], scaling=.01) trace = pm.sample(50000, [step1, step2], progressbar=True)
Regression Mixture in PYMC3 So the problem with this was actually with the BinaryMetropolis sampler, a problem I only discovered by stumbling on this post. I adjusted the scaling parameter of the sampler and after about 35k samp
36,909
(References) How to derive experimental design models, instead of just memorize them?
You're asking for a derivation, but I'd argue that this formula is not derivable. It stands on its own as a mathematical encoding of the outside world. The math doesn't care what a "block" is, but you do. And if you believe it can be modeled as an additive source of variation, then you'll likely end up with the linear model you proposed above. But blocks could interact with treatments, for instance, and then the model you proposed above would be wrong. You can't derive what the "correct" model for the world is. You asked for references, and perhaps a good place to look would be some of R.A. Fisher's writings on experimental design like The design of experiments (1960). He doesn't even bring up the linear model, and instead focuses on partitioning out variance via an Analysis of Variance. I'm curious as to whether Fisher even thought in terms of a linear model at the time when he was partitioning variance this way, and perhaps the closest thing to a derivation would be to show the equivalence of the classical Analysis of Variance and the linear model, if you take the former to be self-evident.
(References) How to derive experimental design models, instead of just memorize them?
You're asking for a derivation, but I'd argue that this formula is not derivable. It stands on its own as a mathematical encoding of the outside world. The math doesn't care what a "block" is, but you
(References) How to derive experimental design models, instead of just memorize them? You're asking for a derivation, but I'd argue that this formula is not derivable. It stands on its own as a mathematical encoding of the outside world. The math doesn't care what a "block" is, but you do. And if you believe it can be modeled as an additive source of variation, then you'll likely end up with the linear model you proposed above. But blocks could interact with treatments, for instance, and then the model you proposed above would be wrong. You can't derive what the "correct" model for the world is. You asked for references, and perhaps a good place to look would be some of R.A. Fisher's writings on experimental design like The design of experiments (1960). He doesn't even bring up the linear model, and instead focuses on partitioning out variance via an Analysis of Variance. I'm curious as to whether Fisher even thought in terms of a linear model at the time when he was partitioning variance this way, and perhaps the closest thing to a derivation would be to show the equivalence of the classical Analysis of Variance and the linear model, if you take the former to be self-evident.
(References) How to derive experimental design models, instead of just memorize them? You're asking for a derivation, but I'd argue that this formula is not derivable. It stands on its own as a mathematical encoding of the outside world. The math doesn't care what a "block" is, but you
36,910
Statistical anecdotes [closed]
Not sure if this is too serious, but there is the Berkeley gender bias case illustrating Simpson's paradox. A very recent nearly identical case illustrating the problem seems a PNAS study on gender bias in research funding, discussed, e.g., in this Science news article.
Statistical anecdotes [closed]
Not sure if this is too serious, but there is the Berkeley gender bias case illustrating Simpson's paradox. A very recent nearly identical case illustrating the problem seems a PNAS study on gender bi
Statistical anecdotes [closed] Not sure if this is too serious, but there is the Berkeley gender bias case illustrating Simpson's paradox. A very recent nearly identical case illustrating the problem seems a PNAS study on gender bias in research funding, discussed, e.g., in this Science news article.
Statistical anecdotes [closed] Not sure if this is too serious, but there is the Berkeley gender bias case illustrating Simpson's paradox. A very recent nearly identical case illustrating the problem seems a PNAS study on gender bi
36,911
expectation of $e^{-x}$ when x is log-normal
Suppose $X$ is log-normal random variable. The question is about the expectation $\DeclareMathOperator{\E}{E} \E \exp(-X)$. This is related to the moment-generating function of $X$, $$ M_X(t) = \E e^{tX} $$ So you are asking for $M_X(-1)$, which do exist, but no closed expression is known. So, you could try numerical integration (example in R): > f <- function(x) exp(-x)*dlnorm(x) > integrate(f,0,+Inf) 0.3817565 with absolute error < 1.8e-05 > # Or by stochastic simulation: > mean(exp(-rlnorm(100E6,0,1))) [1] 0.3818151 If you want some analytic approximations, have a look at: Søren Asmussen, Jens Ledet Jensen, Leonardo Rojas-Nandayapa: "On the Laplace transform of the lognormal distribution."
expectation of $e^{-x}$ when x is log-normal
Suppose $X$ is log-normal random variable. The question is about the expectation $\DeclareMathOperator{\E}{E} \E \exp(-X)$. This is related to the moment-generating function of $X$, $$ M_X(t) = \E
expectation of $e^{-x}$ when x is log-normal Suppose $X$ is log-normal random variable. The question is about the expectation $\DeclareMathOperator{\E}{E} \E \exp(-X)$. This is related to the moment-generating function of $X$, $$ M_X(t) = \E e^{tX} $$ So you are asking for $M_X(-1)$, which do exist, but no closed expression is known. So, you could try numerical integration (example in R): > f <- function(x) exp(-x)*dlnorm(x) > integrate(f,0,+Inf) 0.3817565 with absolute error < 1.8e-05 > # Or by stochastic simulation: > mean(exp(-rlnorm(100E6,0,1))) [1] 0.3818151 If you want some analytic approximations, have a look at: Søren Asmussen, Jens Ledet Jensen, Leonardo Rojas-Nandayapa: "On the Laplace transform of the lognormal distribution."
expectation of $e^{-x}$ when x is log-normal Suppose $X$ is log-normal random variable. The question is about the expectation $\DeclareMathOperator{\E}{E} \E \exp(-X)$. This is related to the moment-generating function of $X$, $$ M_X(t) = \E
36,912
Maximum Likelihood Estimate of Infection Model Parameters
Here's a possibility in which the model is modified (1) to be explicitly probabilistic, and (2) to take place in discrete time. The code below explains the modified model, simulates it, and then uses MLE to recover the parameters (whose true value is known in this toy example, since we simulated the data). Careful: my beta will not be exactly equivalent to your beta -- see "story" in the comments below. library(ggplot2) library(reshape2) ## S(t) susceptible, I(t) infected, R(t) recovered at time t ## Probabilistic model in discrete time: ## S(t+1) = S(t) - DeltaS(t) ## I(t+1) = I(t) + DeltaS(t) - DeltaR(t) ## R(t+1) = R(t) + DeltaR(t) ## DeltaR(t) ~ Binomial(I(t), gamma) >= 0 ## DeltaS(t) ~ Binomial(S(t), 1 - (1 - beta)^I(t)) >= 0 ## Story: each infected has probability gamma of recovering during the period; ## before recoveries are realized, each susceptible interacts with each infected; ## each interaction leads to infection with probability beta; ## susceptible becomes infected if >= 1 of her interactions leads to infection simulate <- function(T=100, S1=100, I1=10, R1=0, beta=0.005, gamma=0.10) { stopifnot(T > 0) stopifnot(beta >= 0 && beta <= 1) stopifnot(gamma >= 0 && gamma <= 1) total_pop <- S1 + I1 + R1 df <- data.frame(t=seq_len(T)) df[, c("S", "I", "R")] <- NA for(t in seq_len(T)) { if(t == 1) { df$S[t] <- S1 df$I[t] <- I1 df$R[t] <- R1 next } DeltaS <- rbinom(n=1, size=df$S[t-1], prob=1 - (1-beta)^df$I[t-1]) DeltaR <- rbinom(n=1, size=df$I[t-1], prob=gamma) df$S[t] <- df$S[t-1] - DeltaS df$I[t] <- df$I[t-1] + DeltaS - DeltaR df$R[t] <- df$R[t-1] + DeltaR stopifnot(df$S[t] + df$I[t] + df$R[t] == total_pop) # Sanity check } return(df) } inverse_logit <- function(x) { p <- exp(x) / (1 + exp(x)) # Maps R to [0, 1] return(p) } curve(inverse_logit, -10, 10) # Sanity check loglik <- function(logit_beta_gamma, df) { stopifnot(length(logit_beta_gamma) == 2) beta <- inverse_logit(logit_beta_gamma[1]) gamma <- inverse_logit(logit_beta_gamma[2]) dS <- -diff(df$S) dR <- diff(df$R) n <- nrow(df) pr_dS <- 1 - (1-beta)^df$I[seq_len(n-1)] # Careful, problematic if 1 or 0 return(sum(dbinom(dS, size=df$S[seq_len(n-1)], prob=pr_dS, log=TRUE) + dbinom(dR, size=df$I[seq_len(n-1)], prob=gamma, log=TRUE))) } get_estimates <- function() { df <- simulate() mle <- optim(par=c(-4, 0), fn=loglik, control=list(fnscale=-1), df=df) beta_gamma_hat <- inverse_logit(mle$par) names(beta_gamma_hat) <- c("beta", "gamma") return(beta_gamma_hat) } set.seed(54321999) df <- simulate() df_melted <- melt(df, id.vars="t") p <- (ggplot(df_melted, aes(x=t, y=value, color=variable)) + geom_line(size=1.1) + theme_bw() + xlab("time") + theme(legend.key=element_blank()) + theme(panel.border=element_blank())) p ## Sampling distribution of beta_gamma_hat estimates <- replicate(100, get_estimates()) df_estimates <- as.data.frame(t(estimates)) summary(df_estimates) # Looks reasonable given true values of (0.005, 0.10) Let me know if anything is not self-explanatory. Disclaimer: I haven't studied the SIR model except once very briefly in a college class, several years ago. The model I simulate and estimate above is not exactly the classic differential equation SIR model you stated in your question. Also I'm feeling a bit feverish today, so check the code for mistakes!
Maximum Likelihood Estimate of Infection Model Parameters
Here's a possibility in which the model is modified (1) to be explicitly probabilistic, and (2) to take place in discrete time. The code below explains the modified model, simulates it, and then uses
Maximum Likelihood Estimate of Infection Model Parameters Here's a possibility in which the model is modified (1) to be explicitly probabilistic, and (2) to take place in discrete time. The code below explains the modified model, simulates it, and then uses MLE to recover the parameters (whose true value is known in this toy example, since we simulated the data). Careful: my beta will not be exactly equivalent to your beta -- see "story" in the comments below. library(ggplot2) library(reshape2) ## S(t) susceptible, I(t) infected, R(t) recovered at time t ## Probabilistic model in discrete time: ## S(t+1) = S(t) - DeltaS(t) ## I(t+1) = I(t) + DeltaS(t) - DeltaR(t) ## R(t+1) = R(t) + DeltaR(t) ## DeltaR(t) ~ Binomial(I(t), gamma) >= 0 ## DeltaS(t) ~ Binomial(S(t), 1 - (1 - beta)^I(t)) >= 0 ## Story: each infected has probability gamma of recovering during the period; ## before recoveries are realized, each susceptible interacts with each infected; ## each interaction leads to infection with probability beta; ## susceptible becomes infected if >= 1 of her interactions leads to infection simulate <- function(T=100, S1=100, I1=10, R1=0, beta=0.005, gamma=0.10) { stopifnot(T > 0) stopifnot(beta >= 0 && beta <= 1) stopifnot(gamma >= 0 && gamma <= 1) total_pop <- S1 + I1 + R1 df <- data.frame(t=seq_len(T)) df[, c("S", "I", "R")] <- NA for(t in seq_len(T)) { if(t == 1) { df$S[t] <- S1 df$I[t] <- I1 df$R[t] <- R1 next } DeltaS <- rbinom(n=1, size=df$S[t-1], prob=1 - (1-beta)^df$I[t-1]) DeltaR <- rbinom(n=1, size=df$I[t-1], prob=gamma) df$S[t] <- df$S[t-1] - DeltaS df$I[t] <- df$I[t-1] + DeltaS - DeltaR df$R[t] <- df$R[t-1] + DeltaR stopifnot(df$S[t] + df$I[t] + df$R[t] == total_pop) # Sanity check } return(df) } inverse_logit <- function(x) { p <- exp(x) / (1 + exp(x)) # Maps R to [0, 1] return(p) } curve(inverse_logit, -10, 10) # Sanity check loglik <- function(logit_beta_gamma, df) { stopifnot(length(logit_beta_gamma) == 2) beta <- inverse_logit(logit_beta_gamma[1]) gamma <- inverse_logit(logit_beta_gamma[2]) dS <- -diff(df$S) dR <- diff(df$R) n <- nrow(df) pr_dS <- 1 - (1-beta)^df$I[seq_len(n-1)] # Careful, problematic if 1 or 0 return(sum(dbinom(dS, size=df$S[seq_len(n-1)], prob=pr_dS, log=TRUE) + dbinom(dR, size=df$I[seq_len(n-1)], prob=gamma, log=TRUE))) } get_estimates <- function() { df <- simulate() mle <- optim(par=c(-4, 0), fn=loglik, control=list(fnscale=-1), df=df) beta_gamma_hat <- inverse_logit(mle$par) names(beta_gamma_hat) <- c("beta", "gamma") return(beta_gamma_hat) } set.seed(54321999) df <- simulate() df_melted <- melt(df, id.vars="t") p <- (ggplot(df_melted, aes(x=t, y=value, color=variable)) + geom_line(size=1.1) + theme_bw() + xlab("time") + theme(legend.key=element_blank()) + theme(panel.border=element_blank())) p ## Sampling distribution of beta_gamma_hat estimates <- replicate(100, get_estimates()) df_estimates <- as.data.frame(t(estimates)) summary(df_estimates) # Looks reasonable given true values of (0.005, 0.10) Let me know if anything is not self-explanatory. Disclaimer: I haven't studied the SIR model except once very briefly in a college class, several years ago. The model I simulate and estimate above is not exactly the classic differential equation SIR model you stated in your question. Also I'm feeling a bit feverish today, so check the code for mistakes!
Maximum Likelihood Estimate of Infection Model Parameters Here's a possibility in which the model is modified (1) to be explicitly probabilistic, and (2) to take place in discrete time. The code below explains the modified model, simulates it, and then uses
36,913
Maximum Likelihood Estimate of Infection Model Parameters
These slides Provide a good initial start by doing iterative least squares fits, this is however only for the SI model. This blog gives this problem a more extensive treatment. This seems to be similar to your approach. Fitting a Gaussian kernel via non-linear least squares might be a good way to get initial parameter estimates. Then you have to identify some kind of a relation between the Gaussian kernel parameters and the parameters in your model.
Maximum Likelihood Estimate of Infection Model Parameters
These slides Provide a good initial start by doing iterative least squares fits, this is however only for the SI model. This blog gives this problem a more extensive treatment. This seems to be simila
Maximum Likelihood Estimate of Infection Model Parameters These slides Provide a good initial start by doing iterative least squares fits, this is however only for the SI model. This blog gives this problem a more extensive treatment. This seems to be similar to your approach. Fitting a Gaussian kernel via non-linear least squares might be a good way to get initial parameter estimates. Then you have to identify some kind of a relation between the Gaussian kernel parameters and the parameters in your model.
Maximum Likelihood Estimate of Infection Model Parameters These slides Provide a good initial start by doing iterative least squares fits, this is however only for the SI model. This blog gives this problem a more extensive treatment. This seems to be simila
36,914
Statistical model to predict the next move on network only using movement history
Do you really want a statistical model, or just an algorithm for guessing the next node given all previous ones? If the latter then consider proceeding as follows. Suppose you've gone $\ldots\rightarrow A\rightarrow B\rightarrow C$ and need to decide which of $X$, $Y$ or $Z$ is the most likely next node. First-order Markov. Historically, let's say $n_C(X)$ moves from $C$ have been to $X$, $n_C(Y)$ to $Y$ and $n_C(Z)$ to $Z$. Define $n_C=n_C(X)+n_C(Y)+n_C(Z)$. Adding a flattening constant $\kappa$ to each count, the (Dirichlet-Multinomial) predicted probabilities for the next move are $p_C(X) = \frac{\kappa+n_C(X)}{3\kappa+n_C}$ etc. Second-order Markov. As above, but we're looking at moves following $BC$. The counts $n_{BC}(X)$ etc will be lower (we're taking a smaller, more specific. slice of the history), so the flattening effect of adding $\kappa$ to the historical counts will be proportionally greater. As before, we define $p_{BC}(X) = \frac{\kappa+n_{BC}(X)}{3\kappa+n_{BC}}$ and so on. Continue in this way, forming probabilities $p_{C}(\cdot), p_{BC}(\cdot), p_{ABC}(\cdot), \ldots$ until the history is long enough that there is only one choice for the next node. Going further back is now pointless. Let $p_\textrm{history}(W)$ be the maximum of all of the $p_\cdot(\cdot)$ probabilities. Your prediction for the next node is $W$. This just leaves the question of: what value should $\kappa$ take? $\kappa=1$ would be the traditional starting point. Try cross-validation (train on part of your data, test on the rest) to fine-tune that value.
Statistical model to predict the next move on network only using movement history
Do you really want a statistical model, or just an algorithm for guessing the next node given all previous ones? If the latter then consider proceeding as follows. Suppose you've gone $\ldots\rightar
Statistical model to predict the next move on network only using movement history Do you really want a statistical model, or just an algorithm for guessing the next node given all previous ones? If the latter then consider proceeding as follows. Suppose you've gone $\ldots\rightarrow A\rightarrow B\rightarrow C$ and need to decide which of $X$, $Y$ or $Z$ is the most likely next node. First-order Markov. Historically, let's say $n_C(X)$ moves from $C$ have been to $X$, $n_C(Y)$ to $Y$ and $n_C(Z)$ to $Z$. Define $n_C=n_C(X)+n_C(Y)+n_C(Z)$. Adding a flattening constant $\kappa$ to each count, the (Dirichlet-Multinomial) predicted probabilities for the next move are $p_C(X) = \frac{\kappa+n_C(X)}{3\kappa+n_C}$ etc. Second-order Markov. As above, but we're looking at moves following $BC$. The counts $n_{BC}(X)$ etc will be lower (we're taking a smaller, more specific. slice of the history), so the flattening effect of adding $\kappa$ to the historical counts will be proportionally greater. As before, we define $p_{BC}(X) = \frac{\kappa+n_{BC}(X)}{3\kappa+n_{BC}}$ and so on. Continue in this way, forming probabilities $p_{C}(\cdot), p_{BC}(\cdot), p_{ABC}(\cdot), \ldots$ until the history is long enough that there is only one choice for the next node. Going further back is now pointless. Let $p_\textrm{history}(W)$ be the maximum of all of the $p_\cdot(\cdot)$ probabilities. Your prediction for the next node is $W$. This just leaves the question of: what value should $\kappa$ take? $\kappa=1$ would be the traditional starting point. Try cross-validation (train on part of your data, test on the rest) to fine-tune that value.
Statistical model to predict the next move on network only using movement history Do you really want a statistical model, or just an algorithm for guessing the next node given all previous ones? If the latter then consider proceeding as follows. Suppose you've gone $\ldots\rightar
36,915
Statistical model to predict the next move on network only using movement history
Hint for the non-time varying version: You can treat this as updating (use Bayes' theorem) probability estimates given some data. A multinomial likelihood and Dirichlet prior would be the standard approach. https://en.wikipedia.org/wiki/Dirichlet-multinomial_distribution For the prior it sounds like you would want the prior probability to assign equal probabilities of transitioning to each possible node. To add in the effects of time (older tranitions matter less than newer ones) is more complex. You could add in a decay function so that you get partial transitions. In general the structure alone of the diagram will tell you nothing about the transition probabilities.
Statistical model to predict the next move on network only using movement history
Hint for the non-time varying version: You can treat this as updating (use Bayes' theorem) probability estimates given some data. A multinomial likelihood and Dirichlet prior would be the standard app
Statistical model to predict the next move on network only using movement history Hint for the non-time varying version: You can treat this as updating (use Bayes' theorem) probability estimates given some data. A multinomial likelihood and Dirichlet prior would be the standard approach. https://en.wikipedia.org/wiki/Dirichlet-multinomial_distribution For the prior it sounds like you would want the prior probability to assign equal probabilities of transitioning to each possible node. To add in the effects of time (older tranitions matter less than newer ones) is more complex. You could add in a decay function so that you get partial transitions. In general the structure alone of the diagram will tell you nothing about the transition probabilities.
Statistical model to predict the next move on network only using movement history Hint for the non-time varying version: You can treat this as updating (use Bayes' theorem) probability estimates given some data. A multinomial likelihood and Dirichlet prior would be the standard app
36,916
Statistical model to predict the next move on network only using movement history
A few answers and a few questions. For simplicity let's start by assuming you're just seeing one long chain of movements. The simplest model would involve a Multinomial distribution for each node (essentially at each node there is a specific die to roll to determine where you go next). Our goal would be to estimate the parameters of these dice. As Ash mentioned the Bayesian approach would be to put a Dirichlet Prior Distribution on each die, and update this prior with new data to obtain a Dirichlet Posterior Distribution. You can think of a Dirichlet distribution as a dice factory. The fact that the posterior distribution is also a Dirichlet is because the Dirichlet distribution is the Conjugate Prior to the Multinomial distribution. While this may sound quite confusing it's actually very simple. The prior can be interpreted as pseudo-counts, essentially pretending that you've already seen some data (even though you haven't). For example, if you are at Z you can go to C, D, Z (our die is three sided here). We can use a Dirichlet prior that acts as though we've already seen one transition from Z to each of those states. So each probability will equal 1/3. If the player transitions to C, we would update our distribution with one more count, so transition from Z to C would have probability 2/4 and the other would each have probability 1/4. If we use a prior with more pseudo-counts as though we had seen 10 transitions from Z to each of the other states, the updated probabilities (11/31, 10/31, 10/31), would be much closer to the original ones, this is a stronger prior. The strength of the prior is normally determined by Cross-Validation. The model I described above is referred to as memoryless, because the probability of transitioning from one state to another depends only on your current state. If you wanted to do something more elaborate you could incorporate not only where you currently are, but also where you were last step, although at this point the number of parameters you have to estimate will increase dramatically, and therefore the variance in estimating will as well. Question: You gave some intuition of the form of "Why would I go from B->C->X when I could just go from B->X?" These ideas seem to be specific to the problem you're working on, so I can speak directly to it. Although if that is a concern, perhaps you want to use the non-memoryless (memoryfull?) model, or incorporate this information in your prior. If you would like to explain what the real life significance of this graph is, and therefore where this intuition is coming from perhaps we can be more helpful. Note: You want to look up Markov Models, maybe no so much Hidden Markov Models. Those have a hidden state that is controlling the observed data, and trying to learn to use them might get in the way of this project.
Statistical model to predict the next move on network only using movement history
A few answers and a few questions. For simplicity let's start by assuming you're just seeing one long chain of movements. The simplest model would involve a Multinomial distribution for each node (es
Statistical model to predict the next move on network only using movement history A few answers and a few questions. For simplicity let's start by assuming you're just seeing one long chain of movements. The simplest model would involve a Multinomial distribution for each node (essentially at each node there is a specific die to roll to determine where you go next). Our goal would be to estimate the parameters of these dice. As Ash mentioned the Bayesian approach would be to put a Dirichlet Prior Distribution on each die, and update this prior with new data to obtain a Dirichlet Posterior Distribution. You can think of a Dirichlet distribution as a dice factory. The fact that the posterior distribution is also a Dirichlet is because the Dirichlet distribution is the Conjugate Prior to the Multinomial distribution. While this may sound quite confusing it's actually very simple. The prior can be interpreted as pseudo-counts, essentially pretending that you've already seen some data (even though you haven't). For example, if you are at Z you can go to C, D, Z (our die is three sided here). We can use a Dirichlet prior that acts as though we've already seen one transition from Z to each of those states. So each probability will equal 1/3. If the player transitions to C, we would update our distribution with one more count, so transition from Z to C would have probability 2/4 and the other would each have probability 1/4. If we use a prior with more pseudo-counts as though we had seen 10 transitions from Z to each of the other states, the updated probabilities (11/31, 10/31, 10/31), would be much closer to the original ones, this is a stronger prior. The strength of the prior is normally determined by Cross-Validation. The model I described above is referred to as memoryless, because the probability of transitioning from one state to another depends only on your current state. If you wanted to do something more elaborate you could incorporate not only where you currently are, but also where you were last step, although at this point the number of parameters you have to estimate will increase dramatically, and therefore the variance in estimating will as well. Question: You gave some intuition of the form of "Why would I go from B->C->X when I could just go from B->X?" These ideas seem to be specific to the problem you're working on, so I can speak directly to it. Although if that is a concern, perhaps you want to use the non-memoryless (memoryfull?) model, or incorporate this information in your prior. If you would like to explain what the real life significance of this graph is, and therefore where this intuition is coming from perhaps we can be more helpful. Note: You want to look up Markov Models, maybe no so much Hidden Markov Models. Those have a hidden state that is controlling the observed data, and trying to learn to use them might get in the way of this project.
Statistical model to predict the next move on network only using movement history A few answers and a few questions. For simplicity let's start by assuming you're just seeing one long chain of movements. The simplest model would involve a Multinomial distribution for each node (es
36,917
What is the point of graphical models?
The value and power of graphical models of conditional probabilistic relations is that they convey information about the causal structure and inferential structure of the system. For example, rain or sprinklers can cause wet sidewalks, but wet sidewalks cannot cause rain or sprinklers spraying. If your evidence is "rain" and "not sprinklers" you can infer certain things. If your evidence is "wet sidewalk" you can infer other things. What you can and can't infer is determined by the structure of the graph. Your example of "a dataset that is observations by features" may or may not be well suited to a probabilistic graph. Adding in ideas/methods like "p-values" will only confuse you, I think. (P-values apply to frequentist hypothesis testing.) Metaphorically, you are combining apples, oranges, and armadillos. I suggest that you view lectures by Judea Pearl (https://www.youtube.com/watch?v=zHjdd--W6o4, https://www.youtube.com/watch?v=IiXvpPyhMw8) plus tutorial lectures like these: https://www.youtube.com/watch?v=YvdpnqMRmfk, https://www.youtube.com/watch?v=Xhdpk9HZQuo.
What is the point of graphical models?
The value and power of graphical models of conditional probabilistic relations is that they convey information about the causal structure and inferential structure of the system. For example, rain or
What is the point of graphical models? The value and power of graphical models of conditional probabilistic relations is that they convey information about the causal structure and inferential structure of the system. For example, rain or sprinklers can cause wet sidewalks, but wet sidewalks cannot cause rain or sprinklers spraying. If your evidence is "rain" and "not sprinklers" you can infer certain things. If your evidence is "wet sidewalk" you can infer other things. What you can and can't infer is determined by the structure of the graph. Your example of "a dataset that is observations by features" may or may not be well suited to a probabilistic graph. Adding in ideas/methods like "p-values" will only confuse you, I think. (P-values apply to frequentist hypothesis testing.) Metaphorically, you are combining apples, oranges, and armadillos. I suggest that you view lectures by Judea Pearl (https://www.youtube.com/watch?v=zHjdd--W6o4, https://www.youtube.com/watch?v=IiXvpPyhMw8) plus tutorial lectures like these: https://www.youtube.com/watch?v=YvdpnqMRmfk, https://www.youtube.com/watch?v=Xhdpk9HZQuo.
What is the point of graphical models? The value and power of graphical models of conditional probabilistic relations is that they convey information about the causal structure and inferential structure of the system. For example, rain or
36,918
Runs of the same type within a deck of cards - distribution of runs of different length
Let $I_i^c$ be an indicator variable such that: $$ I_i^c = \begin{cases} 1 & \text{run of length $c$ starts at $i^{th}$ position}, \\ 0 & \text{otherwise} \end{cases} $$ To find $\mathbb{E}[R_c]$ where $R_c$ represents a run of length $c$ we simply make use of this identity(For a run to be of length $c$ it must start at or before $({n-c+1})^{th}$ position: $$ R_c = \sum_{i=1}^{i=n-c+1} I_i $$ Thus, $$ \mathbb{E}[R_c] = \mathbb{E}[\sum_{i=1}^{i=n-c+1}I_i] = \sum_{i=1}^{i=n-c+1} \mathbb{P}(I_i^c=1) $$ Now, consider the event $I_i^c=1$. When $i=1$, the run starts at position 1. It can be $\underbrace{AAAAA\dots}_\text{c times}B $ or $\underbrace{BBBBB\dots}_\text{c times}A $ and hence, the probability is given by: $$ \mathbb{P}(I_1^c=1) = p^c\times q + q^c\times p $$ Similarly, for $i=n-c+1$, $$ \mathbb{P}(I_{n-c+1}^c=1) = p^c\times q + q^c\times p $$ And, for $2 \leq i \leq n-c$, $$ \mathbb{P}(I_i^c=1) = q\times p^c \times q + p \times q^c \times p $$ And hence, $$ \mathbb{E}[R_c] = (n-c-1)\times(p^cq^2+q^cp^2) +2(p^cq+q^cp) $$ To calculate $\text{Var}[R_c]$ make use of $\text{Var}[R_c] = \mathbb{E}[R_c^2]-(\mathbb{E}[R_c])^2$ Details of variance calculation for runs in flips of coin(which comes close to this problem as you already mentioned) are here
Runs of the same type within a deck of cards - distribution of runs of different length
Let $I_i^c$ be an indicator variable such that: $$ I_i^c = \begin{cases} 1 & \text{run of length $c$ starts at $i^{th}$ position}, \\ 0 & \text{otherwise} \end{cases} $$ To find $\mathbb{E}[R_c]$ wher
Runs of the same type within a deck of cards - distribution of runs of different length Let $I_i^c$ be an indicator variable such that: $$ I_i^c = \begin{cases} 1 & \text{run of length $c$ starts at $i^{th}$ position}, \\ 0 & \text{otherwise} \end{cases} $$ To find $\mathbb{E}[R_c]$ where $R_c$ represents a run of length $c$ we simply make use of this identity(For a run to be of length $c$ it must start at or before $({n-c+1})^{th}$ position: $$ R_c = \sum_{i=1}^{i=n-c+1} I_i $$ Thus, $$ \mathbb{E}[R_c] = \mathbb{E}[\sum_{i=1}^{i=n-c+1}I_i] = \sum_{i=1}^{i=n-c+1} \mathbb{P}(I_i^c=1) $$ Now, consider the event $I_i^c=1$. When $i=1$, the run starts at position 1. It can be $\underbrace{AAAAA\dots}_\text{c times}B $ or $\underbrace{BBBBB\dots}_\text{c times}A $ and hence, the probability is given by: $$ \mathbb{P}(I_1^c=1) = p^c\times q + q^c\times p $$ Similarly, for $i=n-c+1$, $$ \mathbb{P}(I_{n-c+1}^c=1) = p^c\times q + q^c\times p $$ And, for $2 \leq i \leq n-c$, $$ \mathbb{P}(I_i^c=1) = q\times p^c \times q + p \times q^c \times p $$ And hence, $$ \mathbb{E}[R_c] = (n-c-1)\times(p^cq^2+q^cp^2) +2(p^cq+q^cp) $$ To calculate $\text{Var}[R_c]$ make use of $\text{Var}[R_c] = \mathbb{E}[R_c^2]-(\mathbb{E}[R_c])^2$ Details of variance calculation for runs in flips of coin(which comes close to this problem as you already mentioned) are here
Runs of the same type within a deck of cards - distribution of runs of different length Let $I_i^c$ be an indicator variable such that: $$ I_i^c = \begin{cases} 1 & \text{run of length $c$ starts at $i^{th}$ position}, \\ 0 & \text{otherwise} \end{cases} $$ To find $\mathbb{E}[R_c]$ wher
36,919
How to test the difference in two proportions when the outcomes aren't binary?
The first part seems indeed reasonable. Concerning the second part, I think these ratios can't be handled as proportions because they are not related to binary events, this imply that we have no clue how these ratios are distributed, which excludes z-test (well unless you have a lucky empirical normal distribution, but you mentioned to have not). First Proposition : Wilcoxon test. My suggestion would be to simply compare these ratios by a wilcoxon test. >sales_data$ratios=final_value/initial_value >ratios_A=sales_data$ratios[sale_success==1 & target_control==0] >ratios_B=sales_data$ratios[sale_success==1 & target_control==1] >wilcox.test(ratios_A,ratios_B) Thinking twice on it, this test treat "1 dollar bought for 5 dollars" selected the same as "100 dollars bought for 500 dollars selected". I can understand why you want to avoid it and favor your overall ratio. Second Proposition : Permutation test. In order to keep your measure, what I would suggest then is to craft "your own test" with a permutation test. Under the null hypothesis being in random or treatment group makes no difference. Then, the idea is to randomly relabel which subjects are in the control or treatment group and count how many times a randomized permutation grant an equal or better gap between control and treatment group than the one you initially measure. This gap is measured by the difference of your ratio between the two groups. If you divide this number of success by the number of trials, it gives a p-value. p1 <- sum(sales_data[target_control==1,"final_value"])/sum(sales_data[target_control==1,"initial_value"]) p2 <- sum(sales_data[target_control==0,"final_value"])/sum(sales_data[target_control==0,"initial_value"]) yourGap<-abs(p1-p2) L<-sales_data["target_control"]==1 LfilterOnlyBuyers<-sales_data["sale_success"]==1 count=0 for ( i in 1:10000) { Lperm=sample(L) p1_perm <- sum(sales_data[Lperm,"final_value"])/sum(sales_data[Lperm & LfilterOnlyBuyers,"initial_value"]) p2_perm <- sum(sales_data[!Lperm,"final_value"])/sum(sales_data[!Lperm & LfilterOnlyBuyers,"initial_value"]) if (abs(p1_perm-p2_perm)>=yourGap) { count=count+1 } } pvalue=count/10000 Use absolute values when your compute your gap if you want to two-tail test. In this permutation test, as in the wilcoxon I suggested, I filtered out non-buyers. The idea behind it is that you don't want that the first hypothesis you tested comes into a play here. You may prefer to separate both assumptions 1)they buy less/more often 2)when they buy it's closer/farther than the initial amount selected.
How to test the difference in two proportions when the outcomes aren't binary?
The first part seems indeed reasonable. Concerning the second part, I think these ratios can't be handled as proportions because they are not related to binary events, this imply that we have no clue
How to test the difference in two proportions when the outcomes aren't binary? The first part seems indeed reasonable. Concerning the second part, I think these ratios can't be handled as proportions because they are not related to binary events, this imply that we have no clue how these ratios are distributed, which excludes z-test (well unless you have a lucky empirical normal distribution, but you mentioned to have not). First Proposition : Wilcoxon test. My suggestion would be to simply compare these ratios by a wilcoxon test. >sales_data$ratios=final_value/initial_value >ratios_A=sales_data$ratios[sale_success==1 & target_control==0] >ratios_B=sales_data$ratios[sale_success==1 & target_control==1] >wilcox.test(ratios_A,ratios_B) Thinking twice on it, this test treat "1 dollar bought for 5 dollars" selected the same as "100 dollars bought for 500 dollars selected". I can understand why you want to avoid it and favor your overall ratio. Second Proposition : Permutation test. In order to keep your measure, what I would suggest then is to craft "your own test" with a permutation test. Under the null hypothesis being in random or treatment group makes no difference. Then, the idea is to randomly relabel which subjects are in the control or treatment group and count how many times a randomized permutation grant an equal or better gap between control and treatment group than the one you initially measure. This gap is measured by the difference of your ratio between the two groups. If you divide this number of success by the number of trials, it gives a p-value. p1 <- sum(sales_data[target_control==1,"final_value"])/sum(sales_data[target_control==1,"initial_value"]) p2 <- sum(sales_data[target_control==0,"final_value"])/sum(sales_data[target_control==0,"initial_value"]) yourGap<-abs(p1-p2) L<-sales_data["target_control"]==1 LfilterOnlyBuyers<-sales_data["sale_success"]==1 count=0 for ( i in 1:10000) { Lperm=sample(L) p1_perm <- sum(sales_data[Lperm,"final_value"])/sum(sales_data[Lperm & LfilterOnlyBuyers,"initial_value"]) p2_perm <- sum(sales_data[!Lperm,"final_value"])/sum(sales_data[!Lperm & LfilterOnlyBuyers,"initial_value"]) if (abs(p1_perm-p2_perm)>=yourGap) { count=count+1 } } pvalue=count/10000 Use absolute values when your compute your gap if you want to two-tail test. In this permutation test, as in the wilcoxon I suggested, I filtered out non-buyers. The idea behind it is that you don't want that the first hypothesis you tested comes into a play here. You may prefer to separate both assumptions 1)they buy less/more often 2)when they buy it's closer/farther than the initial amount selected.
How to test the difference in two proportions when the outcomes aren't binary? The first part seems indeed reasonable. Concerning the second part, I think these ratios can't be handled as proportions because they are not related to binary events, this imply that we have no clue
36,920
What is the term for the product of a probability and its complement?
(So this doesn't go completely unanswered) I've never seen a term for it. You could call it "the variance of a Bernoulli' I guess, or something similar referencing logistic regression, but I like what you called it in the title. I expect it could have several names in particular application areas, but I really don't think I've seen any.
What is the term for the product of a probability and its complement?
(So this doesn't go completely unanswered) I've never seen a term for it. You could call it "the variance of a Bernoulli' I guess, or something similar referencing logistic regression, but I like wha
What is the term for the product of a probability and its complement? (So this doesn't go completely unanswered) I've never seen a term for it. You could call it "the variance of a Bernoulli' I guess, or something similar referencing logistic regression, but I like what you called it in the title. I expect it could have several names in particular application areas, but I really don't think I've seen any.
What is the term for the product of a probability and its complement? (So this doesn't go completely unanswered) I've never seen a term for it. You could call it "the variance of a Bernoulli' I guess, or something similar referencing logistic regression, but I like wha
36,921
Are aov() with Error() same as lmer() of lme4 package in R?
That the two models give identical $p$ values, and that $\sqrt{F}=\sqrt{45.85}=6.77=t$, is strong a priori evidence that models are indeed the same. Both end up fitting the model $$ \begin{split} \mu_{it} & = \beta_0 + b_{0,i} + (\beta_1 + b_{1,i}) t \\ Y_i & \sim \textrm{Normal}(\mu_{it}, \sigma^2) \\ \boldsymbol{b} & \sim \textrm{MVN}(\boldsymbol{0},\Sigma) \end{split} $$ In general, aov() is simpler and faster, but only works for a simpler subset of models. Note that, although nlme::lme can also fit this model, and gets the same $F$ statistic, its heuristic for guessing the correct denominator degrees of freedom is incorrect in this case (it gets 161 rather than 17): library(nlme) anova(lme(Reaction ~ Days, random = ~Days|Subject, sleepstudy)) ## numDF denDF F-value p-value ## (Intercept) 1 161 1454.0766 <.0001 ## Days 1 161 45.8534 <.0001 @amoeba notes correctly that a really important caveat is that these two models only coincide because Days is treated as numerical variable. If it were a categorical factor, then aov with Error(Subject/Days) and lmer with (Days|Subject) would be two different models. To get [the] lmer equivalent of aov [in this case] one would probably need to use (1|Subject)+(1|Subject:Days) [or equivalently (1|Subject/Days)]
Are aov() with Error() same as lmer() of lme4 package in R?
That the two models give identical $p$ values, and that $\sqrt{F}=\sqrt{45.85}=6.77=t$, is strong a priori evidence that models are indeed the same. Both end up fitting the model $$ \begin{split} \mu_
Are aov() with Error() same as lmer() of lme4 package in R? That the two models give identical $p$ values, and that $\sqrt{F}=\sqrt{45.85}=6.77=t$, is strong a priori evidence that models are indeed the same. Both end up fitting the model $$ \begin{split} \mu_{it} & = \beta_0 + b_{0,i} + (\beta_1 + b_{1,i}) t \\ Y_i & \sim \textrm{Normal}(\mu_{it}, \sigma^2) \\ \boldsymbol{b} & \sim \textrm{MVN}(\boldsymbol{0},\Sigma) \end{split} $$ In general, aov() is simpler and faster, but only works for a simpler subset of models. Note that, although nlme::lme can also fit this model, and gets the same $F$ statistic, its heuristic for guessing the correct denominator degrees of freedom is incorrect in this case (it gets 161 rather than 17): library(nlme) anova(lme(Reaction ~ Days, random = ~Days|Subject, sleepstudy)) ## numDF denDF F-value p-value ## (Intercept) 1 161 1454.0766 <.0001 ## Days 1 161 45.8534 <.0001 @amoeba notes correctly that a really important caveat is that these two models only coincide because Days is treated as numerical variable. If it were a categorical factor, then aov with Error(Subject/Days) and lmer with (Days|Subject) would be two different models. To get [the] lmer equivalent of aov [in this case] one would probably need to use (1|Subject)+(1|Subject:Days) [or equivalently (1|Subject/Days)]
Are aov() with Error() same as lmer() of lme4 package in R? That the two models give identical $p$ values, and that $\sqrt{F}=\sqrt{45.85}=6.77=t$, is strong a priori evidence that models are indeed the same. Both end up fitting the model $$ \begin{split} \mu_
36,922
How to test if social structure is non-random and resulting from genetic relatedness – and how to deal with demography effect
Now I will create two distance matrices. First is association matrix derived from co-occurence data represented by OR-SP index. Observed Roost-Sharing Proportion is calculated for each pair of individuals by dividing the number of days two individuals were found together by the number of all possible days they could be together (overlap bewteen first and last recordngs of both individuals). Regarding this step, I think you would be much more successful if you used Agent-based Modeling (ABM). The approach you describe appears convoluted to me, and ABM code will likely be much simpler -- meaning easier to implement, test, refine, and validate -- and also much more justifiable from a theoretical and empirical point of view. The model you are trying to create is somewhat common within the field of Computational Social Science, which includes ABM as a primary modeling/simulation method. I suggest that you use NetLogo (https://ccl.northwestern.edu/netlogo/). Each of your individuals would be agents in NetLogo. Each time step, each agent executes a program that determines its interaction with the environment, other agents, and changes in its internal state. (If you like, you can also add predator agents, but it sounds like you would like to treat mortality rate as a constant probability each time step, or maybe as a function of age and time.) You can program agent movements in a 2D physical space ("patches"), and therefore you can simulate the process of agents meeting other agents and "roosting" together. They can mate and have babies, too, and passing on their genetic material as internal state for the new agents. Along the way, agents form social network ties, by what ever rules you implement. NetLogo has built-in capabilities for dynamic graphs (i.e. social networks) between agents, and also visualization. After you program your simulation, just run it N times with random initial conditions, where N is chosen to be large enough to give you adequate statistical confidence in your final analysis. You can record data (i.e. your "observations") every T steps to simulate yearly data. You only need to use R for statistical analysis at the end the runs. There is a NetLogo extension to import and export data to R here: https://github.com/NetLogo/NetLogo/wiki/Extensions. You might have reservations about this approach since it involves learning a new system and a new language (NetLogo has it's own scripting language). However, it's quite easy to learn (many beginners and non-programmers learn it and use it successfully). But the primary benefit is that you are modeling the phenomena of interest in a very direct and natural way which greatly simplifies the task and greatly reduces the chances of error along the way. I compare social distance with genetic distance by Mantel test. Regarding this step, it think it is vital that you first establish that the space of possible social distances is a metric space and that it has characteristics that make it comparable to genetic distance within the space of possible genomes. Just because you have both in matrix form is not sufficient, in my view (though I don't have experience with this particular test). For example, genetic distance = zero means identical genomes, right? But what does "social distance = zero" mean? If zero is undefined for social distance, then it fails the definition of a metric (see: https://en.wikipedia.org/wiki/Metric_space#Definition). Second, I think you should be measuring change in distances. You have some initial conditions that involve both initial social distances and initial genetic distances. After some number of years, though mating, mortality, and geographic/social mixing, your population has a final set of social distances and genetic distances. The ABM approach makes this more visible. Regarding the Mantel test in particular, you might also evaluate Bayesian alternatives. From the Wikipedia entry: "...the Mantel and partial Mantel tests can be flawed in the presence of spatial auto-correlation and return erroneously low p-values See e.g. Guillot and Rousset, 2013 [3])" A Bayesian approach might be able to avoid this problem and also others associated with Null Hypothesis Significance Testing (NHST). However, I don't have a specific suggestion on a Bayesian approach for this test.
How to test if social structure is non-random and resulting from genetic relatedness – and how to de
Now I will create two distance matrices. First is association matrix derived from co-occurence data represented by OR-SP index. Observed Roost-Sharing Proportion is calculated for each pair of individ
How to test if social structure is non-random and resulting from genetic relatedness – and how to deal with demography effect Now I will create two distance matrices. First is association matrix derived from co-occurence data represented by OR-SP index. Observed Roost-Sharing Proportion is calculated for each pair of individuals by dividing the number of days two individuals were found together by the number of all possible days they could be together (overlap bewteen first and last recordngs of both individuals). Regarding this step, I think you would be much more successful if you used Agent-based Modeling (ABM). The approach you describe appears convoluted to me, and ABM code will likely be much simpler -- meaning easier to implement, test, refine, and validate -- and also much more justifiable from a theoretical and empirical point of view. The model you are trying to create is somewhat common within the field of Computational Social Science, which includes ABM as a primary modeling/simulation method. I suggest that you use NetLogo (https://ccl.northwestern.edu/netlogo/). Each of your individuals would be agents in NetLogo. Each time step, each agent executes a program that determines its interaction with the environment, other agents, and changes in its internal state. (If you like, you can also add predator agents, but it sounds like you would like to treat mortality rate as a constant probability each time step, or maybe as a function of age and time.) You can program agent movements in a 2D physical space ("patches"), and therefore you can simulate the process of agents meeting other agents and "roosting" together. They can mate and have babies, too, and passing on their genetic material as internal state for the new agents. Along the way, agents form social network ties, by what ever rules you implement. NetLogo has built-in capabilities for dynamic graphs (i.e. social networks) between agents, and also visualization. After you program your simulation, just run it N times with random initial conditions, where N is chosen to be large enough to give you adequate statistical confidence in your final analysis. You can record data (i.e. your "observations") every T steps to simulate yearly data. You only need to use R for statistical analysis at the end the runs. There is a NetLogo extension to import and export data to R here: https://github.com/NetLogo/NetLogo/wiki/Extensions. You might have reservations about this approach since it involves learning a new system and a new language (NetLogo has it's own scripting language). However, it's quite easy to learn (many beginners and non-programmers learn it and use it successfully). But the primary benefit is that you are modeling the phenomena of interest in a very direct and natural way which greatly simplifies the task and greatly reduces the chances of error along the way. I compare social distance with genetic distance by Mantel test. Regarding this step, it think it is vital that you first establish that the space of possible social distances is a metric space and that it has characteristics that make it comparable to genetic distance within the space of possible genomes. Just because you have both in matrix form is not sufficient, in my view (though I don't have experience with this particular test). For example, genetic distance = zero means identical genomes, right? But what does "social distance = zero" mean? If zero is undefined for social distance, then it fails the definition of a metric (see: https://en.wikipedia.org/wiki/Metric_space#Definition). Second, I think you should be measuring change in distances. You have some initial conditions that involve both initial social distances and initial genetic distances. After some number of years, though mating, mortality, and geographic/social mixing, your population has a final set of social distances and genetic distances. The ABM approach makes this more visible. Regarding the Mantel test in particular, you might also evaluate Bayesian alternatives. From the Wikipedia entry: "...the Mantel and partial Mantel tests can be flawed in the presence of spatial auto-correlation and return erroneously low p-values See e.g. Guillot and Rousset, 2013 [3])" A Bayesian approach might be able to avoid this problem and also others associated with Null Hypothesis Significance Testing (NHST). However, I don't have a specific suggestion on a Bayesian approach for this test.
How to test if social structure is non-random and resulting from genetic relatedness – and how to de Now I will create two distance matrices. First is association matrix derived from co-occurence data represented by OR-SP index. Observed Roost-Sharing Proportion is calculated for each pair of individ
36,923
How to test if social structure is non-random and resulting from genetic relatedness – and how to deal with demography effect
I think your question might be less of a method question and more of a theoretical question about what you are trying to achieve with your data. If you are interested in co-occurences only, does it really matters that some individuals have more time than other to form ties in order to find subgroups? Now, you could think of some ways to correct for the fact that some individuals have more time to "meet" others because they are caught more often. You could use the strength of ties to reflect this. You could for example divide the strength of a tie by the number of observation windows an individual is present in. The disadvantage of this is that the strength of the tie will be different for individuals in the same dyad, essentially making your network into a weighted directed network where all ties are reciprocated. The disadvantage of this is that the algorithm in the walktrap.community() function ignores edge direction. This means you would need to look for another community detection algorithm. Another way of reducing the problem with individuals having more or less time to "meet" would be to create several snapshots of your network in which you only keep ties that appear at the n previous periods (you will need your specific knowledge of the species studied and the data to determine which value for n makes sense). This means that ties will decay after a while and that will reduce the tendency of the individuals that are present more often to be the most central. The disadvantage is that you end up with several networks that reflect the state of relationships at different time and therefore you will not be able to obtain one stable community membership for each individual. Instead, running your community detection algorithm on each snapshot of the network you will get a more dynamic picture of change in community membership over time. As I said at the beginning, I believe it is a theoretical question more than anything else. You need to ask yourself questions such as: why do I want to classify individuals into groups? What do I think it means to be members of the same group? Answering those questions will inform how you approach the analysis of your network.
How to test if social structure is non-random and resulting from genetic relatedness – and how to de
I think your question might be less of a method question and more of a theoretical question about what you are trying to achieve with your data. If you are interested in co-occurences only, does it r
How to test if social structure is non-random and resulting from genetic relatedness – and how to deal with demography effect I think your question might be less of a method question and more of a theoretical question about what you are trying to achieve with your data. If you are interested in co-occurences only, does it really matters that some individuals have more time than other to form ties in order to find subgroups? Now, you could think of some ways to correct for the fact that some individuals have more time to "meet" others because they are caught more often. You could use the strength of ties to reflect this. You could for example divide the strength of a tie by the number of observation windows an individual is present in. The disadvantage of this is that the strength of the tie will be different for individuals in the same dyad, essentially making your network into a weighted directed network where all ties are reciprocated. The disadvantage of this is that the algorithm in the walktrap.community() function ignores edge direction. This means you would need to look for another community detection algorithm. Another way of reducing the problem with individuals having more or less time to "meet" would be to create several snapshots of your network in which you only keep ties that appear at the n previous periods (you will need your specific knowledge of the species studied and the data to determine which value for n makes sense). This means that ties will decay after a while and that will reduce the tendency of the individuals that are present more often to be the most central. The disadvantage is that you end up with several networks that reflect the state of relationships at different time and therefore you will not be able to obtain one stable community membership for each individual. Instead, running your community detection algorithm on each snapshot of the network you will get a more dynamic picture of change in community membership over time. As I said at the beginning, I believe it is a theoretical question more than anything else. You need to ask yourself questions such as: why do I want to classify individuals into groups? What do I think it means to be members of the same group? Answering those questions will inform how you approach the analysis of your network.
How to test if social structure is non-random and resulting from genetic relatedness – and how to de I think your question might be less of a method question and more of a theoretical question about what you are trying to achieve with your data. If you are interested in co-occurences only, does it r
36,924
Role of base measure in exponential family
Since $p(x|\theta)$ must integrate to 1, $h(x)$ must be non-negative, but that's the only restriction (according to page 111 in this book). However, I think the question highlights a common confusion (at least one that I've had before). There isn't just one exponential family of distributions. Rather, there are many such exponential families as mentioned in the Exponential family Wikipedia article: exponential families are in a sense very natural sets of distributions to consider. The choice of the functions $h$ and $T$ specify the exponential family (i.e. model) and the parameter vector $\theta$ corresponds to a particular member (i.e. distribution) in that family. Indeed, if you choose a some fixed degrees of freedom for the t-distribution (let's say $\nu = 3$), you could as you say let $T(x) = 0$ and $h(x) = t(x|\nu=3)$ which, following the formula on from the Student's t-distribution Wikipedia article, should give $$ h(x) = \frac{1} {\sqrt{3\pi}\,\Gamma(\frac{3}{2})} \left(1+\frac{x^2}{3} \right)^{-2}\!.$$ However, this doesn't give you the family of t-distributions, i.e. the set of functions $\{t(\cdot|\nu) : \nu > 0\}$. With this base distribution, you could construct a more interesting exponential family of distributions by using more interesting sufficient statistics $T(x)$, but you would not be able to design $T$ such that parameters $\theta$ would correspond to the $\nu$ parameter of the t-distribution.
Role of base measure in exponential family
Since $p(x|\theta)$ must integrate to 1, $h(x)$ must be non-negative, but that's the only restriction (according to page 111 in this book). However, I think the question highlights a common confusion
Role of base measure in exponential family Since $p(x|\theta)$ must integrate to 1, $h(x)$ must be non-negative, but that's the only restriction (according to page 111 in this book). However, I think the question highlights a common confusion (at least one that I've had before). There isn't just one exponential family of distributions. Rather, there are many such exponential families as mentioned in the Exponential family Wikipedia article: exponential families are in a sense very natural sets of distributions to consider. The choice of the functions $h$ and $T$ specify the exponential family (i.e. model) and the parameter vector $\theta$ corresponds to a particular member (i.e. distribution) in that family. Indeed, if you choose a some fixed degrees of freedom for the t-distribution (let's say $\nu = 3$), you could as you say let $T(x) = 0$ and $h(x) = t(x|\nu=3)$ which, following the formula on from the Student's t-distribution Wikipedia article, should give $$ h(x) = \frac{1} {\sqrt{3\pi}\,\Gamma(\frac{3}{2})} \left(1+\frac{x^2}{3} \right)^{-2}\!.$$ However, this doesn't give you the family of t-distributions, i.e. the set of functions $\{t(\cdot|\nu) : \nu > 0\}$. With this base distribution, you could construct a more interesting exponential family of distributions by using more interesting sufficient statistics $T(x)$, but you would not be able to design $T$ such that parameters $\theta$ would correspond to the $\nu$ parameter of the t-distribution.
Role of base measure in exponential family Since $p(x|\theta)$ must integrate to 1, $h(x)$ must be non-negative, but that's the only restriction (according to page 111 in this book). However, I think the question highlights a common confusion
36,925
Role of base measure in exponential family
The central restriction is that $h(x)$ cannot depend on the parameters $\theta$. Intuitively, the base measure is the distribution of $x$ when the exponential term is given no weight i.e. $\theta=0$. As mentioned in a comment to your question, this is related to the distinction between a family of distributions being an exponential family in itself vs. any single distribution being the member of some family.
Role of base measure in exponential family
The central restriction is that $h(x)$ cannot depend on the parameters $\theta$. Intuitively, the base measure is the distribution of $x$ when the exponential term is given no weight i.e. $\theta=0$.
Role of base measure in exponential family The central restriction is that $h(x)$ cannot depend on the parameters $\theta$. Intuitively, the base measure is the distribution of $x$ when the exponential term is given no weight i.e. $\theta=0$. As mentioned in a comment to your question, this is related to the distinction between a family of distributions being an exponential family in itself vs. any single distribution being the member of some family.
Role of base measure in exponential family The central restriction is that $h(x)$ cannot depend on the parameters $\theta$. Intuitively, the base measure is the distribution of $x$ when the exponential term is given no weight i.e. $\theta=0$.
36,926
Why variance of dependent variable differs from variance of error term in linear regression?
G. Seber assumes that $X\beta$ is constant. You do not assume that in your verification. If $X$ is random, then $Var(Y)=Var(X\beta+\varepsilon)=Var(X\beta)+Var(\varepsilon)$, with additional assumption that $X$ is independent from $\varepsilon$. In theory if $X$ is fixed then $Var(X\beta)=0$. Since you take a sample $X\beta$ clearly varies, hence $var(X\beta)$ (I made a distinction to denote empirical variance by $var$) is not zero. Furthermore it should be noted that G. Seber is talking about theoretical model, so the variances are theoretical. This means that verifying it with single sample is bound to be troublesome, i.e. you cannot expect empirical variances to coincide, if theoretical variances do, unless your explicitly prove that they do. G. Seber does not make a claim that empirical variances coincide. Concerning your last question, recall that definition of $R^2$ is the following: $$R^2=1-\frac{SS_{res}}{SS_{tot}},$$ where $SS_{tot}$ happens to be $(n-1)var(y)$. So $(1-R^2)var(y)$ is the residual sum of squares divided by $n-1$. Now residual sum of squares is $\sum(y_i-x_i\hat\beta)^2$, where $\hat\beta$ is the estimate of true $\beta$. Since your model is the correct one, the $\hat\beta$ is close to the true $\beta$, so $y_i-x_i\hat\beta\approx y_i-x_i\beta=\varepsilon_i$. Since $var(\epsilon)=\frac{1}{n-1}(\sum_{i=1}\varepsilon_i-\bar\varepsilon)^2$ and $\bar\epsilon=\frac{1}{n}\sum\varepsilon\approx 0$ in your case you get your relationship. Which as you can see is not so much related to original question.
Why variance of dependent variable differs from variance of error term in linear regression?
G. Seber assumes that $X\beta$ is constant. You do not assume that in your verification. If $X$ is random, then $Var(Y)=Var(X\beta+\varepsilon)=Var(X\beta)+Var(\varepsilon)$, with additional assumptio
Why variance of dependent variable differs from variance of error term in linear regression? G. Seber assumes that $X\beta$ is constant. You do not assume that in your verification. If $X$ is random, then $Var(Y)=Var(X\beta+\varepsilon)=Var(X\beta)+Var(\varepsilon)$, with additional assumption that $X$ is independent from $\varepsilon$. In theory if $X$ is fixed then $Var(X\beta)=0$. Since you take a sample $X\beta$ clearly varies, hence $var(X\beta)$ (I made a distinction to denote empirical variance by $var$) is not zero. Furthermore it should be noted that G. Seber is talking about theoretical model, so the variances are theoretical. This means that verifying it with single sample is bound to be troublesome, i.e. you cannot expect empirical variances to coincide, if theoretical variances do, unless your explicitly prove that they do. G. Seber does not make a claim that empirical variances coincide. Concerning your last question, recall that definition of $R^2$ is the following: $$R^2=1-\frac{SS_{res}}{SS_{tot}},$$ where $SS_{tot}$ happens to be $(n-1)var(y)$. So $(1-R^2)var(y)$ is the residual sum of squares divided by $n-1$. Now residual sum of squares is $\sum(y_i-x_i\hat\beta)^2$, where $\hat\beta$ is the estimate of true $\beta$. Since your model is the correct one, the $\hat\beta$ is close to the true $\beta$, so $y_i-x_i\hat\beta\approx y_i-x_i\beta=\varepsilon_i$. Since $var(\epsilon)=\frac{1}{n-1}(\sum_{i=1}\varepsilon_i-\bar\varepsilon)^2$ and $\bar\epsilon=\frac{1}{n}\sum\varepsilon\approx 0$ in your case you get your relationship. Which as you can see is not so much related to original question.
Why variance of dependent variable differs from variance of error term in linear regression? G. Seber assumes that $X\beta$ is constant. You do not assume that in your verification. If $X$ is random, then $Var(Y)=Var(X\beta+\varepsilon)=Var(X\beta)+Var(\varepsilon)$, with additional assumptio
36,927
Can bootstrap re-sampling be a re-sample of a smaller size [duplicate]
To your first question, yes. This is called block bootstrapping. Any time you think you have dependencies in your data, you should bootstrap groups of observations to capture the dependencies. The things you are bootstrapping over should be independent. To your second question, the answer is also yes. You can make a sample half as big if you want. This won't give you correct standard errors of course. It will give you the standard errors correct for a sample half as big. Perhaps, in your application, you can show analytically that the standard errors are proportional to $1/\sqrt{N}$. In that case, you could bootstrap a sample a quarter as big, get the standard error you care about, and then multiply it by a factor of $1/2$. Finally, four hours isn't that long. If you get to the exact model you want, a 100 replication bootstrap is only going to take 400 hours. That's 400/24 = 17 days. What's the problem with that? It's less than a month. Dividing the sample by 4 is only going to reduce it to 4 days. Also, are you taking advantage of parallel processing? I don't know how you are running your analysis or how you plan to bootstrap, but bootstrapping is about the most parallelizable thing ever. With enough processors (100), you could do the whole bootstrap in 4 hours. This is very plausible if you have access to a high performance computing cluster. Even without that, you can probably speed things up by a factor of four just using your desktop computer properly. It's likely got multiple processors each of which can likely do more than one thing at a time.
Can bootstrap re-sampling be a re-sample of a smaller size [duplicate]
To your first question, yes. This is called block bootstrapping. Any time you think you have dependencies in your data, you should bootstrap groups of observations to capture the dependencies. The
Can bootstrap re-sampling be a re-sample of a smaller size [duplicate] To your first question, yes. This is called block bootstrapping. Any time you think you have dependencies in your data, you should bootstrap groups of observations to capture the dependencies. The things you are bootstrapping over should be independent. To your second question, the answer is also yes. You can make a sample half as big if you want. This won't give you correct standard errors of course. It will give you the standard errors correct for a sample half as big. Perhaps, in your application, you can show analytically that the standard errors are proportional to $1/\sqrt{N}$. In that case, you could bootstrap a sample a quarter as big, get the standard error you care about, and then multiply it by a factor of $1/2$. Finally, four hours isn't that long. If you get to the exact model you want, a 100 replication bootstrap is only going to take 400 hours. That's 400/24 = 17 days. What's the problem with that? It's less than a month. Dividing the sample by 4 is only going to reduce it to 4 days. Also, are you taking advantage of parallel processing? I don't know how you are running your analysis or how you plan to bootstrap, but bootstrapping is about the most parallelizable thing ever. With enough processors (100), you could do the whole bootstrap in 4 hours. This is very plausible if you have access to a high performance computing cluster. Even without that, you can probably speed things up by a factor of four just using your desktop computer properly. It's likely got multiple processors each of which can likely do more than one thing at a time.
Can bootstrap re-sampling be a re-sample of a smaller size [duplicate] To your first question, yes. This is called block bootstrapping. Any time you think you have dependencies in your data, you should bootstrap groups of observations to capture the dependencies. The
36,928
Can bootstrap re-sampling be a re-sample of a smaller size [duplicate]
This was asked a long time ago, but I wrote an answer for a very similar question (maybe these should be linked?) and will post it here as well in case anyone discovers this question in future. For your first question, @Bill is right -- you should "block bootstrap" the individuals to ensure the dependence structures within each individual's data are respected. For your second question, in short, the answer is yes: you can do this in many settings, but you should correct for the sample size, since the estimator you are determining is actually different (i.e., for the sample mean, $\frac{1}{N}\sum_{i=1}^N X_i$ is a different estimator than $\frac{1}{M}\sum_{i=1}^M X_i$ if $M \ne N$). This approach is usually called the $M$ out of $N$ boostrap, and it works (in the sense of being consistent) in most settings that the "traditional" bootstrap does, as well as some settings in which it doesn't. The reason why is that many bootstrap consistency arguments use estimators of the form $\frac{1}{\sqrt{N}} (T_N - \mu)$, where $X_1, \ldots, X_N$ are random variables and $\mu$ is some parameter of the underlying distribution. For example, for the sample mean, $T_N = \frac{1}{N} \sum_{i=1}^N X_i$ and $\mu = \mathbb{E}(X_1)$. Many bootstrap consistency proofs argue that, as $N \to \infty$, given some finite sample $\{x_1, \ldots, x_N\}$ and associated point estimate $\hat{\mu}_N = T_N(x_1, \ldots, x_N)$, $$ \sqrt{N}(T_N(X_1^*, \ldots, X_N^*) - \hat{\mu}_N) \overset{D}{\to} \sqrt{N}(T_N(X_1, \ldots, X_N) - \mu) \tag{1} \label{convergence} $$ where the $X_i$ are drawn from the true underlying distribution and the $X_i^*$ are drawn with replacement from $\{x_1, \ldots, x_N\}$. However, we could also use shorter samples of length $M < N$ and consider the estimator $$ \sqrt{M}(T_M(X_1^*, \ldots, X_M^*) - \hat{\mu}_N). \tag{2} \label{m_out_of_n} $$ It turns out that, as $M, N \to \infty$, the estimator (\ref{m_out_of_n}) has s the same limiting distribution as above in most settings where (\ref{convergence}) holds and some where it does not. In this case, (\ref{convergence}) and (\ref{m_out_of_n}) have the same limiting distribution, motivating the correction factor $\sqrt{\frac{M}{N}}$ in e.g. the sample standard deviation. These arguments are all asymptotic and hold only in the limit $M, N \to \infty$. For this to work, it's important not to pick $M$ too small. There's some theory (e.g. Bickel & Sakov below) as to how to pick the optimal $M$ as a function of $N$ to get the best theoretical results, but in your case computational resources may be the deciding factor. For some intuition: in many cases, we have $\hat{\mu}_N \overset{D}{\to} \mu$ as $N \to \infty$, so that $$ \sqrt{N}(T_N(X_1, \ldots, X_N) - \mu), \tag{3} \label{m_out_of_n_intuition} $$ can be thought of a bit like an $m$ out of $n$ bootstrap with $m=N$ and $n = \infty$ (I'm using lower case to avoid notation confusion). In this way, emulating the distribution of (\ref{m_out_of_n_intuition}) using an $M$ out of $N$ bootstrap with $M < N$ is a more ``right'' thing to do than the traditional ($N$ out of $N$) kind. An added bonus in your case is that it's less computationally expensive to evaluate. I know of two good sources in case anyone wants more details on using bootstrap samples shorter than the original sample: PJ Bickel, F Goetze, WR van Zwet. 1997. Resampling fewer than $n$ observations: gains, losses and remedies for losses. Statistica Sinica. PJ Bickel, A Sakov. 2008. On the choice of $m$ in the $m$ ouf of $n$ bootstrap and confidence bounds for extrema. Statistica Sinica.
Can bootstrap re-sampling be a re-sample of a smaller size [duplicate]
This was asked a long time ago, but I wrote an answer for a very similar question (maybe these should be linked?) and will post it here as well in case anyone discovers this question in future. For yo
Can bootstrap re-sampling be a re-sample of a smaller size [duplicate] This was asked a long time ago, but I wrote an answer for a very similar question (maybe these should be linked?) and will post it here as well in case anyone discovers this question in future. For your first question, @Bill is right -- you should "block bootstrap" the individuals to ensure the dependence structures within each individual's data are respected. For your second question, in short, the answer is yes: you can do this in many settings, but you should correct for the sample size, since the estimator you are determining is actually different (i.e., for the sample mean, $\frac{1}{N}\sum_{i=1}^N X_i$ is a different estimator than $\frac{1}{M}\sum_{i=1}^M X_i$ if $M \ne N$). This approach is usually called the $M$ out of $N$ boostrap, and it works (in the sense of being consistent) in most settings that the "traditional" bootstrap does, as well as some settings in which it doesn't. The reason why is that many bootstrap consistency arguments use estimators of the form $\frac{1}{\sqrt{N}} (T_N - \mu)$, where $X_1, \ldots, X_N$ are random variables and $\mu$ is some parameter of the underlying distribution. For example, for the sample mean, $T_N = \frac{1}{N} \sum_{i=1}^N X_i$ and $\mu = \mathbb{E}(X_1)$. Many bootstrap consistency proofs argue that, as $N \to \infty$, given some finite sample $\{x_1, \ldots, x_N\}$ and associated point estimate $\hat{\mu}_N = T_N(x_1, \ldots, x_N)$, $$ \sqrt{N}(T_N(X_1^*, \ldots, X_N^*) - \hat{\mu}_N) \overset{D}{\to} \sqrt{N}(T_N(X_1, \ldots, X_N) - \mu) \tag{1} \label{convergence} $$ where the $X_i$ are drawn from the true underlying distribution and the $X_i^*$ are drawn with replacement from $\{x_1, \ldots, x_N\}$. However, we could also use shorter samples of length $M < N$ and consider the estimator $$ \sqrt{M}(T_M(X_1^*, \ldots, X_M^*) - \hat{\mu}_N). \tag{2} \label{m_out_of_n} $$ It turns out that, as $M, N \to \infty$, the estimator (\ref{m_out_of_n}) has s the same limiting distribution as above in most settings where (\ref{convergence}) holds and some where it does not. In this case, (\ref{convergence}) and (\ref{m_out_of_n}) have the same limiting distribution, motivating the correction factor $\sqrt{\frac{M}{N}}$ in e.g. the sample standard deviation. These arguments are all asymptotic and hold only in the limit $M, N \to \infty$. For this to work, it's important not to pick $M$ too small. There's some theory (e.g. Bickel & Sakov below) as to how to pick the optimal $M$ as a function of $N$ to get the best theoretical results, but in your case computational resources may be the deciding factor. For some intuition: in many cases, we have $\hat{\mu}_N \overset{D}{\to} \mu$ as $N \to \infty$, so that $$ \sqrt{N}(T_N(X_1, \ldots, X_N) - \mu), \tag{3} \label{m_out_of_n_intuition} $$ can be thought of a bit like an $m$ out of $n$ bootstrap with $m=N$ and $n = \infty$ (I'm using lower case to avoid notation confusion). In this way, emulating the distribution of (\ref{m_out_of_n_intuition}) using an $M$ out of $N$ bootstrap with $M < N$ is a more ``right'' thing to do than the traditional ($N$ out of $N$) kind. An added bonus in your case is that it's less computationally expensive to evaluate. I know of two good sources in case anyone wants more details on using bootstrap samples shorter than the original sample: PJ Bickel, F Goetze, WR van Zwet. 1997. Resampling fewer than $n$ observations: gains, losses and remedies for losses. Statistica Sinica. PJ Bickel, A Sakov. 2008. On the choice of $m$ in the $m$ ouf of $n$ bootstrap and confidence bounds for extrema. Statistica Sinica.
Can bootstrap re-sampling be a re-sample of a smaller size [duplicate] This was asked a long time ago, but I wrote an answer for a very similar question (maybe these should be linked?) and will post it here as well in case anyone discovers this question in future. For yo
36,929
What is a reasonable noninformative prior for quadratic and cubic coefficients in Bayesian polynomial regression?
To be honest, in the absence of a clear theory, I'd be inclined to frame the model in terms of orthogonal polynomials, and then put priors on the higher order terms that indicate that I expect them to be small -- which would tend to pull the posterior toward zero, rather than be uninformative. If I wanted an uninformative prior, I'd still be tempted to do it with orthogonal polynomials. Edit: Elvis' question about why orthogonal polynomials is important -- One big advantage of orthogonal polynomials is that (because of the orthogonality) lower order coefficients are not affected if the higher order coefficients are shrunk or even set to 0. It makes it more sensible to try to do things like order selection with averaging of parameter estimates across models. (It's less important if interest is only on the function as a whole, but sometimes the values of particular coefficients, or functions of them, can be important.) (There may also be some advantages in accuracy and computational effort; in particular if you're doing all possible degrees of polynomial, there can be an advantage in effort.) The polynomials are orthogonal in the following sense - $\sum_i p_j(x_i)\,p_k(x_i)=0$ (when $j\neq k$).
What is a reasonable noninformative prior for quadratic and cubic coefficients in Bayesian polynomia
To be honest, in the absence of a clear theory, I'd be inclined to frame the model in terms of orthogonal polynomials, and then put priors on the higher order terms that indicate that I expect them t
What is a reasonable noninformative prior for quadratic and cubic coefficients in Bayesian polynomial regression? To be honest, in the absence of a clear theory, I'd be inclined to frame the model in terms of orthogonal polynomials, and then put priors on the higher order terms that indicate that I expect them to be small -- which would tend to pull the posterior toward zero, rather than be uninformative. If I wanted an uninformative prior, I'd still be tempted to do it with orthogonal polynomials. Edit: Elvis' question about why orthogonal polynomials is important -- One big advantage of orthogonal polynomials is that (because of the orthogonality) lower order coefficients are not affected if the higher order coefficients are shrunk or even set to 0. It makes it more sensible to try to do things like order selection with averaging of parameter estimates across models. (It's less important if interest is only on the function as a whole, but sometimes the values of particular coefficients, or functions of them, can be important.) (There may also be some advantages in accuracy and computational effort; in particular if you're doing all possible degrees of polynomial, there can be an advantage in effort.) The polynomials are orthogonal in the following sense - $\sum_i p_j(x_i)\,p_k(x_i)=0$ (when $j\neq k$).
What is a reasonable noninformative prior for quadratic and cubic coefficients in Bayesian polynomia To be honest, in the absence of a clear theory, I'd be inclined to frame the model in terms of orthogonal polynomials, and then put priors on the higher order terms that indicate that I expect them t
36,930
What is a reasonable noninformative prior for quadratic and cubic coefficients in Bayesian polynomial regression?
Have you tried to use Jeffrey's prior? This is a standard method for generating non-informative priors (though I admit I have no experience with complicated likelihood functions you have mentioned) http://en.wikipedia.org/wiki/Jeffreys_prior The basic idea is that a non-informative prior will contain no information on transformation and relates to the Fisher information which I don't think should not be too complicated to find (finding posteriors is another issue). Apoligies if you have already tried this! A slight addendum to my previous answer It just occurred to me that the problem is a standard linear regression Consider a matrix $Z$ whose $i^{th}$ row is given by $[1, x_{i}, x_{i}^{2}....]$. Your model is essentially $ \mu = Z\beta + \epsilon$ where $\epsilon\sim$ $N(0,\sigma^{2})$
What is a reasonable noninformative prior for quadratic and cubic coefficients in Bayesian polynomia
Have you tried to use Jeffrey's prior? This is a standard method for generating non-informative priors (though I admit I have no experience with complicated likelihood functions you have mentioned) ht
What is a reasonable noninformative prior for quadratic and cubic coefficients in Bayesian polynomial regression? Have you tried to use Jeffrey's prior? This is a standard method for generating non-informative priors (though I admit I have no experience with complicated likelihood functions you have mentioned) http://en.wikipedia.org/wiki/Jeffreys_prior The basic idea is that a non-informative prior will contain no information on transformation and relates to the Fisher information which I don't think should not be too complicated to find (finding posteriors is another issue). Apoligies if you have already tried this! A slight addendum to my previous answer It just occurred to me that the problem is a standard linear regression Consider a matrix $Z$ whose $i^{th}$ row is given by $[1, x_{i}, x_{i}^{2}....]$. Your model is essentially $ \mu = Z\beta + \epsilon$ where $\epsilon\sim$ $N(0,\sigma^{2})$
What is a reasonable noninformative prior for quadratic and cubic coefficients in Bayesian polynomia Have you tried to use Jeffrey's prior? This is a standard method for generating non-informative priors (though I admit I have no experience with complicated likelihood functions you have mentioned) ht
36,931
Null deviance in glm R
Thanks to @jbaums. y = c(2,3,6,7,8,9,10,12,15) x = c(-1, -1, 0, 0, 0, 0, 1, 1, 1) For the no intercept null model we have: $$ Y \sim {\rm Poisson}(1) $$ leading to the following null model likelihood term: $$ \mathcal L(y) = \exp(-1)/y! $$ or loglikelihood term: $$ l(y) = -1 - \log(y!) $$ The log-likehood for the null model is then the sum of these terms: lnull = sum(-1 - log(factorial(y))) As usual the log-likelhood for the saturated model is: lf = sum(y * log(y) - y - log(factorial(y))) so the null deviance is: 2*(lf - lnull) # [1] 191.8602
Null deviance in glm R
Thanks to @jbaums. y = c(2,3,6,7,8,9,10,12,15) x = c(-1, -1, 0, 0, 0, 0, 1, 1, 1) For the no intercept null model we have: $$ Y \sim {\rm Poisson}(1) $$ leading to the following null model likelih
Null deviance in glm R Thanks to @jbaums. y = c(2,3,6,7,8,9,10,12,15) x = c(-1, -1, 0, 0, 0, 0, 1, 1, 1) For the no intercept null model we have: $$ Y \sim {\rm Poisson}(1) $$ leading to the following null model likelihood term: $$ \mathcal L(y) = \exp(-1)/y! $$ or loglikelihood term: $$ l(y) = -1 - \log(y!) $$ The log-likehood for the null model is then the sum of these terms: lnull = sum(-1 - log(factorial(y))) As usual the log-likelhood for the saturated model is: lf = sum(y * log(y) - y - log(factorial(y))) so the null deviance is: 2*(lf - lnull) # [1] 191.8602
Null deviance in glm R Thanks to @jbaums. y = c(2,3,6,7,8,9,10,12,15) x = c(-1, -1, 0, 0, 0, 0, 1, 1, 1) For the no intercept null model we have: $$ Y \sim {\rm Poisson}(1) $$ leading to the following null model likelih
36,932
Updating bias with RBMs (Restricted Boltzmann Machines)
TLDR For $n$-step Contrastive Divergence, update visible bias $b_j$, based on data vector $\mathbf{d}$ using: $$ b_j^{(t)} \gets b_j^{(t-1)} + \eta \left( d_j - \hat{v}_j^{(n)} \right) $$ Update hidden bias $h_i$ using: $$ c_i^{(t)} \gets c_i^{(t-1)} + \eta \left( \hat{h}_{i}^{(0)} - \hat{h}_{i}^{(n)} \right) $$ Where $b_j^{(t)}$ and $c_i^{(t)}$ are the biases after update number t, $\eta$ is the learning rate, $d_j$ is the $j$th component of the data vector, and where $\hat{h}_j^{(n)}$ and $\hat{v}_j^{(n)}$ are the probabilities of hidden unit $i$ and visible unit $j$ being active once the RBM has been exposed to the data and run for $n$ steps. This assumes a minibatch size of 1; for practical minibatch size $k$, average the updates obtained over the $k$ data vectors. Full explanation I had the same trouble. A good way to think of it is that the biases are themselves just weights. Often in neural network models, the bias of a unit is modeled as the weight of a link connecting the unit in question to an "always on" unit, i.e., an imaginary unit whose activation is always 1. In the RBM case, that would mean that you think of there being one extra visible unit whose output is always 1. This visible unit attaches to each of the hidden units (just like any other visible unit does), and the weight of these connections are the biases of the respective hidden units. Similarly, the biases of the visible units can be modeled by imagining an extra hidden unit, whose value is always one, and which connects to each of the visible units, with the weights of these connections being the visible biases. You could even implement your RBM this way, but I don't think people usually do that. The point is that, thinking about it in this way, you can use (essentially) the same update rule for the biases as you do for the weights, since biases are just weights connecting to "always on" units. Let's be concrete. I'll write down the usual $n$-step Contrastive Divergence update rule, ignoring regularization for simplicity. Also for simplicity, this update rule is for a "minibatch" of 1 data vector. The update for a minibatch with $k$ vectors is the average update over all $k$ vectors. The update rule is: $$ W_{i,j}^{(t)} \gets W_{i,j}^{(t-1)} + \eta\left( \hat{h}_{i}^{(0)} \cdot d_j - \hat{h}_{i}^{(n)} \cdot v_j^{(n)} \right) $$ where: $W_{i,j}^{(t)}$ is the weight connecting visible unit $v_j$ to hidden unit $h_i$ after update number $t$ $\eta$ is the learning rate $\hat{h}_{i}^{(n)}$ is the probability of hidden unit $i$ being active once the machine has been exposed to data vector $\mathbf{d}$ and evolved for $n$ steps. which means that $\hat{h}_{i}^{(0)}$ is just the activation of hidden unit $i$ in immediate response to the data vector $d_j$ is the $j$th component of the data vector $\mathbf{d}$ $v_{j}^{(n)}$ is the state of visible unit $j$ once the machine has been exposed to the data vector and evolved for $n$ steps. (Some people use $i$ to index the visible units and $j$ to index the hidden ones, but still write $W_{i,j}$ --- it doesn't matter as long as you multiply the correct values together.) Be careful to distinguish the "state" of a unit, denoted by $h_i^{(n)}$ or $v_j^{(n)}$, and the "activation" of a unit, denoted $\hat{h}_i^{(n)}$ or $\hat{v}_i^{(n)}$. The state of a unit is either 0 or 1, whereas the activation is any real number between 0 and 1. If the activation is 0.8, then the state is likely to be 1, but 20% of the time it will be 0. By treating biases as weights to "always on" units, you'll find that the equation above simplifies to the ones given for bias updates under the "TLDR". There is one slight difference, however, in the update to visible biases: here the visible activation is used instead of the state. The activation has the same expected value, but has lower variance than the state, so this reduces noise in the learning signal. See this guide $\S3$ for a brief discussion of when using activations instead of states is desirable.
Updating bias with RBMs (Restricted Boltzmann Machines)
TLDR For $n$-step Contrastive Divergence, update visible bias $b_j$, based on data vector $\mathbf{d}$ using: $$ b_j^{(t)} \gets b_j^{(t-1)} + \eta \left( d_j - \hat{v}_j^{(n)} \right) $$ Update hidde
Updating bias with RBMs (Restricted Boltzmann Machines) TLDR For $n$-step Contrastive Divergence, update visible bias $b_j$, based on data vector $\mathbf{d}$ using: $$ b_j^{(t)} \gets b_j^{(t-1)} + \eta \left( d_j - \hat{v}_j^{(n)} \right) $$ Update hidden bias $h_i$ using: $$ c_i^{(t)} \gets c_i^{(t-1)} + \eta \left( \hat{h}_{i}^{(0)} - \hat{h}_{i}^{(n)} \right) $$ Where $b_j^{(t)}$ and $c_i^{(t)}$ are the biases after update number t, $\eta$ is the learning rate, $d_j$ is the $j$th component of the data vector, and where $\hat{h}_j^{(n)}$ and $\hat{v}_j^{(n)}$ are the probabilities of hidden unit $i$ and visible unit $j$ being active once the RBM has been exposed to the data and run for $n$ steps. This assumes a minibatch size of 1; for practical minibatch size $k$, average the updates obtained over the $k$ data vectors. Full explanation I had the same trouble. A good way to think of it is that the biases are themselves just weights. Often in neural network models, the bias of a unit is modeled as the weight of a link connecting the unit in question to an "always on" unit, i.e., an imaginary unit whose activation is always 1. In the RBM case, that would mean that you think of there being one extra visible unit whose output is always 1. This visible unit attaches to each of the hidden units (just like any other visible unit does), and the weight of these connections are the biases of the respective hidden units. Similarly, the biases of the visible units can be modeled by imagining an extra hidden unit, whose value is always one, and which connects to each of the visible units, with the weights of these connections being the visible biases. You could even implement your RBM this way, but I don't think people usually do that. The point is that, thinking about it in this way, you can use (essentially) the same update rule for the biases as you do for the weights, since biases are just weights connecting to "always on" units. Let's be concrete. I'll write down the usual $n$-step Contrastive Divergence update rule, ignoring regularization for simplicity. Also for simplicity, this update rule is for a "minibatch" of 1 data vector. The update for a minibatch with $k$ vectors is the average update over all $k$ vectors. The update rule is: $$ W_{i,j}^{(t)} \gets W_{i,j}^{(t-1)} + \eta\left( \hat{h}_{i}^{(0)} \cdot d_j - \hat{h}_{i}^{(n)} \cdot v_j^{(n)} \right) $$ where: $W_{i,j}^{(t)}$ is the weight connecting visible unit $v_j$ to hidden unit $h_i$ after update number $t$ $\eta$ is the learning rate $\hat{h}_{i}^{(n)}$ is the probability of hidden unit $i$ being active once the machine has been exposed to data vector $\mathbf{d}$ and evolved for $n$ steps. which means that $\hat{h}_{i}^{(0)}$ is just the activation of hidden unit $i$ in immediate response to the data vector $d_j$ is the $j$th component of the data vector $\mathbf{d}$ $v_{j}^{(n)}$ is the state of visible unit $j$ once the machine has been exposed to the data vector and evolved for $n$ steps. (Some people use $i$ to index the visible units and $j$ to index the hidden ones, but still write $W_{i,j}$ --- it doesn't matter as long as you multiply the correct values together.) Be careful to distinguish the "state" of a unit, denoted by $h_i^{(n)}$ or $v_j^{(n)}$, and the "activation" of a unit, denoted $\hat{h}_i^{(n)}$ or $\hat{v}_i^{(n)}$. The state of a unit is either 0 or 1, whereas the activation is any real number between 0 and 1. If the activation is 0.8, then the state is likely to be 1, but 20% of the time it will be 0. By treating biases as weights to "always on" units, you'll find that the equation above simplifies to the ones given for bias updates under the "TLDR". There is one slight difference, however, in the update to visible biases: here the visible activation is used instead of the state. The activation has the same expected value, but has lower variance than the state, so this reduces noise in the learning signal. See this guide $\S3$ for a brief discussion of when using activations instead of states is desirable.
Updating bias with RBMs (Restricted Boltzmann Machines) TLDR For $n$-step Contrastive Divergence, update visible bias $b_j$, based on data vector $\mathbf{d}$ using: $$ b_j^{(t)} \gets b_j^{(t-1)} + \eta \left( d_j - \hat{v}_j^{(n)} \right) $$ Update hidde
36,933
Should I use epochs > 1 when training data is unlimited?
If you have access to unlimited data, unless the order in which that data is generated has an influence on the data, it is better not to have epochs and just train for as long as desired while synthetising examples on the fly. (You want each of your examples to be iid). However, if your data generating process is biased, for example if a variable X taking values in $\{0,1\}$ has its $0$ values generated first, it will quite probably be better to generate a finite sample and shuffle it, and then train with several epochs (possibly even shuffling between epochs. Otherwise, you will always "show" your $0$ examples before the $1$ examples, and after a long period of learning, the network will only have seen $1$'s in its recent past and thus never fitted to the $0$'s.
Should I use epochs > 1 when training data is unlimited?
If you have access to unlimited data, unless the order in which that data is generated has an influence on the data, it is better not to have epochs and just train for as long as desired while synthet
Should I use epochs > 1 when training data is unlimited? If you have access to unlimited data, unless the order in which that data is generated has an influence on the data, it is better not to have epochs and just train for as long as desired while synthetising examples on the fly. (You want each of your examples to be iid). However, if your data generating process is biased, for example if a variable X taking values in $\{0,1\}$ has its $0$ values generated first, it will quite probably be better to generate a finite sample and shuffle it, and then train with several epochs (possibly even shuffling between epochs. Otherwise, you will always "show" your $0$ examples before the $1$ examples, and after a long period of learning, the network will only have seen $1$'s in its recent past and thus never fitted to the $0$'s.
Should I use epochs > 1 when training data is unlimited? If you have access to unlimited data, unless the order in which that data is generated has an influence on the data, it is better not to have epochs and just train for as long as desired while synthet
36,934
Should I use epochs > 1 when training data is unlimited?
For this issue you can use Online learning. Defenition you can find at Wikipedia. More information about online learning in NN you can check at this article.
Should I use epochs > 1 when training data is unlimited?
For this issue you can use Online learning. Defenition you can find at Wikipedia. More information about online learning in NN you can check at this article.
Should I use epochs > 1 when training data is unlimited? For this issue you can use Online learning. Defenition you can find at Wikipedia. More information about online learning in NN you can check at this article.
Should I use epochs > 1 when training data is unlimited? For this issue you can use Online learning. Defenition you can find at Wikipedia. More information about online learning in NN you can check at this article.
36,935
Distribution of the Levenshtein distance between two random strings
I guess it is not a direct answer, but you can try to simulate the scenario and check the empirical distribution to have a rough idea (R code below). So it seems that for strings longer than ~ 100 the distribution is symmetric and quite narrow around .53 times the length of the string. # dependencies library(ggplot2); theme_set(theme_classic()) library(parallel) library(RecordLinkage) # settings alphabet <- c("A", "C", "G", "T") Nsim <- 1e3 read_lengths <- seq(60, 500, 20) # function to create a random string of length "n" using letters of the alphabet "alph" random_read <- function(n, alph=alphabet) paste(sample(alph, size=n, replace=T), collapse="") # simulate res <- mclapply(read_lengths, function(N) replicate(Nsim, levenshteinDist(random_read(N), random_read(N))), mc.cores=6) # arrange results as data.frame res_df <- data.frame(dist=unlist(res), length=rep(read_lengths, sapply(res, length))) # plot densities ggplot(res_df, aes(x=dist / length, col=length, group=length)) + geom_density() + ggtitle("Distribution of Levenshtein distance / length") ggplot(res_df, aes(x=length, y=dist / length, col=length)) + geom_violin(aes(group=length)) + geom_smooth(col="black", lwd=1) + ggtitle("Distribution of Levenshtein distance / length")
Distribution of the Levenshtein distance between two random strings
I guess it is not a direct answer, but you can try to simulate the scenario and check the empirical distribution to have a rough idea (R code below). So it seems that for strings longer than ~ 100 t
Distribution of the Levenshtein distance between two random strings I guess it is not a direct answer, but you can try to simulate the scenario and check the empirical distribution to have a rough idea (R code below). So it seems that for strings longer than ~ 100 the distribution is symmetric and quite narrow around .53 times the length of the string. # dependencies library(ggplot2); theme_set(theme_classic()) library(parallel) library(RecordLinkage) # settings alphabet <- c("A", "C", "G", "T") Nsim <- 1e3 read_lengths <- seq(60, 500, 20) # function to create a random string of length "n" using letters of the alphabet "alph" random_read <- function(n, alph=alphabet) paste(sample(alph, size=n, replace=T), collapse="") # simulate res <- mclapply(read_lengths, function(N) replicate(Nsim, levenshteinDist(random_read(N), random_read(N))), mc.cores=6) # arrange results as data.frame res_df <- data.frame(dist=unlist(res), length=rep(read_lengths, sapply(res, length))) # plot densities ggplot(res_df, aes(x=dist / length, col=length, group=length)) + geom_density() + ggtitle("Distribution of Levenshtein distance / length") ggplot(res_df, aes(x=length, y=dist / length, col=length)) + geom_violin(aes(group=length)) + geom_smooth(col="black", lwd=1) + ggtitle("Distribution of Levenshtein distance / length")
Distribution of the Levenshtein distance between two random strings I guess it is not a direct answer, but you can try to simulate the scenario and check the empirical distribution to have a rough idea (R code below). So it seems that for strings longer than ~ 100 t
36,936
Distribution of the Levenshtein distance between two random strings
This looks a bit like the Tracy-Widom distribution perhaps? For longest common subsequences there is a "famous" result relating the distribution of LCS between random strings (under a bunch of limiting assumptions) to the Tracy-Widom distribution: https://arxiv.org/abs/q-bio/0410012. https://www.quantamagazine.org/beyond-the-bell-curve-a-new-universal-law-20141015/
Distribution of the Levenshtein distance between two random strings
This looks a bit like the Tracy-Widom distribution perhaps? For longest common subsequences there is a "famous" result relating the distribution of LCS between random strings (under a bunch of limitin
Distribution of the Levenshtein distance between two random strings This looks a bit like the Tracy-Widom distribution perhaps? For longest common subsequences there is a "famous" result relating the distribution of LCS between random strings (under a bunch of limiting assumptions) to the Tracy-Widom distribution: https://arxiv.org/abs/q-bio/0410012. https://www.quantamagazine.org/beyond-the-bell-curve-a-new-universal-law-20141015/
Distribution of the Levenshtein distance between two random strings This looks a bit like the Tracy-Widom distribution perhaps? For longest common subsequences there is a "famous" result relating the distribution of LCS between random strings (under a bunch of limitin
36,937
normalization effect on polynomial regression
Polynomial (least squares) regression of data $\newcommand{\y}{\mathrm{y}}\y$ (thought of as an $n$-vector $(y_i)$) against a variable $\newcommand{\x}{\mathrm{x}}\x$ (also an $n$-vector ($x_i)$) uses the variables $\mathrm {1} = \x^0$ (a constant $n$-vector), $\x = \x^1$, $\x^2 = (x_i^2)$, ... and $\x^d = (x_i^d)$. The fit $\hat \y$ is the projection of $\y$ onto the linear subspace $E$ spanned by these $d+1$ variables. Suppose now that $\x$ is "normalized" by means of some affine transformation $$\x^\prime = \alpha \x + \beta.$$ If we recompute the powers of the components $\x^\prime$ we find (after expanding them) that $$x_i^{\prime k} = (\alpha x_i + \beta)^k = \sum_{j=0}^k c(k,j,\alpha,\beta)x_i^j$$ for some set of numbers $c(k,j,\alpha,\beta)$ (whose values we could write down explicitly, but the details do not matter). This exhibits every vector $(x_i^{\prime k})$ as a linear combination of the $x^j$, with $j$ varying from $0$ through nothing larger than $k$. Moreover, provided $\alpha \ne 0$ we can invert this process by noting $$\x = \frac{1}{\alpha} \x^\prime - \frac{\beta}{\alpha}$$ and similarly expanding the powers of $\x$ in terms of powers of $\x^\prime$. Therefore the subspace spanned by $\x^\prime$ and its powers through degree $d$ is the same subspace $E$ as that spanned by $\x$ and its powers through degree $d$. Consequently the normalization does not change the geometric description, whence the fit with both models is identical, QED. This argument generalizes, with essentially no change, to the cases where there may be more than one variable (expanded into a multivariate polynomial) as well as other non-polynomial covariates included in the model.
normalization effect on polynomial regression
Polynomial (least squares) regression of data $\newcommand{\y}{\mathrm{y}}\y$ (thought of as an $n$-vector $(y_i)$) against a variable $\newcommand{\x}{\mathrm{x}}\x$ (also an $n$-vector ($x_i)$) uses
normalization effect on polynomial regression Polynomial (least squares) regression of data $\newcommand{\y}{\mathrm{y}}\y$ (thought of as an $n$-vector $(y_i)$) against a variable $\newcommand{\x}{\mathrm{x}}\x$ (also an $n$-vector ($x_i)$) uses the variables $\mathrm {1} = \x^0$ (a constant $n$-vector), $\x = \x^1$, $\x^2 = (x_i^2)$, ... and $\x^d = (x_i^d)$. The fit $\hat \y$ is the projection of $\y$ onto the linear subspace $E$ spanned by these $d+1$ variables. Suppose now that $\x$ is "normalized" by means of some affine transformation $$\x^\prime = \alpha \x + \beta.$$ If we recompute the powers of the components $\x^\prime$ we find (after expanding them) that $$x_i^{\prime k} = (\alpha x_i + \beta)^k = \sum_{j=0}^k c(k,j,\alpha,\beta)x_i^j$$ for some set of numbers $c(k,j,\alpha,\beta)$ (whose values we could write down explicitly, but the details do not matter). This exhibits every vector $(x_i^{\prime k})$ as a linear combination of the $x^j$, with $j$ varying from $0$ through nothing larger than $k$. Moreover, provided $\alpha \ne 0$ we can invert this process by noting $$\x = \frac{1}{\alpha} \x^\prime - \frac{\beta}{\alpha}$$ and similarly expanding the powers of $\x$ in terms of powers of $\x^\prime$. Therefore the subspace spanned by $\x^\prime$ and its powers through degree $d$ is the same subspace $E$ as that spanned by $\x$ and its powers through degree $d$. Consequently the normalization does not change the geometric description, whence the fit with both models is identical, QED. This argument generalizes, with essentially no change, to the cases where there may be more than one variable (expanded into a multivariate polynomial) as well as other non-polynomial covariates included in the model.
normalization effect on polynomial regression Polynomial (least squares) regression of data $\newcommand{\y}{\mathrm{y}}\y$ (thought of as an $n$-vector $(y_i)$) against a variable $\newcommand{\x}{\mathrm{x}}\x$ (also an $n$-vector ($x_i)$) uses
36,938
Working with the bootstrap sample vs the original sample
The estimator in #2 is the thing you're generating the interval for ... the sample mean. You're using the bootstrap to try to get at the sampling distribution of the sample mean, by using the resampling distribution to approximate it. Since it's the exact same estimator in #1 and #2, #2 will have the same true properties (whatever they are, since you don't actually know the true distribution, the true level of dependence, and so on) as in #1, you're just trying to get at one of those properties in two different ways.
Working with the bootstrap sample vs the original sample
The estimator in #2 is the thing you're generating the interval for ... the sample mean. You're using the bootstrap to try to get at the sampling distribution of the sample mean, by using the resampli
Working with the bootstrap sample vs the original sample The estimator in #2 is the thing you're generating the interval for ... the sample mean. You're using the bootstrap to try to get at the sampling distribution of the sample mean, by using the resampling distribution to approximate it. Since it's the exact same estimator in #1 and #2, #2 will have the same true properties (whatever they are, since you don't actually know the true distribution, the true level of dependence, and so on) as in #1, you're just trying to get at one of those properties in two different ways.
Working with the bootstrap sample vs the original sample The estimator in #2 is the thing you're generating the interval for ... the sample mean. You're using the bootstrap to try to get at the sampling distribution of the sample mean, by using the resampli
36,939
Best practice for ADF/KPSS unit root testing sequence?
The steps where the null hypothesis is rejected relates to the following processes: Step 1.1 is related to (iii) is stationary around a linear trend, Step 2.1 is related to (ii) is stationary around a non-zero mean, Step 3.1 is related to (i) is stationary around a zero mean. When the null is not rejected, then you may consider the processes (iv) a unit root with a zero drift, (v) a unit root with a non-zero drift or even a unit root with a linear trend. Be aware that the effect of an intercept or a linear trend in a random walk is not the same as in a stationary series. See this post for a graphical illustration of unit root processes with zero intercept (no drift), drift and trend. If the null of a unit root is rejected, then the the $t$-statistic for $\mu=0$ would follow the standard distribution and you could test that $\mu=0$ under a Gaussian or Student-$t$ distribution of the test statistic. Nevertheless, I think it is a better idea what you mention in the last point, i.e., using the KPSS test where the null hypothesis is stationarity. In this way, combining the ADF and the KPSS tests we may arrive to strong conclusions rejecting either a unit root or stationarity. In this post I summarize a sequential procedure of both tests and the conclusions that can be obtained in each case. In section 5 of this document we elaborate further on this approach in the context of seasonal time series (where the HEGY test plays the role of the ADF test and the CH test plays the role of the KPSS test).
Best practice for ADF/KPSS unit root testing sequence?
The steps where the null hypothesis is rejected relates to the following processes: Step 1.1 is related to (iii) is stationary around a linear trend, Step 2.1 is related to (ii) is stationary around
Best practice for ADF/KPSS unit root testing sequence? The steps where the null hypothesis is rejected relates to the following processes: Step 1.1 is related to (iii) is stationary around a linear trend, Step 2.1 is related to (ii) is stationary around a non-zero mean, Step 3.1 is related to (i) is stationary around a zero mean. When the null is not rejected, then you may consider the processes (iv) a unit root with a zero drift, (v) a unit root with a non-zero drift or even a unit root with a linear trend. Be aware that the effect of an intercept or a linear trend in a random walk is not the same as in a stationary series. See this post for a graphical illustration of unit root processes with zero intercept (no drift), drift and trend. If the null of a unit root is rejected, then the the $t$-statistic for $\mu=0$ would follow the standard distribution and you could test that $\mu=0$ under a Gaussian or Student-$t$ distribution of the test statistic. Nevertheless, I think it is a better idea what you mention in the last point, i.e., using the KPSS test where the null hypothesis is stationarity. In this way, combining the ADF and the KPSS tests we may arrive to strong conclusions rejecting either a unit root or stationarity. In this post I summarize a sequential procedure of both tests and the conclusions that can be obtained in each case. In section 5 of this document we elaborate further on this approach in the context of seasonal time series (where the HEGY test plays the role of the ADF test and the CH test plays the role of the KPSS test).
Best practice for ADF/KPSS unit root testing sequence? The steps where the null hypothesis is rejected relates to the following processes: Step 1.1 is related to (iii) is stationary around a linear trend, Step 2.1 is related to (ii) is stationary around
36,940
How to quickly identify participants responding randomly to self-report psychometric tests with many items?
Jeromy's own answer is more useful than mine, but since I am working on this myself, I have collected a few handy R code bits that can also be helpful or steer one in the right direction of detecting 'suspicious' responses. The assumption here is that participants often (I find) respond in a pattern of some sort. Especially so in longer questionnaires. For example, if participants choose the middle response category from top to bottom of a given scale, one you could check how many responses are unique in the scale (or even the entire survey) by using: table(apply(data,1, function(X) {length(unique(X))})) If you interested to know which cases in your data present this pattern, rather than the total per category, you can use this code: apply(data, 1, function(X) all(abs(diff(X)) == abs(1))) Yet another way of looking at this is by at those participants whose responses alternate the response categories in diagonal lines (e.g., 1, 2, 3, 4, 5, 4, 3, 2, 1 or 2, 3, 4, 3, 2, 3, 4 which use just the center response categories.) For these respondents, one would need to calculate the lagged differences between responses with the following code: apply(data, 1, function(X) all(abs(diff(X)) == abs(2)))
How to quickly identify participants responding randomly to self-report psychometric tests with many
Jeromy's own answer is more useful than mine, but since I am working on this myself, I have collected a few handy R code bits that can also be helpful or steer one in the right direction of detecting
How to quickly identify participants responding randomly to self-report psychometric tests with many items? Jeromy's own answer is more useful than mine, but since I am working on this myself, I have collected a few handy R code bits that can also be helpful or steer one in the right direction of detecting 'suspicious' responses. The assumption here is that participants often (I find) respond in a pattern of some sort. Especially so in longer questionnaires. For example, if participants choose the middle response category from top to bottom of a given scale, one you could check how many responses are unique in the scale (or even the entire survey) by using: table(apply(data,1, function(X) {length(unique(X))})) If you interested to know which cases in your data present this pattern, rather than the total per category, you can use this code: apply(data, 1, function(X) all(abs(diff(X)) == abs(1))) Yet another way of looking at this is by at those participants whose responses alternate the response categories in diagonal lines (e.g., 1, 2, 3, 4, 5, 4, 3, 2, 1 or 2, 3, 4, 3, 2, 3, 4 which use just the center response categories.) For these respondents, one would need to calculate the lagged differences between responses with the following code: apply(data, 1, function(X) all(abs(diff(X)) == abs(2)))
How to quickly identify participants responding randomly to self-report psychometric tests with many Jeromy's own answer is more useful than mine, but since I am working on this myself, I have collected a few handy R code bits that can also be helpful or steer one in the right direction of detecting
36,941
How to quickly identify participants responding randomly to self-report psychometric tests with many items?
The careless R package on github includes a few nice functions. https://github.com/ryentes/careless Collection of Implementations for Indices of Careless Responding... [It] provides functions to support the computation of indices of careless responding. Initial indices include even/odd, psychometric synonyms, outlier, and longstring as described in Meade & Craig (2012) Meade, A. W., & Craig, S. B. (2012). Identifying careless responses in survey data. Psychological methods, 17(3), 437. PDF Another package of the same name on github but with different code is available here: https://github.com/mattsigal/careless
How to quickly identify participants responding randomly to self-report psychometric tests with many
The careless R package on github includes a few nice functions. https://github.com/ryentes/careless Collection of Implementations for Indices of Careless Responding... [It] provides functions to supp
How to quickly identify participants responding randomly to self-report psychometric tests with many items? The careless R package on github includes a few nice functions. https://github.com/ryentes/careless Collection of Implementations for Indices of Careless Responding... [It] provides functions to support the computation of indices of careless responding. Initial indices include even/odd, psychometric synonyms, outlier, and longstring as described in Meade & Craig (2012) Meade, A. W., & Craig, S. B. (2012). Identifying careless responses in survey data. Psychological methods, 17(3), 437. PDF Another package of the same name on github but with different code is available here: https://github.com/mattsigal/careless
How to quickly identify participants responding randomly to self-report psychometric tests with many The careless R package on github includes a few nice functions. https://github.com/ryentes/careless Collection of Implementations for Indices of Careless Responding... [It] provides functions to supp
36,942
Distribution of Trace of non-centered Wishart matrix
It looks like you can find it in: S. Kourouklis and P.G. Moschopoulos (1985) On the distribution of the trace of a non-central Wishart. Metron XLIII(1--2): 85--92. It looks like they cover the case of general covariance matrix $\Sigma$ there. They also give pointers to in the paper to: Mathai, A.M. and Pillai, K.C.S. (1982) Further results on the trace of a non-central Wishart matrix, Comm. Statist.-Theor. Meth., A 11, 1077-1086. A.M. Mathai (1980) Moments of the trace of a noncentral Wishart matrix. Comm. Statist. - Theor. Meth., A9(8), 795--801. That latter may be useful for computational purposes.
Distribution of Trace of non-centered Wishart matrix
It looks like you can find it in: S. Kourouklis and P.G. Moschopoulos (1985) On the distribution of the trace of a non-central Wishart. Metron XLIII(1--2): 85--92. It looks like they cover the case o
Distribution of Trace of non-centered Wishart matrix It looks like you can find it in: S. Kourouklis and P.G. Moschopoulos (1985) On the distribution of the trace of a non-central Wishart. Metron XLIII(1--2): 85--92. It looks like they cover the case of general covariance matrix $\Sigma$ there. They also give pointers to in the paper to: Mathai, A.M. and Pillai, K.C.S. (1982) Further results on the trace of a non-central Wishart matrix, Comm. Statist.-Theor. Meth., A 11, 1077-1086. A.M. Mathai (1980) Moments of the trace of a noncentral Wishart matrix. Comm. Statist. - Theor. Meth., A9(8), 795--801. That latter may be useful for computational purposes.
Distribution of Trace of non-centered Wishart matrix It looks like you can find it in: S. Kourouklis and P.G. Moschopoulos (1985) On the distribution of the trace of a non-central Wishart. Metron XLIII(1--2): 85--92. It looks like they cover the case o
36,943
Longitudinal data: baseline effect versus random intercept
I assume $j=1,...,9$. Yes, you can treat $\beta_1t_{0i}$ as object-specific intercept. The difference from random intercept is that $\beta_1t_{0i}$ is fixed. It is kind of like the difference between fixed and random effects in econometrics. All objects share the same $\beta_1$, which is then weighted by the baseline value of each object. If the baseline measurement is important, it is fine to do so.
Longitudinal data: baseline effect versus random intercept
I assume $j=1,...,9$. Yes, you can treat $\beta_1t_{0i}$ as object-specific intercept. The difference from random intercept is that $\beta_1t_{0i}$ is fixed. It is kind of like the difference between
Longitudinal data: baseline effect versus random intercept I assume $j=1,...,9$. Yes, you can treat $\beta_1t_{0i}$ as object-specific intercept. The difference from random intercept is that $\beta_1t_{0i}$ is fixed. It is kind of like the difference between fixed and random effects in econometrics. All objects share the same $\beta_1$, which is then weighted by the baseline value of each object. If the baseline measurement is important, it is fine to do so.
Longitudinal data: baseline effect versus random intercept I assume $j=1,...,9$. Yes, you can treat $\beta_1t_{0i}$ as object-specific intercept. The difference from random intercept is that $\beta_1t_{0i}$ is fixed. It is kind of like the difference between
36,944
Longitudinal data: baseline effect versus random intercept
First of all, I think your model specification is somewhat confusing. I would use $x_i=y_{i0}$ instead of $t_{0i}$ as $t_{ij}$ was used to represent time $j$ for individual $i$. You probably want to use baseline measurement rather than baseline time as covariate. So your model should be $$y_{ij} = \beta_0 + \beta_1 x_i +(\beta_2 + \gamma_i)t_{ij} + \epsilon_{ij}$$ for $i= 1\ldots n$ and $j=1\ldots 9$. The purpose of random intercept is to describe the difference at baseline, which is carried forward to later time points. i.e A person with higher measurement at baseline is more likely to have higher measurement later. Here comes the challenge: The above model cannot be used to describe what happened at baseline as the baseline measurement is already included in the model as a covariate. So using the above model to predict baseline outcome is meaningless. In this case, it is really hard to interpret the random effect and you shouldn't include it in the model. Having said that, it does make sense to include random intercept if you shift your time variable so $t_1 = 0$. In this case, you avoid interpreting regression parameters at a time point that your model doesn't apply. Peter
Longitudinal data: baseline effect versus random intercept
First of all, I think your model specification is somewhat confusing. I would use $x_i=y_{i0}$ instead of $t_{0i}$ as $t_{ij}$ was used to represent time $j$ for individual $i$. You probably want to u
Longitudinal data: baseline effect versus random intercept First of all, I think your model specification is somewhat confusing. I would use $x_i=y_{i0}$ instead of $t_{0i}$ as $t_{ij}$ was used to represent time $j$ for individual $i$. You probably want to use baseline measurement rather than baseline time as covariate. So your model should be $$y_{ij} = \beta_0 + \beta_1 x_i +(\beta_2 + \gamma_i)t_{ij} + \epsilon_{ij}$$ for $i= 1\ldots n$ and $j=1\ldots 9$. The purpose of random intercept is to describe the difference at baseline, which is carried forward to later time points. i.e A person with higher measurement at baseline is more likely to have higher measurement later. Here comes the challenge: The above model cannot be used to describe what happened at baseline as the baseline measurement is already included in the model as a covariate. So using the above model to predict baseline outcome is meaningless. In this case, it is really hard to interpret the random effect and you shouldn't include it in the model. Having said that, it does make sense to include random intercept if you shift your time variable so $t_1 = 0$. In this case, you avoid interpreting regression parameters at a time point that your model doesn't apply. Peter
Longitudinal data: baseline effect versus random intercept First of all, I think your model specification is somewhat confusing. I would use $x_i=y_{i0}$ instead of $t_{0i}$ as $t_{ij}$ was used to represent time $j$ for individual $i$. You probably want to u
36,945
Probabilistic interpretation from sigmoid functions
Why do we interpret the results of logistic regression as probabilities? Because the logistic regression model can be viewed as arising from a linear regression latent variable model, where the error term of this linear regression is assumed to follow the standard logistic distribution. See for example this post. Given that the output is between 0 and 1, is it enough to interpret the results as probabilities? No. The "output" must come from a function that satisfies the properties of a distribution function in order for us to interpret it as probabilities. These properties are: 1) The function $F$ under consideration must be non-decreasing and right-continuous ("cadlag") 2) $\lim_{x\rightarrow -\infty}F(x) =0$ 3) $\lim_{x\rightarrow \infty}F(x) =1$ The "sigmoid function" satisfies these properties.
Probabilistic interpretation from sigmoid functions
Why do we interpret the results of logistic regression as probabilities? Because the logistic regression model can be viewed as arising from a linear regression latent variable model, where the e
Probabilistic interpretation from sigmoid functions Why do we interpret the results of logistic regression as probabilities? Because the logistic regression model can be viewed as arising from a linear regression latent variable model, where the error term of this linear regression is assumed to follow the standard logistic distribution. See for example this post. Given that the output is between 0 and 1, is it enough to interpret the results as probabilities? No. The "output" must come from a function that satisfies the properties of a distribution function in order for us to interpret it as probabilities. These properties are: 1) The function $F$ under consideration must be non-decreasing and right-continuous ("cadlag") 2) $\lim_{x\rightarrow -\infty}F(x) =0$ 3) $\lim_{x\rightarrow \infty}F(x) =1$ The "sigmoid function" satisfies these properties.
Probabilistic interpretation from sigmoid functions Why do we interpret the results of logistic regression as probabilities? Because the logistic regression model can be viewed as arising from a linear regression latent variable model, where the e
36,946
Probabilistic interpretation from sigmoid functions
A probability is bounded between 0 and 1 (inclusive), and a sigmoid curve is a convenient curve that can be forced to respect those bounds. It is not the only one, but the sigmoid curve has proven to be the most popular one. So, not all probability models have a sigmoid cure, though many do. Moreover, not all models with a sigmoid curve model probabilities. For example, models that model a dependent variable that is a fraction also often use a sigmoid curve. What makes logit, probit, and similar models model a probability is the fact that they model the conditional mean of an indicator variable, which is the conditional proportion of $1$s, which in turn is interpreted as the probability of having a $1$ on that indicator variable.
Probabilistic interpretation from sigmoid functions
A probability is bounded between 0 and 1 (inclusive), and a sigmoid curve is a convenient curve that can be forced to respect those bounds. It is not the only one, but the sigmoid curve has proven to
Probabilistic interpretation from sigmoid functions A probability is bounded between 0 and 1 (inclusive), and a sigmoid curve is a convenient curve that can be forced to respect those bounds. It is not the only one, but the sigmoid curve has proven to be the most popular one. So, not all probability models have a sigmoid cure, though many do. Moreover, not all models with a sigmoid curve model probabilities. For example, models that model a dependent variable that is a fraction also often use a sigmoid curve. What makes logit, probit, and similar models model a probability is the fact that they model the conditional mean of an indicator variable, which is the conditional proportion of $1$s, which in turn is interpreted as the probability of having a $1$ on that indicator variable.
Probabilistic interpretation from sigmoid functions A probability is bounded between 0 and 1 (inclusive), and a sigmoid curve is a convenient curve that can be forced to respect those bounds. It is not the only one, but the sigmoid curve has proven to
36,947
Persistence in GJR-GARCH (asymmetric GARCH)
I found an answer in the "vignette" to the "rugarch" package in R. Here is a quote from pages 7-8 (emphasis is mine): Because of the presence of the indicator function, the persistence of the model now crucially depends on the asymmetry of the conditional distribution used. The persistence of the model $\hat P$ is, $$ \hat P = \sum_{j=1}^q \alpha_j + \sum_{j=1}^p \beta_j + \sum_{j=1}^q \gamma_j\kappa $$ where $\kappa$ is the expected value of the standardized residuals $z_t$ below zero (effectively the probability of being below zero), $$ \kappa = \mathbb{E}(\mathbb{I}_{t-j} z_{t-j}^2) = \int_{-\infty}^0 f(z,1,0,\dotsc) dz $$ where $f$ is the standardized conditional density with any additional skew and shape parameters $(\dotsc)$. In the case of symmetric distributions the value of $\kappa$ is simply equal to 0.5.
Persistence in GJR-GARCH (asymmetric GARCH)
I found an answer in the "vignette" to the "rugarch" package in R. Here is a quote from pages 7-8 (emphasis is mine): Because of the presence of the indicator function, the persistence of the model
Persistence in GJR-GARCH (asymmetric GARCH) I found an answer in the "vignette" to the "rugarch" package in R. Here is a quote from pages 7-8 (emphasis is mine): Because of the presence of the indicator function, the persistence of the model now crucially depends on the asymmetry of the conditional distribution used. The persistence of the model $\hat P$ is, $$ \hat P = \sum_{j=1}^q \alpha_j + \sum_{j=1}^p \beta_j + \sum_{j=1}^q \gamma_j\kappa $$ where $\kappa$ is the expected value of the standardized residuals $z_t$ below zero (effectively the probability of being below zero), $$ \kappa = \mathbb{E}(\mathbb{I}_{t-j} z_{t-j}^2) = \int_{-\infty}^0 f(z,1,0,\dotsc) dz $$ where $f$ is the standardized conditional density with any additional skew and shape parameters $(\dotsc)$. In the case of symmetric distributions the value of $\kappa$ is simply equal to 0.5.
Persistence in GJR-GARCH (asymmetric GARCH) I found an answer in the "vignette" to the "rugarch" package in R. Here is a quote from pages 7-8 (emphasis is mine): Because of the presence of the indicator function, the persistence of the model
36,948
Interpretation of multiple logistic regression with interactions in R
The relation of age or Hip.Prox.Femhip to the probability of LENIpos depends on the value of the other variable. That is suggested by the interaction term in your second model. In the usual R presentaton of regression coefficients, the coefficient for age in the second model is the relation of LENIpos to age in the absence of fracture, and the interaction term (age:Hip.Prox.Femhip fracture) is the difference from that relation in the presence of fracture. So the data seem consistent with age having a relation toLENIpos in the absence of fracture, but not in the presence of fracture. Plots of the +/- fracture subsets should help clarify this.
Interpretation of multiple logistic regression with interactions in R
The relation of age or Hip.Prox.Femhip to the probability of LENIpos depends on the value of the other variable. That is suggested by the interaction term in your second model. In the usual R presenta
Interpretation of multiple logistic regression with interactions in R The relation of age or Hip.Prox.Femhip to the probability of LENIpos depends on the value of the other variable. That is suggested by the interaction term in your second model. In the usual R presentaton of regression coefficients, the coefficient for age in the second model is the relation of LENIpos to age in the absence of fracture, and the interaction term (age:Hip.Prox.Femhip fracture) is the difference from that relation in the presence of fracture. So the data seem consistent with age having a relation toLENIpos in the absence of fracture, but not in the presence of fracture. Plots of the +/- fracture subsets should help clarify this.
Interpretation of multiple logistic regression with interactions in R The relation of age or Hip.Prox.Femhip to the probability of LENIpos depends on the value of the other variable. That is suggested by the interaction term in your second model. In the usual R presenta
36,949
Interpretation of multiple logistic regression with interactions in R
@EdM is right. The fact that the interaction's p-value is .06 (i.e., 'not-significant') is meaningless; you have an interaction. Let me add a few more details to supplement his (?) answer: A Mann-Whitney U-test of age~LENIpos isn't really the same as the univariate logistic regression of LENIpos~age (although the p-values will almost always be both significant or both not). You would do better to assess the univariate association by running the logistic regression. In R, a multiple linear regression comes with a global F-test of the model by default, but a multiple logistic regression does not (unfortunately). However, you can get a global test by assessing the difference between the null and residual deviances against a chi-squared distribution with the degrees of freedom equal to the difference between the null and residual dfs. Here is the test for your first model: > pchisq(q=145.23-135.48, df=151-149, lower.tail=FALSE) [1] 0.007635094 So it is clear that your first model is significant. This seeming paradox (both univariate analyses significant, and the two predictor model significant even though neither predictor itself is significant) has a hidden cause: Your two predictors are themselves correlated. (The general name for this is multicollinearity.) As a result, the model doesn't know which of the two to attribute the association and expands both standard errors to acknowledge this fact. (Note that the preceding discussion ignores the existence of the interaction.) As @EdM states, plotting these functions can help you understand the interaction. Here is a basic plot with your output: lo.to.p = function(lo){ odds = exp(lo) prob = odds / (odds+1) return(prob) } age = 0:80 lo.no = -5.89984 + 0.05851*age lo.fr = (-5.89984 + 5.04990) + (0.05851 + -0.06058)*age p.no = lo.to.p(lo.no) p.fr = lo.to.p(lo.fr) windows() plot( age, p.no, col="blue", type="l", ylim=c(0,1), ylab="probability of LENIpos") lines(age, p.fr, col="red") legend("topleft", legend=c("no fracture", "fracture"), lty=1, col=c("blue","red"))
Interpretation of multiple logistic regression with interactions in R
@EdM is right. The fact that the interaction's p-value is .06 (i.e., 'not-significant') is meaningless; you have an interaction. Let me add a few more details to supplement his (?) answer: A Mann
Interpretation of multiple logistic regression with interactions in R @EdM is right. The fact that the interaction's p-value is .06 (i.e., 'not-significant') is meaningless; you have an interaction. Let me add a few more details to supplement his (?) answer: A Mann-Whitney U-test of age~LENIpos isn't really the same as the univariate logistic regression of LENIpos~age (although the p-values will almost always be both significant or both not). You would do better to assess the univariate association by running the logistic regression. In R, a multiple linear regression comes with a global F-test of the model by default, but a multiple logistic regression does not (unfortunately). However, you can get a global test by assessing the difference between the null and residual deviances against a chi-squared distribution with the degrees of freedom equal to the difference between the null and residual dfs. Here is the test for your first model: > pchisq(q=145.23-135.48, df=151-149, lower.tail=FALSE) [1] 0.007635094 So it is clear that your first model is significant. This seeming paradox (both univariate analyses significant, and the two predictor model significant even though neither predictor itself is significant) has a hidden cause: Your two predictors are themselves correlated. (The general name for this is multicollinearity.) As a result, the model doesn't know which of the two to attribute the association and expands both standard errors to acknowledge this fact. (Note that the preceding discussion ignores the existence of the interaction.) As @EdM states, plotting these functions can help you understand the interaction. Here is a basic plot with your output: lo.to.p = function(lo){ odds = exp(lo) prob = odds / (odds+1) return(prob) } age = 0:80 lo.no = -5.89984 + 0.05851*age lo.fr = (-5.89984 + 5.04990) + (0.05851 + -0.06058)*age p.no = lo.to.p(lo.no) p.fr = lo.to.p(lo.fr) windows() plot( age, p.no, col="blue", type="l", ylim=c(0,1), ylab="probability of LENIpos") lines(age, p.fr, col="red") legend("topleft", legend=c("no fracture", "fracture"), lty=1, col=c("blue","red"))
Interpretation of multiple logistic regression with interactions in R @EdM is right. The fact that the interaction's p-value is .06 (i.e., 'not-significant') is meaningless; you have an interaction. Let me add a few more details to supplement his (?) answer: A Mann
36,950
Estimating $n$ and $p$ for Binomial distribution, repeated counting of partly hidden population
How could a Bayesian estimation proceed without additional information, is there any sensible prior for $n$? Your question is almost exactly the same question that Adrian Raftery answers in his paper "Inference for the Binomial $N$ parameter." Instead of aquariums, the author was looking at counts of animals in a wildlife preserve. He assesses this question from several different directions, comparing Bayesian estimates to some classical but ad hoc estimators. Is there a good choice of prior? How to select priors is a question that is far too broad for this forum, is somewhat subjective, and entirely depends on what kind of problem you're trying to solve, and what an acceptable prior means to you, for your problem. No one else can do your analysis for you. For example, one might characterize priors as noninformative, weakly informative and strongly informative. Within each of these taxonomies, reasonable people may disagree about which specific prior fits in each category. And you might disagree about which of those three paradigms are most appropriate. The more elaborate models sound like reasonable elaborations of the basic problem. Clearly, constraining the range of values to lie in some interval will dramatically change your inferences. Likewise will attempting to model deaths, especially if different species have different lifetimes and if there are inter-dependencies between different species. There is something to be said for parsimony: estimating a model of baroque complexity from a single vector places an enormous demand on both your prior and your data collection. One must wonder how sensitive your results would be to small changes in the values of observed data.
Estimating $n$ and $p$ for Binomial distribution, repeated counting of partly hidden population
How could a Bayesian estimation proceed without additional information, is there any sensible prior for $n$? Your question is almost exactly the same question that Adrian Raftery answers in his paper
Estimating $n$ and $p$ for Binomial distribution, repeated counting of partly hidden population How could a Bayesian estimation proceed without additional information, is there any sensible prior for $n$? Your question is almost exactly the same question that Adrian Raftery answers in his paper "Inference for the Binomial $N$ parameter." Instead of aquariums, the author was looking at counts of animals in a wildlife preserve. He assesses this question from several different directions, comparing Bayesian estimates to some classical but ad hoc estimators. Is there a good choice of prior? How to select priors is a question that is far too broad for this forum, is somewhat subjective, and entirely depends on what kind of problem you're trying to solve, and what an acceptable prior means to you, for your problem. No one else can do your analysis for you. For example, one might characterize priors as noninformative, weakly informative and strongly informative. Within each of these taxonomies, reasonable people may disagree about which specific prior fits in each category. And you might disagree about which of those three paradigms are most appropriate. The more elaborate models sound like reasonable elaborations of the basic problem. Clearly, constraining the range of values to lie in some interval will dramatically change your inferences. Likewise will attempting to model deaths, especially if different species have different lifetimes and if there are inter-dependencies between different species. There is something to be said for parsimony: estimating a model of baroque complexity from a single vector places an enormous demand on both your prior and your data collection. One must wonder how sensitive your results would be to small changes in the values of observed data.
Estimating $n$ and $p$ for Binomial distribution, repeated counting of partly hidden population How could a Bayesian estimation proceed without additional information, is there any sensible prior for $n$? Your question is almost exactly the same question that Adrian Raftery answers in his paper
36,951
How does Vowpal Wabbit handle NA's or missing values? [closed]
To elaborate on my answer: Lets say the first line of your data is: y, v1, v2, v3 10, 5, NA, 3 The VW string encoding of that line is: 10 |v1:4 v2:NA v3:3 As you probably discovered v2:NA doesn't work for VW, as the part after the colon needs to be a number. An easy solution to this is to find :NA in your VW string, and replace it with _NA: 10 |v1:4 v2_NA v3:3 This will work fine in VW, as it will internally recode v2_NA as v2_NA:1. This will allow the model to learn what happens when v2 is NA, and how that differs from the case where it is known. You could impute medians, but it's probably a better idea to: Compute a "NA flag" for each variable that is 1 when it is NA and 0 when it is not. Omit NA variables from your VW training file. Train on your dataset, omitting NAs and including flags. This will let VW build a model that predicts one thing for an NA variable and another when it is present.
How does Vowpal Wabbit handle NA's or missing values? [closed]
To elaborate on my answer: Lets say the first line of your data is: y, v1, v2, v3 10, 5, NA, 3 The VW string encoding of that line is: 10 |v1:4 v2:NA v3:3 As you probably discovered v2:NA doesn't
How does Vowpal Wabbit handle NA's or missing values? [closed] To elaborate on my answer: Lets say the first line of your data is: y, v1, v2, v3 10, 5, NA, 3 The VW string encoding of that line is: 10 |v1:4 v2:NA v3:3 As you probably discovered v2:NA doesn't work for VW, as the part after the colon needs to be a number. An easy solution to this is to find :NA in your VW string, and replace it with _NA: 10 |v1:4 v2_NA v3:3 This will work fine in VW, as it will internally recode v2_NA as v2_NA:1. This will allow the model to learn what happens when v2 is NA, and how that differs from the case where it is known. You could impute medians, but it's probably a better idea to: Compute a "NA flag" for each variable that is 1 when it is NA and 0 when it is not. Omit NA variables from your VW training file. Train on your dataset, omitting NAs and including flags. This will let VW build a model that predicts one thing for an NA variable and another when it is present.
How does Vowpal Wabbit handle NA's or missing values? [closed] To elaborate on my answer: Lets say the first line of your data is: y, v1, v2, v3 10, 5, NA, 3 The VW string encoding of that line is: 10 |v1:4 v2:NA v3:3 As you probably discovered v2:NA doesn't
36,952
two-sample Kolmogorov-Smirnov test p-value in R confusion
No, it's wrong. The default Kolmogorov-Smirnov in R is already two sided (i.e. already tests $F_X\neq F_Y$ rather than $F_X<F_Y$ or $F_X>F_Y$ (in all three cases, we should add "somewhere"). If you had done a one-tailed test but intended to do a two tail test (and if the sample turned out to have a difference in the direction you tested for), it's usually reasonably-near-to-correct to double the p-value for a two-tailed test, but strictly speaking, still wrong. While in the case of the t-test the events of rejecting in each tail are mutually exclusive - so you can just add their probabilities, and symmetric so adding is doubling - for the Kolmogorov-Smirnov they're not mutually exclusive -- each of the one-tailed Kolmogorov-Smirnov tests can reject on the same sample. However, under the null it's relatively rare to be able to reject both directions and so it's generally not a bad approximation to double. It's just unnecessary, since the ks.test function will happily calculate two-tailed p-values for us without doing a thing -- in fact we have to explicitly ask for a one-tailed one.
two-sample Kolmogorov-Smirnov test p-value in R confusion
No, it's wrong. The default Kolmogorov-Smirnov in R is already two sided (i.e. already tests $F_X\neq F_Y$ rather than $F_X<F_Y$ or $F_X>F_Y$ (in all three cases, we should add "somewhere"). If you ha
two-sample Kolmogorov-Smirnov test p-value in R confusion No, it's wrong. The default Kolmogorov-Smirnov in R is already two sided (i.e. already tests $F_X\neq F_Y$ rather than $F_X<F_Y$ or $F_X>F_Y$ (in all three cases, we should add "somewhere"). If you had done a one-tailed test but intended to do a two tail test (and if the sample turned out to have a difference in the direction you tested for), it's usually reasonably-near-to-correct to double the p-value for a two-tailed test, but strictly speaking, still wrong. While in the case of the t-test the events of rejecting in each tail are mutually exclusive - so you can just add their probabilities, and symmetric so adding is doubling - for the Kolmogorov-Smirnov they're not mutually exclusive -- each of the one-tailed Kolmogorov-Smirnov tests can reject on the same sample. However, under the null it's relatively rare to be able to reject both directions and so it's generally not a bad approximation to double. It's just unnecessary, since the ks.test function will happily calculate two-tailed p-values for us without doing a thing -- in fact we have to explicitly ask for a one-tailed one.
two-sample Kolmogorov-Smirnov test p-value in R confusion No, it's wrong. The default Kolmogorov-Smirnov in R is already two sided (i.e. already tests $F_X\neq F_Y$ rather than $F_X<F_Y$ or $F_X>F_Y$ (in all three cases, we should add "somewhere"). If you ha
36,953
Combining data from different sources
Your model estimate would be a useful prior. I have applied the following approach in LeBauer et al 2013, and have adapted code from priors_demo.Rmd below. To parameterize this prior using simulation, consider your model $$ \textrm{logLC}_{50} = b_0 X+b_1$$ Assume $b_0 \sim N(0.94, 0.03)$ and $b_1 \sim N(1.33, 0.1)$; $\textrm{Lkow}$ is known (a fixed parameter; for example physical constants are often known very precisely relative to other parameters). In addition, there is some model uncertainty, I'll make this $\epsilon \sim N(0,1)$, but should be an accurate representation of your information, for example the model's RMSE could be used to inform the scale of the standard deviation. I am intentionally making this an 'informative' prior. b0 <- rnorm(1000, -0.94, 0.03) b1 <- rnorm(1000, -1.33, 0.1) e <- rnorm(1000, 0, 1) lkow <- 3.8 theprior <- b0 * lkow + b1 + e Now imagine theprior is your prior and thedata <- log10(epa/ (mw * 1000000)) is your data: library(ggplot2) ggplot() + geom_density(aes(theprior)) + theme_bw() + geom_rug(aes(thedata)) The easiest way to use the prior is going to be to parameterize a distribution that JAGS will recognize. This can be done in many ways. Since the data don't have to be normal, you might consider finding a distribution using the package fitdistrplus. For simplicity, lets just assume that your prior is N(mean(theprior), sd(theprior)), or approximately $N(-4.9, 1.04)$. If you want to inflate the variance (to give the data more strength) you could use $N(-4.9, 2)$ Then we can fit a model using JAGS writeLines(con = "mymodel.bug", text = " model{ for(k in 1:length(Y)) { Y[k] ~ dnorm(mu, tau) } # informative prior on mu mu ~ dnorm(-4.9, 0.25) # precision tau = 1/variance # weak prior tau ~ dgamma(0.01, 0.01) sd <- 1 / sqrt(tau) }") require(rjags) j.model <- jags.model(file = "mymodel.bug", data = data.frame(Y = thedata), n.adapt = 500, n.chains = 4) mcmc.object <- coda.samples(model = j.model, variable.names = c('mu', 'tau'), n.iter = 10000) library(ggmcmc) ## look at diagnostics ggmcmc(ggs(mcmc.object), file = NULL) ## good convergence, but can start half-way through the simulation mcmc.o <- window(mcmc.object, start = 10000/2) summary(mcmc.o) Finally, a plot: ggplot() + theme_bw() + xlab("mu") + geom_density(aes(theprior), color = "grey") + geom_rug(aes(thedata)) + geom_density(aes(unlist(mcmc.o[,"mu"])), color = "pink") + geom_density(aes(unlist(mcmc.o[,"pred"])), color = "red") And you can consider mu=5.08 to be your estimate of the mean parameter value (pink), and sd = 0.8 its standard deviation; the posterior predictive estimate of the logLC_50 (where you are getting your samples from) is in red. Reference LeBauer, D.S., D. Wang, K. Richter, C. Davidson, & M.C. Dietze. (2013). Facilitating feedbacks between field measurements and ecosystem models. Ecological Monographs 83:133–154. doi:10.1890/12-0137.1
Combining data from different sources
Your model estimate would be a useful prior. I have applied the following approach in LeBauer et al 2013, and have adapted code from priors_demo.Rmd below. To parameterize this prior using simu
Combining data from different sources Your model estimate would be a useful prior. I have applied the following approach in LeBauer et al 2013, and have adapted code from priors_demo.Rmd below. To parameterize this prior using simulation, consider your model $$ \textrm{logLC}_{50} = b_0 X+b_1$$ Assume $b_0 \sim N(0.94, 0.03)$ and $b_1 \sim N(1.33, 0.1)$; $\textrm{Lkow}$ is known (a fixed parameter; for example physical constants are often known very precisely relative to other parameters). In addition, there is some model uncertainty, I'll make this $\epsilon \sim N(0,1)$, but should be an accurate representation of your information, for example the model's RMSE could be used to inform the scale of the standard deviation. I am intentionally making this an 'informative' prior. b0 <- rnorm(1000, -0.94, 0.03) b1 <- rnorm(1000, -1.33, 0.1) e <- rnorm(1000, 0, 1) lkow <- 3.8 theprior <- b0 * lkow + b1 + e Now imagine theprior is your prior and thedata <- log10(epa/ (mw * 1000000)) is your data: library(ggplot2) ggplot() + geom_density(aes(theprior)) + theme_bw() + geom_rug(aes(thedata)) The easiest way to use the prior is going to be to parameterize a distribution that JAGS will recognize. This can be done in many ways. Since the data don't have to be normal, you might consider finding a distribution using the package fitdistrplus. For simplicity, lets just assume that your prior is N(mean(theprior), sd(theprior)), or approximately $N(-4.9, 1.04)$. If you want to inflate the variance (to give the data more strength) you could use $N(-4.9, 2)$ Then we can fit a model using JAGS writeLines(con = "mymodel.bug", text = " model{ for(k in 1:length(Y)) { Y[k] ~ dnorm(mu, tau) } # informative prior on mu mu ~ dnorm(-4.9, 0.25) # precision tau = 1/variance # weak prior tau ~ dgamma(0.01, 0.01) sd <- 1 / sqrt(tau) }") require(rjags) j.model <- jags.model(file = "mymodel.bug", data = data.frame(Y = thedata), n.adapt = 500, n.chains = 4) mcmc.object <- coda.samples(model = j.model, variable.names = c('mu', 'tau'), n.iter = 10000) library(ggmcmc) ## look at diagnostics ggmcmc(ggs(mcmc.object), file = NULL) ## good convergence, but can start half-way through the simulation mcmc.o <- window(mcmc.object, start = 10000/2) summary(mcmc.o) Finally, a plot: ggplot() + theme_bw() + xlab("mu") + geom_density(aes(theprior), color = "grey") + geom_rug(aes(thedata)) + geom_density(aes(unlist(mcmc.o[,"mu"])), color = "pink") + geom_density(aes(unlist(mcmc.o[,"pred"])), color = "red") And you can consider mu=5.08 to be your estimate of the mean parameter value (pink), and sd = 0.8 its standard deviation; the posterior predictive estimate of the logLC_50 (where you are getting your samples from) is in red. Reference LeBauer, D.S., D. Wang, K. Richter, C. Davidson, & M.C. Dietze. (2013). Facilitating feedbacks between field measurements and ecosystem models. Ecological Monographs 83:133–154. doi:10.1890/12-0137.1
Combining data from different sources Your model estimate would be a useful prior. I have applied the following approach in LeBauer et al 2013, and have adapted code from priors_demo.Rmd below. To parameterize this prior using simu
36,954
Calculating Perplexity
I stumbled upon this searching how perplexity is calculated. I think applying the Jurafsky formula I find the right number (I used R): P1 <- 1/4 P2 <- 1/4 P3 <- 1/4 P4 <- 1/120000 SP <- P1*P2*P3*P4 Result <- SP**(-1/4) Result is 52.64296
Calculating Perplexity
I stumbled upon this searching how perplexity is calculated. I think applying the Jurafsky formula I find the right number (I used R): P1 <- 1/4 P2 <- 1/4 P3 <- 1/4 P4 <- 1/120000 SP <- P1*P2*P3*P4 R
Calculating Perplexity I stumbled upon this searching how perplexity is calculated. I think applying the Jurafsky formula I find the right number (I used R): P1 <- 1/4 P2 <- 1/4 P3 <- 1/4 P4 <- 1/120000 SP <- P1*P2*P3*P4 Result <- SP**(-1/4) Result is 52.64296
Calculating Perplexity I stumbled upon this searching how perplexity is calculated. I think applying the Jurafsky formula I find the right number (I used R): P1 <- 1/4 P2 <- 1/4 P3 <- 1/4 P4 <- 1/120000 SP <- P1*P2*P3*P4 R
36,955
Calculating Perplexity
I interpreted the probabilities here as: Let's imagine there are 120000 words in total, where by probability distribution: Operator, Sales and Technical Support each occur 30,000 times (P = 1/4) Each of the name occur only once (P = 1/120000). Perplexity can be calculated then, using the formula: $(\frac{1}{4}^{30000} * \frac{1}{4}^{30000} * \frac{1}{4}^{30000} * \frac{1}{120000}^{30000}) ^ \frac{-1}{120000}$
Calculating Perplexity
I interpreted the probabilities here as: Let's imagine there are 120000 words in total, where by probability distribution: Operator, Sales and Technical Support each occur 30,000 times (P = 1/4) Each
Calculating Perplexity I interpreted the probabilities here as: Let's imagine there are 120000 words in total, where by probability distribution: Operator, Sales and Technical Support each occur 30,000 times (P = 1/4) Each of the name occur only once (P = 1/120000). Perplexity can be calculated then, using the formula: $(\frac{1}{4}^{30000} * \frac{1}{4}^{30000} * \frac{1}{4}^{30000} * \frac{1}{120000}^{30000}) ^ \frac{-1}{120000}$
Calculating Perplexity I interpreted the probabilities here as: Let's imagine there are 120000 words in total, where by probability distribution: Operator, Sales and Technical Support each occur 30,000 times (P = 1/4) Each
36,956
How to summarize GAM model result from multiple imputation data in R
First, GAM's are basically a combination of GLMs, splines, and ridge regression (loosely speaking). You might be well advised to work on your understanding of these three things before attempting to work with their combination. Second, I've done multiple imputation with GAMs, but not with mice. In general, you're interested in fitting a model: $$ y = f(\mathbf{X}) + \epsilon $$ (in the gaussian, identity-linked case). $\mathbf{X}$ has holes in it -- missing data. Without going into the detail about how multiple imputation works (Gelman and Hill have a very good and less-technical chapter explaining missing data imputation), what it does is create many different $\mathbf{X}$'s, call them $\mathbf{X}_m$ where $m$ indexes imputed datasets from 1 to the number of imputations, with the missing values filled in with plausible guesses about what the missing values might be -- based on correlations in your dataset. You then fit your model $$ y = f(\mathbf{X}_m) + \epsilon $$ to each of those $m$ partially-imputed datasets. Since you're fitting $m$ models to $m$ different datasets, you're going to get $m$ different vectors of regression coefficients. These are combined according to "Rubin's Rules" (after the statistician who invented MI). Basically you average the coefficients; $$\hat\beta = \frac{1}{M}\displaystyle\sum_{m=1}^M \hat\beta_m$$ The variance-covariance matrix $\hat V_\beta$ of the estimated parameters is calculated by first averaging variance-covariance matrices, and then adding a correction to account for variation between imputation models: \begin{equation} \hat V_{\hat\beta} = W + \left(1 + \frac{1}{M} \right)B \end{equation} where $W = \frac{1}{M}\displaystyle\sum_{m=1}^M \widehat{VCV}_m$, $\widehat{VCV}$ is the estimated variance-covariance matrix of the estimated parameters, and $B = \frac{1}{M-1}\displaystyle\sum_{m=1}^M \left(\hat\beta_m - \hat{\bar\beta}\right)\left(\hat\beta_m - \hat{\bar\beta}\right)^T$. This procedure inflates the standard errors on coefficients about which the imputation model is relatively less certain, either due to a lot of missing data, or due to a poorly-informative imputation model. You can then use the vector of coefficients and the VCV as if they were gotten from a single complete-case model. OP's question in a comment makes me realize that the below isn't quite right! Read EDIT2 below to see why So what is different about doing this with a GAM? Only a couple of things. Your variables represented by smooth functions are associated with a number of coefficients (mgcv's default is 10). During estimation they are subject to ridge penalties, which smooths the estimated function. But otherwise they can be slotted into Rubin's rules just like the parametric coefficients. Each of the different $m$ models will have different estimated smoothing parameters, as they are estimated from the data. I don't think there is a problem with this, though I'd be interested to hear if someone has another perspective. You do want to take care that you pre-specify the location of the knots of each spline so that they are uniform across the $m$ models -- otherwise your coefficients won't be comparable, and combining them won't be appropriate. Once you have calculated the combined coefficients and VCV, you can simply stuff them into a GAM object (one of your $m$ models). Functions that summarize data and make plots draw from those two objects, and will thereby use your imputation estimates rather than those from the $m$th model. There is code online illustrating the whole process from this paper. EDIT I just saw the comment about how you've got your models fitted to your imputed datasets already. If you can coerce those into a list object with the 5 GAM models, then you can run something like the following to combine them: bhat=results[[1]]$coeff for (i in 2:reps){ bhat=bhat+results[[i]]$coeff } bhat = bhat/reps W=results[[1]]$Vp for (i in 2:reps){ W = W+results[[i]]$Vp } W = W/reps B= (results[[1]]$coeff-bhat) %*% t(results[[1]]$coeff-bhat) for (i in 2:reps){ B = B+(results[[i]]$coeff-bhat) %*% t(results[[i]]$coeff-bhat) } B=B/(reps-1) Vb = W+(1+1/reps)*B dfr=results[[1]]$df.residual for (i in 2:reps){ dfr=dfr+results[[i]]$df.residual } dfr = dfr/reps MI = results[[1]] MI$coefficients=bhat MI$Vp = Vb MI$df.residual = dfr EDIT2 OP's question in a comment about p-values makes me realize that the above isn't quite right. It should get you appropriate coefficient and VCV estimates. But p-values are based on a reduced-rank Wald statistic that relies on the model matrix for its calculation. Obviously the model matrix will differ between different imputations. So if you take a single one of many gam objects (which will all have their own model frames) and stuff the VCV and coefficient vectors into it, you won't get the same result as you would if you chose a different one of your models fit to a different imputed dataset. I'm not sure how Rubin's Rules would be generalized to combine imputations here! Maybe a short-term hack would be to also average the model R matrices from each model? This should be about as valid as averaging the effective degrees of freedom (which may also be a hack).
How to summarize GAM model result from multiple imputation data in R
First, GAM's are basically a combination of GLMs, splines, and ridge regression (loosely speaking). You might be well advised to work on your understanding of these three things before attempting to
How to summarize GAM model result from multiple imputation data in R First, GAM's are basically a combination of GLMs, splines, and ridge regression (loosely speaking). You might be well advised to work on your understanding of these three things before attempting to work with their combination. Second, I've done multiple imputation with GAMs, but not with mice. In general, you're interested in fitting a model: $$ y = f(\mathbf{X}) + \epsilon $$ (in the gaussian, identity-linked case). $\mathbf{X}$ has holes in it -- missing data. Without going into the detail about how multiple imputation works (Gelman and Hill have a very good and less-technical chapter explaining missing data imputation), what it does is create many different $\mathbf{X}$'s, call them $\mathbf{X}_m$ where $m$ indexes imputed datasets from 1 to the number of imputations, with the missing values filled in with plausible guesses about what the missing values might be -- based on correlations in your dataset. You then fit your model $$ y = f(\mathbf{X}_m) + \epsilon $$ to each of those $m$ partially-imputed datasets. Since you're fitting $m$ models to $m$ different datasets, you're going to get $m$ different vectors of regression coefficients. These are combined according to "Rubin's Rules" (after the statistician who invented MI). Basically you average the coefficients; $$\hat\beta = \frac{1}{M}\displaystyle\sum_{m=1}^M \hat\beta_m$$ The variance-covariance matrix $\hat V_\beta$ of the estimated parameters is calculated by first averaging variance-covariance matrices, and then adding a correction to account for variation between imputation models: \begin{equation} \hat V_{\hat\beta} = W + \left(1 + \frac{1}{M} \right)B \end{equation} where $W = \frac{1}{M}\displaystyle\sum_{m=1}^M \widehat{VCV}_m$, $\widehat{VCV}$ is the estimated variance-covariance matrix of the estimated parameters, and $B = \frac{1}{M-1}\displaystyle\sum_{m=1}^M \left(\hat\beta_m - \hat{\bar\beta}\right)\left(\hat\beta_m - \hat{\bar\beta}\right)^T$. This procedure inflates the standard errors on coefficients about which the imputation model is relatively less certain, either due to a lot of missing data, or due to a poorly-informative imputation model. You can then use the vector of coefficients and the VCV as if they were gotten from a single complete-case model. OP's question in a comment makes me realize that the below isn't quite right! Read EDIT2 below to see why So what is different about doing this with a GAM? Only a couple of things. Your variables represented by smooth functions are associated with a number of coefficients (mgcv's default is 10). During estimation they are subject to ridge penalties, which smooths the estimated function. But otherwise they can be slotted into Rubin's rules just like the parametric coefficients. Each of the different $m$ models will have different estimated smoothing parameters, as they are estimated from the data. I don't think there is a problem with this, though I'd be interested to hear if someone has another perspective. You do want to take care that you pre-specify the location of the knots of each spline so that they are uniform across the $m$ models -- otherwise your coefficients won't be comparable, and combining them won't be appropriate. Once you have calculated the combined coefficients and VCV, you can simply stuff them into a GAM object (one of your $m$ models). Functions that summarize data and make plots draw from those two objects, and will thereby use your imputation estimates rather than those from the $m$th model. There is code online illustrating the whole process from this paper. EDIT I just saw the comment about how you've got your models fitted to your imputed datasets already. If you can coerce those into a list object with the 5 GAM models, then you can run something like the following to combine them: bhat=results[[1]]$coeff for (i in 2:reps){ bhat=bhat+results[[i]]$coeff } bhat = bhat/reps W=results[[1]]$Vp for (i in 2:reps){ W = W+results[[i]]$Vp } W = W/reps B= (results[[1]]$coeff-bhat) %*% t(results[[1]]$coeff-bhat) for (i in 2:reps){ B = B+(results[[i]]$coeff-bhat) %*% t(results[[i]]$coeff-bhat) } B=B/(reps-1) Vb = W+(1+1/reps)*B dfr=results[[1]]$df.residual for (i in 2:reps){ dfr=dfr+results[[i]]$df.residual } dfr = dfr/reps MI = results[[1]] MI$coefficients=bhat MI$Vp = Vb MI$df.residual = dfr EDIT2 OP's question in a comment about p-values makes me realize that the above isn't quite right. It should get you appropriate coefficient and VCV estimates. But p-values are based on a reduced-rank Wald statistic that relies on the model matrix for its calculation. Obviously the model matrix will differ between different imputations. So if you take a single one of many gam objects (which will all have their own model frames) and stuff the VCV and coefficient vectors into it, you won't get the same result as you would if you chose a different one of your models fit to a different imputed dataset. I'm not sure how Rubin's Rules would be generalized to combine imputations here! Maybe a short-term hack would be to also average the model R matrices from each model? This should be about as valid as averaging the effective degrees of freedom (which may also be a hack).
How to summarize GAM model result from multiple imputation data in R First, GAM's are basically a combination of GLMs, splines, and ridge regression (loosely speaking). You might be well advised to work on your understanding of these three things before attempting to
36,957
How to summarize GAM model result from multiple imputation data in R
See https://stat.ethz.ch/R-manual/R-devel/library/mgcv/html/missing.data.html Or enter help(mgcv::missing.data) in an R session. An approach that can be effective, with sample code on the help page, is then to substitute a simple random effects model in which the by variable mechanism is used to set s(x) to zero for any missing x, while a Gaussian random effect is then substituted for the ‘missing’ s(x). Factors are required, one for each variable that has missing values, for use as missing value indicators, in each case with as many levels as there are missing values. The NAs are replaced in each case, by the mean for the relevant variable.
How to summarize GAM model result from multiple imputation data in R
See https://stat.ethz.ch/R-manual/R-devel/library/mgcv/html/missing.data.html Or enter help(mgcv::missing.data) in an R session. An approach that can be effective, with sample code on the help page,
How to summarize GAM model result from multiple imputation data in R See https://stat.ethz.ch/R-manual/R-devel/library/mgcv/html/missing.data.html Or enter help(mgcv::missing.data) in an R session. An approach that can be effective, with sample code on the help page, is then to substitute a simple random effects model in which the by variable mechanism is used to set s(x) to zero for any missing x, while a Gaussian random effect is then substituted for the ‘missing’ s(x). Factors are required, one for each variable that has missing values, for use as missing value indicators, in each case with as many levels as there are missing values. The NAs are replaced in each case, by the mean for the relevant variable.
How to summarize GAM model result from multiple imputation data in R See https://stat.ethz.ch/R-manual/R-devel/library/mgcv/html/missing.data.html Or enter help(mgcv::missing.data) in an R session. An approach that can be effective, with sample code on the help page,
36,958
MLE for mean of symmetric but otherwise unknown distribution
Consider the single-parameter Exponential Family of distributions, i.e. distributions whose probability density (or mass) function can be written as $$f(x) = h(x)\cdot \exp{\big\{\eta(\theta)T(x)-A(\theta)\big\}}$$ The log-likelihood from an i.i.d sample of size $n$ is then $$\tilde L = \sum_{i=1}^n\ln h(x_i) + \eta(\theta)\sum_{i=1}^nT(x_i) - nA(\theta)$$ and the derivative with respect to $\theta$ is $$\frac {\partial \tilde L}{\partial \theta}=\eta'(\theta)\sum_{i=1}^nT(x_i)-nA'(\theta) = 0$$ $$\Rightarrow \frac 1n \sum_{i=1}^nT(x_i) = \frac {A'(\hat \theta_{MLE})}{\eta'(\hat \theta_{MLE})}$$ it is obvious from the above that, to arrive at "the sample mean is the MLE for the mean", the involved functions must have suitable forms. Examples where the result holds 1) For the Normal distribution (with known variance $\sigma^2$) : $T(x_i) = x_i/\sigma$, $A(\theta)=\mu^2 / 2\sigma^2 \Rightarrow A'(\theta) = \mu / \sigma^2$, $\eta(\theta) = \mu/\sigma\Rightarrow \eta'(\theta) = 1/\sigma$ 2) For the Bernoulli(p) distribution, $T(x_i) = x_i$, $A(\theta) -\ln (1-p)\Rightarrow A'(\theta) = 1/(1-p) $, $\eta (\theta) = \ln(p/(1-p)\Rightarrow \eta'(\theta) = 1/p(1-p)$ In these cases, indeed the MLE for the mean is the sample mean. It is perhaps easier to find counter-examples, as Whuber hinted.
MLE for mean of symmetric but otherwise unknown distribution
Consider the single-parameter Exponential Family of distributions, i.e. distributions whose probability density (or mass) function can be written as $$f(x) = h(x)\cdot \exp{\big\{\eta(\theta)T(x)-A(\t
MLE for mean of symmetric but otherwise unknown distribution Consider the single-parameter Exponential Family of distributions, i.e. distributions whose probability density (or mass) function can be written as $$f(x) = h(x)\cdot \exp{\big\{\eta(\theta)T(x)-A(\theta)\big\}}$$ The log-likelihood from an i.i.d sample of size $n$ is then $$\tilde L = \sum_{i=1}^n\ln h(x_i) + \eta(\theta)\sum_{i=1}^nT(x_i) - nA(\theta)$$ and the derivative with respect to $\theta$ is $$\frac {\partial \tilde L}{\partial \theta}=\eta'(\theta)\sum_{i=1}^nT(x_i)-nA'(\theta) = 0$$ $$\Rightarrow \frac 1n \sum_{i=1}^nT(x_i) = \frac {A'(\hat \theta_{MLE})}{\eta'(\hat \theta_{MLE})}$$ it is obvious from the above that, to arrive at "the sample mean is the MLE for the mean", the involved functions must have suitable forms. Examples where the result holds 1) For the Normal distribution (with known variance $\sigma^2$) : $T(x_i) = x_i/\sigma$, $A(\theta)=\mu^2 / 2\sigma^2 \Rightarrow A'(\theta) = \mu / \sigma^2$, $\eta(\theta) = \mu/\sigma\Rightarrow \eta'(\theta) = 1/\sigma$ 2) For the Bernoulli(p) distribution, $T(x_i) = x_i$, $A(\theta) -\ln (1-p)\Rightarrow A'(\theta) = 1/(1-p) $, $\eta (\theta) = \ln(p/(1-p)\Rightarrow \eta'(\theta) = 1/p(1-p)$ In these cases, indeed the MLE for the mean is the sample mean. It is perhaps easier to find counter-examples, as Whuber hinted.
MLE for mean of symmetric but otherwise unknown distribution Consider the single-parameter Exponential Family of distributions, i.e. distributions whose probability density (or mass) function can be written as $$f(x) = h(x)\cdot \exp{\big\{\eta(\theta)T(x)-A(\t
36,959
Deviance Residuals
Any of the various forms of residuals used in connection with GLMs (raw, Pearson, deviance, Anscombe and even working residuals) can be difficult to interpret visually. However, broadly speaking, your deviance residuals should be expected to have mean close to 0 and nearly constant variance, when plotted against any predictor, or against fitted values, or even against their index (which usually isn't especially meaningful, unless it represents an ordering in the time the observation was collected or something, in which case it could be quite useful). In this case, as near as I can discern, you have what looks like mean near 0 against Index. It can be hard to see where the typical value is in the case of logistic regression (sometimes it may help to consider looking at a smooth of the values for that reason). If you have not already done so, try plot(rf1).
Deviance Residuals
Any of the various forms of residuals used in connection with GLMs (raw, Pearson, deviance, Anscombe and even working residuals) can be difficult to interpret visually. However, broadly speaking, your
Deviance Residuals Any of the various forms of residuals used in connection with GLMs (raw, Pearson, deviance, Anscombe and even working residuals) can be difficult to interpret visually. However, broadly speaking, your deviance residuals should be expected to have mean close to 0 and nearly constant variance, when plotted against any predictor, or against fitted values, or even against their index (which usually isn't especially meaningful, unless it represents an ordering in the time the observation was collected or something, in which case it could be quite useful). In this case, as near as I can discern, you have what looks like mean near 0 against Index. It can be hard to see where the typical value is in the case of logistic regression (sometimes it may help to consider looking at a smooth of the values for that reason). If you have not already done so, try plot(rf1).
Deviance Residuals Any of the various forms of residuals used in connection with GLMs (raw, Pearson, deviance, Anscombe and even working residuals) can be difficult to interpret visually. However, broadly speaking, your
36,960
Can effective sample size in MCMC simulation be greater than the actual sample size?
For a particular definition of autocorrelation, negative autocorrelation can cause $N_{eff} > n$. This answer gives a MWE using coda.
Can effective sample size in MCMC simulation be greater than the actual sample size?
For a particular definition of autocorrelation, negative autocorrelation can cause $N_{eff} > n$. This answer gives a MWE using coda.
Can effective sample size in MCMC simulation be greater than the actual sample size? For a particular definition of autocorrelation, negative autocorrelation can cause $N_{eff} > n$. This answer gives a MWE using coda.
Can effective sample size in MCMC simulation be greater than the actual sample size? For a particular definition of autocorrelation, negative autocorrelation can cause $N_{eff} > n$. This answer gives a MWE using coda.
36,961
Can effective sample size in MCMC simulation be greater than the actual sample size?
In principle yes, you are right. The sample size should not be larger. One possibility is that the package is using some optimization routine to improve the variance such as VEGAS. As kjetil b halvorsen pointed out, it could be that autocorrelation is negative. But I'm not seeing how.
Can effective sample size in MCMC simulation be greater than the actual sample size?
In principle yes, you are right. The sample size should not be larger. One possibility is that the package is using some optimization routine to improve the variance such as VEGAS. As kjetil b halvor
Can effective sample size in MCMC simulation be greater than the actual sample size? In principle yes, you are right. The sample size should not be larger. One possibility is that the package is using some optimization routine to improve the variance such as VEGAS. As kjetil b halvorsen pointed out, it could be that autocorrelation is negative. But I'm not seeing how.
Can effective sample size in MCMC simulation be greater than the actual sample size? In principle yes, you are right. The sample size should not be larger. One possibility is that the package is using some optimization routine to improve the variance such as VEGAS. As kjetil b halvor
36,962
Averaging multiple distributions
(I expand this answer to cover more completely a setup that occurs frequently, and also, to focus on the estimation of the population variance). The setup is as follows: from $K$ independent samples that all come from a normal i.i.d. population $N(\mu, \sigma^2)$ and have varying sizes, $n_1+...+n_K = N$, we are not given the actual sample data but only a) The sample sizes $n_i, i=1,...,k$ b) The sample mean of each sample, $m_i = \frac 1{n_i}\sum_{j=1}^{n_i}x_j$ c) The sample variance of each sample, $v_i = \frac 1{n_i}\sum_{j=1}^{n_i}(x_j-m_i)^2 = \frac 1{n_i}\sum_{j=1}^{n_i}x_j^2-m_i^2$ Note that we consider the maximum likelihood estimator of the population variance, i.e. we divide by $n_i$ and not by $n_i-1$. We want to derive maximum likelihood estimators for the unknown population parameters, $\mu$, and $\sigma^2$, by using the information we are given. A) MLE of population mean Under the maintained hypothesis the sample means are normally distributed, and each sample mean $m_i \sim N(\mu, \frac {\sigma^2}{n_i})$. The samples are independent so the joint density/likelihood function of the sample means is $$L(\mu, \sigma^2\mid \{m_1,...,m_K\})= \prod_{i=1}^K\frac {\sqrt {n_i}} {\sqrt{2\pi}\sigma}\exp\left\{-\frac 12 \frac {(m_i-\mu)^2}{\sigma^2/n_i}\right\}$$ and the log-likelihood is $$\ln L(\mu, \sigma^2\mid \{m_1,...,m_K\})= c -K\ln\sigma -\frac 1{2\sigma^2} \sum_{i=1}^Kn_i(m_i-\mu)^2$$ Setting the first derivative of $\ln L$ w.r.t to $\mu$ equal to zero we have $$\frac {\partial}{\partial \mu} \ln L = 0 \Rightarrow \frac 1{\sigma^2} \sum_{i=1}^Kn_i(m_i-\mu) =0 \Rightarrow \sum_{i=1}^Kn_im_i - \mu\sum_{i=1}^Kn_i =0$$ $$\Rightarrow \hat \mu_{ML} = \sum_{i=1}^K\frac {n_i}{N}m_i = \sum_{i=1}^K\frac {n_i}{N}\left(\frac 1{n_i}\sum_{j=1}^{n_i}x_j\right) = \frac 1N\sum_{j=1}^{N}x_j = \bar X_N \qquad [1]$$ So the MLE of the population mean, weighs each sample mean by the (relative) sample size from which it was derived, becoming a convex combination of the $K$ sample means, and so it ends up numerically equivalent to the full-sample mean we would obtain if we had the original data available and had pooled them in one sample. Note: although we have $k$ estimates of the population variance available, they do not enter the likelihood, because the maintained assumption is that all samples come from the same population. If instead of $\sigma^2/n_i$ we had included in the likelihood $v_i/n_i$, we would have violated this assumption. A comment that refers to known variances (and provides the correct formula for this case), covers essentially the case where the various samples do not come from the same population (and more over, the variances are known and not estimated). B) MLE of population variance We could derive an MLE of the population variance using the above likelihood as $$\hat \sigma ^2_{ML} = \frac 1K\sum_{i=1}^Kn_i(m_i-\hat \mu_{ML})^2 \qquad [2]$$ This is a biased estimator (due to the estimation error associated with $\hat \mu_{ML}$), and also, shouldn't we take into account the estimated variances derived from each sample, the $v_i$'s? We know that $$\frac {n_iv_i}{\sigma^2} \equiv z \sim \chi^2(n_i-1)$$ Then $$v_i = \frac {\sigma^2}{n_i} z \sim \operatorname{Gamma}(k_i,\theta_i),\;\; k_i = \frac {n_i-1}{2},\;\; \theta_i = \frac {2\sigma^2}{n_i}$$ with the Gamma density given by $$f_{v_i}(v_i) = \frac 1{\Gamma(k_i)\theta_i^{k_i}}v_i^{k_i-1}\exp\left\{-\frac {v_i}{\theta_i}\right\}$$ The $v_i$'s are independent random variables, so they form the following log-likelihood: $$\ln L_v = c- \sum_{i=1}^Kk_i\ln \theta_i+\sum_{i=1}^K(k_i-1)\ln v_i-\sum_{i=1}^K\frac {v_i}{\theta_i}$$ Note that the shape parameters, $k_i$'s are known, and all $\theta$'s are functions of the same unknown parameter, $\sigma^2$. Setting the first derivative of the log-likelihood w.r.t. $\sigma^2$ equal to zero we get $$\frac {\partial}{\partial \sigma^2} \ln L_v = 0 \Rightarrow -\sum_{i=1}^K\frac {k_i}{\theta_i}\frac {2}{n_i} + \sum_{i=1}^K\frac {v_i}{\theta_i^2}\frac {2}{n_i} =0$$ $$\Rightarrow \frac 1{\sigma^4}\sum_{i=1}^K\frac {n_i^2v_i}{4}\frac {2}{n_i} = \frac 1{\sigma^2}\sum_{i=1}^Kk_i\frac {n_i}{2}\frac {2}{n_i}$$ and simplifying and using also $k_i=(n_i-1)/2$ we obtain $$\frac 1{2\sigma^2}\sum_{i=1}^Kn_iv_i = \frac 1{2}\sum_{i=1}^K(n_i-1) $$ $$\Rightarrow \hat \sigma^2_{ML}(v) = \sum_{i=1}^{K}\frac {n_i}{N-K} v_i \qquad [3]$$ Note that here, unlike the case of the MLE for the population mean, the sample variances are not combined into a convex combination - and this has the interesting consequence that by combining in this way the biased estimators $v_i$, the estimator $\hat \sigma^2_{ML}(v)$ becomes an unbiased estimator. By using the scaling and summation properties of the Gamma distribution we have that $$v_i \sim \operatorname{Gamma}\left(\frac {n_i-1}{2},\; \frac {2\sigma^2}{n_i}\right) \Rightarrow \frac {n_i}{N-K} v_i \sim \operatorname{Gamma}\left(\frac {n_i-1}{2},\; \frac {2\sigma^2}{N-K}\right)$$ $$\Rightarrow \sum_{i=1}^{K}\frac {n_i}{N-K} v_i \sim \operatorname{Gamma}\left(\frac {N-K}{2},\; \frac {2\sigma^2}{N-K}\right) $$ and so $$E\left(\hat \sigma^2_{ML}(v)\right) = \frac {N-K}{2}\frac {2\sigma^2}{N-K} =\sigma^2$$ and $$\operatorname{Var}\left(\hat \sigma^2_{ML}(v)\right) = \frac {N-K}{2}\left(\frac {2\sigma^2}{N-K}\right)^2 = \frac {2\sigma^4}{N-K}$$ Note that this unbiasedness property of $\hat \sigma^2_{ML}(v)$ would not obtain if we have used the unbiased formula (dividing the sum of squared differences in each sample by $n_i-1$ instead of $n_i$) to calculate each sample variance: we need to... "be loyal to ML spirit" from the beginning to be rewarded in the end!
Averaging multiple distributions
(I expand this answer to cover more completely a setup that occurs frequently, and also, to focus on the estimation of the population variance). The setup is as follows: from $K$ independent samples
Averaging multiple distributions (I expand this answer to cover more completely a setup that occurs frequently, and also, to focus on the estimation of the population variance). The setup is as follows: from $K$ independent samples that all come from a normal i.i.d. population $N(\mu, \sigma^2)$ and have varying sizes, $n_1+...+n_K = N$, we are not given the actual sample data but only a) The sample sizes $n_i, i=1,...,k$ b) The sample mean of each sample, $m_i = \frac 1{n_i}\sum_{j=1}^{n_i}x_j$ c) The sample variance of each sample, $v_i = \frac 1{n_i}\sum_{j=1}^{n_i}(x_j-m_i)^2 = \frac 1{n_i}\sum_{j=1}^{n_i}x_j^2-m_i^2$ Note that we consider the maximum likelihood estimator of the population variance, i.e. we divide by $n_i$ and not by $n_i-1$. We want to derive maximum likelihood estimators for the unknown population parameters, $\mu$, and $\sigma^2$, by using the information we are given. A) MLE of population mean Under the maintained hypothesis the sample means are normally distributed, and each sample mean $m_i \sim N(\mu, \frac {\sigma^2}{n_i})$. The samples are independent so the joint density/likelihood function of the sample means is $$L(\mu, \sigma^2\mid \{m_1,...,m_K\})= \prod_{i=1}^K\frac {\sqrt {n_i}} {\sqrt{2\pi}\sigma}\exp\left\{-\frac 12 \frac {(m_i-\mu)^2}{\sigma^2/n_i}\right\}$$ and the log-likelihood is $$\ln L(\mu, \sigma^2\mid \{m_1,...,m_K\})= c -K\ln\sigma -\frac 1{2\sigma^2} \sum_{i=1}^Kn_i(m_i-\mu)^2$$ Setting the first derivative of $\ln L$ w.r.t to $\mu$ equal to zero we have $$\frac {\partial}{\partial \mu} \ln L = 0 \Rightarrow \frac 1{\sigma^2} \sum_{i=1}^Kn_i(m_i-\mu) =0 \Rightarrow \sum_{i=1}^Kn_im_i - \mu\sum_{i=1}^Kn_i =0$$ $$\Rightarrow \hat \mu_{ML} = \sum_{i=1}^K\frac {n_i}{N}m_i = \sum_{i=1}^K\frac {n_i}{N}\left(\frac 1{n_i}\sum_{j=1}^{n_i}x_j\right) = \frac 1N\sum_{j=1}^{N}x_j = \bar X_N \qquad [1]$$ So the MLE of the population mean, weighs each sample mean by the (relative) sample size from which it was derived, becoming a convex combination of the $K$ sample means, and so it ends up numerically equivalent to the full-sample mean we would obtain if we had the original data available and had pooled them in one sample. Note: although we have $k$ estimates of the population variance available, they do not enter the likelihood, because the maintained assumption is that all samples come from the same population. If instead of $\sigma^2/n_i$ we had included in the likelihood $v_i/n_i$, we would have violated this assumption. A comment that refers to known variances (and provides the correct formula for this case), covers essentially the case where the various samples do not come from the same population (and more over, the variances are known and not estimated). B) MLE of population variance We could derive an MLE of the population variance using the above likelihood as $$\hat \sigma ^2_{ML} = \frac 1K\sum_{i=1}^Kn_i(m_i-\hat \mu_{ML})^2 \qquad [2]$$ This is a biased estimator (due to the estimation error associated with $\hat \mu_{ML}$), and also, shouldn't we take into account the estimated variances derived from each sample, the $v_i$'s? We know that $$\frac {n_iv_i}{\sigma^2} \equiv z \sim \chi^2(n_i-1)$$ Then $$v_i = \frac {\sigma^2}{n_i} z \sim \operatorname{Gamma}(k_i,\theta_i),\;\; k_i = \frac {n_i-1}{2},\;\; \theta_i = \frac {2\sigma^2}{n_i}$$ with the Gamma density given by $$f_{v_i}(v_i) = \frac 1{\Gamma(k_i)\theta_i^{k_i}}v_i^{k_i-1}\exp\left\{-\frac {v_i}{\theta_i}\right\}$$ The $v_i$'s are independent random variables, so they form the following log-likelihood: $$\ln L_v = c- \sum_{i=1}^Kk_i\ln \theta_i+\sum_{i=1}^K(k_i-1)\ln v_i-\sum_{i=1}^K\frac {v_i}{\theta_i}$$ Note that the shape parameters, $k_i$'s are known, and all $\theta$'s are functions of the same unknown parameter, $\sigma^2$. Setting the first derivative of the log-likelihood w.r.t. $\sigma^2$ equal to zero we get $$\frac {\partial}{\partial \sigma^2} \ln L_v = 0 \Rightarrow -\sum_{i=1}^K\frac {k_i}{\theta_i}\frac {2}{n_i} + \sum_{i=1}^K\frac {v_i}{\theta_i^2}\frac {2}{n_i} =0$$ $$\Rightarrow \frac 1{\sigma^4}\sum_{i=1}^K\frac {n_i^2v_i}{4}\frac {2}{n_i} = \frac 1{\sigma^2}\sum_{i=1}^Kk_i\frac {n_i}{2}\frac {2}{n_i}$$ and simplifying and using also $k_i=(n_i-1)/2$ we obtain $$\frac 1{2\sigma^2}\sum_{i=1}^Kn_iv_i = \frac 1{2}\sum_{i=1}^K(n_i-1) $$ $$\Rightarrow \hat \sigma^2_{ML}(v) = \sum_{i=1}^{K}\frac {n_i}{N-K} v_i \qquad [3]$$ Note that here, unlike the case of the MLE for the population mean, the sample variances are not combined into a convex combination - and this has the interesting consequence that by combining in this way the biased estimators $v_i$, the estimator $\hat \sigma^2_{ML}(v)$ becomes an unbiased estimator. By using the scaling and summation properties of the Gamma distribution we have that $$v_i \sim \operatorname{Gamma}\left(\frac {n_i-1}{2},\; \frac {2\sigma^2}{n_i}\right) \Rightarrow \frac {n_i}{N-K} v_i \sim \operatorname{Gamma}\left(\frac {n_i-1}{2},\; \frac {2\sigma^2}{N-K}\right)$$ $$\Rightarrow \sum_{i=1}^{K}\frac {n_i}{N-K} v_i \sim \operatorname{Gamma}\left(\frac {N-K}{2},\; \frac {2\sigma^2}{N-K}\right) $$ and so $$E\left(\hat \sigma^2_{ML}(v)\right) = \frac {N-K}{2}\frac {2\sigma^2}{N-K} =\sigma^2$$ and $$\operatorname{Var}\left(\hat \sigma^2_{ML}(v)\right) = \frac {N-K}{2}\left(\frac {2\sigma^2}{N-K}\right)^2 = \frac {2\sigma^4}{N-K}$$ Note that this unbiasedness property of $\hat \sigma^2_{ML}(v)$ would not obtain if we have used the unbiased formula (dividing the sum of squared differences in each sample by $n_i-1$ instead of $n_i$) to calculate each sample variance: we need to... "be loyal to ML spirit" from the beginning to be rewarded in the end!
Averaging multiple distributions (I expand this answer to cover more completely a setup that occurs frequently, and also, to focus on the estimation of the population variance). The setup is as follows: from $K$ independent samples
36,963
T-test with sample standard deviation of zero. Possible?
Since this question is getting a fair number of hits, and I stumbled across it on Google when I was looking for similar information, I am going to expand on the comments above. The Purpose Of The T Test What we are doing when we do a t test is measuring the number of standard deviations our measured mean is from the baseline mean, while taking into account that the standard deviation of the mean can change as we get more data. For instance if I have a know the standard deviation of a set, and I draw a single point from that set, we expect a bell curve to define the probability distribution of the point that I draw. The bell curve is defined by the 's' in the t test equation. However as you draw more samples from that set, and interesting thing happens. The standard deviation of the mean value of all the samples is actually less than the standard deviation of the set. The decrease is proportional to the square root of n, which is the division by the square root of n that is in the t test equation. A useful example that I like to think of is what happens when you are rolling dice. When you roll a single die you are equally likely to get any value between 1 and 6, with an average value of 3.5. The standard deviation of that result is 1.7078. Now if you roll two dice and take their average, it is still 3.5. But not equally likely to get all the possible averages. You are actually more likely to get an average near 3.5 than one near 1 or 6. (This is a fact the casinos exploit in the game 'craps' since 7 is the most likely sum of two dice) The probability distribution of that average for 1, 2, and 3 dice is shown below. The standard deviation for the average of 1 die is 1.7078, for two dice it is 1.207, for 3 dice it is .986. This has the effect of narrowing the bell curve in the t-test, which results in a higher 't' value. This is shown below As the bell curve gets narrower and narrower, the t value increases towards infinity. What you have seen in your question is a standard deviation of zero. That reflects an infinitely narrow bell curve. As a result t value would be infinity, i.e. you could be completely confident that you had a statistically significant difference. That is a similar effect as what you would see if you had an infinitely large sample size, since that would also make the bell curve infinitely narrow. Now as whuber and Nick Cox pointed out in the comments on the original question, you do have to think if you really have a zero standard deviation. Rounding of the data or other forms of truncation could give zero standard deviation when in fact you have some. And if the difference that you are trying to measure is within your measurement error that is a problem not addressed by the t-test. I have expanded on the analogy of how the normal curve decreasing in width vs rolling dice in this blog post here and I also have a short Kindle book on different examples of using the t-test and z test here
T-test with sample standard deviation of zero. Possible?
Since this question is getting a fair number of hits, and I stumbled across it on Google when I was looking for similar information, I am going to expand on the comments above. The Purpose Of The T Te
T-test with sample standard deviation of zero. Possible? Since this question is getting a fair number of hits, and I stumbled across it on Google when I was looking for similar information, I am going to expand on the comments above. The Purpose Of The T Test What we are doing when we do a t test is measuring the number of standard deviations our measured mean is from the baseline mean, while taking into account that the standard deviation of the mean can change as we get more data. For instance if I have a know the standard deviation of a set, and I draw a single point from that set, we expect a bell curve to define the probability distribution of the point that I draw. The bell curve is defined by the 's' in the t test equation. However as you draw more samples from that set, and interesting thing happens. The standard deviation of the mean value of all the samples is actually less than the standard deviation of the set. The decrease is proportional to the square root of n, which is the division by the square root of n that is in the t test equation. A useful example that I like to think of is what happens when you are rolling dice. When you roll a single die you are equally likely to get any value between 1 and 6, with an average value of 3.5. The standard deviation of that result is 1.7078. Now if you roll two dice and take their average, it is still 3.5. But not equally likely to get all the possible averages. You are actually more likely to get an average near 3.5 than one near 1 or 6. (This is a fact the casinos exploit in the game 'craps' since 7 is the most likely sum of two dice) The probability distribution of that average for 1, 2, and 3 dice is shown below. The standard deviation for the average of 1 die is 1.7078, for two dice it is 1.207, for 3 dice it is .986. This has the effect of narrowing the bell curve in the t-test, which results in a higher 't' value. This is shown below As the bell curve gets narrower and narrower, the t value increases towards infinity. What you have seen in your question is a standard deviation of zero. That reflects an infinitely narrow bell curve. As a result t value would be infinity, i.e. you could be completely confident that you had a statistically significant difference. That is a similar effect as what you would see if you had an infinitely large sample size, since that would also make the bell curve infinitely narrow. Now as whuber and Nick Cox pointed out in the comments on the original question, you do have to think if you really have a zero standard deviation. Rounding of the data or other forms of truncation could give zero standard deviation when in fact you have some. And if the difference that you are trying to measure is within your measurement error that is a problem not addressed by the t-test. I have expanded on the analogy of how the normal curve decreasing in width vs rolling dice in this blog post here and I also have a short Kindle book on different examples of using the t-test and z test here
T-test with sample standard deviation of zero. Possible? Since this question is getting a fair number of hits, and I stumbled across it on Google when I was looking for similar information, I am going to expand on the comments above. The Purpose Of The T Te
36,964
Time Varying System Matrices in Kalman Filter
If your dynamic system is $$ x_t = A_t x_{t-1} + \eta_t $$ $$ y_t = B_t x_t + \varepsilon_t $$ Then when people say system matrices $A_t, B_t$ should be deterministic, this means that Kalman Filter gives you an estimate of state $x_t$ conditional on past and current values of parameters $$\mathbf E\left(x_t|\,y_t,\dots,y_1, \,A_t,\dots,A_1, \,B_t, \dots, B_1\right).$$ So when you do a filtering step to estimate this conditional expectation of state, you consider those matrices to be already known (observed) rather than unknown and random. Of course they can be realizations of some external random process (which is often the case) or be deterministic functions of time - this doesn't matter much. What seems authors in above paper describe in 3.2 is an extension of KF when they assume $A_t, B_t$ to be random but they don't what to condition on their values when filtering. So they don't assume matrices to be known at the moment of filtering, but rather assume that they come from a distribution with known mean/variance.
Time Varying System Matrices in Kalman Filter
If your dynamic system is $$ x_t = A_t x_{t-1} + \eta_t $$ $$ y_t = B_t x_t + \varepsilon_t $$ Then when people say system matrices $A_t, B_t$ should be deterministic, this means that Kalman Filter g
Time Varying System Matrices in Kalman Filter If your dynamic system is $$ x_t = A_t x_{t-1} + \eta_t $$ $$ y_t = B_t x_t + \varepsilon_t $$ Then when people say system matrices $A_t, B_t$ should be deterministic, this means that Kalman Filter gives you an estimate of state $x_t$ conditional on past and current values of parameters $$\mathbf E\left(x_t|\,y_t,\dots,y_1, \,A_t,\dots,A_1, \,B_t, \dots, B_1\right).$$ So when you do a filtering step to estimate this conditional expectation of state, you consider those matrices to be already known (observed) rather than unknown and random. Of course they can be realizations of some external random process (which is often the case) or be deterministic functions of time - this doesn't matter much. What seems authors in above paper describe in 3.2 is an extension of KF when they assume $A_t, B_t$ to be random but they don't what to condition on their values when filtering. So they don't assume matrices to be known at the moment of filtering, but rather assume that they come from a distribution with known mean/variance.
Time Varying System Matrices in Kalman Filter If your dynamic system is $$ x_t = A_t x_{t-1} + \eta_t $$ $$ y_t = B_t x_t + \varepsilon_t $$ Then when people say system matrices $A_t, B_t$ should be deterministic, this means that Kalman Filter g
36,965
Time Varying System Matrices in Kalman Filter
Can the evolution of time varying system matrices be stochastic? Yes. If your model is $$ x_t = A_t x_{t-1} + \eta_t $$ $$ y_t = B_t x_t + \varepsilon_t $$ and you assume further that $A_t$ and $B_t$ are themselves latent Markov processes, then you might have a model amenable to particle filtering, and in particular Rao-Blackwellized or marginal particle filters. Using these, it will be possible to obtain sampling-based approximations to distributions of the form $$ p(x_{t} \mid y_{1:t}), $$ which would be considered a marginal of the filtering distribution. You wouldn't have to condition on unknown quantities such as $B_t$ or $A_t$. I have some fast c++ code that will allow you to obtain the filtering distributions for models with pretty general dynamics on the "system matrices." Subclass rbpf_kalman with your own model, and all of the functionality is there ready to go.
Time Varying System Matrices in Kalman Filter
Can the evolution of time varying system matrices be stochastic? Yes. If your model is $$ x_t = A_t x_{t-1} + \eta_t $$ $$ y_t = B_t x_t + \varepsilon_t $$ and you assume further that $A_t$ and $B_t$
Time Varying System Matrices in Kalman Filter Can the evolution of time varying system matrices be stochastic? Yes. If your model is $$ x_t = A_t x_{t-1} + \eta_t $$ $$ y_t = B_t x_t + \varepsilon_t $$ and you assume further that $A_t$ and $B_t$ are themselves latent Markov processes, then you might have a model amenable to particle filtering, and in particular Rao-Blackwellized or marginal particle filters. Using these, it will be possible to obtain sampling-based approximations to distributions of the form $$ p(x_{t} \mid y_{1:t}), $$ which would be considered a marginal of the filtering distribution. You wouldn't have to condition on unknown quantities such as $B_t$ or $A_t$. I have some fast c++ code that will allow you to obtain the filtering distributions for models with pretty general dynamics on the "system matrices." Subclass rbpf_kalman with your own model, and all of the functionality is there ready to go.
Time Varying System Matrices in Kalman Filter Can the evolution of time varying system matrices be stochastic? Yes. If your model is $$ x_t = A_t x_{t-1} + \eta_t $$ $$ y_t = B_t x_t + \varepsilon_t $$ and you assume further that $A_t$ and $B_t$
36,966
Standard errors from flexsurvreg
Getting the confidence interval directly Firstly, printing an flexsurvreg object (or its res element) already shows the 95% confidence interval: > expFit Estimates: est L95% U95% se rate 0.007341 0.005746 0.009379 0.000918 Reproducing the the confidence interval manually So I guess you’re asking how to reproduce the above CI manually using the estimated covariance matrix for the parameter estimator. The help page (?flexsurvreg) says that ‘Parameters defined to be positive are estimated on the log scale.’ So we get log-transformed values when we extract the estimates: > lrate = coef(expFit) > lrate [1] -4.914262 To get the actual estimated rate parameter, we need to exponentiate this number: > rate = exp(lrate) > rate [1] 0.007341133 Now to generate a confidence interval, we just need the standard error, and then we can use the normal approximation (Wald confidence interval). The standard error is: > se = sqrt(vcov(expFit)) > se rate rate 0.125 So the confidence interval for the log rate is: > z_alpha = qnorm(1-.05/2) > ci = lrate + c(-1,1)*z_alpha*se > ci [1] -5.159258 -4.669267 To get a 95% CI for the actual rate parameter, we need only exponentiate the two CI limits: > exp(ci) [1] 0.005745964 0.009379146 Which is what expFit$res gave us. Why use the log scale? To get this answer back to statistics instead of just R, why do we calculate the confidence interval on the log scale? Can’t we just use the standard error returned by expFit? Well, we can (in this case): > expFit$res[1] + c(-1,1)*z_alpha*expFit$res[4] [1] 0.005542589 0.009139678 This CI is very similar to the log-based CI. The reason is the large sample size. The actual formula for estimating the rate parameter in an exponential distribution is actually very simple; it’s the number of events divided by the total amount of time: > with(testPatients, sum(status)/sum(time)) [1] 0.007341133 If none of the events were censored, this is 1 divided by the average time to event, which makes sense intuitively. For example, if the time to event is on average 15 minutes (1/4 of an hour), you would expect the events to happen with a rate of 4 per hour. The times were assumed to be i.i.d. exponential with a fixed ‘rate’ parameter. These time variables are thus all right-skewed. The sum of many such independent time variables has a gamma distribution – or approximately a normal distribution for large n (per the central limit theorem). But we’re looking at a constant divided by this sum, i.e. divided by something with a distribution that is a (right-skewed) gamma (for small $n$) or approximately symmetric (a normal distribution in the limit). It’s right-skewed in both cases. For large $n$, the amount of skewness is small (the value of the rate parameter is actually not important for the skewness). The effect of the number of observations in practice In the example data we had 68 observations (of which 4 were censored), which is quite a lot. The distributions of 1) the mean of 68 independent exponential observations (let’s just ignore the censored ones for now) with rate 0.0073, 2) the rate estimate (68 divided by this mean) and 3) the logarithm of this rate estimate look approximately like this: The R code for this image is: library(MASS) sim = function(n, rate) { x = replicate(10^5, mean(rexp(n, rate))) par(mfrow = c(1,3), mai = c(0.9,0.4,0.2,0)) truehist(x, col = "brown", border = NA) truehist(n / x, col = "brown", border = NA) truehist(log(n / x), col = "brown", border = NA) } sim(n = 68, rate = rate) We see that there is some skewness in the distribution for the rate estimator (the middle panel): there’s a tail to the right. But the distribution is approximately symmetric (and normal), so the estimate based on the normal approximation without a log-transform should be quite good. Still, we see from the right-most panel that it is better to use the log-transform even here. If we had only 15 observations, the picture would change: sim(n=15, rate=rate) Here we have very much skewness in the middle panel, and we need to use the log-transform (right panel) to get a good CI. Summary and closing words We calculate the (approximate) confidence interval for the rate parameter on the log scale because the sample distribution of the estimator is more symmetrical and normal on this scale. Note that this is common practice for parameters that must be positive, since the sample distribution of the estimators are then typically right-skewed. (When the standard error is large, using the normal approximation without log-transforming first can in some cases even result in the lower confidence limit for the parameter being less than 0.) Also note there are also other transformations besides the log transformation that can be useful for transforming estimators to be more symmetrical/normal, and that can be more suitable for some distributions/parameters. But the log transform is the most commonly used.
Standard errors from flexsurvreg
Getting the confidence interval directly Firstly, printing an flexsurvreg object (or its res element) already shows the 95% confidence interval: > expFit Estimates: est L95% U95%
Standard errors from flexsurvreg Getting the confidence interval directly Firstly, printing an flexsurvreg object (or its res element) already shows the 95% confidence interval: > expFit Estimates: est L95% U95% se rate 0.007341 0.005746 0.009379 0.000918 Reproducing the the confidence interval manually So I guess you’re asking how to reproduce the above CI manually using the estimated covariance matrix for the parameter estimator. The help page (?flexsurvreg) says that ‘Parameters defined to be positive are estimated on the log scale.’ So we get log-transformed values when we extract the estimates: > lrate = coef(expFit) > lrate [1] -4.914262 To get the actual estimated rate parameter, we need to exponentiate this number: > rate = exp(lrate) > rate [1] 0.007341133 Now to generate a confidence interval, we just need the standard error, and then we can use the normal approximation (Wald confidence interval). The standard error is: > se = sqrt(vcov(expFit)) > se rate rate 0.125 So the confidence interval for the log rate is: > z_alpha = qnorm(1-.05/2) > ci = lrate + c(-1,1)*z_alpha*se > ci [1] -5.159258 -4.669267 To get a 95% CI for the actual rate parameter, we need only exponentiate the two CI limits: > exp(ci) [1] 0.005745964 0.009379146 Which is what expFit$res gave us. Why use the log scale? To get this answer back to statistics instead of just R, why do we calculate the confidence interval on the log scale? Can’t we just use the standard error returned by expFit? Well, we can (in this case): > expFit$res[1] + c(-1,1)*z_alpha*expFit$res[4] [1] 0.005542589 0.009139678 This CI is very similar to the log-based CI. The reason is the large sample size. The actual formula for estimating the rate parameter in an exponential distribution is actually very simple; it’s the number of events divided by the total amount of time: > with(testPatients, sum(status)/sum(time)) [1] 0.007341133 If none of the events were censored, this is 1 divided by the average time to event, which makes sense intuitively. For example, if the time to event is on average 15 minutes (1/4 of an hour), you would expect the events to happen with a rate of 4 per hour. The times were assumed to be i.i.d. exponential with a fixed ‘rate’ parameter. These time variables are thus all right-skewed. The sum of many such independent time variables has a gamma distribution – or approximately a normal distribution for large n (per the central limit theorem). But we’re looking at a constant divided by this sum, i.e. divided by something with a distribution that is a (right-skewed) gamma (for small $n$) or approximately symmetric (a normal distribution in the limit). It’s right-skewed in both cases. For large $n$, the amount of skewness is small (the value of the rate parameter is actually not important for the skewness). The effect of the number of observations in practice In the example data we had 68 observations (of which 4 were censored), which is quite a lot. The distributions of 1) the mean of 68 independent exponential observations (let’s just ignore the censored ones for now) with rate 0.0073, 2) the rate estimate (68 divided by this mean) and 3) the logarithm of this rate estimate look approximately like this: The R code for this image is: library(MASS) sim = function(n, rate) { x = replicate(10^5, mean(rexp(n, rate))) par(mfrow = c(1,3), mai = c(0.9,0.4,0.2,0)) truehist(x, col = "brown", border = NA) truehist(n / x, col = "brown", border = NA) truehist(log(n / x), col = "brown", border = NA) } sim(n = 68, rate = rate) We see that there is some skewness in the distribution for the rate estimator (the middle panel): there’s a tail to the right. But the distribution is approximately symmetric (and normal), so the estimate based on the normal approximation without a log-transform should be quite good. Still, we see from the right-most panel that it is better to use the log-transform even here. If we had only 15 observations, the picture would change: sim(n=15, rate=rate) Here we have very much skewness in the middle panel, and we need to use the log-transform (right panel) to get a good CI. Summary and closing words We calculate the (approximate) confidence interval for the rate parameter on the log scale because the sample distribution of the estimator is more symmetrical and normal on this scale. Note that this is common practice for parameters that must be positive, since the sample distribution of the estimators are then typically right-skewed. (When the standard error is large, using the normal approximation without log-transforming first can in some cases even result in the lower confidence limit for the parameter being less than 0.) Also note there are also other transformations besides the log transformation that can be useful for transforming estimators to be more symmetrical/normal, and that can be more suitable for some distributions/parameters. But the log transform is the most commonly used.
Standard errors from flexsurvreg Getting the confidence interval directly Firstly, printing an flexsurvreg object (or its res element) already shows the 95% confidence interval: > expFit Estimates: est L95% U95%
36,967
Weights in quantile regression for complex survey in R
i am not sure @Metrics answer will give the correct standard errors for a survey-weighted quantreg call. here's an example of what you're trying to do. you are certainly hitting a bug because the qr function nested within the withReplicates function at this point cannot handle multiple tau parameters at once (even though the qr function on its own might). just call one at a time, perhaps like this :) library(survey) library(quantreg) # load some fake data data(scd) repweights <- cbind(c(4,0,3,0,4,0), c(3,0,0,4,0,3),c(0,3,4,0,0,2),c(0,1,0,4,3,0)) # tack on the fake replicate weights x <- cbind( scd , repweights ) # tack on some fake main weights x[,9] <- c( 3 , 2 , 3 , 4 , 1 , 4 ) # name your weight columns names( x )[ 5:9 ] <- c( paste0( 'rep' , 1:4 ) , "wgt" ) # create a replicate-weighted survey design object scdrep <- svrepdesign( data = x , type = "BRR" , repweights = "rep" , weights = ~wgt , combined.weights = TRUE ) # loop through each desired value of `tau` for ( i in seq( 0.1 , 0.9 , by = 0.1 ) ){ print( i ) # follow the call described here: # http://www.isr.umich.edu/src/smp/asda/Additional%20R%20Examples%20bootstrapping%20with%20quantile%20regression.pdf print( withReplicates( scdrep , quote( coef( rq( arrests ~ alive , tau = i , weights = .weights ) ) ) ) ) }
Weights in quantile regression for complex survey in R
i am not sure @Metrics answer will give the correct standard errors for a survey-weighted quantreg call. here's an example of what you're trying to do. you are certainly hitting a bug because the qr
Weights in quantile regression for complex survey in R i am not sure @Metrics answer will give the correct standard errors for a survey-weighted quantreg call. here's an example of what you're trying to do. you are certainly hitting a bug because the qr function nested within the withReplicates function at this point cannot handle multiple tau parameters at once (even though the qr function on its own might). just call one at a time, perhaps like this :) library(survey) library(quantreg) # load some fake data data(scd) repweights <- cbind(c(4,0,3,0,4,0), c(3,0,0,4,0,3),c(0,3,4,0,0,2),c(0,1,0,4,3,0)) # tack on the fake replicate weights x <- cbind( scd , repweights ) # tack on some fake main weights x[,9] <- c( 3 , 2 , 3 , 4 , 1 , 4 ) # name your weight columns names( x )[ 5:9 ] <- c( paste0( 'rep' , 1:4 ) , "wgt" ) # create a replicate-weighted survey design object scdrep <- svrepdesign( data = x , type = "BRR" , repweights = "rep" , weights = ~wgt , combined.weights = TRUE ) # loop through each desired value of `tau` for ( i in seq( 0.1 , 0.9 , by = 0.1 ) ){ print( i ) # follow the call described here: # http://www.isr.umich.edu/src/smp/asda/Additional%20R%20Examples%20bootstrapping%20with%20quantile%20regression.pdf print( withReplicates( scdrep , quote( coef( rq( arrests ~ alive , tau = i , weights = .weights ) ) ) ) ) }
Weights in quantile regression for complex survey in R i am not sure @Metrics answer will give the correct standard errors for a survey-weighted quantreg call. here's an example of what you're trying to do. you are certainly hitting a bug because the qr
36,968
Weights in quantile regression for complex survey in R
The usage of rq in quantreg package rq(formula, tau=.5, data, subset, weights, na.action, method="br", model = TRUE, contrasts, ...) where, weights=vector of observation weights; if supplied, the algorithm fits to minimize the sum of the weights multiplied into the absolute residuals. The length of weights must be the same as the number of observations. The weights must be nonnegative and it is strongly recommended that they be strictly positive, since zero weights are ambiguous. Please make sure whether you have zero weights in your observations.
Weights in quantile regression for complex survey in R
The usage of rq in quantreg package rq(formula, tau=.5, data, subset, weights, na.action, method="br", model = TRUE, contrasts, ...) where, weights=vector of observation weights; if supplied, the al
Weights in quantile regression for complex survey in R The usage of rq in quantreg package rq(formula, tau=.5, data, subset, weights, na.action, method="br", model = TRUE, contrasts, ...) where, weights=vector of observation weights; if supplied, the algorithm fits to minimize the sum of the weights multiplied into the absolute residuals. The length of weights must be the same as the number of observations. The weights must be nonnegative and it is strongly recommended that they be strictly positive, since zero weights are ambiguous. Please make sure whether you have zero weights in your observations.
Weights in quantile regression for complex survey in R The usage of rq in quantreg package rq(formula, tau=.5, data, subset, weights, na.action, method="br", model = TRUE, contrasts, ...) where, weights=vector of observation weights; if supplied, the al
36,969
Models for Generalized Estimating Equation?
I prefer to call GEE an estimation method compared to ML or REML, since it combines quasi-likelihood estimation with robust variance estimation to estimate generalized linear marginal models for longitudinal data. Some texts and papers also call "GEE models", e.g. Hedeker, D., & Gibbons, R. D. (2006). Longitudinal data analysis. Wiley-Interscience. I guess it is to separate it from subject-specific (fixed and random effects) models, since GEE is mainly regarded as or marginal (population average) models. We have no idea about the distribution function of the outcome, but we know its mean ($\mu$) and variance ($V$). So we cannot do ML but we can turn to the quasi-likelihood, $$Q(\mu,y)=\int^{\mu}_y(y-t)^TV^{-1}dt,$$ and the quasi-likelihood estimating equations (quasi-score function) is $$\sum_i\frac{\partial{\mu_i^{'}}}{\partial{\beta}}V_i^{-1}(y_i-\mu_i)=0.$$ Thus the estimating equations are derived without specifying the joint distribution of a outcomes but they reduce to the score equations (marginal distributions). The approach based on maximum likelihood (ML) estimation specifies the joint multivariate normal distribution of outcome variables, while the approach of GEE based on the quasi-likelihood specifies only the marginal distributions. I have seen GEE was applied in statistical genetics, but I am afraid it is also under the framework of generalized linear models.
Models for Generalized Estimating Equation?
I prefer to call GEE an estimation method compared to ML or REML, since it combines quasi-likelihood estimation with robust variance estimation to estimate generalized linear marginal models for longi
Models for Generalized Estimating Equation? I prefer to call GEE an estimation method compared to ML or REML, since it combines quasi-likelihood estimation with robust variance estimation to estimate generalized linear marginal models for longitudinal data. Some texts and papers also call "GEE models", e.g. Hedeker, D., & Gibbons, R. D. (2006). Longitudinal data analysis. Wiley-Interscience. I guess it is to separate it from subject-specific (fixed and random effects) models, since GEE is mainly regarded as or marginal (population average) models. We have no idea about the distribution function of the outcome, but we know its mean ($\mu$) and variance ($V$). So we cannot do ML but we can turn to the quasi-likelihood, $$Q(\mu,y)=\int^{\mu}_y(y-t)^TV^{-1}dt,$$ and the quasi-likelihood estimating equations (quasi-score function) is $$\sum_i\frac{\partial{\mu_i^{'}}}{\partial{\beta}}V_i^{-1}(y_i-\mu_i)=0.$$ Thus the estimating equations are derived without specifying the joint distribution of a outcomes but they reduce to the score equations (marginal distributions). The approach based on maximum likelihood (ML) estimation specifies the joint multivariate normal distribution of outcome variables, while the approach of GEE based on the quasi-likelihood specifies only the marginal distributions. I have seen GEE was applied in statistical genetics, but I am afraid it is also under the framework of generalized linear models.
Models for Generalized Estimating Equation? I prefer to call GEE an estimation method compared to ML or REML, since it combines quasi-likelihood estimation with robust variance estimation to estimate generalized linear marginal models for longi
36,970
Estimating the mean and variance of a stationary time series
On the question about the mean - yes, I would have thought so. Stationarity means $E[Y_t]=c$ for all $t$ and the sample mean should estimate $c$. On the variance (I hope this helps): Say you have a stationary, zero mean AR(1) series: $Y_t = \phi Y_{t-1} + e_t$ Where $\{e_t\}$ is white noise. Then if you take Var$(Y_t)$ you get: Var$(Y_t) = \frac{\sigma^2}{1 - \phi^2} > \sigma^2 = $Var$(e_t)$ Say we have just observed $Y_{t}$ and are about to tick into time $t+1$, then we are in a conditional situation instead: Var$(Y_{t+1}|Y_t)=E[(Y_{t+1}-E[Y_{t+1}|Y_t])^2|Y_t] $ $= E[(Y_{t+1} - \phi Y_t)^2 | Y_t]$ $= E[ e_{t+1}^2 | Y_t] = $Var$(e_t) = \sigma^2$ Thinking about it, it seems to me this is the right way to imagine the process, as it can only be constructed one step at a time since each step depends on previous values. Thinking about Var$(Y_{t+1})$ assumes we have all the instantiations of $\{Y_t\}$ at once, but they had to be laid down one-at-a-time, leading us to Var$(Y_{t+1}|Y_t)$. Obviously, this is just for AR(1)...
Estimating the mean and variance of a stationary time series
On the question about the mean - yes, I would have thought so. Stationarity means $E[Y_t]=c$ for all $t$ and the sample mean should estimate $c$. On the variance (I hope this helps): Say you have a st
Estimating the mean and variance of a stationary time series On the question about the mean - yes, I would have thought so. Stationarity means $E[Y_t]=c$ for all $t$ and the sample mean should estimate $c$. On the variance (I hope this helps): Say you have a stationary, zero mean AR(1) series: $Y_t = \phi Y_{t-1} + e_t$ Where $\{e_t\}$ is white noise. Then if you take Var$(Y_t)$ you get: Var$(Y_t) = \frac{\sigma^2}{1 - \phi^2} > \sigma^2 = $Var$(e_t)$ Say we have just observed $Y_{t}$ and are about to tick into time $t+1$, then we are in a conditional situation instead: Var$(Y_{t+1}|Y_t)=E[(Y_{t+1}-E[Y_{t+1}|Y_t])^2|Y_t] $ $= E[(Y_{t+1} - \phi Y_t)^2 | Y_t]$ $= E[ e_{t+1}^2 | Y_t] = $Var$(e_t) = \sigma^2$ Thinking about it, it seems to me this is the right way to imagine the process, as it can only be constructed one step at a time since each step depends on previous values. Thinking about Var$(Y_{t+1})$ assumes we have all the instantiations of $\{Y_t\}$ at once, but they had to be laid down one-at-a-time, leading us to Var$(Y_{t+1}|Y_t)$. Obviously, this is just for AR(1)...
Estimating the mean and variance of a stationary time series On the question about the mean - yes, I would have thought so. Stationarity means $E[Y_t]=c$ for all $t$ and the sample mean should estimate $c$. On the variance (I hope this helps): Say you have a st
36,971
Estimating the mean and variance of a stationary time series
If the time series is indeed stationary, you may take the sample variance. However, since your time series is auto-correlated, you may be more interested in the variance of the residuals. Stationary means that the joint distribution of the time series is unaffected by time shifts. Thus, you can define a meaningful marginal distribution for a single point. However, since your time series is auto-correlated, the conditional distribution of a particular value given the preceding values may be quite different from that marginal distribution. The difference between the expected mean at time t, given the time series prior to t, and the actual value is called the innovation. Measuring the variance of the innovation will give you a better idea of how "noisy" the process is. For instance, suppose your time series is given by $X_t = 0.999 X_{t-1} + \epsilon_t$, with $\epsilon_t \sim \mathcal{N}(0,1)$. The variance of $X$ would be $1000$, but, depending on what you're looking at, the variance of $\epsilon$: $1$, might be a better metric.
Estimating the mean and variance of a stationary time series
If the time series is indeed stationary, you may take the sample variance. However, since your time series is auto-correlated, you may be more interested in the variance of the residuals. Stationary m
Estimating the mean and variance of a stationary time series If the time series is indeed stationary, you may take the sample variance. However, since your time series is auto-correlated, you may be more interested in the variance of the residuals. Stationary means that the joint distribution of the time series is unaffected by time shifts. Thus, you can define a meaningful marginal distribution for a single point. However, since your time series is auto-correlated, the conditional distribution of a particular value given the preceding values may be quite different from that marginal distribution. The difference between the expected mean at time t, given the time series prior to t, and the actual value is called the innovation. Measuring the variance of the innovation will give you a better idea of how "noisy" the process is. For instance, suppose your time series is given by $X_t = 0.999 X_{t-1} + \epsilon_t$, with $\epsilon_t \sim \mathcal{N}(0,1)$. The variance of $X$ would be $1000$, but, depending on what you're looking at, the variance of $\epsilon$: $1$, might be a better metric.
Estimating the mean and variance of a stationary time series If the time series is indeed stationary, you may take the sample variance. However, since your time series is auto-correlated, you may be more interested in the variance of the residuals. Stationary m
36,972
How statistical packages calculate power
You're correct that one way to perform a power analysis would be via simulation. You could repeatedly generate 100 observations from a distribution and test those observations against the null hypothesis. If it consistently reported a (true) difference, you could say the test has high power. However, for many common tests, like the t-test, the power/required sample size are computed analytically. If you look at the "guts" of a $t$-statistic, it is based on a few things: The "effect size" $ES$: in your example, $\overline{(X-6)}$ The sample size $n$: 100 in your example, but very necessary! The sample variance $s_n$: not given in your example The significance level/Type I error rate $\alpha$: customarily 0.05 The test works by comparing $$t =\frac{ES\cdot \sqrt{n}}{s_n}$$ to a "critical value"$t_{crit}$ that depends on $\alpha$ and $n$. You could easily rearrange this to solve for $n$ for specific values of the other parameters, and using a bit more math, extend that to calculate power directly. This chapter by John M. Lachin contains a lot more details.
How statistical packages calculate power
You're correct that one way to perform a power analysis would be via simulation. You could repeatedly generate 100 observations from a distribution and test those observations against the null hypothe
How statistical packages calculate power You're correct that one way to perform a power analysis would be via simulation. You could repeatedly generate 100 observations from a distribution and test those observations against the null hypothesis. If it consistently reported a (true) difference, you could say the test has high power. However, for many common tests, like the t-test, the power/required sample size are computed analytically. If you look at the "guts" of a $t$-statistic, it is based on a few things: The "effect size" $ES$: in your example, $\overline{(X-6)}$ The sample size $n$: 100 in your example, but very necessary! The sample variance $s_n$: not given in your example The significance level/Type I error rate $\alpha$: customarily 0.05 The test works by comparing $$t =\frac{ES\cdot \sqrt{n}}{s_n}$$ to a "critical value"$t_{crit}$ that depends on $\alpha$ and $n$. You could easily rearrange this to solve for $n$ for specific values of the other parameters, and using a bit more math, extend that to calculate power directly. This chapter by John M. Lachin contains a lot more details.
How statistical packages calculate power You're correct that one way to perform a power analysis would be via simulation. You could repeatedly generate 100 observations from a distribution and test those observations against the null hypothe
36,973
Appropriate Application of Survival Analysis
I recently had a set of interval censored survival data, so I know exactly what you need. If you have ever used R, this should help. If you don't want to assume a parametric form, how about an interval censored Cox proportional hazards model? The intcox package that would do this is no longer in the R repository. I would suggest imputing survival times and then using the coxph function from the survival library. Keep in mind that your standard errors will be too low using this method; you have not accounted for the uncertainty of not knowing the exact survival time. If you want interval censored survival estimates, use the icfit function from the interval package. Another way analyze the effect of covariates on survival time is by using interval censored, nonparametric regression. See the R package ICE: http://cran.r-project.org/web/packages/ICE/ICE.pdf. You first need to impute the midpoints of survival time, then you do a local linear regression using the locpoly function from the np package. It's not as hard as it sounds.
Appropriate Application of Survival Analysis
I recently had a set of interval censored survival data, so I know exactly what you need. If you have ever used R, this should help. If you don't want to assume a parametric form, how about an interva
Appropriate Application of Survival Analysis I recently had a set of interval censored survival data, so I know exactly what you need. If you have ever used R, this should help. If you don't want to assume a parametric form, how about an interval censored Cox proportional hazards model? The intcox package that would do this is no longer in the R repository. I would suggest imputing survival times and then using the coxph function from the survival library. Keep in mind that your standard errors will be too low using this method; you have not accounted for the uncertainty of not knowing the exact survival time. If you want interval censored survival estimates, use the icfit function from the interval package. Another way analyze the effect of covariates on survival time is by using interval censored, nonparametric regression. See the R package ICE: http://cran.r-project.org/web/packages/ICE/ICE.pdf. You first need to impute the midpoints of survival time, then you do a local linear regression using the locpoly function from the np package. It's not as hard as it sounds.
Appropriate Application of Survival Analysis I recently had a set of interval censored survival data, so I know exactly what you need. If you have ever used R, this should help. If you don't want to assume a parametric form, how about an interva
36,974
Appropriate Application of Survival Analysis
Survival function is usually right-continuous since it is a distribution function, I will use $a_k:=[t_{k-1}, t_k),k=1,2,\cdots,n$ as the interval. Let $T_{ij}$ and $C_{ij}$ be the true continuous survival and censoring time for subject $j$ in sample $i$, respectively. Both variables may not be observed directly, but only in one of the intervals $a_1,a_2,\cdots$. Furthermore, let $X_{ij}$ denote the interval within which $T_{ij}$ falls, essentially a discrete survival time, and similarly $\mathcal{C}_{ij}$ for $C_{ij}$. Then the censoring indicator is given by $\delta_{ij}=\mathbf{1}(X_{ij} \le \mathcal{C}_{ij})$. The hazard function $h_{ij}(x)$ for the discrete survival time is defined as the conditional probability of the event occurring in the $x$th time interval given that it has not occurred prior to the $x-1$th interval, i.e $$ h_{ij}(x)=P(X_{ij}=x | X_{ij} \ge x) $$ and the corresponding survival function $S_{ij}=P(X>x)$ can be written recursively using conditional product law: $$ S_{ij}(x)=P(X_{ij}>x | X_{ij}\ge x)\cdots P(X_{ij}>1 | X_{ij} \ge 1)=\prod_{m=1}^x (1-h_{ij}(m)) $$ The likelihood function of the pair $(x_{ij},\delta_{ij})$ can be constructed as the product of two types of subjects, namely those who experienced an event at $x_{ij}$ ($X_{ij}=x_{ij},\delta_{ij}=1$) and those who were censored at $x_{ij}$ ($X_{ij}>x_{ij},\delta_{ij}=0$): $$ \begin{split} \mathcal{L} &= \prod_{i=1}^{s}\prod_{j=1}^{n_{i}}[P(X_{ij}=x_{ij})]^{\delta_{ij}}[P(X_{ij}>x_{ij})]^{1-\delta_{ij}}\\ & = \prod_{i=1}^{s}\prod_{j=1}^{n_{i}}\left\{\left(h_{ij}(x_{ij})\prod_{m=1}^{x_{ij}-1}[1-h_{ij}(m)]\right)^{\delta_{ij}}\left( \prod_{m=1}^{x_{ij}}[1-h_{ij}(m)]\right)^{1-\delta_{ij}}\right\}\\ & = \prod_{i=1}^{s}\prod_{j=1}^{n_{i}}\left\{\left[\frac{h_{ij}(x_{ij})}{1-h_{ij}(x_{ij})}\right]^{\delta_{ij}}\prod_{m=1}^{x_{ij}}[1-h_{ij}(m)]\right\}. \end{split} $$ and corresponding log-likelihood function is: $$ \ell=\sum_{i=1}^{M}\sum_{j=1}^{n_{i}}\left\{\delta_{ij}\log[\frac{h_{ij}(x_{ij})}{1-h_{ij}(x_{ij})}]+\sum_{m=1}^{x_{ij}}\log[1-h_{ij}(m)]\right\} $$ Now if we reconstruct our data into event history structure, that is recording at each interval, a event indicator variable $y_{ijk}$ for the $k$th interval of the $j$th subject from sample $i$, we can see that $\delta_{ij}\log[h_{ij}(x_{ij})/(1-h_{ij}(x_{ij})]$ in the above rewritten into $\sum_{k=1}^{x_{ij}}y_{ijk} \log[h_{ij}(k)/(1-h_{ij}(k))]$ (basically summing up all the 0's until the last observed interval of this subject, if he has event, it will be 1, if censored 0). Then we can rewrite our log-likelihood as $$ \ell=\sum_{i=1}^s \sum_{j=1}^{n_i} \sum_{k=1}^{x_{ij}} \left\{ y_{ijk} \log h_{ij}(k) + (1 - y_{ijk}) \log [1 - h_{ij}(k)] \right\}. $$ This is identical to the log likelihood for a binary random variable $y_{ijk}$, but now with the proportion $p_{ijk}$ for an event in interval $k$ defined by $h_{ij}(k)$. Now we finally can answer your question. If we would assume, that at same interval, $y_{ijk}$ is i.i.d. for different subject $j$ in sample $i$, and also across different sample, then $\bar{M_j}=(\sum_i n_i)^{-1}\sum_{i=1}^{s}\sum_{j=1}^{n_i}y_{ijk}$ is the appropriate estimator for $h_{ij}(k)=h(k)$. And the appropriate estimator for $S(x)$ is therefore $\hat{S}(x)=\prod_{k=1}^{x}(1-\bar{M}_j)$.
Appropriate Application of Survival Analysis
Survival function is usually right-continuous since it is a distribution function, I will use $a_k:=[t_{k-1}, t_k),k=1,2,\cdots,n$ as the interval. Let $T_{ij}$ and $C_{ij}$ be the true continuous su
Appropriate Application of Survival Analysis Survival function is usually right-continuous since it is a distribution function, I will use $a_k:=[t_{k-1}, t_k),k=1,2,\cdots,n$ as the interval. Let $T_{ij}$ and $C_{ij}$ be the true continuous survival and censoring time for subject $j$ in sample $i$, respectively. Both variables may not be observed directly, but only in one of the intervals $a_1,a_2,\cdots$. Furthermore, let $X_{ij}$ denote the interval within which $T_{ij}$ falls, essentially a discrete survival time, and similarly $\mathcal{C}_{ij}$ for $C_{ij}$. Then the censoring indicator is given by $\delta_{ij}=\mathbf{1}(X_{ij} \le \mathcal{C}_{ij})$. The hazard function $h_{ij}(x)$ for the discrete survival time is defined as the conditional probability of the event occurring in the $x$th time interval given that it has not occurred prior to the $x-1$th interval, i.e $$ h_{ij}(x)=P(X_{ij}=x | X_{ij} \ge x) $$ and the corresponding survival function $S_{ij}=P(X>x)$ can be written recursively using conditional product law: $$ S_{ij}(x)=P(X_{ij}>x | X_{ij}\ge x)\cdots P(X_{ij}>1 | X_{ij} \ge 1)=\prod_{m=1}^x (1-h_{ij}(m)) $$ The likelihood function of the pair $(x_{ij},\delta_{ij})$ can be constructed as the product of two types of subjects, namely those who experienced an event at $x_{ij}$ ($X_{ij}=x_{ij},\delta_{ij}=1$) and those who were censored at $x_{ij}$ ($X_{ij}>x_{ij},\delta_{ij}=0$): $$ \begin{split} \mathcal{L} &= \prod_{i=1}^{s}\prod_{j=1}^{n_{i}}[P(X_{ij}=x_{ij})]^{\delta_{ij}}[P(X_{ij}>x_{ij})]^{1-\delta_{ij}}\\ & = \prod_{i=1}^{s}\prod_{j=1}^{n_{i}}\left\{\left(h_{ij}(x_{ij})\prod_{m=1}^{x_{ij}-1}[1-h_{ij}(m)]\right)^{\delta_{ij}}\left( \prod_{m=1}^{x_{ij}}[1-h_{ij}(m)]\right)^{1-\delta_{ij}}\right\}\\ & = \prod_{i=1}^{s}\prod_{j=1}^{n_{i}}\left\{\left[\frac{h_{ij}(x_{ij})}{1-h_{ij}(x_{ij})}\right]^{\delta_{ij}}\prod_{m=1}^{x_{ij}}[1-h_{ij}(m)]\right\}. \end{split} $$ and corresponding log-likelihood function is: $$ \ell=\sum_{i=1}^{M}\sum_{j=1}^{n_{i}}\left\{\delta_{ij}\log[\frac{h_{ij}(x_{ij})}{1-h_{ij}(x_{ij})}]+\sum_{m=1}^{x_{ij}}\log[1-h_{ij}(m)]\right\} $$ Now if we reconstruct our data into event history structure, that is recording at each interval, a event indicator variable $y_{ijk}$ for the $k$th interval of the $j$th subject from sample $i$, we can see that $\delta_{ij}\log[h_{ij}(x_{ij})/(1-h_{ij}(x_{ij})]$ in the above rewritten into $\sum_{k=1}^{x_{ij}}y_{ijk} \log[h_{ij}(k)/(1-h_{ij}(k))]$ (basically summing up all the 0's until the last observed interval of this subject, if he has event, it will be 1, if censored 0). Then we can rewrite our log-likelihood as $$ \ell=\sum_{i=1}^s \sum_{j=1}^{n_i} \sum_{k=1}^{x_{ij}} \left\{ y_{ijk} \log h_{ij}(k) + (1 - y_{ijk}) \log [1 - h_{ij}(k)] \right\}. $$ This is identical to the log likelihood for a binary random variable $y_{ijk}$, but now with the proportion $p_{ijk}$ for an event in interval $k$ defined by $h_{ij}(k)$. Now we finally can answer your question. If we would assume, that at same interval, $y_{ijk}$ is i.i.d. for different subject $j$ in sample $i$, and also across different sample, then $\bar{M_j}=(\sum_i n_i)^{-1}\sum_{i=1}^{s}\sum_{j=1}^{n_i}y_{ijk}$ is the appropriate estimator for $h_{ij}(k)=h(k)$. And the appropriate estimator for $S(x)$ is therefore $\hat{S}(x)=\prod_{k=1}^{x}(1-\bar{M}_j)$.
Appropriate Application of Survival Analysis Survival function is usually right-continuous since it is a distribution function, I will use $a_k:=[t_{k-1}, t_k),k=1,2,\cdots,n$ as the interval. Let $T_{ij}$ and $C_{ij}$ be the true continuous su
36,975
Capture-recapture sampling valid in literary analysis?
Capture-recapture relies on random samples on both occasions. You somehow need to make a random sample from the unknown pool of characters, count them, then make another, totally independent sample, and count the overlap. In biology, capture-recapture works because you expect that marked fish mingle with others in the closed volume to the extent that two months later, the marked fish have distributed themselves in the entire volume of the lake, so by taking another random measurement, you can get an independent sample. Thus randomness of the two samples is comprised of (i) taking the samples of fish in randomly selected portions of the lake; (ii) relying on natural biological mixing processes to re-distribute the marked fish around. Implementing capture-recapture in social sciences (which is where your little project falls into) is very difficult, as some people/characters are systematically easier to capture into the sample than others. Sometimes, network samples are used to estimate the sizes of unknown hard to reach populations, but they rely on some sort of social dynamics to move the sample on. Among other works that tried to look into how complete a given collection/list may be, I can recall David Banks' work on how complete Wikipedia is and Brad Efron's and Ron Thisted's empirical Bayes work on how many words Shakespeare knew. So using capture-recapture for literary work is about 35 years old -- sorry to break the bad news to you ;). I think if you produce a solid research, this would be a very appropriate publication for Significance joint magazine of the Royal Statistical Society and the American Statistical Association.
Capture-recapture sampling valid in literary analysis?
Capture-recapture relies on random samples on both occasions. You somehow need to make a random sample from the unknown pool of characters, count them, then make another, totally independent sample, a
Capture-recapture sampling valid in literary analysis? Capture-recapture relies on random samples on both occasions. You somehow need to make a random sample from the unknown pool of characters, count them, then make another, totally independent sample, and count the overlap. In biology, capture-recapture works because you expect that marked fish mingle with others in the closed volume to the extent that two months later, the marked fish have distributed themselves in the entire volume of the lake, so by taking another random measurement, you can get an independent sample. Thus randomness of the two samples is comprised of (i) taking the samples of fish in randomly selected portions of the lake; (ii) relying on natural biological mixing processes to re-distribute the marked fish around. Implementing capture-recapture in social sciences (which is where your little project falls into) is very difficult, as some people/characters are systematically easier to capture into the sample than others. Sometimes, network samples are used to estimate the sizes of unknown hard to reach populations, but they rely on some sort of social dynamics to move the sample on. Among other works that tried to look into how complete a given collection/list may be, I can recall David Banks' work on how complete Wikipedia is and Brad Efron's and Ron Thisted's empirical Bayes work on how many words Shakespeare knew. So using capture-recapture for literary work is about 35 years old -- sorry to break the bad news to you ;). I think if you produce a solid research, this would be a very appropriate publication for Significance joint magazine of the Royal Statistical Society and the American Statistical Association.
Capture-recapture sampling valid in literary analysis? Capture-recapture relies on random samples on both occasions. You somehow need to make a random sample from the unknown pool of characters, count them, then make another, totally independent sample, a
36,976
What level to use when comparing subjects in a hierarchical Bayesian analysis?
Just to clarify your model Let $y_{ij}$ be reaction time for participant $i$ on trial $j$. $$y_{ij} \sim N(\mu_i, \sigma^2_i)$$ And then you model $\mu_i$ and $\sigma^2_i$ as coming from some other distribution with hyperparameters. You ask if I would want to compare two subjects what distributions should I compare? So for example, if you wanted to compare subject $i=1$ to subject $i=2$. Then you would have the estimated degree to which participant 2 had a greater mean as: $$\Delta\mu_{1,2} = \mu_2 - \mu_1$$ Alternatively, you could have the increase in estimated standard deviation as: $$\Delta\sigma_{1,2} = \sigma_2 - \sigma_1$$ Naturally, under normal conditions the more observations you have per individual, the more precise your estimates of $\mu_i$ and $\sigma_i$ will be. And as a consequence your estimates of $\Delta\mu$ and $\Delta\sigma$ will also improve. I don't quite understand what you are asking about blocks and trials.
What level to use when comparing subjects in a hierarchical Bayesian analysis?
Just to clarify your model Let $y_{ij}$ be reaction time for participant $i$ on trial $j$. $$y_{ij} \sim N(\mu_i, \sigma^2_i)$$ And then you model $\mu_i$ and $\sigma^2_i$ as coming from some other di
What level to use when comparing subjects in a hierarchical Bayesian analysis? Just to clarify your model Let $y_{ij}$ be reaction time for participant $i$ on trial $j$. $$y_{ij} \sim N(\mu_i, \sigma^2_i)$$ And then you model $\mu_i$ and $\sigma^2_i$ as coming from some other distribution with hyperparameters. You ask if I would want to compare two subjects what distributions should I compare? So for example, if you wanted to compare subject $i=1$ to subject $i=2$. Then you would have the estimated degree to which participant 2 had a greater mean as: $$\Delta\mu_{1,2} = \mu_2 - \mu_1$$ Alternatively, you could have the increase in estimated standard deviation as: $$\Delta\sigma_{1,2} = \sigma_2 - \sigma_1$$ Naturally, under normal conditions the more observations you have per individual, the more precise your estimates of $\mu_i$ and $\sigma_i$ will be. And as a consequence your estimates of $\Delta\mu$ and $\Delta\sigma$ will also improve. I don't quite understand what you are asking about blocks and trials.
What level to use when comparing subjects in a hierarchical Bayesian analysis? Just to clarify your model Let $y_{ij}$ be reaction time for participant $i$ on trial $j$. $$y_{ij} \sim N(\mu_i, \sigma^2_i)$$ And then you model $\mu_i$ and $\sigma^2_i$ as coming from some other di
36,977
Can a neural network output represent a posterior probability?
The conditions under which the output of a neural net can be treated as estimates of posterior probabilities are fairly broad, I remember the following paper as being pretty interesting and informative (caveat: but I've not read it since 2002) Marco Saerens, Patrice Latinne, Christine Decaestecker: Any reasonable cost function can be used for a posteriori probability approximation. IEEE Transactions on Neural Networks 13(5): 1204-1210 (2002) I suspect it has references to the classic papers in the text as well. Prof. Saerens has written several really nice papers; I would recommend anyone seriously interested in neural nets to look up his papers in Google scholar etc. You could view the output layer of a neural net as being a logistic regression model (with outputs that represent probabilities), and the hidden layer as being a non-linear transformation of the inputs. It is the output layer that matters regarding the interpretation of the outputs, so the MLP is essentially just a non-linear logistic regression model.
Can a neural network output represent a posterior probability?
The conditions under which the output of a neural net can be treated as estimates of posterior probabilities are fairly broad, I remember the following paper as being pretty interesting and informativ
Can a neural network output represent a posterior probability? The conditions under which the output of a neural net can be treated as estimates of posterior probabilities are fairly broad, I remember the following paper as being pretty interesting and informative (caveat: but I've not read it since 2002) Marco Saerens, Patrice Latinne, Christine Decaestecker: Any reasonable cost function can be used for a posteriori probability approximation. IEEE Transactions on Neural Networks 13(5): 1204-1210 (2002) I suspect it has references to the classic papers in the text as well. Prof. Saerens has written several really nice papers; I would recommend anyone seriously interested in neural nets to look up his papers in Google scholar etc. You could view the output layer of a neural net as being a logistic regression model (with outputs that represent probabilities), and the hidden layer as being a non-linear transformation of the inputs. It is the output layer that matters regarding the interpretation of the outputs, so the MLP is essentially just a non-linear logistic regression model.
Can a neural network output represent a posterior probability? The conditions under which the output of a neural net can be treated as estimates of posterior probabilities are fairly broad, I remember the following paper as being pretty interesting and informativ
36,978
Hyperplane problem in linear congruent generator
$\text{corr}(R_t,R_{t-1}) \leq \frac{1}{a}\left(1-\frac{6c}{m}+6(\frac{_{c}}{^m})^2\right)+\frac{a+6}{m}$ This formula is an adaptation from Greenberger, 1961$^{[1]}$, who gives the first term above in an initial approximation and later gives another approximation with an additional term. The serial correlation is typically quite small, even for a poor generator your own animation indicates that the points don't "firstly fill out one hyperplane", since you see different planes get more points over time. The first step of the animation shows points from several different planes, then more, and as it progresses, the earlier planes get more points Is the time interval between every two consecutive visits to each fixed hyperplane fixed, and same for all hyperplanes? This I don't know for certain. I believe there's a cycle through the hyperplanes. Does taking a small front portion of a sequence of a full period somehow overcome this drawback of LCG? No. Yes, it should. An edit to the indicated page as at 31 May 2014 has made it match your formula I'd suggest looking at the DIEHARD tests and similar tests of RNGs $\ $ [1]: Greenberger, Martin (1961), "An a priori determination of serial correlation in computer generated random numbers", Math. Comp. 15, 383-389 (pdf) (Corrigendum: Math. Comp. 16 (1962), 406-406.)
Hyperplane problem in linear congruent generator
$\text{corr}(R_t,R_{t-1}) \leq \frac{1}{a}\left(1-\frac{6c}{m}+6(\frac{_{c}}{^m})^2\right)+\frac{a+6}{m}$ This formula is an adaptation from Greenberger, 1961$^{[1]}$, who gives the first term above i
Hyperplane problem in linear congruent generator $\text{corr}(R_t,R_{t-1}) \leq \frac{1}{a}\left(1-\frac{6c}{m}+6(\frac{_{c}}{^m})^2\right)+\frac{a+6}{m}$ This formula is an adaptation from Greenberger, 1961$^{[1]}$, who gives the first term above in an initial approximation and later gives another approximation with an additional term. The serial correlation is typically quite small, even for a poor generator your own animation indicates that the points don't "firstly fill out one hyperplane", since you see different planes get more points over time. The first step of the animation shows points from several different planes, then more, and as it progresses, the earlier planes get more points Is the time interval between every two consecutive visits to each fixed hyperplane fixed, and same for all hyperplanes? This I don't know for certain. I believe there's a cycle through the hyperplanes. Does taking a small front portion of a sequence of a full period somehow overcome this drawback of LCG? No. Yes, it should. An edit to the indicated page as at 31 May 2014 has made it match your formula I'd suggest looking at the DIEHARD tests and similar tests of RNGs $\ $ [1]: Greenberger, Martin (1961), "An a priori determination of serial correlation in computer generated random numbers", Math. Comp. 15, 383-389 (pdf) (Corrigendum: Math. Comp. 16 (1962), 406-406.)
Hyperplane problem in linear congruent generator $\text{corr}(R_t,R_{t-1}) \leq \frac{1}{a}\left(1-\frac{6c}{m}+6(\frac{_{c}}{^m})^2\right)+\frac{a+6}{m}$ This formula is an adaptation from Greenberger, 1961$^{[1]}$, who gives the first term above i
36,979
Looking for a good followup to the Stanford AI course
I wanted to refer you to the Statistical Learning book but I wanted to be sure that it wasn't your text. It was written by Stanford Statistics faculty Trevor Hastie, Jerome Friedman and Rob Tibshirani. Here is a link to it on amazon.
Looking for a good followup to the Stanford AI course
I wanted to refer you to the Statistical Learning book but I wanted to be sure that it wasn't your text. It was written by Stanford Statistics faculty Trevor Hastie, Jerome Friedman and Rob Tibshiran
Looking for a good followup to the Stanford AI course I wanted to refer you to the Statistical Learning book but I wanted to be sure that it wasn't your text. It was written by Stanford Statistics faculty Trevor Hastie, Jerome Friedman and Rob Tibshirani. Here is a link to it on amazon.
Looking for a good followup to the Stanford AI course I wanted to refer you to the Statistical Learning book but I wanted to be sure that it wasn't your text. It was written by Stanford Statistics faculty Trevor Hastie, Jerome Friedman and Rob Tibshiran
36,980
Looking for a good followup to the Stanford AI course
I'm finding that the machine learning course from Coursera/Andrew Ng/Stanford is really great. It has a balance of statistics, AI, linear algebra, programming. The motivations/intuitions that are given in the video lectures get me pumped to solve some problems.
Looking for a good followup to the Stanford AI course
I'm finding that the machine learning course from Coursera/Andrew Ng/Stanford is really great. It has a balance of statistics, AI, linear algebra, programming. The motivations/intuitions that are give
Looking for a good followup to the Stanford AI course I'm finding that the machine learning course from Coursera/Andrew Ng/Stanford is really great. It has a balance of statistics, AI, linear algebra, programming. The motivations/intuitions that are given in the video lectures get me pumped to solve some problems.
Looking for a good followup to the Stanford AI course I'm finding that the machine learning course from Coursera/Andrew Ng/Stanford is really great. It has a balance of statistics, AI, linear algebra, programming. The motivations/intuitions that are give
36,981
Different random effects in nlme and nlmer
Short: It's lack of precision in nlmer In order to obtain the same results as nlme I needed to move away form the laplacian approximatoin which is set with nAGQ=1. According to the nlmer manpage the nAGQ sets the number of points per axis for the evaluation of the adaptive Gauss-Hermite approximation. Basically, increasing the number of points per axis increases precision. With nAGQ=2 random and fixed effects are virtually the same - this is also the case for the SD of the fixed effecs, as John had noted. In the present case increasing the nAGQ to 2 or 3 does the trick, however, larger numbers will slow down the computation and maybe reach the iteration limit without convergence. I guess it's good practice to run the model with the standard settings and then go back and increase the precision to see if, and how strong the parameter estimates change. For the present model it takes 10 sec with nAGQ=1 22 sec with nAGQ=2 24 with nAGQ=3 nAGQ=4 does not converge within the given iterations. In my case, the results obtained from nAGQ=2 and nAGQ=3 were the same. As a comparison, in nlme it takes 3.8 seconds to obtain the result, which I find quite surprising because in the past I had the impression that nlmer is faster than nlme. Bottom line: It's probably safer to use nlme, as long as lme4 and with it nlmer is under development.
Different random effects in nlme and nlmer
Short: It's lack of precision in nlmer In order to obtain the same results as nlme I needed to move away form the laplacian approximatoin which is set with nAGQ=1. According to the nlmer manpage the n
Different random effects in nlme and nlmer Short: It's lack of precision in nlmer In order to obtain the same results as nlme I needed to move away form the laplacian approximatoin which is set with nAGQ=1. According to the nlmer manpage the nAGQ sets the number of points per axis for the evaluation of the adaptive Gauss-Hermite approximation. Basically, increasing the number of points per axis increases precision. With nAGQ=2 random and fixed effects are virtually the same - this is also the case for the SD of the fixed effecs, as John had noted. In the present case increasing the nAGQ to 2 or 3 does the trick, however, larger numbers will slow down the computation and maybe reach the iteration limit without convergence. I guess it's good practice to run the model with the standard settings and then go back and increase the precision to see if, and how strong the parameter estimates change. For the present model it takes 10 sec with nAGQ=1 22 sec with nAGQ=2 24 with nAGQ=3 nAGQ=4 does not converge within the given iterations. In my case, the results obtained from nAGQ=2 and nAGQ=3 were the same. As a comparison, in nlme it takes 3.8 seconds to obtain the result, which I find quite surprising because in the past I had the impression that nlmer is faster than nlme. Bottom line: It's probably safer to use nlme, as long as lme4 and with it nlmer is under development.
Different random effects in nlme and nlmer Short: It's lack of precision in nlmer In order to obtain the same results as nlme I needed to move away form the laplacian approximatoin which is set with nAGQ=1. According to the nlmer manpage the n
36,982
Supervised approaches vs. topic models in sentiment analysis
One disadvantage of an unsupervised method like LDA is it will generally take considerably longer to train compared to supervised methods. I'm also confused about the 2% increase you mention, based on table 2 it looks like an 8% difference between the best supervised approach they compared against and their best unsupervised model. While I generally like the idea of "how far can you push unsupervised learning", sentiment seems like a poor fit in pracitce. I say this because sentiment analysis is one of the domains where it's easiest (cost, effort) to get labeled data due to the massive amount of reviews and review like content available on the internet. If your ultimate goal is to classify accurately, even the unsupervised paper you linked seems to suggest you will be better off spending your time scraping this data, as opposed to spending your time building dictionaries of positive negative words and incorporating priors.
Supervised approaches vs. topic models in sentiment analysis
One disadvantage of an unsupervised method like LDA is it will generally take considerably longer to train compared to supervised methods. I'm also confused about the 2% increase you mention, based on
Supervised approaches vs. topic models in sentiment analysis One disadvantage of an unsupervised method like LDA is it will generally take considerably longer to train compared to supervised methods. I'm also confused about the 2% increase you mention, based on table 2 it looks like an 8% difference between the best supervised approach they compared against and their best unsupervised model. While I generally like the idea of "how far can you push unsupervised learning", sentiment seems like a poor fit in pracitce. I say this because sentiment analysis is one of the domains where it's easiest (cost, effort) to get labeled data due to the massive amount of reviews and review like content available on the internet. If your ultimate goal is to classify accurately, even the unsupervised paper you linked seems to suggest you will be better off spending your time scraping this data, as opposed to spending your time building dictionaries of positive negative words and incorporating priors.
Supervised approaches vs. topic models in sentiment analysis One disadvantage of an unsupervised method like LDA is it will generally take considerably longer to train compared to supervised methods. I'm also confused about the 2% increase you mention, based on
36,983
Supervised approaches vs. topic models in sentiment analysis
As an additional note, by using unsupervised model, possible to have more domain specific result, especially if you are interested in a outlier domain. In that case it is not easy to find a good dataset for supervised learning thus you might need to use one of the unsupervised method. Or an semi-unsupervied method like, creating a lexicon list for your specific domain using one of the algorithm (there are some) than using that lexicon list you might classify your text with a supervised method.
Supervised approaches vs. topic models in sentiment analysis
As an additional note, by using unsupervised model, possible to have more domain specific result, especially if you are interested in a outlier domain. In that case it is not easy to find a good datas
Supervised approaches vs. topic models in sentiment analysis As an additional note, by using unsupervised model, possible to have more domain specific result, especially if you are interested in a outlier domain. In that case it is not easy to find a good dataset for supervised learning thus you might need to use one of the unsupervised method. Or an semi-unsupervied method like, creating a lexicon list for your specific domain using one of the algorithm (there are some) than using that lexicon list you might classify your text with a supervised method.
Supervised approaches vs. topic models in sentiment analysis As an additional note, by using unsupervised model, possible to have more domain specific result, especially if you are interested in a outlier domain. In that case it is not easy to find a good datas
36,984
Language modeling: why is adding up to 1 so important?
The main advantages of using strict probabilities are a) ease of interpretation of the numbers; and b) being able to use Bayes theorem and other probabilistic methods in subsequent analysis. In some situations though, it is unnecessary. For example if you just want to rank the results with no further analysis, then there's no need to normalise the scores.
Language modeling: why is adding up to 1 so important?
The main advantages of using strict probabilities are a) ease of interpretation of the numbers; and b) being able to use Bayes theorem and other probabilistic methods in subsequent analysis. In some s
Language modeling: why is adding up to 1 so important? The main advantages of using strict probabilities are a) ease of interpretation of the numbers; and b) being able to use Bayes theorem and other probabilistic methods in subsequent analysis. In some situations though, it is unnecessary. For example if you just want to rank the results with no further analysis, then there's no need to normalise the scores.
Language modeling: why is adding up to 1 so important? The main advantages of using strict probabilities are a) ease of interpretation of the numbers; and b) being able to use Bayes theorem and other probabilistic methods in subsequent analysis. In some s
36,985
Cluster clickstream data
It is a good question with many practical applications. Your data are sequential so we need a similarity measure between any pair of sequences. I recommend Levensthein distance since it is very intuitive and very nicely defined. See also this nice bachelor thesis with an overview of more measures for sequential data. Finally, if one has the distances between all pairs of sequences, we can use any clustering algorithm that takes a distance matrix as input (for example any hierarchical algorithm).
Cluster clickstream data
It is a good question with many practical applications. Your data are sequential so we need a similarity measure between any pair of sequences. I recommend Levensthein distance since it is very intuit
Cluster clickstream data It is a good question with many practical applications. Your data are sequential so we need a similarity measure between any pair of sequences. I recommend Levensthein distance since it is very intuitive and very nicely defined. See also this nice bachelor thesis with an overview of more measures for sequential data. Finally, if one has the distances between all pairs of sequences, we can use any clustering algorithm that takes a distance matrix as input (for example any hierarchical algorithm).
Cluster clickstream data It is a good question with many practical applications. Your data are sequential so we need a similarity measure between any pair of sequences. I recommend Levensthein distance since it is very intuit
36,986
Cluster clickstream data
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. You can use package clickstream or clickclust in R language. It performs exactly what you are looking for.
Cluster clickstream data
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.
Cluster clickstream data 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. You can use package clickstream or clickclust in R language. It performs exactly what you are looking for.
Cluster clickstream data 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.
36,987
Hierarchical multinomial logit with R/JAGS
After a bit og Googling I found the following package which does the trick: http://cran.r-project.org/web/packages/ChoiceModelR/index.html
Hierarchical multinomial logit with R/JAGS
After a bit og Googling I found the following package which does the trick: http://cran.r-project.org/web/packages/ChoiceModelR/index.html
Hierarchical multinomial logit with R/JAGS After a bit og Googling I found the following package which does the trick: http://cran.r-project.org/web/packages/ChoiceModelR/index.html
Hierarchical multinomial logit with R/JAGS After a bit og Googling I found the following package which does the trick: http://cran.r-project.org/web/packages/ChoiceModelR/index.html
36,988
Hierarchical multinomial logit with R/JAGS
MCMCpack has implemented a multinomial logit which will probably be considerably faster than one you've implemented yourself in JAGS, presuming that it meets your needs. MCMCmnl(formula, baseline=NULL, data=NULL, burnin = 1000, mcmc = 10000, thin = 1, mcmc.method = c("IndMH", "RWM", "slice"), tune = 1, tdf=6, verbose = 0, seed = NA, beta.start = NA, b0 = 0, B0 = 0, ...) More documentation: http://mcmcpack.wustl.edu/
Hierarchical multinomial logit with R/JAGS
MCMCpack has implemented a multinomial logit which will probably be considerably faster than one you've implemented yourself in JAGS, presuming that it meets your needs. MCMCmnl(formula, baseline=NULL
Hierarchical multinomial logit with R/JAGS MCMCpack has implemented a multinomial logit which will probably be considerably faster than one you've implemented yourself in JAGS, presuming that it meets your needs. MCMCmnl(formula, baseline=NULL, data=NULL, burnin = 1000, mcmc = 10000, thin = 1, mcmc.method = c("IndMH", "RWM", "slice"), tune = 1, tdf=6, verbose = 0, seed = NA, beta.start = NA, b0 = 0, B0 = 0, ...) More documentation: http://mcmcpack.wustl.edu/
Hierarchical multinomial logit with R/JAGS MCMCpack has implemented a multinomial logit which will probably be considerably faster than one you've implemented yourself in JAGS, presuming that it meets your needs. MCMCmnl(formula, baseline=NULL
36,989
How to perform inter-rater reliability with multiple raters, different raters per participant, and possible changes over time?
How are you planning to account for the fact that some ratings were done by the same rater? Off the top of my head, I can't think of any measures that take that into account when it isn't consistently done. After all, if you compare the same rater twice, you're looking at consistency; if you compare two raters, you're looking at agreement. So, when you say you want to evaluate the "reliability", it's not totally clear what you are seeking to evaluate. If you believe that the ability level of the subjects is likely to have changed, it's also important to consider how you can account for that fact. Do you have some gold-standard measurement to compare the raters against? So, in summary, before you can assess how reliable the raters are, you need to answer two key questions: How can you quantify and correct for change between the timepoints attributed to legitimate changes in ability, instead of poor consistency in rating? Are you principally interested in how often the raters agree with each other, or in how consistently they apply the ratings?
How to perform inter-rater reliability with multiple raters, different raters per participant, and p
How are you planning to account for the fact that some ratings were done by the same rater? Off the top of my head, I can't think of any measures that take that into account when it isn't consistently
How to perform inter-rater reliability with multiple raters, different raters per participant, and possible changes over time? How are you planning to account for the fact that some ratings were done by the same rater? Off the top of my head, I can't think of any measures that take that into account when it isn't consistently done. After all, if you compare the same rater twice, you're looking at consistency; if you compare two raters, you're looking at agreement. So, when you say you want to evaluate the "reliability", it's not totally clear what you are seeking to evaluate. If you believe that the ability level of the subjects is likely to have changed, it's also important to consider how you can account for that fact. Do you have some gold-standard measurement to compare the raters against? So, in summary, before you can assess how reliable the raters are, you need to answer two key questions: How can you quantify and correct for change between the timepoints attributed to legitimate changes in ability, instead of poor consistency in rating? Are you principally interested in how often the raters agree with each other, or in how consistently they apply the ratings?
How to perform inter-rater reliability with multiple raters, different raters per participant, and p How are you planning to account for the fact that some ratings were done by the same rater? Off the top of my head, I can't think of any measures that take that into account when it isn't consistently
36,990
How to evaluate quality of probability estimator for Bernoulli experiments?
You can quantify the quality of the estimator by calculating the total surprisal of all of the coin flips. Suppose that your expert makes predictions $q_i$ for each coin. Then, given indicator variables for the coins coming up heads $x_i$, the total surprisal is: \begin{align} \sum_i\left[ -x_i\log q_i - (1-x_i)\log (1-q_i)\right]. \end{align} The expected value of the surprisal given the true values $\{p_i\}$ is the cross-entropy: \begin{align} \sum_i \left[-p_i\log q_i -(1-p_i)\log (1-q_i)\right]. \end{align} It is nonnegative, and achieves its minimum value (the entropy of $\{p_i\}$) if and only if $p_i = q_i \forall i$. If you subtract the entropy from the cross-entropy, you get the relative entropy (whose minimum value is zero). If you take $e^{-x}$ of that, you have a number in $[0, 1]$ as you wanted with a reasonable probabilistic interpretation.
How to evaluate quality of probability estimator for Bernoulli experiments?
You can quantify the quality of the estimator by calculating the total surprisal of all of the coin flips. Suppose that your expert makes predictions $q_i$ for each coin. Then, given indicator variab
How to evaluate quality of probability estimator for Bernoulli experiments? You can quantify the quality of the estimator by calculating the total surprisal of all of the coin flips. Suppose that your expert makes predictions $q_i$ for each coin. Then, given indicator variables for the coins coming up heads $x_i$, the total surprisal is: \begin{align} \sum_i\left[ -x_i\log q_i - (1-x_i)\log (1-q_i)\right]. \end{align} The expected value of the surprisal given the true values $\{p_i\}$ is the cross-entropy: \begin{align} \sum_i \left[-p_i\log q_i -(1-p_i)\log (1-q_i)\right]. \end{align} It is nonnegative, and achieves its minimum value (the entropy of $\{p_i\}$) if and only if $p_i = q_i \forall i$. If you subtract the entropy from the cross-entropy, you get the relative entropy (whose minimum value is zero). If you take $e^{-x}$ of that, you have a number in $[0, 1]$ as you wanted with a reasonable probabilistic interpretation.
How to evaluate quality of probability estimator for Bernoulli experiments? You can quantify the quality of the estimator by calculating the total surprisal of all of the coin flips. Suppose that your expert makes predictions $q_i$ for each coin. Then, given indicator variab
36,991
How to evaluate quality of probability estimator for Bernoulli experiments?
If I understand your question correctly, you might want to check out this question. As I explained there, one way of assessing the calibration of probability predictions is with a scoring rule. A common example of a scoring rule is the Brier score: $$BS = \frac{1}{N}\sum\limits _{t=1}^{N}(f_t-o_t)^2$$ where $f_t$ is the forecasted probability of the event happening and $o_t$ is 1 if the event did happen and 0 if it did not. Of course the type of scoring rule you choose might depend on what type of event you are trying to predict. However, this should give you some ideas to research further. Perfect prediction with the Brier score would actually be 0 though, so you could take $1 - BS$ if that quality is important to you. Note though that the other extreme score (0 or 1 depending upon whether you decide to flip the Brier score) actually would not be pure randomness but rather would represent getting the wrong answer every time.
How to evaluate quality of probability estimator for Bernoulli experiments?
If I understand your question correctly, you might want to check out this question. As I explained there, one way of assessing the calibration of probability predictions is with a scoring rule. A co
How to evaluate quality of probability estimator for Bernoulli experiments? If I understand your question correctly, you might want to check out this question. As I explained there, one way of assessing the calibration of probability predictions is with a scoring rule. A common example of a scoring rule is the Brier score: $$BS = \frac{1}{N}\sum\limits _{t=1}^{N}(f_t-o_t)^2$$ where $f_t$ is the forecasted probability of the event happening and $o_t$ is 1 if the event did happen and 0 if it did not. Of course the type of scoring rule you choose might depend on what type of event you are trying to predict. However, this should give you some ideas to research further. Perfect prediction with the Brier score would actually be 0 though, so you could take $1 - BS$ if that quality is important to you. Note though that the other extreme score (0 or 1 depending upon whether you decide to flip the Brier score) actually would not be pure randomness but rather would represent getting the wrong answer every time.
How to evaluate quality of probability estimator for Bernoulli experiments? If I understand your question correctly, you might want to check out this question. As I explained there, one way of assessing the calibration of probability predictions is with a scoring rule. A co
36,992
How to evaluate quality of probability estimator for Bernoulli experiments?
The above answer may be useful but is complicated and I am not sure how to apply it. Thinking in simple terms this is a special case of testing whether or not a person has psychic powers (really no different from a scientific evaluation of the mechanics and physics of the coin flip). Obviously have psychic capability would have to be defined as doing something much better than by random chance. I would first want to define what is enough. The difficulty is to decide how much better than random guessing is and what random guessing will do. If all the coins were fair random choice would be 0.5 and so maybe saying anything over 0.75 is Then testing the hypothesis that the person has psychic powers is doing a one-sided hypothesis that a binomial parameter p is <= to 0.75 versus the alternative that it is greater. As an estimator I have chosen the binomial parameter for successfullu calling heads or tails and the variance of my estimator is p(1-p)/n. The added difficulty is that the coins are not fair and the individual pis are unknown. I would still define chance as random guessing of heads or tails and 0.5 is what I would test against. However with unfair coins there may be statistical strategies that would lead to a better than chance success rate but neither indicate skill with the individual coin flips or psychic powers. To illustrate suppose the average for the pis is 0.80. Then after seing heads come up much more frequently than tails we could switch to an all heads strategy and tend to be correct close to 80% of the time. This assumes randomguessing until we are convinced that head occurs much more often than tails and at that point we switch to all heads. So without knowing the pis or at least their averages I cannot tell what success rate would indicate skill. Comparing against random guessing is not the standard to beat in this case. Note that my argument only makes sense if the stack of coins is very large.
How to evaluate quality of probability estimator for Bernoulli experiments?
The above answer may be useful but is complicated and I am not sure how to apply it. Thinking in simple terms this is a special case of testing whether or not a person has psychic powers (really no di
How to evaluate quality of probability estimator for Bernoulli experiments? The above answer may be useful but is complicated and I am not sure how to apply it. Thinking in simple terms this is a special case of testing whether or not a person has psychic powers (really no different from a scientific evaluation of the mechanics and physics of the coin flip). Obviously have psychic capability would have to be defined as doing something much better than by random chance. I would first want to define what is enough. The difficulty is to decide how much better than random guessing is and what random guessing will do. If all the coins were fair random choice would be 0.5 and so maybe saying anything over 0.75 is Then testing the hypothesis that the person has psychic powers is doing a one-sided hypothesis that a binomial parameter p is <= to 0.75 versus the alternative that it is greater. As an estimator I have chosen the binomial parameter for successfullu calling heads or tails and the variance of my estimator is p(1-p)/n. The added difficulty is that the coins are not fair and the individual pis are unknown. I would still define chance as random guessing of heads or tails and 0.5 is what I would test against. However with unfair coins there may be statistical strategies that would lead to a better than chance success rate but neither indicate skill with the individual coin flips or psychic powers. To illustrate suppose the average for the pis is 0.80. Then after seing heads come up much more frequently than tails we could switch to an all heads strategy and tend to be correct close to 80% of the time. This assumes randomguessing until we are convinced that head occurs much more often than tails and at that point we switch to all heads. So without knowing the pis or at least their averages I cannot tell what success rate would indicate skill. Comparing against random guessing is not the standard to beat in this case. Note that my argument only makes sense if the stack of coins is very large.
How to evaluate quality of probability estimator for Bernoulli experiments? The above answer may be useful but is complicated and I am not sure how to apply it. Thinking in simple terms this is a special case of testing whether or not a person has psychic powers (really no di
36,993
How to evaluate quality of probability estimator for Bernoulli experiments?
Another way to evaluate the quality is to look at the Reliability Diagram. This does not immediately yield a value between 0 and 1, but can be used for a first visual evaluation.
How to evaluate quality of probability estimator for Bernoulli experiments?
Another way to evaluate the quality is to look at the Reliability Diagram. This does not immediately yield a value between 0 and 1, but can be used for a first visual evaluation.
How to evaluate quality of probability estimator for Bernoulli experiments? Another way to evaluate the quality is to look at the Reliability Diagram. This does not immediately yield a value between 0 and 1, but can be used for a first visual evaluation.
How to evaluate quality of probability estimator for Bernoulli experiments? Another way to evaluate the quality is to look at the Reliability Diagram. This does not immediately yield a value between 0 and 1, but can be used for a first visual evaluation.
36,994
How to fit the model for crossed and nested design using lme function in R?
The tricky part here is to specify the right formula. library(nlme) # Assume y is your response variable. lme(fixed = y ~ A, random = ~ A | B/C) Here B/C stands for C nested in B and is short for B + B:C. The interaction with A is present because A is repeated in the random part. For a basic introduction to nlme, I recommend this document.
How to fit the model for crossed and nested design using lme function in R?
The tricky part here is to specify the right formula. library(nlme) # Assume y is your response variable. lme(fixed = y ~ A, random = ~ A | B/C) Here B/C stands for C nested in B and is short for B +
How to fit the model for crossed and nested design using lme function in R? The tricky part here is to specify the right formula. library(nlme) # Assume y is your response variable. lme(fixed = y ~ A, random = ~ A | B/C) Here B/C stands for C nested in B and is short for B + B:C. The interaction with A is present because A is repeated in the random part. For a basic introduction to nlme, I recommend this document.
How to fit the model for crossed and nested design using lme function in R? The tricky part here is to specify the right formula. library(nlme) # Assume y is your response variable. lme(fixed = y ~ A, random = ~ A | B/C) Here B/C stands for C nested in B and is short for B +
36,995
Difference between survdiff log-rank and coxph log-rank
Without actual output it is difficult to tell, but generally an "overall logrank score" will test the null hypothesis that all of the coefficients are 0. Therefore a significant result could be due to one or more of your covariates being related to survival while your 2 groups are still identical (or they could be different). It is better to fit the model with your group variable (and the covariates) and fit another model without your group variable (but still with the same covariates) and compare the 2 fits.
Difference between survdiff log-rank and coxph log-rank
Without actual output it is difficult to tell, but generally an "overall logrank score" will test the null hypothesis that all of the coefficients are 0. Therefore a significant result could be due t
Difference between survdiff log-rank and coxph log-rank Without actual output it is difficult to tell, but generally an "overall logrank score" will test the null hypothesis that all of the coefficients are 0. Therefore a significant result could be due to one or more of your covariates being related to survival while your 2 groups are still identical (or they could be different). It is better to fit the model with your group variable (and the covariates) and fit another model without your group variable (but still with the same covariates) and compare the 2 fits.
Difference between survdiff log-rank and coxph log-rank Without actual output it is difficult to tell, but generally an "overall logrank score" will test the null hypothesis that all of the coefficients are 0. Therefore a significant result could be due t
36,996
Confidence intervals for a polynomial
In my answer, I provide many links to background material to save space here. I'm going to write my answer taking the info in the links as given. I think a Bayesian approach is a natural fit to this problem, especially since you seek to convince only yourself. It's a bit convoluted to use confidence intervals to answer the question you really care about, to wit, how plausible is it that $Q_{7}<Q_{6}$ and $Q_{7}<Q_{8}$ given the sample from the $z_{i}$ distribution? The Bayesian approach allows you to address this question directly. Likelihood function Let $f_k$ be the observed frequency of integer outcome $k$ in your sample and let $N$ be the sample size. The likelihood function is proportional to the multinomial distribution. It has the form $L(z_{0},...z_{8};f_{0},...f_{8})=\prod_{i=0}^{8}{z_{i}}^{Nf_{i}}$. Prior distribution The Dirichlet distribution is the natural choice for the prior distribution because it is the conjugate prior for the multinomial likelihood. It has the form $p(z_{0},...z_{8};\alpha_{0},...,\alpha_{8})\propto\prod_{i=0}^{8}{z_{i}}^{\alpha_{i}-1}$ This prior has nine hyperparameters (the $\alpha_i$ values), and they're a bit of a pain to deal with. In this “large sample” context, any reasonable choice of hyperparameter values will have negligible influence on the result, but still, I think it's worth devoting a bit of effort to selecting sensible values. Here's how I recommend setting the hyperparameters. First, note that under this distribution $\mathrm{E}(z_{i})=\frac{\alpha_{i}}{\sum_{i=0}^{8}\alpha_{i}}$. Next, note that the simplest maximum entropy distribution over the naturals is the geometric distribution. So set $\alpha_{i+1}=r\alpha_{i}=r^{i}\alpha_{0},\,0<r<1,$ $\alpha_{0}=A\left(\frac{1-r}{1-r^{9}}\right).$ Then $\mathrm{E}(z_{i})=r^{i}\left(\frac{1-r}{1-r^{9}}\right)$, so the distribution of the $z_{i}$ values is centered on a (truncated) geometric distribution. Furthermore, $\mathrm{Var}\left(z_{i}\right)\propto\frac{1}{(A+1)}$, so the value of $A$ controls the dispersion around this expectation but has no effect on the expectation itself. This specification reduces the number of hyperparameters from the nine $\alpha_{i}$ values to just $r$ and $A$. I'll defer discussion of specific values of $r$ and $A$ for now. Posterior probability of the proposition of interest The posterior distribution of the $z_{i}$ values is the following Dirichlet distribution: $p(z_{0},...z_{8}|f_{0},...,f_{8})\propto\prod_{i=0}^{8}{z_{i}}^{\alpha_{i}+Nf_{i}-1}.$ Let $\mathbb{Y}=\left\{ z_{0},...z_{8}|Q_7<Q_6 \text{ and } Q_7<Q_8\right\} $. The posterior probability you're interested in is $\Pr(Q_7<Q_6 \text{ and } Q_7<Q_8|f_0,...,f_8) \propto \int_{\mathbb{Y}}\prod_{i=0}^{8}{z_{i}}^{\alpha_{i}+Nf_i-1}dz_{i}.$ This integral is intractible, but you can compute the probability of interest numerically using the following Monte Carlo algorithm. For $j$ from $1$ to $J$, Sample a set of $z_i$ values from their posterior distribution. Use the sampled values to compute $y_j=I(Q_{7}<Q_{6})I(Q_{7}<Q_{8})$ where $I(\cdot)$ is the indicator function. Then $\Pr(Q_7<Q_6 \text{ and }Q_7<Q_8|f_{0},...,f_{8})\approx \frac{\sum_{j=0}^Jy_j}{J}$. The accuracy of the Monte Carlo approximation goes as $\sqrt{J}$: $J=10^4$ will get you at least two decimal places of accuracy 19 times out of 20, $J=10^6$ will get you at least three decimal places of accuracy 19 times out of 20, etc. And if your posterior probability of interest isn't close to 0 or 1, just sample more data, rinse, and repeat. Prior hyperparameters, part two The exponent of $z_i$ in the expression for the posterior density is $\alpha_i + Nf_i - 1 = Ar^{i}\left(\frac{1-r}{1-r^{9}}\right) +Nf_i - 1 = A\mathrm{E}(z_i) +Nf_i - 1$ It can be seen that the hyperparameter $A$ plays the same role in the prior distribution as $N$ plays in the likelihood -- it's a kind of "prior sample size". To ensure that the prior has a negligible influence on the conclusion, just pick a value of $A$ such that $A\ll N$; for example, $A = 1$. To set $r$, note that you can calculate the prior probability of the proposition $Q_7<Q_6 \text{ and } Q_7<Q_8$ using the same Monte Carlo algorithm described above but with the prior distribution in place of the posterior distribution in step 1 of the loop. Try to find a value of $r$ that gives a prior probability of 0.5 (or lower, if you feel that's more reasonable).
Confidence intervals for a polynomial
In my answer, I provide many links to background material to save space here. I'm going to write my answer taking the info in the links as given. I think a Bayesian approach is a natural fit to this p
Confidence intervals for a polynomial In my answer, I provide many links to background material to save space here. I'm going to write my answer taking the info in the links as given. I think a Bayesian approach is a natural fit to this problem, especially since you seek to convince only yourself. It's a bit convoluted to use confidence intervals to answer the question you really care about, to wit, how plausible is it that $Q_{7}<Q_{6}$ and $Q_{7}<Q_{8}$ given the sample from the $z_{i}$ distribution? The Bayesian approach allows you to address this question directly. Likelihood function Let $f_k$ be the observed frequency of integer outcome $k$ in your sample and let $N$ be the sample size. The likelihood function is proportional to the multinomial distribution. It has the form $L(z_{0},...z_{8};f_{0},...f_{8})=\prod_{i=0}^{8}{z_{i}}^{Nf_{i}}$. Prior distribution The Dirichlet distribution is the natural choice for the prior distribution because it is the conjugate prior for the multinomial likelihood. It has the form $p(z_{0},...z_{8};\alpha_{0},...,\alpha_{8})\propto\prod_{i=0}^{8}{z_{i}}^{\alpha_{i}-1}$ This prior has nine hyperparameters (the $\alpha_i$ values), and they're a bit of a pain to deal with. In this “large sample” context, any reasonable choice of hyperparameter values will have negligible influence on the result, but still, I think it's worth devoting a bit of effort to selecting sensible values. Here's how I recommend setting the hyperparameters. First, note that under this distribution $\mathrm{E}(z_{i})=\frac{\alpha_{i}}{\sum_{i=0}^{8}\alpha_{i}}$. Next, note that the simplest maximum entropy distribution over the naturals is the geometric distribution. So set $\alpha_{i+1}=r\alpha_{i}=r^{i}\alpha_{0},\,0<r<1,$ $\alpha_{0}=A\left(\frac{1-r}{1-r^{9}}\right).$ Then $\mathrm{E}(z_{i})=r^{i}\left(\frac{1-r}{1-r^{9}}\right)$, so the distribution of the $z_{i}$ values is centered on a (truncated) geometric distribution. Furthermore, $\mathrm{Var}\left(z_{i}\right)\propto\frac{1}{(A+1)}$, so the value of $A$ controls the dispersion around this expectation but has no effect on the expectation itself. This specification reduces the number of hyperparameters from the nine $\alpha_{i}$ values to just $r$ and $A$. I'll defer discussion of specific values of $r$ and $A$ for now. Posterior probability of the proposition of interest The posterior distribution of the $z_{i}$ values is the following Dirichlet distribution: $p(z_{0},...z_{8}|f_{0},...,f_{8})\propto\prod_{i=0}^{8}{z_{i}}^{\alpha_{i}+Nf_{i}-1}.$ Let $\mathbb{Y}=\left\{ z_{0},...z_{8}|Q_7<Q_6 \text{ and } Q_7<Q_8\right\} $. The posterior probability you're interested in is $\Pr(Q_7<Q_6 \text{ and } Q_7<Q_8|f_0,...,f_8) \propto \int_{\mathbb{Y}}\prod_{i=0}^{8}{z_{i}}^{\alpha_{i}+Nf_i-1}dz_{i}.$ This integral is intractible, but you can compute the probability of interest numerically using the following Monte Carlo algorithm. For $j$ from $1$ to $J$, Sample a set of $z_i$ values from their posterior distribution. Use the sampled values to compute $y_j=I(Q_{7}<Q_{6})I(Q_{7}<Q_{8})$ where $I(\cdot)$ is the indicator function. Then $\Pr(Q_7<Q_6 \text{ and }Q_7<Q_8|f_{0},...,f_{8})\approx \frac{\sum_{j=0}^Jy_j}{J}$. The accuracy of the Monte Carlo approximation goes as $\sqrt{J}$: $J=10^4$ will get you at least two decimal places of accuracy 19 times out of 20, $J=10^6$ will get you at least three decimal places of accuracy 19 times out of 20, etc. And if your posterior probability of interest isn't close to 0 or 1, just sample more data, rinse, and repeat. Prior hyperparameters, part two The exponent of $z_i$ in the expression for the posterior density is $\alpha_i + Nf_i - 1 = Ar^{i}\left(\frac{1-r}{1-r^{9}}\right) +Nf_i - 1 = A\mathrm{E}(z_i) +Nf_i - 1$ It can be seen that the hyperparameter $A$ plays the same role in the prior distribution as $N$ plays in the likelihood -- it's a kind of "prior sample size". To ensure that the prior has a negligible influence on the conclusion, just pick a value of $A$ such that $A\ll N$; for example, $A = 1$. To set $r$, note that you can calculate the prior probability of the proposition $Q_7<Q_6 \text{ and } Q_7<Q_8$ using the same Monte Carlo algorithm described above but with the prior distribution in place of the posterior distribution in step 1 of the loop. Try to find a value of $r$ that gives a prior probability of 0.5 (or lower, if you feel that's more reasonable).
Confidence intervals for a polynomial In my answer, I provide many links to background material to save space here. I'm going to write my answer taking the info in the links as given. I think a Bayesian approach is a natural fit to this p
36,997
Confidence intervals for a polynomial
I presume the z_k are not probabilities but sample frequencies. This is because, otherwise, Q_i(z_0, ..., z_i) is not a random variable. In that case, computing the variance of the Q_i's is straightforward algebra. Define, first, the event indicators Z_i which is 1 if Z == i, 0 otherwise. It's a Bernoulli random variable with probability p_i. You can compute the first and second moments of any of these variables and they should give you all the necessary terms for computing the variance of the Q_i's.
Confidence intervals for a polynomial
I presume the z_k are not probabilities but sample frequencies. This is because, otherwise, Q_i(z_0, ..., z_i) is not a random variable. In that case, computing the variance of the Q_i's is straightfo
Confidence intervals for a polynomial I presume the z_k are not probabilities but sample frequencies. This is because, otherwise, Q_i(z_0, ..., z_i) is not a random variable. In that case, computing the variance of the Q_i's is straightforward algebra. Define, first, the event indicators Z_i which is 1 if Z == i, 0 otherwise. It's a Bernoulli random variable with probability p_i. You can compute the first and second moments of any of these variables and they should give you all the necessary terms for computing the variance of the Q_i's.
Confidence intervals for a polynomial I presume the z_k are not probabilities but sample frequencies. This is because, otherwise, Q_i(z_0, ..., z_i) is not a random variable. In that case, computing the variance of the Q_i's is straightfo
36,998
Confidence intervals for a polynomial
Kevin, please be carefull since I'll have to change your notation a little bit: your $z_i$'s are not my $z_i$'s. I think the following Bayesian solution is worth a try. Cook a random parameter $\Lambda>0$ and let $Z_1,\dots,Z_n$ be conditionally i.i.d., given $\Lambda=\lambda$, with $Z_i\mid\Lambda = \lambda \sim \textrm{Poisson}(\lambda)$. Use the notation $Z=(Z_1,\dots,Z_n)$. You already have a sample $z=(z_1,\dots,z_n)$ of the $Z_i$'s, with $n=2^{28}$. Define the random variables $$\Theta_i = P\{Z_i=k\mid \Lambda\} = \frac{e^{-\Lambda}\Lambda^k }{k!} \, , $$ for $i\geq 0$ (if this is not clear, take a look). Now, in this formulation your quadratic forms $Q_i=Q_i(\Theta_0,\dots,\Theta_i) = Q_i(\Lambda)$ are functions of $\Lambda$. So, the $Q_i$'s are random and you want to determine the posterior probability $$ P\{Q_7<Q_6 \,\,\,\textrm{and}\,\,\, Q_7<Q_8\mid Z=z\} \, . \qquad (*) $$ With a prior $\Lambda\sim\textrm{Gamma}(a,b)$, using Bayes Theorem we have $$ \Lambda\mid Z=z \sim \, \textrm{Gamma}\left( a + \sum_{i=1}^n z_i, b + n\right) \, . $$ You calculate $(*)$ generating i.i.d. $\lambda_i$'s from the former distribution (use R!) and computing $$ \frac{1}{N} \sum_{i=1}^N I_{(-\infty,Q_6(\lambda_i))\cap(Q_8(\lambda_i),\infty)}(Q_7(\lambda_i)) \, , $$ which converges, by the strong law of large numbers, to $(*)$ almost surely. To get a "yes" to your original question, this posterior probability must be "big enough". With such a huge sample ($n=2^{28}$), I think it is possible to play with the values of $a$ and $b$ to make your prior choice not much "informative".
Confidence intervals for a polynomial
Kevin, please be carefull since I'll have to change your notation a little bit: your $z_i$'s are not my $z_i$'s. I think the following Bayesian solution is worth a try. Cook a random parameter $\Lamb
Confidence intervals for a polynomial Kevin, please be carefull since I'll have to change your notation a little bit: your $z_i$'s are not my $z_i$'s. I think the following Bayesian solution is worth a try. Cook a random parameter $\Lambda>0$ and let $Z_1,\dots,Z_n$ be conditionally i.i.d., given $\Lambda=\lambda$, with $Z_i\mid\Lambda = \lambda \sim \textrm{Poisson}(\lambda)$. Use the notation $Z=(Z_1,\dots,Z_n)$. You already have a sample $z=(z_1,\dots,z_n)$ of the $Z_i$'s, with $n=2^{28}$. Define the random variables $$\Theta_i = P\{Z_i=k\mid \Lambda\} = \frac{e^{-\Lambda}\Lambda^k }{k!} \, , $$ for $i\geq 0$ (if this is not clear, take a look). Now, in this formulation your quadratic forms $Q_i=Q_i(\Theta_0,\dots,\Theta_i) = Q_i(\Lambda)$ are functions of $\Lambda$. So, the $Q_i$'s are random and you want to determine the posterior probability $$ P\{Q_7<Q_6 \,\,\,\textrm{and}\,\,\, Q_7<Q_8\mid Z=z\} \, . \qquad (*) $$ With a prior $\Lambda\sim\textrm{Gamma}(a,b)$, using Bayes Theorem we have $$ \Lambda\mid Z=z \sim \, \textrm{Gamma}\left( a + \sum_{i=1}^n z_i, b + n\right) \, . $$ You calculate $(*)$ generating i.i.d. $\lambda_i$'s from the former distribution (use R!) and computing $$ \frac{1}{N} \sum_{i=1}^N I_{(-\infty,Q_6(\lambda_i))\cap(Q_8(\lambda_i),\infty)}(Q_7(\lambda_i)) \, , $$ which converges, by the strong law of large numbers, to $(*)$ almost surely. To get a "yes" to your original question, this posterior probability must be "big enough". With such a huge sample ($n=2^{28}$), I think it is possible to play with the values of $a$ and $b$ to make your prior choice not much "informative".
Confidence intervals for a polynomial Kevin, please be carefull since I'll have to change your notation a little bit: your $z_i$'s are not my $z_i$'s. I think the following Bayesian solution is worth a try. Cook a random parameter $\Lamb
36,999
Classification of conversations based on content
This is how I would approach it. You actually need to check if a text is in class I or III (else it would be class II). First, define a bag of words for classes I and III. You can manually do this For each text, calculate the tf-idf for the words in these two classes and sum it (get two sums). If some of these two sums is above some predefined threshold then it belongs in that class. If you have a learning dataset big enough, you can easily find out what are the two bags of words, as well as the two thresholds for them.
Classification of conversations based on content
This is how I would approach it. You actually need to check if a text is in class I or III (else it would be class II). First, define a bag of words for classes I and III. You can manually do this F
Classification of conversations based on content This is how I would approach it. You actually need to check if a text is in class I or III (else it would be class II). First, define a bag of words for classes I and III. You can manually do this For each text, calculate the tf-idf for the words in these two classes and sum it (get two sums). If some of these two sums is above some predefined threshold then it belongs in that class. If you have a learning dataset big enough, you can easily find out what are the two bags of words, as well as the two thresholds for them.
Classification of conversations based on content This is how I would approach it. You actually need to check if a text is in class I or III (else it would be class II). First, define a bag of words for classes I and III. You can manually do this F
37,000
Comparing a sample distribution to an implied distribution
That's a familiar problem from a previous life! First, you're not going to be able to do exactly what you want, which is to come up with a probability that the observations could have come from a specified distribution etc. This is because you don't have a well-specified alternative distribution, one which the data comes from if all is not well. There are too many ways things could go wrong to come up with such a distribution easily, but without it, you have nothing to use to help you say something like "this collection of observations is more likely to have come from the inventory error demand distribution than from the regular demand distribution." Having said that, though, you can still calculate $p(\text{new data} | \text{estimated parameters})$ and use that, along with the monetary value of the nominal on-hand inventory, to develop a ranking system for cycle counting the SKUs. There will undoubtedly be some trial-and-error involved, as low probabilities can be due to errors in the inventory records or misspecification of the probability distributions (or chance), and you want to count the former cases but not the latter cases. In R, such a calculation, for your example, could be: NewData <- c(6,7,7,5,7,8,9,4,4,9) EstMean <- 5 EstSD <- 3 exp(sum(dnorm(NewData, EstMean, EstSD, log=TRUE))) Having written that, I would highly recommend using the negative binomial distribution in preference to the Poisson for mean demands < 10 or 15 or so (and something continuous for higher demand levels.) In a long life of inventory control, I have only seen a situation where demands were well-modeled by a Poisson distribution once. The Gamma, too, has problems, since zero demands are not possible if demands are truly distributed Gamma, but stockouts do occur... in fact, I've found zero-inflated negative binomial distributions tend to fit a wide range of SKUs better than the standard form, and of course with the Gamma and (truncated) Normal also.
Comparing a sample distribution to an implied distribution
That's a familiar problem from a previous life! First, you're not going to be able to do exactly what you want, which is to come up with a probability that the observations could have come from a sp
Comparing a sample distribution to an implied distribution That's a familiar problem from a previous life! First, you're not going to be able to do exactly what you want, which is to come up with a probability that the observations could have come from a specified distribution etc. This is because you don't have a well-specified alternative distribution, one which the data comes from if all is not well. There are too many ways things could go wrong to come up with such a distribution easily, but without it, you have nothing to use to help you say something like "this collection of observations is more likely to have come from the inventory error demand distribution than from the regular demand distribution." Having said that, though, you can still calculate $p(\text{new data} | \text{estimated parameters})$ and use that, along with the monetary value of the nominal on-hand inventory, to develop a ranking system for cycle counting the SKUs. There will undoubtedly be some trial-and-error involved, as low probabilities can be due to errors in the inventory records or misspecification of the probability distributions (or chance), and you want to count the former cases but not the latter cases. In R, such a calculation, for your example, could be: NewData <- c(6,7,7,5,7,8,9,4,4,9) EstMean <- 5 EstSD <- 3 exp(sum(dnorm(NewData, EstMean, EstSD, log=TRUE))) Having written that, I would highly recommend using the negative binomial distribution in preference to the Poisson for mean demands < 10 or 15 or so (and something continuous for higher demand levels.) In a long life of inventory control, I have only seen a situation where demands were well-modeled by a Poisson distribution once. The Gamma, too, has problems, since zero demands are not possible if demands are truly distributed Gamma, but stockouts do occur... in fact, I've found zero-inflated negative binomial distributions tend to fit a wide range of SKUs better than the standard form, and of course with the Gamma and (truncated) Normal also.
Comparing a sample distribution to an implied distribution That's a familiar problem from a previous life! First, you're not going to be able to do exactly what you want, which is to come up with a probability that the observations could have come from a sp