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
35,301
Can Negative Binomial parameters be treated like Poisson?
This is how I would do it in R. If correct, it should be easy to translate to python. First estimate the parameters of the negative binomial distribution that best fit a given training dataset. Then map the new data to the distribution function with those parameters. library(MASS) set.seed(1234) data_stream <- rnbinom(n= 1000, size= 1, mu= 10) params <- fitdistr(x= data_stream, densfun= 'negative binomial', lower= c(1e-9, 0)) params size mu 0.96289937 10.02900002 ( 0.04719405) ( 0.33835666) new_time_point <- 30 pnbinom(new_time_point, size= params$estimate[1], mu= params$estimate[2]) 0.94562 # This is how extreme the new data is
Can Negative Binomial parameters be treated like Poisson?
This is how I would do it in R. If correct, it should be easy to translate to python. First estimate the parameters of the negative binomial distribution that best fit a given training dataset. Then m
Can Negative Binomial parameters be treated like Poisson? This is how I would do it in R. If correct, it should be easy to translate to python. First estimate the parameters of the negative binomial distribution that best fit a given training dataset. Then map the new data to the distribution function with those parameters. library(MASS) set.seed(1234) data_stream <- rnbinom(n= 1000, size= 1, mu= 10) params <- fitdistr(x= data_stream, densfun= 'negative binomial', lower= c(1e-9, 0)) params size mu 0.96289937 10.02900002 ( 0.04719405) ( 0.33835666) new_time_point <- 30 pnbinom(new_time_point, size= params$estimate[1], mu= params$estimate[2]) 0.94562 # This is how extreme the new data is
Can Negative Binomial parameters be treated like Poisson? This is how I would do it in R. If correct, it should be easy to translate to python. First estimate the parameters of the negative binomial distribution that best fit a given training dataset. Then m
35,302
Cross Validation: Averaging across estimates vs re-estimating on full sample
This is uncommon and can be quite risky, especially when there are multiple local minima for the cost function. You might even end up in the neighbourhood of a local maximum after averaging them out! This is similar (not the same since subsets are not bootstrap samples) to ensembling (e.g. random forests). Not very common, and not preferable when training is expensive. It might be useful when you want to reduce the variance of your model, but there are other ways to reduce it as well. This is the most common approach. Preferable since in the end you can claim one model and it'll be cheaper than training $K$ models. Moreover, in this one, your model sees the whole data together.
Cross Validation: Averaging across estimates vs re-estimating on full sample
This is uncommon and can be quite risky, especially when there are multiple local minima for the cost function. You might even end up in the neighbourhood of a local maximum after averaging them out!
Cross Validation: Averaging across estimates vs re-estimating on full sample This is uncommon and can be quite risky, especially when there are multiple local minima for the cost function. You might even end up in the neighbourhood of a local maximum after averaging them out! This is similar (not the same since subsets are not bootstrap samples) to ensembling (e.g. random forests). Not very common, and not preferable when training is expensive. It might be useful when you want to reduce the variance of your model, but there are other ways to reduce it as well. This is the most common approach. Preferable since in the end you can claim one model and it'll be cheaper than training $K$ models. Moreover, in this one, your model sees the whole data together.
Cross Validation: Averaging across estimates vs re-estimating on full sample This is uncommon and can be quite risky, especially when there are multiple local minima for the cost function. You might even end up in the neighbourhood of a local maximum after averaging them out!
35,303
log(1 - softmax(X))? [closed]
Usually these values are not computed alone: the entire collection of $v_i$ and $\log(1 - \exp(v_i))$ is needed. That changes the analysis of computational effort. To this end, let $$\bar x = \log\left(\sum_{j} e^{x_j}\right) = x_k + \log\left(1 + \sum_{j\ne k} e^{x_j-x_k}\right)$$ for any index $k.$ The right hand expression shows how $\bar x - x_k$ can be computed in a numerically stable way when $k$ is the index of the largest argument, for then the argument of the logarithm is between $1$ and $n$ (the number of the $x_i$) and the sum can be accurately computed using exp (especially when the $x_j$ are ordered from smallest to largest in the sum). The relation $$\eqalign{ \log\left(1 - \frac{e^{x_i}}{\sum_{j} e^{x_j}}\right) &= \log\left(\frac{\sum_{j\ne i} e^{x_j}}{\sum_{j} e^{x_j}}\right) \\ &= \log\left(\sum_{j\ne i} e^{x_j}\right) - x_k + \log\left(\frac{e^{x_k}}{\sum_{j} e^{x_j}}\right) \\ &= \log\left(-e^{x_i} + \sum_{j} e^{x_j}\right) - x_k + v_k \\ &= \log\left(1 - e^{x_i - \bar x}\right) + (\bar x - x_k) + v_k }$$ reduces the problem to finding that last logarithm, which is accomplished by applying a log1mexp function to the difference $x_i - \bar x.$ For $n$ arguments $x_i,$ $i=1,2,\ldots, n,$ the total effort to compute all $2n$ values is $n$ computations of the $v_i$ using logsoftmax. One computation of $\bar x - x_k$ (using $n-1$ exponentials and a logarithm). $n$ invocations of log1mexp.
log(1 - softmax(X))? [closed]
Usually these values are not computed alone: the entire collection of $v_i$ and $\log(1 - \exp(v_i))$ is needed. That changes the analysis of computational effort. To this end, let $$\bar x = \log\le
log(1 - softmax(X))? [closed] Usually these values are not computed alone: the entire collection of $v_i$ and $\log(1 - \exp(v_i))$ is needed. That changes the analysis of computational effort. To this end, let $$\bar x = \log\left(\sum_{j} e^{x_j}\right) = x_k + \log\left(1 + \sum_{j\ne k} e^{x_j-x_k}\right)$$ for any index $k.$ The right hand expression shows how $\bar x - x_k$ can be computed in a numerically stable way when $k$ is the index of the largest argument, for then the argument of the logarithm is between $1$ and $n$ (the number of the $x_i$) and the sum can be accurately computed using exp (especially when the $x_j$ are ordered from smallest to largest in the sum). The relation $$\eqalign{ \log\left(1 - \frac{e^{x_i}}{\sum_{j} e^{x_j}}\right) &= \log\left(\frac{\sum_{j\ne i} e^{x_j}}{\sum_{j} e^{x_j}}\right) \\ &= \log\left(\sum_{j\ne i} e^{x_j}\right) - x_k + \log\left(\frac{e^{x_k}}{\sum_{j} e^{x_j}}\right) \\ &= \log\left(-e^{x_i} + \sum_{j} e^{x_j}\right) - x_k + v_k \\ &= \log\left(1 - e^{x_i - \bar x}\right) + (\bar x - x_k) + v_k }$$ reduces the problem to finding that last logarithm, which is accomplished by applying a log1mexp function to the difference $x_i - \bar x.$ For $n$ arguments $x_i,$ $i=1,2,\ldots, n,$ the total effort to compute all $2n$ values is $n$ computations of the $v_i$ using logsoftmax. One computation of $\bar x - x_k$ (using $n-1$ exponentials and a logarithm). $n$ invocations of log1mexp.
log(1 - softmax(X))? [closed] Usually these values are not computed alone: the entire collection of $v_i$ and $\log(1 - \exp(v_i))$ is needed. That changes the analysis of computational effort. To this end, let $$\bar x = \log\le
35,304
log(1 - softmax(X))? [closed]
One option is to use the numerically stable log-softmax implementation in combination with a numerically stable $\text{log1m_exp}(x):=\log(1-\exp(x))$ function. I believe the following is pretty good for $\text{log1m_exp}$: if x > -0.693147 you use $\log(-\text{expm1}(x))$, otherwise $\text{log1m}(\exp(x))$, where $\text{log1m}(x):= \text{log1p}(-x)$. $\text{log1p}(x):=\log(1+x)$ is usually implemented (e.g. in numpy or base R, similarly the inverse function for $\text{log1p}$, i.e. $\text{expm1}(x) = \text{log1p}^{-1}(x)$).
log(1 - softmax(X))? [closed]
One option is to use the numerically stable log-softmax implementation in combination with a numerically stable $\text{log1m_exp}(x):=\log(1-\exp(x))$ function. I believe the following is pretty good
log(1 - softmax(X))? [closed] One option is to use the numerically stable log-softmax implementation in combination with a numerically stable $\text{log1m_exp}(x):=\log(1-\exp(x))$ function. I believe the following is pretty good for $\text{log1m_exp}$: if x > -0.693147 you use $\log(-\text{expm1}(x))$, otherwise $\text{log1m}(\exp(x))$, where $\text{log1m}(x):= \text{log1p}(-x)$. $\text{log1p}(x):=\log(1+x)$ is usually implemented (e.g. in numpy or base R, similarly the inverse function for $\text{log1p}$, i.e. $\text{expm1}(x) = \text{log1p}^{-1}(x)$).
log(1 - softmax(X))? [closed] One option is to use the numerically stable log-softmax implementation in combination with a numerically stable $\text{log1m_exp}(x):=\log(1-\exp(x))$ function. I believe the following is pretty good
35,305
log(1 - softmax(X))? [closed]
Here is a possible way to do this, in Julia code (which I think is quite readable even if one does not know Julia): function log1msoftmax(x::AbstractArray; dims=1) m = maximum(x; dims=dims) e = exp.(x .- m) s = sum(e; dims=dims) return log.((s .- e) ./ s) end This has the same complexity as a logsoftmax (it does one exp and one log call per entry).
log(1 - softmax(X))? [closed]
Here is a possible way to do this, in Julia code (which I think is quite readable even if one does not know Julia): function log1msoftmax(x::AbstractArray; dims=1) m = maximum(x; dims=dims) e = ex
log(1 - softmax(X))? [closed] Here is a possible way to do this, in Julia code (which I think is quite readable even if one does not know Julia): function log1msoftmax(x::AbstractArray; dims=1) m = maximum(x; dims=dims) e = exp.(x .- m) s = sum(e; dims=dims) return log.((s .- e) ./ s) end This has the same complexity as a logsoftmax (it does one exp and one log call per entry).
log(1 - softmax(X))? [closed] Here is a possible way to do this, in Julia code (which I think is quite readable even if one does not know Julia): function log1msoftmax(x::AbstractArray; dims=1) m = maximum(x; dims=dims) e = ex
35,306
Expected value of the absolute standardized t distribution
Per whuber's answer to Standardized Student's-t distribution, the density of the standardized $t$ distribution on $\nu$ degrees of freedom is $$f(x) = \frac{\Gamma(\frac{\nu + 1}{2})}{\Gamma(\frac{\nu}{2})} \frac{1}{\sqrt{\pi(\nu-2)}} \left[1+\frac{x^2}{\nu-2}\right]^{-\frac{\nu+1}{2}}.$$ (Note that we need $\nu>2$ so we have two moments to standardize.) Thus, your expectation is $$ \begin{align*} E(|X|) & = 2\int_0^\infty xf(x)\,dx \\ & = \frac{\Gamma(\frac{\nu + 1}{2})}{\Gamma(\frac{\nu}{2})} \frac{2}{\sqrt{\pi(\nu-2)}} \int_0^\infty x\left[1+\frac{x^2}{\nu-2}\right]^{-\frac{\nu+1}{2}}\,dx \\ &= \frac{\Gamma(\frac{\nu + 1}{2})}{\Gamma(\frac{\nu}{2})} \frac{2}{\sqrt{\pi(\nu-2)}} \left(-\frac{\nu-2}{\nu-1}\right)\left(1+\frac{x^2}{\nu-2}\right)^{\frac{1-\nu}{2}}\bigg|_0^\infty \\ & = \frac{2}{\sqrt{\pi}}\frac{\Gamma(\frac{\nu + 1}{2})}{\Gamma(\frac{\nu}{2})} \frac{\sqrt{\nu-2}}{\nu-1} \end{align*} $$ by a rather simple integral evaluation. I like sanity checking calculations like these using simulation, and it seems to check out: > df <- 10 > nn <- 1e6 > > sims <- rt(nn,df)/(sqrt(df/(df-2)))# standardize by the variance > mean(sims) [1] -0.0006262779 > var(sims) [1] 0.9995302 > > mean(abs(sims)) [1] 0.7732408 > 2/sqrt(pi)*gamma((df+1)/2)/gamma(df/2)*sqrt(df-2)/(df-1) [1] 0.773398
Expected value of the absolute standardized t distribution
Per whuber's answer to Standardized Student's-t distribution, the density of the standardized $t$ distribution on $\nu$ degrees of freedom is $$f(x) = \frac{\Gamma(\frac{\nu + 1}{2})}{\Gamma(\frac{\nu
Expected value of the absolute standardized t distribution Per whuber's answer to Standardized Student's-t distribution, the density of the standardized $t$ distribution on $\nu$ degrees of freedom is $$f(x) = \frac{\Gamma(\frac{\nu + 1}{2})}{\Gamma(\frac{\nu}{2})} \frac{1}{\sqrt{\pi(\nu-2)}} \left[1+\frac{x^2}{\nu-2}\right]^{-\frac{\nu+1}{2}}.$$ (Note that we need $\nu>2$ so we have two moments to standardize.) Thus, your expectation is $$ \begin{align*} E(|X|) & = 2\int_0^\infty xf(x)\,dx \\ & = \frac{\Gamma(\frac{\nu + 1}{2})}{\Gamma(\frac{\nu}{2})} \frac{2}{\sqrt{\pi(\nu-2)}} \int_0^\infty x\left[1+\frac{x^2}{\nu-2}\right]^{-\frac{\nu+1}{2}}\,dx \\ &= \frac{\Gamma(\frac{\nu + 1}{2})}{\Gamma(\frac{\nu}{2})} \frac{2}{\sqrt{\pi(\nu-2)}} \left(-\frac{\nu-2}{\nu-1}\right)\left(1+\frac{x^2}{\nu-2}\right)^{\frac{1-\nu}{2}}\bigg|_0^\infty \\ & = \frac{2}{\sqrt{\pi}}\frac{\Gamma(\frac{\nu + 1}{2})}{\Gamma(\frac{\nu}{2})} \frac{\sqrt{\nu-2}}{\nu-1} \end{align*} $$ by a rather simple integral evaluation. I like sanity checking calculations like these using simulation, and it seems to check out: > df <- 10 > nn <- 1e6 > > sims <- rt(nn,df)/(sqrt(df/(df-2)))# standardize by the variance > mean(sims) [1] -0.0006262779 > var(sims) [1] 0.9995302 > > mean(abs(sims)) [1] 0.7732408 > 2/sqrt(pi)*gamma((df+1)/2)/gamma(df/2)*sqrt(df-2)/(df-1) [1] 0.773398
Expected value of the absolute standardized t distribution Per whuber's answer to Standardized Student's-t distribution, the density of the standardized $t$ distribution on $\nu$ degrees of freedom is $$f(x) = \frac{\Gamma(\frac{\nu + 1}{2})}{\Gamma(\frac{\nu
35,307
Variable slopes in a fixed effects model
There seems to be some confusion in your question. The purpose of random effects (intercepts) in a growth model, is to account for the correlations within individuals. The difference in slope that you expect, between boys and girls would be modelled with an interaction between the slope (ie the fixed effect for the time variable) and sex. Additionally, you can allow each subject to have their own slope, or rather an offset from the fixed slope, by fitting random slopes. You say: boy and girl are fixed effects so a random effect model seems inappropriate This is correct. Sex is a fixed effect. In the example in your question you would fit a model such as: height ~ sex * time + (1 | subject) This will estimate an overall linear trend for time (the fixed effect for time) for both boys and girls (the fixed effect for sex) and also allow trend to be different for boys and girls (the sex:time interaction), while also adjusting the dependence between measurements in each person (the subject random intercept). As mentioned in the first paragraph, You could also allow each subject to have their own slope by fitting random slopes for time: height ~ sex * time + (time | subject)
Variable slopes in a fixed effects model
There seems to be some confusion in your question. The purpose of random effects (intercepts) in a growth model, is to account for the correlations within individuals. The difference in slope that you
Variable slopes in a fixed effects model There seems to be some confusion in your question. The purpose of random effects (intercepts) in a growth model, is to account for the correlations within individuals. The difference in slope that you expect, between boys and girls would be modelled with an interaction between the slope (ie the fixed effect for the time variable) and sex. Additionally, you can allow each subject to have their own slope, or rather an offset from the fixed slope, by fitting random slopes. You say: boy and girl are fixed effects so a random effect model seems inappropriate This is correct. Sex is a fixed effect. In the example in your question you would fit a model such as: height ~ sex * time + (1 | subject) This will estimate an overall linear trend for time (the fixed effect for time) for both boys and girls (the fixed effect for sex) and also allow trend to be different for boys and girls (the sex:time interaction), while also adjusting the dependence between measurements in each person (the subject random intercept). As mentioned in the first paragraph, You could also allow each subject to have their own slope by fitting random slopes for time: height ~ sex * time + (time | subject)
Variable slopes in a fixed effects model There seems to be some confusion in your question. The purpose of random effects (intercepts) in a growth model, is to account for the correlations within individuals. The difference in slope that you
35,308
Can I ignore the negative R-squared value when I am using instrumental variable regression?
Yes, the linked STATA post answers your question in a single sentence: $R^2$ really has no statistical meaning in the context of 2SLS/IV. How can $R^2$ be negative? Wikipedia has a great visualization of $R^2$: On the left, we see the $\color{red}{\text{total sum of squares}}$, obtained by using the mean ($\bar{y}$) as a prediction: $${\text{total sum of squares}} = \sum_{i = 1}^n (y_i - \bar{y})^2$$ On the right, we see the $\color{blue}{\text{residual sum of squares}}$, obtained by using the model's predictions ($\hat{y}$): $${\text{residual sum of squares}} = \sum_{i = 1}^n (y_i - \hat{y})^2 = \sum_{i = 1}^n \bigg(y_i - \Big( \hat{\beta}_0 + \sum_{j = 1}^p \hat{\beta}_j \cdot x_j \Big) \bigg)^2$$ Ordinarily, $R^2 = 1 - \frac{\color{blue}{\text{residual sum of squares}}}{\color{red}{\text{total sum of squares}}} \geq 0$, because any model with an intercept ($\beta_0$) should perform at least as well as the image on the left (the intercept could simply be the mean). However, if you interpret instrumental variable regression as a two-stage linear regression, it is easy to show why it could end up being negative. Namely, suppose the endogenous variables ($\mathbf{X}$) are regressed on the exogenous variables ($\mathbf{Z}$), and the predicted values ($\hat{\mathbf{X}}$) are then used as covariates in the second stage: $$\text{Stage 1:} \quad \mathbf{X} = \mathbf{Z\delta} + \text{error} \\ \text{Stage 2:} \quad \mathbf{y} = \hat{\mathbf{X}}\mathbf{\beta} + \text{error}$$ Since $\hat{\mathbf{X}} \neq \mathbf{X}$, the error that is minimized in the second stage is not the same as the error used to calculate the residual sum of squares. Consequently, the residual sum of squares need not be less than the total sum of squares anymore. (And more importantly, the $R^2$ has become meaningless.)
Can I ignore the negative R-squared value when I am using instrumental variable regression?
Yes, the linked STATA post answers your question in a single sentence: $R^2$ really has no statistical meaning in the context of 2SLS/IV. How can $R^2$ be negative? Wikipedia has a great visualizat
Can I ignore the negative R-squared value when I am using instrumental variable regression? Yes, the linked STATA post answers your question in a single sentence: $R^2$ really has no statistical meaning in the context of 2SLS/IV. How can $R^2$ be negative? Wikipedia has a great visualization of $R^2$: On the left, we see the $\color{red}{\text{total sum of squares}}$, obtained by using the mean ($\bar{y}$) as a prediction: $${\text{total sum of squares}} = \sum_{i = 1}^n (y_i - \bar{y})^2$$ On the right, we see the $\color{blue}{\text{residual sum of squares}}$, obtained by using the model's predictions ($\hat{y}$): $${\text{residual sum of squares}} = \sum_{i = 1}^n (y_i - \hat{y})^2 = \sum_{i = 1}^n \bigg(y_i - \Big( \hat{\beta}_0 + \sum_{j = 1}^p \hat{\beta}_j \cdot x_j \Big) \bigg)^2$$ Ordinarily, $R^2 = 1 - \frac{\color{blue}{\text{residual sum of squares}}}{\color{red}{\text{total sum of squares}}} \geq 0$, because any model with an intercept ($\beta_0$) should perform at least as well as the image on the left (the intercept could simply be the mean). However, if you interpret instrumental variable regression as a two-stage linear regression, it is easy to show why it could end up being negative. Namely, suppose the endogenous variables ($\mathbf{X}$) are regressed on the exogenous variables ($\mathbf{Z}$), and the predicted values ($\hat{\mathbf{X}}$) are then used as covariates in the second stage: $$\text{Stage 1:} \quad \mathbf{X} = \mathbf{Z\delta} + \text{error} \\ \text{Stage 2:} \quad \mathbf{y} = \hat{\mathbf{X}}\mathbf{\beta} + \text{error}$$ Since $\hat{\mathbf{X}} \neq \mathbf{X}$, the error that is minimized in the second stage is not the same as the error used to calculate the residual sum of squares. Consequently, the residual sum of squares need not be less than the total sum of squares anymore. (And more importantly, the $R^2$ has become meaningless.)
Can I ignore the negative R-squared value when I am using instrumental variable regression? Yes, the linked STATA post answers your question in a single sentence: $R^2$ really has no statistical meaning in the context of 2SLS/IV. How can $R^2$ be negative? Wikipedia has a great visualizat
35,309
Marginalize probability with three variables
As noted here, any rule, theorem, or formula that you have learned about probabilities is also applicable if everything is assumed to be conditioned on the occurrence of some event. For example, knowing that $$P(B^c) = 1-P(B)$$ allows us to immediately conclude that $$P(B^c\mid A) = 1 - P(B\mid A)$$ is a valid result without going through writing out the formal definitions and completing a proof of the result. So, apply this notion to what you know, viz., $$ P(X) = \sum_{z}P(X\mid z)P(z)$$ to get $$ P(X\mid\theta) = \sum_{z}P(X\mid z,\theta)P(z\mid\theta).$$ All you are doing is conditioning everything on the new variable or event $\theta$. Don't believe all this high-faluting nonsense? Then just grind it out the hard way by using all the definitions: \begin{align} \sum_{z}P(X|z,\theta)P(z|\theta) &= \sum_{z}\frac{P(X, z,\theta)}{P(z,\theta)}\times \frac{P(z,\theta)}{P(\theta)}\\ &= \sum_{z}\frac{P(X, z,\theta)}{P(\theta)}\\ &= \frac{1}{P(\theta)}\sum_{z} {P(X, z, \theta)}\\ &= \frac{P(X, \theta)}{P(\theta)}\\ &= P(X\mid\theta). \end{align}
Marginalize probability with three variables
As noted here, any rule, theorem, or formula that you have learned about probabilities is also applicable if everything is assumed to be conditioned on the occurrence of some event. For example, know
Marginalize probability with three variables As noted here, any rule, theorem, or formula that you have learned about probabilities is also applicable if everything is assumed to be conditioned on the occurrence of some event. For example, knowing that $$P(B^c) = 1-P(B)$$ allows us to immediately conclude that $$P(B^c\mid A) = 1 - P(B\mid A)$$ is a valid result without going through writing out the formal definitions and completing a proof of the result. So, apply this notion to what you know, viz., $$ P(X) = \sum_{z}P(X\mid z)P(z)$$ to get $$ P(X\mid\theta) = \sum_{z}P(X\mid z,\theta)P(z\mid\theta).$$ All you are doing is conditioning everything on the new variable or event $\theta$. Don't believe all this high-faluting nonsense? Then just grind it out the hard way by using all the definitions: \begin{align} \sum_{z}P(X|z,\theta)P(z|\theta) &= \sum_{z}\frac{P(X, z,\theta)}{P(z,\theta)}\times \frac{P(z,\theta)}{P(\theta)}\\ &= \sum_{z}\frac{P(X, z,\theta)}{P(\theta)}\\ &= \frac{1}{P(\theta)}\sum_{z} {P(X, z, \theta)}\\ &= \frac{P(X, \theta)}{P(\theta)}\\ &= P(X\mid\theta). \end{align}
Marginalize probability with three variables As noted here, any rule, theorem, or formula that you have learned about probabilities is also applicable if everything is assumed to be conditioned on the occurrence of some event. For example, know
35,310
Marginalize probability with three variables
One way to think, and I think it is the easier way, is to imagine that we can add any number of RVs to the given side of the probability formulas, i.e. we'd also have $$P(X|\theta_1,\theta_2)=\sum_z P(X|z,\theta_1,\theta_2)P(z|\theta_1,\theta_2)$$ Or, you can multiply both sides of the above equation with $P(\theta)$ and have $$P(X,\theta)=\sum_z P(X|z,\theta)P(z,\theta)=\sum_z P(X,z,\theta)$$ which is actually the marginalization.
Marginalize probability with three variables
One way to think, and I think it is the easier way, is to imagine that we can add any number of RVs to the given side of the probability formulas, i.e. we'd also have $$P(X|\theta_1,\theta_2)=\sum_z P
Marginalize probability with three variables One way to think, and I think it is the easier way, is to imagine that we can add any number of RVs to the given side of the probability formulas, i.e. we'd also have $$P(X|\theta_1,\theta_2)=\sum_z P(X|z,\theta_1,\theta_2)P(z|\theta_1,\theta_2)$$ Or, you can multiply both sides of the above equation with $P(\theta)$ and have $$P(X,\theta)=\sum_z P(X|z,\theta)P(z,\theta)=\sum_z P(X,z,\theta)$$ which is actually the marginalization.
Marginalize probability with three variables One way to think, and I think it is the easier way, is to imagine that we can add any number of RVs to the given side of the probability formulas, i.e. we'd also have $$P(X|\theta_1,\theta_2)=\sum_z P
35,311
What is meant by 'Black box variational inference'?
So he’s referring the technique introduced in this paper: https://arxiv.org/abs/1401.0118 The idea behind black box VI is that normally in VI it takes a significant amount of work to decide on a variational posterior and derive the ELBO and it’s gradients. As such there was room for a more general algorithm that can be easily implemented and doesn’t require the practitioner to derive these forms every time. The “black box” part of the name is just from the fact it’s a general algorithm that works and you don’t need to think about what’s going on inside. Essentially black box VI is a method that yields an estimator for the gradient of the ELBO with respect to the variational parameters with very little constraint on the form of the posterior or the variational distribution. These constraints (the black box criteria you mention) are only that you can evaluate the first derivatives of the log of the variational distribution with respect to its parameters (which you should be able to as you would normally pick a relatively simple distribution for the variational) and that you can evaluate the log of the joint of the data and latent variables (again very standard in the setting of probabilistic modelling).
What is meant by 'Black box variational inference'?
So he’s referring the technique introduced in this paper: https://arxiv.org/abs/1401.0118 The idea behind black box VI is that normally in VI it takes a significant amount of work to decide on a varia
What is meant by 'Black box variational inference'? So he’s referring the technique introduced in this paper: https://arxiv.org/abs/1401.0118 The idea behind black box VI is that normally in VI it takes a significant amount of work to decide on a variational posterior and derive the ELBO and it’s gradients. As such there was room for a more general algorithm that can be easily implemented and doesn’t require the practitioner to derive these forms every time. The “black box” part of the name is just from the fact it’s a general algorithm that works and you don’t need to think about what’s going on inside. Essentially black box VI is a method that yields an estimator for the gradient of the ELBO with respect to the variational parameters with very little constraint on the form of the posterior or the variational distribution. These constraints (the black box criteria you mention) are only that you can evaluate the first derivatives of the log of the variational distribution with respect to its parameters (which you should be able to as you would normally pick a relatively simple distribution for the variational) and that you can evaluate the log of the joint of the data and latent variables (again very standard in the setting of probabilistic modelling).
What is meant by 'Black box variational inference'? So he’s referring the technique introduced in this paper: https://arxiv.org/abs/1401.0118 The idea behind black box VI is that normally in VI it takes a significant amount of work to decide on a varia
35,312
What is meant by 'Black box variational inference'?
The main algorithm used in VI before was the Coordinate Ascent VI (CAVI), which does a "variational" coordinate ascent on the ELBO. An alternative to doing Coordinate Ascent is doing Gradient Ascent. Why should we do that? Gradient Ascent / Descent can also be done stochastically (SGA / SGD), by sampling only part of the data. As the data size becomes larger each iteration of CAVI becomes more expensive. The CAVI update rule might be too complicated for some problems, while the gradient may be simple. For certain problems where we can assume the distributions are from the Exponential Family, the gradient is actually easy to compute (even more so if we use the “natural” gradient instead of the regular gradient). For other problems, we can still use Monte-Carlo (MC) integration and calculate the gradients. Two known algorithms that do so are Automatic-Differentiation VI (ADVI) and Black-Box VI (BBVI). BBVI computes an MC estimator of the gradient, using what is known as the "log-derivative" or the "REINFORCE" trick. The "vanilla" version is quite simple, with just a little bit of derivation you get to: $$ \hat {\nabla_{\phi}\text{ELBO}} ^{(t+1)} = \frac{1}{m}\sum_{i=1}^m \nabla_{\phi} \log q(\theta_{i}) \cdot (\log p(\theta_{i},x)-\log q(\theta_{i}))) \\ \phi ^{(t+1)} = \phi^{(t)}+\alpha \cdot \hat {\nabla_{\phi}\text{ELBO}} ^{(t+1)}$$ Where $q$ is the variational family parameterized by $\phi$, and $p(\theta,x)$ is the joint. Unfortunately, this suffers from high variance (the ELBO-derivative can give extremely different results depending on the sample of θ’s at each iteration), and so some variance reduction techniques are used, which complicate things a bit. You can check my medium article on the topic, or my YouTube video, for more information.
What is meant by 'Black box variational inference'?
The main algorithm used in VI before was the Coordinate Ascent VI (CAVI), which does a "variational" coordinate ascent on the ELBO. An alternative to doing Coordinate Ascent is doing Gradient Ascent.
What is meant by 'Black box variational inference'? The main algorithm used in VI before was the Coordinate Ascent VI (CAVI), which does a "variational" coordinate ascent on the ELBO. An alternative to doing Coordinate Ascent is doing Gradient Ascent. Why should we do that? Gradient Ascent / Descent can also be done stochastically (SGA / SGD), by sampling only part of the data. As the data size becomes larger each iteration of CAVI becomes more expensive. The CAVI update rule might be too complicated for some problems, while the gradient may be simple. For certain problems where we can assume the distributions are from the Exponential Family, the gradient is actually easy to compute (even more so if we use the “natural” gradient instead of the regular gradient). For other problems, we can still use Monte-Carlo (MC) integration and calculate the gradients. Two known algorithms that do so are Automatic-Differentiation VI (ADVI) and Black-Box VI (BBVI). BBVI computes an MC estimator of the gradient, using what is known as the "log-derivative" or the "REINFORCE" trick. The "vanilla" version is quite simple, with just a little bit of derivation you get to: $$ \hat {\nabla_{\phi}\text{ELBO}} ^{(t+1)} = \frac{1}{m}\sum_{i=1}^m \nabla_{\phi} \log q(\theta_{i}) \cdot (\log p(\theta_{i},x)-\log q(\theta_{i}))) \\ \phi ^{(t+1)} = \phi^{(t)}+\alpha \cdot \hat {\nabla_{\phi}\text{ELBO}} ^{(t+1)}$$ Where $q$ is the variational family parameterized by $\phi$, and $p(\theta,x)$ is the joint. Unfortunately, this suffers from high variance (the ELBO-derivative can give extremely different results depending on the sample of θ’s at each iteration), and so some variance reduction techniques are used, which complicate things a bit. You can check my medium article on the topic, or my YouTube video, for more information.
What is meant by 'Black box variational inference'? The main algorithm used in VI before was the Coordinate Ascent VI (CAVI), which does a "variational" coordinate ascent on the ELBO. An alternative to doing Coordinate Ascent is doing Gradient Ascent.
35,313
What is the computational cost of gradient descent vs linear regression?
The computational cost of gradient descent depends on the number of iterations it takes to converge. But according to the Machine Learning course by Stanford University, the complexity of gradient descent is $O(kn^2)$, so when $n$ is very large is recommended to use gradient descent instead of the closed form of linear regression. source: https://www.coursera.org/learn/machine-learning/supplement/bjjZW/normal-equation
What is the computational cost of gradient descent vs linear regression?
The computational cost of gradient descent depends on the number of iterations it takes to converge. But according to the Machine Learning course by Stanford University, the complexity of gradient des
What is the computational cost of gradient descent vs linear regression? The computational cost of gradient descent depends on the number of iterations it takes to converge. But according to the Machine Learning course by Stanford University, the complexity of gradient descent is $O(kn^2)$, so when $n$ is very large is recommended to use gradient descent instead of the closed form of linear regression. source: https://www.coursera.org/learn/machine-learning/supplement/bjjZW/normal-equation
What is the computational cost of gradient descent vs linear regression? The computational cost of gradient descent depends on the number of iterations it takes to converge. But according to the Machine Learning course by Stanford University, the complexity of gradient des
35,314
What is the computational cost of gradient descent vs linear regression?
The number of iterations a gradient method takes to reach a local optimum for a prescribed tolerance is problem dependent: depends on the shape of the surface you are exloring and the initial guess. Hence, no general O() expression for complexity can be given.
What is the computational cost of gradient descent vs linear regression?
The number of iterations a gradient method takes to reach a local optimum for a prescribed tolerance is problem dependent: depends on the shape of the surface you are exloring and the initial guess. H
What is the computational cost of gradient descent vs linear regression? The number of iterations a gradient method takes to reach a local optimum for a prescribed tolerance is problem dependent: depends on the shape of the surface you are exloring and the initial guess. Hence, no general O() expression for complexity can be given.
What is the computational cost of gradient descent vs linear regression? The number of iterations a gradient method takes to reach a local optimum for a prescribed tolerance is problem dependent: depends on the shape of the surface you are exloring and the initial guess. H
35,315
What is the computational cost of gradient descent vs linear regression?
Gradient descent has a time complexity of O(ndk), where d is the number of features, and n Is the number of rows. So, when d and n and large, it is better to use gradient descent.
What is the computational cost of gradient descent vs linear regression?
Gradient descent has a time complexity of O(ndk), where d is the number of features, and n Is the number of rows. So, when d and n and large, it is better to use gradient descent.
What is the computational cost of gradient descent vs linear regression? Gradient descent has a time complexity of O(ndk), where d is the number of features, and n Is the number of rows. So, when d and n and large, it is better to use gradient descent.
What is the computational cost of gradient descent vs linear regression? Gradient descent has a time complexity of O(ndk), where d is the number of features, and n Is the number of rows. So, when d and n and large, it is better to use gradient descent.
35,316
What is the computational cost of gradient descent vs linear regression?
The time complexity of gradient descent is: $O(knd)$ where: $k$ is number of iterations $n$ is number of samples $d$ is number of features (or equally number of parameters that are being updated iteratively during the gradient descent) As Valentina Sánchez Bermúdez already pointed out (which is indeed based on the Machine Learning course by Stanford University), the time complexity of gradient descent is defined as $O(kn^2)$ there. I find such definition less intuitive and seemingly incorrect. In either case, as the number of features grows (say $d > 10^4$), then it becomes computationally difficult to calculate $\theta = (X^TX)^{-1}X^Ty$ matrix (aka. the Normal Equation) in the linear regression (particularly the $(X^TX)^{-1}$ part). In those cases, we tend to use the gradient descend method to find the optimal parameters of the linear regression. This is also pointed out in the above course.
What is the computational cost of gradient descent vs linear regression?
The time complexity of gradient descent is: $O(knd)$ where: $k$ is number of iterations $n$ is number of samples $d$ is number of features (or equally number of parameters that are being updated iter
What is the computational cost of gradient descent vs linear regression? The time complexity of gradient descent is: $O(knd)$ where: $k$ is number of iterations $n$ is number of samples $d$ is number of features (or equally number of parameters that are being updated iteratively during the gradient descent) As Valentina Sánchez Bermúdez already pointed out (which is indeed based on the Machine Learning course by Stanford University), the time complexity of gradient descent is defined as $O(kn^2)$ there. I find such definition less intuitive and seemingly incorrect. In either case, as the number of features grows (say $d > 10^4$), then it becomes computationally difficult to calculate $\theta = (X^TX)^{-1}X^Ty$ matrix (aka. the Normal Equation) in the linear regression (particularly the $(X^TX)^{-1}$ part). In those cases, we tend to use the gradient descend method to find the optimal parameters of the linear regression. This is also pointed out in the above course.
What is the computational cost of gradient descent vs linear regression? The time complexity of gradient descent is: $O(knd)$ where: $k$ is number of iterations $n$ is number of samples $d$ is number of features (or equally number of parameters that are being updated iter
35,317
What exactly is the extratrees option in ranger?
Your understanding is correct, extraTrees does implement Geurts et al. (2006) Extremely randomized trees. The implementation of extraTrees has been discussed in detail in Github's thread on that issue so I would strongly urge you read it further here. Regarding the particular questions raised: Yes, but read on! By default the same number of candidates mtry is used, this being calculated as the (rounded down) square root of the number variables. It makes sense for ranger to use a particular number for mtry because that way it can be effectively regularised. Theoretically, we should indeed restrict the choice to a random subset to begin within each tree. Nevertheless as the choice of the attribute to split as well as the split itself are random this difference is mostly a formality. Yes, you can. By far the main novelty in Geurts et al. is the way that nodes are split by choosing cut-points fully at random; that is something that ranger definitely does. You could/should specify in the paper that the implementation used is the one from ranger to alleviate any uncertainties. You are correct; the default values hurt us here. That said if during training, we sample without replacement (i.e. we set replace = FALSE) as well as set the fractions of observation to sample to 1 (i.e. we set sample.fraction = 1) we will not get a OOB error and the forest is trained on the whole sample. You might want to create a new issue about this in ranger's github repo. It will mostly be a case of re-adjusting the defaults when splitrule='extraTrees' but we can do it manually too. To recap: If we use rf <- ranger( ..., splitrule = "extratrees", replace = FALSE, sample.fraction = 1) we can safely say that we use Geurts et al. implementation. All the core differences between extremely randomized trees and "standard" random forests are respected. Minor point on regarding reporting OOB or not: While indeed OOB estimates can substitute the presence of a separate test set, I find it much more clear if there is a distinct test set and/or we use repeated CV or bootstrapping. It makes the comparison with other approaches (e.g. a simple linear model or an SVM) more comparable and coherent.
What exactly is the extratrees option in ranger?
Your understanding is correct, extraTrees does implement Geurts et al. (2006) Extremely randomized trees. The implementation of extraTrees has been discussed in detail in Github's thread on that issue
What exactly is the extratrees option in ranger? Your understanding is correct, extraTrees does implement Geurts et al. (2006) Extremely randomized trees. The implementation of extraTrees has been discussed in detail in Github's thread on that issue so I would strongly urge you read it further here. Regarding the particular questions raised: Yes, but read on! By default the same number of candidates mtry is used, this being calculated as the (rounded down) square root of the number variables. It makes sense for ranger to use a particular number for mtry because that way it can be effectively regularised. Theoretically, we should indeed restrict the choice to a random subset to begin within each tree. Nevertheless as the choice of the attribute to split as well as the split itself are random this difference is mostly a formality. Yes, you can. By far the main novelty in Geurts et al. is the way that nodes are split by choosing cut-points fully at random; that is something that ranger definitely does. You could/should specify in the paper that the implementation used is the one from ranger to alleviate any uncertainties. You are correct; the default values hurt us here. That said if during training, we sample without replacement (i.e. we set replace = FALSE) as well as set the fractions of observation to sample to 1 (i.e. we set sample.fraction = 1) we will not get a OOB error and the forest is trained on the whole sample. You might want to create a new issue about this in ranger's github repo. It will mostly be a case of re-adjusting the defaults when splitrule='extraTrees' but we can do it manually too. To recap: If we use rf <- ranger( ..., splitrule = "extratrees", replace = FALSE, sample.fraction = 1) we can safely say that we use Geurts et al. implementation. All the core differences between extremely randomized trees and "standard" random forests are respected. Minor point on regarding reporting OOB or not: While indeed OOB estimates can substitute the presence of a separate test set, I find it much more clear if there is a distinct test set and/or we use repeated CV or bootstrapping. It makes the comparison with other approaches (e.g. a simple linear model or an SVM) more comparable and coherent.
What exactly is the extratrees option in ranger? Your understanding is correct, extraTrees does implement Geurts et al. (2006) Extremely randomized trees. The implementation of extraTrees has been discussed in detail in Github's thread on that issue
35,318
Conditional expectation of uniform random variable given order statistics
Consider the case of an iid sample $X_1, X_2, \ldots, X_n$ from a Uniform$(0,1)$ distribution. Scaling these variables by $\theta$ and translating them by $\theta$ endows them with a Uniform$(\theta, 2\theta)$ distribution. Everything relevant to this problem changes in the same way: the order statistics and the conditional expectations. Thus, the answer obtained in this special case will hold generally. Let $1\lt k\lt n.$ By emulating the reasoning at https://stats.stackexchange.com/a/225990/919 (or elsewhere), find that the joint distribution of $(X_{(1)}, X_{(k)}, X_{(n)})$ has density function $$f_{k;n}(x,y,z) = \mathcal{I}(0\le x\le y\le z \le 1) (y-x)^{k-2}(z-y)^{n-k-1}.$$ Fixing $(x,z)$ and viewing this as a function of $y,$ this is recognizable as a Beta$(k-1, n-k)$ distribution that has been scaled and translated into the interval $[x,z].$ Thus, the scale factor must be $z-x$ and the translation takes $0$ to $x.$ Since the expectation of a Beta$(k-1,n-k)$ distribution is $(k-1)/(n-1),$ we find that the conditional expectation of $X_{(k)}$ must be the scaled, translated expectation; namely, $$\mathbb{E}\left(X_{(k)}\mid X_{(1)}, X_{(n)}\right) = X_{(1)} + \left(X_{(n)}-X_{(1)}\right) \frac{k-1}{n-1}.$$ The cases $k=1$ and $k=n$ are trivial: their conditional expectations are, respectively, $X_{(1)}$ and $X_{(k)}.$ Let's find the expectation of the sum of all order statistics: $$\mathbb{E}\left(\sum_{k=1}^n X_{(k)}\right) = X_{(1)} + \sum_{k=2}^{n-1} \left(X_{(1)} + \left(X_{(n)}-X_{(1)}\right) \frac{k-1}{n-1}\right) + X_{(n)}.$$ The algebra comes down to obtaining the sum $$\sum_{k=2}^{n-1}(k-1) = (n-1)(n-2)/2.$$ Thus $$\eqalign{ \mathbb{E}\left(\sum_{k=1}^n X_{(k)}\right) &= (n-1)X_{(1)} + \left(X_{(n)}-X_{(1)}\right) \frac{(n-1)(n-2)}{2(n-1)} + X_{(n)} \\ &= \frac{n}{2}\left(X_{(n)}+X_{(1)}\right). }$$ Finally, because the $X_i$ are identically distributed, they all have the same expectation, whence $$\eqalign{n\mathbb{E}\left(X_1\mid X_{(1)}, X_{(n)}\right) &= \mathbb{E}\left(X_1\right) + \mathbb{E}\left(X_2\right) + \cdots + \mathbb{E}\left(X_n\right)\\ &= \mathbb{E}\left(X_{(1)}\right) + \mathbb{E}\left(X_{(2)}\right) + \cdots + \mathbb{E}\left(X_{(n)}\right) \\ &= \frac{n}{2}\left(X_{(n)}+X_{(1)}\right), }$$ with the unique solution $$\mathbb{E}\left(X_1\mid X_{(1)}, X_{(n)}\right) = \left(X_{(n)}+X_{(1)}\right)/2.$$ It seems worth remarking that this result is not a sole consequence of the symmetry of the uniform distribution: it is particular to the uniform family of distributions. For some intuition, consider data drawn from a Beta$(a,a)$ distribution with $a \lt 1.$ This distribution's probabilities are concentrated near $0$ and $1$ (its density has a U or "bathtub" shape). When $X_{(n)}\lt 1/2,$ we can be sure most of the data are piled up close to $X_{(1)}$ and therefore will tend to have expectations less than the midpoint $(X_{(1)}+X_{(n)})/2;$ and when $X_{(1)}\gt 1/2,$ the opposite happens and most of the data are likely piled up close to $X_{(n)}.$
Conditional expectation of uniform random variable given order statistics
Consider the case of an iid sample $X_1, X_2, \ldots, X_n$ from a Uniform$(0,1)$ distribution. Scaling these variables by $\theta$ and translating them by $\theta$ endows them with a Uniform$(\theta,
Conditional expectation of uniform random variable given order statistics Consider the case of an iid sample $X_1, X_2, \ldots, X_n$ from a Uniform$(0,1)$ distribution. Scaling these variables by $\theta$ and translating them by $\theta$ endows them with a Uniform$(\theta, 2\theta)$ distribution. Everything relevant to this problem changes in the same way: the order statistics and the conditional expectations. Thus, the answer obtained in this special case will hold generally. Let $1\lt k\lt n.$ By emulating the reasoning at https://stats.stackexchange.com/a/225990/919 (or elsewhere), find that the joint distribution of $(X_{(1)}, X_{(k)}, X_{(n)})$ has density function $$f_{k;n}(x,y,z) = \mathcal{I}(0\le x\le y\le z \le 1) (y-x)^{k-2}(z-y)^{n-k-1}.$$ Fixing $(x,z)$ and viewing this as a function of $y,$ this is recognizable as a Beta$(k-1, n-k)$ distribution that has been scaled and translated into the interval $[x,z].$ Thus, the scale factor must be $z-x$ and the translation takes $0$ to $x.$ Since the expectation of a Beta$(k-1,n-k)$ distribution is $(k-1)/(n-1),$ we find that the conditional expectation of $X_{(k)}$ must be the scaled, translated expectation; namely, $$\mathbb{E}\left(X_{(k)}\mid X_{(1)}, X_{(n)}\right) = X_{(1)} + \left(X_{(n)}-X_{(1)}\right) \frac{k-1}{n-1}.$$ The cases $k=1$ and $k=n$ are trivial: their conditional expectations are, respectively, $X_{(1)}$ and $X_{(k)}.$ Let's find the expectation of the sum of all order statistics: $$\mathbb{E}\left(\sum_{k=1}^n X_{(k)}\right) = X_{(1)} + \sum_{k=2}^{n-1} \left(X_{(1)} + \left(X_{(n)}-X_{(1)}\right) \frac{k-1}{n-1}\right) + X_{(n)}.$$ The algebra comes down to obtaining the sum $$\sum_{k=2}^{n-1}(k-1) = (n-1)(n-2)/2.$$ Thus $$\eqalign{ \mathbb{E}\left(\sum_{k=1}^n X_{(k)}\right) &= (n-1)X_{(1)} + \left(X_{(n)}-X_{(1)}\right) \frac{(n-1)(n-2)}{2(n-1)} + X_{(n)} \\ &= \frac{n}{2}\left(X_{(n)}+X_{(1)}\right). }$$ Finally, because the $X_i$ are identically distributed, they all have the same expectation, whence $$\eqalign{n\mathbb{E}\left(X_1\mid X_{(1)}, X_{(n)}\right) &= \mathbb{E}\left(X_1\right) + \mathbb{E}\left(X_2\right) + \cdots + \mathbb{E}\left(X_n\right)\\ &= \mathbb{E}\left(X_{(1)}\right) + \mathbb{E}\left(X_{(2)}\right) + \cdots + \mathbb{E}\left(X_{(n)}\right) \\ &= \frac{n}{2}\left(X_{(n)}+X_{(1)}\right), }$$ with the unique solution $$\mathbb{E}\left(X_1\mid X_{(1)}, X_{(n)}\right) = \left(X_{(n)}+X_{(1)}\right)/2.$$ It seems worth remarking that this result is not a sole consequence of the symmetry of the uniform distribution: it is particular to the uniform family of distributions. For some intuition, consider data drawn from a Beta$(a,a)$ distribution with $a \lt 1.$ This distribution's probabilities are concentrated near $0$ and $1$ (its density has a U or "bathtub" shape). When $X_{(n)}\lt 1/2,$ we can be sure most of the data are piled up close to $X_{(1)}$ and therefore will tend to have expectations less than the midpoint $(X_{(1)}+X_{(n)})/2;$ and when $X_{(1)}\gt 1/2,$ the opposite happens and most of the data are likely piled up close to $X_{(n)}.$
Conditional expectation of uniform random variable given order statistics Consider the case of an iid sample $X_1, X_2, \ldots, X_n$ from a Uniform$(0,1)$ distribution. Scaling these variables by $\theta$ and translating them by $\theta$ endows them with a Uniform$(\theta,
35,319
What are "fringeliers"?
Fringeliers appears to be defined as a less extreme kind of outlier. I.e., data on the fringes of the distribution. For example, were you to define a cutoff for outliers, fringeliers might be operationalised to be those values that are close to either side of the cutoff (e.g., for a 3 SD cutoff, between 2.7 and 3.3 SD from the mean). Osborne and Overbay (2008) write the following: Although definitions vary, an outlier is generally considered to be a data point that is far outside the norm for a variable or population (e.g., Jarrell, 1994; Rasmussen, 1988; Stevens, 1984). Hawkins (1980) described an outlier as an observation that “deviates so much from other observations as to arouse suspicions that it was generated by a different mechanism” (p. 1). Outliers have also been defined as values that are “dubious in the eyes of the researcher” (Dixon, 1950, p. 488) and contaminants (Wainer, 1976). And go on to introduce the term "fringelier" from Wainer (1976) Wainer (1976) also introduced the concept of the “fringelier,” referring to “unusual events which occur more often than seldom” (p. 286). These points lie near three standard deviations from the mean and hence may have a disproportionately strong influence on parameter estimates, yet are not as obvious or easily identified as ordinary outliers due to their relative proximity to the distribution center. Some examples: In some contexts, outliers suggest that the data is invalid. For example, if a man's height is recorded as 8 foot tall (say 6.5 SD above the mean), this is probably an invalid measurement. In contrast, if someone's height is recorded as 6 foot 10 inches tall (3 SD above the mean - a fringelier), this might be a valid measurement, but equally, it might suggest a problem with measurement as this is pretty rare. The point is that determining whether a value is invalid gets harder, the less extreme the value becomes. In other contexts, outliers are a concern because they have an excessive influence on parameter estimates, particularly when using standard statistical methods using least squares and so on. Thus, fringeliers may have greater impact than some most cases, but decisions about whether to retain the data or not for modelling purposes may be less clear. References Osborne, J. & Overbay, A. (2008). Best practices in data cleaning: how outliers and “fringeliers” can increase error rates and decrease the quality and precision of your results. In Osborne, J. Best practices in quantitative methods (pp. 205-213). Thousand Oaks, CA: SAGE Publications, Inc. doi: 10.4135/9781412995627 Wainer, H.Robust statistics: A survey and some prescriptions1(4)285-312(1976).
What are "fringeliers"?
Fringeliers appears to be defined as a less extreme kind of outlier. I.e., data on the fringes of the distribution. For example, were you to define a cutoff for outliers, fringeliers might be operatio
What are "fringeliers"? Fringeliers appears to be defined as a less extreme kind of outlier. I.e., data on the fringes of the distribution. For example, were you to define a cutoff for outliers, fringeliers might be operationalised to be those values that are close to either side of the cutoff (e.g., for a 3 SD cutoff, between 2.7 and 3.3 SD from the mean). Osborne and Overbay (2008) write the following: Although definitions vary, an outlier is generally considered to be a data point that is far outside the norm for a variable or population (e.g., Jarrell, 1994; Rasmussen, 1988; Stevens, 1984). Hawkins (1980) described an outlier as an observation that “deviates so much from other observations as to arouse suspicions that it was generated by a different mechanism” (p. 1). Outliers have also been defined as values that are “dubious in the eyes of the researcher” (Dixon, 1950, p. 488) and contaminants (Wainer, 1976). And go on to introduce the term "fringelier" from Wainer (1976) Wainer (1976) also introduced the concept of the “fringelier,” referring to “unusual events which occur more often than seldom” (p. 286). These points lie near three standard deviations from the mean and hence may have a disproportionately strong influence on parameter estimates, yet are not as obvious or easily identified as ordinary outliers due to their relative proximity to the distribution center. Some examples: In some contexts, outliers suggest that the data is invalid. For example, if a man's height is recorded as 8 foot tall (say 6.5 SD above the mean), this is probably an invalid measurement. In contrast, if someone's height is recorded as 6 foot 10 inches tall (3 SD above the mean - a fringelier), this might be a valid measurement, but equally, it might suggest a problem with measurement as this is pretty rare. The point is that determining whether a value is invalid gets harder, the less extreme the value becomes. In other contexts, outliers are a concern because they have an excessive influence on parameter estimates, particularly when using standard statistical methods using least squares and so on. Thus, fringeliers may have greater impact than some most cases, but decisions about whether to retain the data or not for modelling purposes may be less clear. References Osborne, J. & Overbay, A. (2008). Best practices in data cleaning: how outliers and “fringeliers” can increase error rates and decrease the quality and precision of your results. In Osborne, J. Best practices in quantitative methods (pp. 205-213). Thousand Oaks, CA: SAGE Publications, Inc. doi: 10.4135/9781412995627 Wainer, H.Robust statistics: A survey and some prescriptions1(4)285-312(1976).
What are "fringeliers"? Fringeliers appears to be defined as a less extreme kind of outlier. I.e., data on the fringes of the distribution. For example, were you to define a cutoff for outliers, fringeliers might be operatio
35,320
What are "fringeliers"?
I would think that you'd need to consider the frequency of the fringeliers w.r.t. the data points residing below the cutoff. If the proportion of fringeliers to "valid" data is high (based on some factor(s)), perhaps the cutoff is unrealistically defined. Imagine you're in a tent, and the only bears in the area are 3 miles away; but there are 500 of them! :)
What are "fringeliers"?
I would think that you'd need to consider the frequency of the fringeliers w.r.t. the data points residing below the cutoff. If the proportion of fringeliers to "valid" data is high (based on some f
What are "fringeliers"? I would think that you'd need to consider the frequency of the fringeliers w.r.t. the data points residing below the cutoff. If the proportion of fringeliers to "valid" data is high (based on some factor(s)), perhaps the cutoff is unrealistically defined. Imagine you're in a tent, and the only bears in the area are 3 miles away; but there are 500 of them! :)
What are "fringeliers"? I would think that you'd need to consider the frequency of the fringeliers w.r.t. the data points residing below the cutoff. If the proportion of fringeliers to "valid" data is high (based on some f
35,321
Time series analysis via generalized additive models: model assumptions and stationarity
The idea here is that by estimating the trend as a smooth function, the residuals then are a stationary process and the ARMA model is being estimated in the residuals. In other words, the estimated smoother is detrending the data and the residuals are subjected to an ARMA model. Of course it doesn't happen in a two-step process like this, but hopefully it is clearer why we don't require stationarity when modelling time series using GAM(M)s. Another issue you'll potentially need to grapple with is identifiability of the trend and the correlation structure. If we have a high degree of autocorrelation in the observed series, then we could model this as: a wiggly trend (to capture the runs above and below the mean that high autocorrelation implies) and no autocorrelation in the residuals, or a simple, perhaps linear, trend, with strong autocorrelation in the residuals (say a large $\rho$ for an AR(1) process). These two models are very similar to one another and absent any information you can give to separate the two (say by fixing the degrees of freedom of the spline or setting the parameters of the correlation structure in the residuals), then the data may not contain enough information to uniquely identify the separate trend and autocorrelation processes. The whole reason behind my use of GAMs in my research is that I'm interested in estimating the trends in my time series and those trends are in general non-linear. The GAM allows me to estimate the thing I want. In classical time series modelling, the interest is in modelling data as stochastic trends using lagged versions of the response and / or current and lagged versions of a white noise process. This is of less interest in my work, but is clearly of broad interest in others. I've written a paper on modelling time series using GAMs, which hopefully explains some of the approach. It's written for palaeoecologists but applies to any univariate time series, and Open Access so free to read and supported by full R code in the Supplements.
Time series analysis via generalized additive models: model assumptions and stationarity
The idea here is that by estimating the trend as a smooth function, the residuals then are a stationary process and the ARMA model is being estimated in the residuals. In other words, the estimated sm
Time series analysis via generalized additive models: model assumptions and stationarity The idea here is that by estimating the trend as a smooth function, the residuals then are a stationary process and the ARMA model is being estimated in the residuals. In other words, the estimated smoother is detrending the data and the residuals are subjected to an ARMA model. Of course it doesn't happen in a two-step process like this, but hopefully it is clearer why we don't require stationarity when modelling time series using GAM(M)s. Another issue you'll potentially need to grapple with is identifiability of the trend and the correlation structure. If we have a high degree of autocorrelation in the observed series, then we could model this as: a wiggly trend (to capture the runs above and below the mean that high autocorrelation implies) and no autocorrelation in the residuals, or a simple, perhaps linear, trend, with strong autocorrelation in the residuals (say a large $\rho$ for an AR(1) process). These two models are very similar to one another and absent any information you can give to separate the two (say by fixing the degrees of freedom of the spline or setting the parameters of the correlation structure in the residuals), then the data may not contain enough information to uniquely identify the separate trend and autocorrelation processes. The whole reason behind my use of GAMs in my research is that I'm interested in estimating the trends in my time series and those trends are in general non-linear. The GAM allows me to estimate the thing I want. In classical time series modelling, the interest is in modelling data as stochastic trends using lagged versions of the response and / or current and lagged versions of a white noise process. This is of less interest in my work, but is clearly of broad interest in others. I've written a paper on modelling time series using GAMs, which hopefully explains some of the approach. It's written for palaeoecologists but applies to any univariate time series, and Open Access so free to read and supported by full R code in the Supplements.
Time series analysis via generalized additive models: model assumptions and stationarity The idea here is that by estimating the trend as a smooth function, the residuals then are a stationary process and the ARMA model is being estimated in the residuals. In other words, the estimated sm
35,322
Interpreting a Quadratic Term in Binary Logistic Regression
So your model is something like $$ \log(\frac{p}{1-p}) = -0.000462 x^2 + 0.0265 x + c $$ implying that $$ \frac{p}{1-p} = e^{-0.000462 x^2}e^{0.0265 x} e^c $$ You can interpret $ e^c $ as the "baseline odds". Then, note that the positive and negative effects are zero when $ x = \frac{0.0265}{0.000462} \approx 57.36 $. This is the point where odds begin to decrease; thus, you can say for values of $ x \in (-\infty, 57.36) $ the odds are increasing as $ x $ increases, but afterwards odds decrease as $ x $ decreases. You could go further and see where the maximum odds are attained, and maybe if you take the derivative of this function you can see the rate of odds increase/decrease at each point, but it gets pretty contrived and case-specific.
Interpreting a Quadratic Term in Binary Logistic Regression
So your model is something like $$ \log(\frac{p}{1-p}) = -0.000462 x^2 + 0.0265 x + c $$ implying that $$ \frac{p}{1-p} = e^{-0.000462 x^2}e^{0.0265 x} e^c $$ You can interpret $ e^c $ as the "baselin
Interpreting a Quadratic Term in Binary Logistic Regression So your model is something like $$ \log(\frac{p}{1-p}) = -0.000462 x^2 + 0.0265 x + c $$ implying that $$ \frac{p}{1-p} = e^{-0.000462 x^2}e^{0.0265 x} e^c $$ You can interpret $ e^c $ as the "baseline odds". Then, note that the positive and negative effects are zero when $ x = \frac{0.0265}{0.000462} \approx 57.36 $. This is the point where odds begin to decrease; thus, you can say for values of $ x \in (-\infty, 57.36) $ the odds are increasing as $ x $ increases, but afterwards odds decrease as $ x $ decreases. You could go further and see where the maximum odds are attained, and maybe if you take the derivative of this function you can see the rate of odds increase/decrease at each point, but it gets pretty contrived and case-specific.
Interpreting a Quadratic Term in Binary Logistic Regression So your model is something like $$ \log(\frac{p}{1-p}) = -0.000462 x^2 + 0.0265 x + c $$ implying that $$ \frac{p}{1-p} = e^{-0.000462 x^2}e^{0.0265 x} e^c $$ You can interpret $ e^c $ as the "baselin
35,323
Interpreting a Quadratic Term in Binary Logistic Regression
Just a small edit to Kevin's answer: I think there's a small typo as the derivative of the expression $\frac{p}{1-p}$ written above reaches a stationary point at $x=\frac{0.0265}{2 * 0.000462}$. So $57.36$ should be divided by 2.
Interpreting a Quadratic Term in Binary Logistic Regression
Just a small edit to Kevin's answer: I think there's a small typo as the derivative of the expression $\frac{p}{1-p}$ written above reaches a stationary point at $x=\frac{0.0265}{2 * 0.000462}$. So $5
Interpreting a Quadratic Term in Binary Logistic Regression Just a small edit to Kevin's answer: I think there's a small typo as the derivative of the expression $\frac{p}{1-p}$ written above reaches a stationary point at $x=\frac{0.0265}{2 * 0.000462}$. So $57.36$ should be divided by 2.
Interpreting a Quadratic Term in Binary Logistic Regression Just a small edit to Kevin's answer: I think there's a small typo as the derivative of the expression $\frac{p}{1-p}$ written above reaches a stationary point at $x=\frac{0.0265}{2 * 0.000462}$. So $5
35,324
Evaluating quality of predicted distributions
The standard approach to this is using the log-likelihood of the exponential distribution. This is actually exactly how the cross-entropy is derived, it is the log-likelihood of the Bernoulli distribution. In the case of an exponential distribution, the pdf is: $$ f(y; \lambda) = \lambda e^{-\lambda y} $$ So the log-likelihood is: $$ LL(\lambda_i; y_i ) = \log(f(y_i; \lambda_i)) = \log(\lambda_i) - \lambda_i y_i$$ So, if $y_i$ are your true values, and $\lambda_i$ are your predictions, an exponential model would minimize: $$ LL(\{\lambda_i\}; \{y_i\}) = \sum_i \log(\lambda_i) -\lambda_i y_i$$ Fitting models by maximizing the log-likelihood in this way leads to the the theory of generalized linear models; the exponential model is a special case.
Evaluating quality of predicted distributions
The standard approach to this is using the log-likelihood of the exponential distribution. This is actually exactly how the cross-entropy is derived, it is the log-likelihood of the Bernoulli distrib
Evaluating quality of predicted distributions The standard approach to this is using the log-likelihood of the exponential distribution. This is actually exactly how the cross-entropy is derived, it is the log-likelihood of the Bernoulli distribution. In the case of an exponential distribution, the pdf is: $$ f(y; \lambda) = \lambda e^{-\lambda y} $$ So the log-likelihood is: $$ LL(\lambda_i; y_i ) = \log(f(y_i; \lambda_i)) = \log(\lambda_i) - \lambda_i y_i$$ So, if $y_i$ are your true values, and $\lambda_i$ are your predictions, an exponential model would minimize: $$ LL(\{\lambda_i\}; \{y_i\}) = \sum_i \log(\lambda_i) -\lambda_i y_i$$ Fitting models by maximizing the log-likelihood in this way leads to the the theory of generalized linear models; the exponential model is a special case.
Evaluating quality of predicted distributions The standard approach to this is using the log-likelihood of the exponential distribution. This is actually exactly how the cross-entropy is derived, it is the log-likelihood of the Bernoulli distrib
35,325
Evaluating quality of predicted distributions
The standard way to assess predictive distributions is via scoring rules. The log-likelihood that Matthew Drury recommends is one example, it's the logarithmic scoring rule. There are also others. Merkle & Steyvers (2013, Decision Analysis) discuss how different scoring rules hang together, and how to choose one. More information can be found in the tag wiki, and we have a number of questions carrying the scoring-rules tag.
Evaluating quality of predicted distributions
The standard way to assess predictive distributions is via scoring rules. The log-likelihood that Matthew Drury recommends is one example, it's the logarithmic scoring rule. There are also others. Mer
Evaluating quality of predicted distributions The standard way to assess predictive distributions is via scoring rules. The log-likelihood that Matthew Drury recommends is one example, it's the logarithmic scoring rule. There are also others. Merkle & Steyvers (2013, Decision Analysis) discuss how different scoring rules hang together, and how to choose one. More information can be found in the tag wiki, and we have a number of questions carrying the scoring-rules tag.
Evaluating quality of predicted distributions The standard way to assess predictive distributions is via scoring rules. The log-likelihood that Matthew Drury recommends is one example, it's the logarithmic scoring rule. There are also others. Mer
35,326
Normal distribution $var(X^2+Y^2)$
Since you are dealing with IID normal data, it is worth generalising your problem slightly to look at the case where you have $X_1, ..., X_n \sim \text{IID N}(a, b^2)$ and you want $Q_n \equiv \mathbb{V}(\sum_{i=1}^n X_i^2)$. (Your question corresponds to the case where $n=2$.) As other users have pointed out, the sum of squares of IID normal random variables is a scaled non-central chi-squared random variable, and so the variance of interest can be obtained from knowledge of that distribution. However, it is also possible to obtain the required variance using ordinary moment rules, combined with knowledge of the moments of the normal distribution. I will show you how to do this below, in steps. Finding the variance using moments of the normal distribution: Since the values $X_1, ..., X_n$ are IID (and taking $X$ to be a generic value from this distribution) you have:$$\begin{equation} \begin{aligned}Q_n \equiv \mathbb{V}\Big( \sum_{i=1}^n X_i^2 \Big) &= \sum_{i=1}^n \mathbb{V}(X_i^2) \\[6pt]&= n\mathbb{V}(X^2) \\[6pt]&= n(\mathbb{E}(X^4) - \mathbb{E}(X^2)^2) \\[6pt]&= n(\mu_4' - \mu_2'^2), \\[6pt]\end{aligned} \end{equation}$$ where we are denoting the raw moments as $\mu_k' \equiv \mathbb{E}(X^k)$. These raw moments can be written in terms of the central moments $\mu_k \equiv \mathbb{E}((X-\mathbb{E}(X))^k)$ and the mean $\mu_1' = \mathbb{E}(X)$ using standard conversion formulae, and we can then look up the central moments of the normal distribution and substitute them in. Using the moment conversion formulae you should get:$$\begin{equation} \begin{aligned}\mu_2' &= \mu_2 + \mu_1'^2, \\[6pt]\mu_3' &= \mu_3 + 3 \mu_1' \mu_2 + \mu_1'^3, \\[6pt]\mu_4' &= \mu_4 + 4 \mu_1' \mu_3 + 6 \mu_1'^2 \mu_2 + \mu_1'^4. \\[6pt]\end{aligned} \end{equation}$$For the distribution $X \sim \text{N}(a,b^2)$ we have mean $\mu_1' = a$ and higher-order central moments $\mu_2 = b^2$, $\mu_3 = 0$ and $\mu_4 = 3 b^4$. This gives us the raw moments:$$\begin{equation} \begin{aligned}\mu_2' &= b^2 + a^2, \\[6pt]\mu_3' &= 3 a b^2 + a^3, \\[6pt]\mu_4' &= 3 b^4 + 6 a^2 b^2 + a^4. \\[6pt]\end{aligned} \end{equation}$$ Now, try substituting these back into the original expression to find the variance of interest. Substituting back into the first expression gives:$$\begin{equation} \begin{aligned}Q_n &= n(\mu_4' - \mu_2'^2) \\[6pt]&= n[(3 b^4 + 6 a^2 b^2 + a^4) - (b^2 + a^2)^2] \\[6pt]&= n[(3 b^4 + 6 a^2 b^2 + a^4) - (b^4 + 2 a^2 b^2 + a^4)] \\[6pt]&= n[2 b^4 + 4 a^2 b^2] \\[6pt]&= 2nb^2 (b^2 + 2a^2). \\[6pt]\end{aligned} \end{equation}$$For the special case where $n=2$ you have $Q_2 = 4b^2 (b^2 + 2a^2)$. It can be shown that this result accords with the solution you would get if you used the alternative method of deriving your result from the scaled non-central chi-squared distribution. Alternative working based on use of the non-central chi-squared distribution: Since $X_i / b \sim \text{N}(a/b, 1)$ we have:$$\sum_{i=1}^n \Big(\frac{X_i}{b} \Big)^2 \sim \text{Non-central Chi-Sq}\Big( k=n, \lambda= \frac{n a^2}{b^2} \Big).$$Using the known variance of this distribution we have:$$\begin{equation} \begin{aligned}Q_n \equiv \mathbb{V}\Big( \sum_{i=1}^n X_i^2 \Big) &= b^4 \cdot \mathbb{V}\Big( \sum_{i=1}^n \Big(\frac{X_i}{b} \Big)^2 \Big) \\[6pt]&= b^4 \cdot 2(k+2 \lambda) \\[6pt]&= 2 b^4 \Big( n + 2 \frac{na^2}{b^2} \Big) \\[6pt]&= 2 n b^2 (b^2 + 2a^2). \\[6pt]\end{aligned} \end{equation}$$ This result matches with the result above.
Normal distribution $var(X^2+Y^2)$
Since you are dealing with IID normal data, it is worth generalising your problem slightly to look at the case where you have $X_1, ..., X_n \sim \text{IID N}(a, b^2)$ and you want $Q_n \equiv \mathbb
Normal distribution $var(X^2+Y^2)$ Since you are dealing with IID normal data, it is worth generalising your problem slightly to look at the case where you have $X_1, ..., X_n \sim \text{IID N}(a, b^2)$ and you want $Q_n \equiv \mathbb{V}(\sum_{i=1}^n X_i^2)$. (Your question corresponds to the case where $n=2$.) As other users have pointed out, the sum of squares of IID normal random variables is a scaled non-central chi-squared random variable, and so the variance of interest can be obtained from knowledge of that distribution. However, it is also possible to obtain the required variance using ordinary moment rules, combined with knowledge of the moments of the normal distribution. I will show you how to do this below, in steps. Finding the variance using moments of the normal distribution: Since the values $X_1, ..., X_n$ are IID (and taking $X$ to be a generic value from this distribution) you have:$$\begin{equation} \begin{aligned}Q_n \equiv \mathbb{V}\Big( \sum_{i=1}^n X_i^2 \Big) &= \sum_{i=1}^n \mathbb{V}(X_i^2) \\[6pt]&= n\mathbb{V}(X^2) \\[6pt]&= n(\mathbb{E}(X^4) - \mathbb{E}(X^2)^2) \\[6pt]&= n(\mu_4' - \mu_2'^2), \\[6pt]\end{aligned} \end{equation}$$ where we are denoting the raw moments as $\mu_k' \equiv \mathbb{E}(X^k)$. These raw moments can be written in terms of the central moments $\mu_k \equiv \mathbb{E}((X-\mathbb{E}(X))^k)$ and the mean $\mu_1' = \mathbb{E}(X)$ using standard conversion formulae, and we can then look up the central moments of the normal distribution and substitute them in. Using the moment conversion formulae you should get:$$\begin{equation} \begin{aligned}\mu_2' &= \mu_2 + \mu_1'^2, \\[6pt]\mu_3' &= \mu_3 + 3 \mu_1' \mu_2 + \mu_1'^3, \\[6pt]\mu_4' &= \mu_4 + 4 \mu_1' \mu_3 + 6 \mu_1'^2 \mu_2 + \mu_1'^4. \\[6pt]\end{aligned} \end{equation}$$For the distribution $X \sim \text{N}(a,b^2)$ we have mean $\mu_1' = a$ and higher-order central moments $\mu_2 = b^2$, $\mu_3 = 0$ and $\mu_4 = 3 b^4$. This gives us the raw moments:$$\begin{equation} \begin{aligned}\mu_2' &= b^2 + a^2, \\[6pt]\mu_3' &= 3 a b^2 + a^3, \\[6pt]\mu_4' &= 3 b^4 + 6 a^2 b^2 + a^4. \\[6pt]\end{aligned} \end{equation}$$ Now, try substituting these back into the original expression to find the variance of interest. Substituting back into the first expression gives:$$\begin{equation} \begin{aligned}Q_n &= n(\mu_4' - \mu_2'^2) \\[6pt]&= n[(3 b^4 + 6 a^2 b^2 + a^4) - (b^2 + a^2)^2] \\[6pt]&= n[(3 b^4 + 6 a^2 b^2 + a^4) - (b^4 + 2 a^2 b^2 + a^4)] \\[6pt]&= n[2 b^4 + 4 a^2 b^2] \\[6pt]&= 2nb^2 (b^2 + 2a^2). \\[6pt]\end{aligned} \end{equation}$$For the special case where $n=2$ you have $Q_2 = 4b^2 (b^2 + 2a^2)$. It can be shown that this result accords with the solution you would get if you used the alternative method of deriving your result from the scaled non-central chi-squared distribution. Alternative working based on use of the non-central chi-squared distribution: Since $X_i / b \sim \text{N}(a/b, 1)$ we have:$$\sum_{i=1}^n \Big(\frac{X_i}{b} \Big)^2 \sim \text{Non-central Chi-Sq}\Big( k=n, \lambda= \frac{n a^2}{b^2} \Big).$$Using the known variance of this distribution we have:$$\begin{equation} \begin{aligned}Q_n \equiv \mathbb{V}\Big( \sum_{i=1}^n X_i^2 \Big) &= b^4 \cdot \mathbb{V}\Big( \sum_{i=1}^n \Big(\frac{X_i}{b} \Big)^2 \Big) \\[6pt]&= b^4 \cdot 2(k+2 \lambda) \\[6pt]&= 2 b^4 \Big( n + 2 \frac{na^2}{b^2} \Big) \\[6pt]&= 2 n b^2 (b^2 + 2a^2). \\[6pt]\end{aligned} \end{equation}$$ This result matches with the result above.
Normal distribution $var(X^2+Y^2)$ Since you are dealing with IID normal data, it is worth generalising your problem slightly to look at the case where you have $X_1, ..., X_n \sim \text{IID N}(a, b^2)$ and you want $Q_n \equiv \mathbb
35,327
Normal distribution $var(X^2+Y^2)$
If $X$ and $Y$ are $\text{N} (a, b^2)$ independent random variables, then $\left( \frac{X - a}{b} \right)^2 + \left( \frac{Y - a}{b} \right)^2$ is a $\chi ^2(2)$ random variable. Do you think you can take it from there?
Normal distribution $var(X^2+Y^2)$
If $X$ and $Y$ are $\text{N} (a, b^2)$ independent random variables, then $\left( \frac{X - a}{b} \right)^2 + \left( \frac{Y - a}{b} \right)^2$ is a $\chi ^2(2)$ random variable. Do you think you can
Normal distribution $var(X^2+Y^2)$ If $X$ and $Y$ are $\text{N} (a, b^2)$ independent random variables, then $\left( \frac{X - a}{b} \right)^2 + \left( \frac{Y - a}{b} \right)^2$ is a $\chi ^2(2)$ random variable. Do you think you can take it from there?
Normal distribution $var(X^2+Y^2)$ If $X$ and $Y$ are $\text{N} (a, b^2)$ independent random variables, then $\left( \frac{X - a}{b} \right)^2 + \left( \frac{Y - a}{b} \right)^2$ is a $\chi ^2(2)$ random variable. Do you think you can
35,328
Normal distribution $var(X^2+Y^2)$
The answer is in the non-central Chi-squared distribution. For example, if b=1, the answer to your question is: $2(k + 2(a^2))$, where $k=2$ is the number of components ($X$ and $Y$).
Normal distribution $var(X^2+Y^2)$
The answer is in the non-central Chi-squared distribution. For example, if b=1, the answer to your question is: $2(k + 2(a^2))$, where $k=2$ is the number of components ($X$ and $Y$).
Normal distribution $var(X^2+Y^2)$ The answer is in the non-central Chi-squared distribution. For example, if b=1, the answer to your question is: $2(k + 2(a^2))$, where $k=2$ is the number of components ($X$ and $Y$).
Normal distribution $var(X^2+Y^2)$ The answer is in the non-central Chi-squared distribution. For example, if b=1, the answer to your question is: $2(k + 2(a^2))$, where $k=2$ is the number of components ($X$ and $Y$).
35,329
The graphical intuiton of the LASSO in case p=2 [duplicate]
Recall that the Lasso minimization problem can be viewed as the minimization of two terms: $OLS + L_1$. To answer your question: The intersection depends on the "graphical position" of the OLS solution. But I can't explain to myself how the dependence works. The solution to the constrained optimization lies at the intersection between the contours of the two functions, and this intersection varies as a function of $\lambda$. For $\lambda = 0$ the solution is the MLE (as usual) and for $\lambda = \infty$ the solution is at $[0,0]$. Since at the vertices of the diamond, one or many of the variables have value 0, there is a non zero probability that one or many of the coefficients will have a value exactly equal to 0. As you can see from your picture, there must be some values of $\lambda$ for which the solution does not take place at the vertex of the diamond. The solution cannot simply jump from the OLS minimum (when $\lambda = 0$) to a vertex of the diamond. This is a misunderstanding many people have. The lasso doesn't magically set coefficients to zero ! It optimizes the lasso cost function, and the particular structure of this optimization problem makes it likely that the solution lies at the vertex of the diamond. Can some of you give me some graphical intuition in the case of p=2, when the LASSO will not set coefficients to zero? The answer is every time the optimal solutions is not at a vertex of the diamond. Now to answer the question you have not asked. What makes it more likely for the lasso coefficient to not be zero One obvious factor is when features are correlated - or if there is strong multi-correlation in your data set. Visually this will have the effect of "flattening" the OLS cost function in one direction (in 2d) and thus will strongly influence the path of the lasso solution by forcing it to take a less "direct" path towards one of the vertex. See this picture for a case where the two features are very correlated. If there were less correlation, the OLS contour plot would look more circular and the lasso solution may converge faster to a vertex. But again this depends on the particular shape of the OLS cost function for your given data set. In this case the OLS solution has a valley that is at an angle w.r.t the $0,0$ point. This where the notion of graphical position comes from Sources This post is strongly based on my previous post - For anyone interested, you can find most of the code and associated mathematical derivations on my blog and at this page
The graphical intuiton of the LASSO in case p=2 [duplicate]
Recall that the Lasso minimization problem can be viewed as the minimization of two terms: $OLS + L_1$. To answer your question: The intersection depends on the "graphical position" of the OLS solu
The graphical intuiton of the LASSO in case p=2 [duplicate] Recall that the Lasso minimization problem can be viewed as the minimization of two terms: $OLS + L_1$. To answer your question: The intersection depends on the "graphical position" of the OLS solution. But I can't explain to myself how the dependence works. The solution to the constrained optimization lies at the intersection between the contours of the two functions, and this intersection varies as a function of $\lambda$. For $\lambda = 0$ the solution is the MLE (as usual) and for $\lambda = \infty$ the solution is at $[0,0]$. Since at the vertices of the diamond, one or many of the variables have value 0, there is a non zero probability that one or many of the coefficients will have a value exactly equal to 0. As you can see from your picture, there must be some values of $\lambda$ for which the solution does not take place at the vertex of the diamond. The solution cannot simply jump from the OLS minimum (when $\lambda = 0$) to a vertex of the diamond. This is a misunderstanding many people have. The lasso doesn't magically set coefficients to zero ! It optimizes the lasso cost function, and the particular structure of this optimization problem makes it likely that the solution lies at the vertex of the diamond. Can some of you give me some graphical intuition in the case of p=2, when the LASSO will not set coefficients to zero? The answer is every time the optimal solutions is not at a vertex of the diamond. Now to answer the question you have not asked. What makes it more likely for the lasso coefficient to not be zero One obvious factor is when features are correlated - or if there is strong multi-correlation in your data set. Visually this will have the effect of "flattening" the OLS cost function in one direction (in 2d) and thus will strongly influence the path of the lasso solution by forcing it to take a less "direct" path towards one of the vertex. See this picture for a case where the two features are very correlated. If there were less correlation, the OLS contour plot would look more circular and the lasso solution may converge faster to a vertex. But again this depends on the particular shape of the OLS cost function for your given data set. In this case the OLS solution has a valley that is at an angle w.r.t the $0,0$ point. This where the notion of graphical position comes from Sources This post is strongly based on my previous post - For anyone interested, you can find most of the code and associated mathematical derivations on my blog and at this page
The graphical intuiton of the LASSO in case p=2 [duplicate] Recall that the Lasso minimization problem can be viewed as the minimization of two terms: $OLS + L_1$. To answer your question: The intersection depends on the "graphical position" of the OLS solu
35,330
The graphical intuiton of the LASSO in case p=2 [duplicate]
The ellipses are the equi-value contours of the loss, and the blue shapes are the regions of the penalty. By duality, the optimum occurs when a contour line intersects with a boundary of a blue shape. The case you've shown is indeed one that foils Lasso sparsity - the axis of the ellipses is perpendicular to the surface of the diamond. This is possible, but not very likely. In higher dimensions, it is even less likely. For the 2D case it is easy to see that when the axis is not perpendicular to the surface of the diamond, the intersection will be either on the x or y axis.
The graphical intuiton of the LASSO in case p=2 [duplicate]
The ellipses are the equi-value contours of the loss, and the blue shapes are the regions of the penalty. By duality, the optimum occurs when a contour line intersects with a boundary of a blue shape.
The graphical intuiton of the LASSO in case p=2 [duplicate] The ellipses are the equi-value contours of the loss, and the blue shapes are the regions of the penalty. By duality, the optimum occurs when a contour line intersects with a boundary of a blue shape. The case you've shown is indeed one that foils Lasso sparsity - the axis of the ellipses is perpendicular to the surface of the diamond. This is possible, but not very likely. In higher dimensions, it is even less likely. For the 2D case it is easy to see that when the axis is not perpendicular to the surface of the diamond, the intersection will be either on the x or y axis.
The graphical intuiton of the LASSO in case p=2 [duplicate] The ellipses are the equi-value contours of the loss, and the blue shapes are the regions of the penalty. By duality, the optimum occurs when a contour line intersects with a boundary of a blue shape.
35,331
Expected value of maximum of samples from normal distribution
If we combine two of the answers here (Approximate order statistics for normal random variables), we have for the $r$th $\it{smallest}$ order statistic $$E[r,n] \approx \mu + \sigma \ \Phi^{-1} \left( \frac{r-\frac{\pi}{8}}{n-\frac{\pi}{4}+1}\right) $$ For the largest value we want $r=n,$ so we have $$E[Y] \approx \mu + \sigma \ \Phi^{-1} \left( \frac{n-\frac{\pi}{8}}{n-\frac{\pi}{4}+1}\right) $$
Expected value of maximum of samples from normal distribution
If we combine two of the answers here (Approximate order statistics for normal random variables), we have for the $r$th $\it{smallest}$ order statistic $$E[r,n] \approx \mu + \sigma \ \Phi^{-1} \left(
Expected value of maximum of samples from normal distribution If we combine two of the answers here (Approximate order statistics for normal random variables), we have for the $r$th $\it{smallest}$ order statistic $$E[r,n] \approx \mu + \sigma \ \Phi^{-1} \left( \frac{r-\frac{\pi}{8}}{n-\frac{\pi}{4}+1}\right) $$ For the largest value we want $r=n,$ so we have $$E[Y] \approx \mu + \sigma \ \Phi^{-1} \left( \frac{n-\frac{\pi}{8}}{n-\frac{\pi}{4}+1}\right) $$
Expected value of maximum of samples from normal distribution If we combine two of the answers here (Approximate order statistics for normal random variables), we have for the $r$th $\it{smallest}$ order statistic $$E[r,n] \approx \mu + \sigma \ \Phi^{-1} \left(
35,332
Expected value of maximum of samples from normal distribution
First note that\begin{align}Y_n=\max\{X_1,\ldots,X_n\}&=\max\{\sigma\epsilon_1+\mu,\ldots,\sigma\epsilon_n+\mu\}\\&=\sigma\max\{\epsilon_1,\ldots,\epsilon_n\}+\mu\\&=\sigma\xi_n+\mu\end{align} hence that $(\mu,\sigma)$ is also a location-scale parameter for the maximum. Asymptotically, the Normal distribution belongs to the domain of attraction of the Gumbel distribution, meaning that $$\sqrt{2\log(n)}(\xi_n-d_n)\stackrel{{\cal L}}{\longrightarrow} G_0$$with $G_0(x)=\exp\{-\exp(-x)\}$ the Gumbel pdf and $$d_n = \sqrt{2\log(n)}-\dfrac{\log\log n + \log(4\pi)}{2\sqrt{2\log(n)}}$$
Expected value of maximum of samples from normal distribution
First note that\begin{align}Y_n=\max\{X_1,\ldots,X_n\}&=\max\{\sigma\epsilon_1+\mu,\ldots,\sigma\epsilon_n+\mu\}\\&=\sigma\max\{\epsilon_1,\ldots,\epsilon_n\}+\mu\\&=\sigma\xi_n+\mu\end{align} hence t
Expected value of maximum of samples from normal distribution First note that\begin{align}Y_n=\max\{X_1,\ldots,X_n\}&=\max\{\sigma\epsilon_1+\mu,\ldots,\sigma\epsilon_n+\mu\}\\&=\sigma\max\{\epsilon_1,\ldots,\epsilon_n\}+\mu\\&=\sigma\xi_n+\mu\end{align} hence that $(\mu,\sigma)$ is also a location-scale parameter for the maximum. Asymptotically, the Normal distribution belongs to the domain of attraction of the Gumbel distribution, meaning that $$\sqrt{2\log(n)}(\xi_n-d_n)\stackrel{{\cal L}}{\longrightarrow} G_0$$with $G_0(x)=\exp\{-\exp(-x)\}$ the Gumbel pdf and $$d_n = \sqrt{2\log(n)}-\dfrac{\log\log n + \log(4\pi)}{2\sqrt{2\log(n)}}$$
Expected value of maximum of samples from normal distribution First note that\begin{align}Y_n=\max\{X_1,\ldots,X_n\}&=\max\{\sigma\epsilon_1+\mu,\ldots,\sigma\epsilon_n+\mu\}\\&=\sigma\max\{\epsilon_1,\ldots,\epsilon_n\}+\mu\\&=\sigma\xi_n+\mu\end{align} hence t
35,333
Expected value of maximum of samples from normal distribution
EDIT: I found this paper referenced in a thread on the maths stack exchange (Approximate order statistics for normal random variables), so I had a look. For the maximum, $r=n$. "In a sample of size n the expected value of the rth largest order statistic is given by $$E(r,n)=\frac{n!}{(r-1)!(n-r)!}\int_{-\infty}^{\infty}x\{1-\Phi(x)\}^{r-1}\{\Phi(x)\}^{n-r}\phi(x)dx,$$ where $\phi(x)=1/\sqrt(2\pi)exp(-\frac{1}{2}x^2)$ and $\Phi(x)=\int^x_{-\infty}\phi(z)dz.$" Royston, J. P. (1982), 'Algorithm AS 177: Expected Normal Order Statistics (Exact and Approximate)', Journal of the Royal Statistical Society. Series C (Applied Statistics), 31(2):161-165. So $Y$ is an order statistic. Let's label its density function $g_{(n)}(x)$, to indicate that it's the pdf of the variable in the nth position (i.e. its the pdf of the maximum in the sample). Let's also label the normal $N(\mu, \sigma^2)$ density function as $f(x)$. It's a standard result that $$g_{(n)}(x)=n[F(x)]^{n-1}f(x),$$ where $F(x)$ is the cumulative density function of $N(\mu, \sigma^2)$ (as a reference, I suggest Mathematical Statistics (7th ed.) by Wackerly, Mendenhall, and Scheaffer, p.333). It is at this point that I'm unable to proceed - I don't know how to evaluate the expected value of $Y$, given that it has such a strange pdf. However, I'd advise you to search for "expected value of order statistic" - in particular, I found a thread on this topic on the maths stack exchange site: EDIT: As pointed out by Khol, thread is for a uniform distribution, not a normal distribution. The uniform is apparently more straightforward to deal with. Apologies for the partial answer! https://math.stackexchange.com/questions/751229/order-statistics-finding-the-expectation-and-variance-of-the-maximum?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
Expected value of maximum of samples from normal distribution
EDIT: I found this paper referenced in a thread on the maths stack exchange (Approximate order statistics for normal random variables), so I had a look. For the maximum, $r=n$. "In a sample of size n
Expected value of maximum of samples from normal distribution EDIT: I found this paper referenced in a thread on the maths stack exchange (Approximate order statistics for normal random variables), so I had a look. For the maximum, $r=n$. "In a sample of size n the expected value of the rth largest order statistic is given by $$E(r,n)=\frac{n!}{(r-1)!(n-r)!}\int_{-\infty}^{\infty}x\{1-\Phi(x)\}^{r-1}\{\Phi(x)\}^{n-r}\phi(x)dx,$$ where $\phi(x)=1/\sqrt(2\pi)exp(-\frac{1}{2}x^2)$ and $\Phi(x)=\int^x_{-\infty}\phi(z)dz.$" Royston, J. P. (1982), 'Algorithm AS 177: Expected Normal Order Statistics (Exact and Approximate)', Journal of the Royal Statistical Society. Series C (Applied Statistics), 31(2):161-165. So $Y$ is an order statistic. Let's label its density function $g_{(n)}(x)$, to indicate that it's the pdf of the variable in the nth position (i.e. its the pdf of the maximum in the sample). Let's also label the normal $N(\mu, \sigma^2)$ density function as $f(x)$. It's a standard result that $$g_{(n)}(x)=n[F(x)]^{n-1}f(x),$$ where $F(x)$ is the cumulative density function of $N(\mu, \sigma^2)$ (as a reference, I suggest Mathematical Statistics (7th ed.) by Wackerly, Mendenhall, and Scheaffer, p.333). It is at this point that I'm unable to proceed - I don't know how to evaluate the expected value of $Y$, given that it has such a strange pdf. However, I'd advise you to search for "expected value of order statistic" - in particular, I found a thread on this topic on the maths stack exchange site: EDIT: As pointed out by Khol, thread is for a uniform distribution, not a normal distribution. The uniform is apparently more straightforward to deal with. Apologies for the partial answer! https://math.stackexchange.com/questions/751229/order-statistics-finding-the-expectation-and-variance-of-the-maximum?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
Expected value of maximum of samples from normal distribution EDIT: I found this paper referenced in a thread on the maths stack exchange (Approximate order statistics for normal random variables), so I had a look. For the maximum, $r=n$. "In a sample of size n
35,334
Gradient of the expectation of a function w.r.t. distribution parameters
Without knowing anything in partuclar about auto-encoders: (1) $E_{q(z|\phi)}[f(Z)]$ this notation is not really 'standard' but usually means the expression $$ E_{q(z|\phi)}[f(Z)] = \int_Z f(z) q(z|\phi) dz $$ I.e. it is a quirky way of writing the (factorization) of the conditional expectation $E[f(Z)|\Phi=\phi]$ where the common distribution $f_{Z|\Phi}(z|\phi)$ is given by $q(z|\phi)$. Now we want to proceed like this: $$\partial_\phi E_{q(z|\phi)}[f(Z)] = \partial_\phi \int_Z f(z) q(z|\phi) dz = \int_Z f(z) \partial_\phi q(z|\phi) dz$$ It is mathematically not clear ad hoc that you may do this (and there are examples where this in general, i.e. $\partial_\phi \int f(x,\phi) dx = \int \partial_\phi f(x,\phi) dx$ is false!). The reason is that one needs to verify some assumptions that allows us to interchange two limits (differentiation and integration) but in probability theory these assumptions are usually met or assumed in turn. The assumption more precisely is that we can bound the functions $$ \frac{f(z) q(z|\phi + \delta) - f(z) q(z|\phi)}{\delta}$$ uniformly in all $z$ and $\delta$ ($\delta$ being close to $0$) by a single function that is still integrable (then we can use the Lebesgue dominated convergence theorem in order to interchange the limits). In your case it will (probably) work like this: Use the mean value theorem to write $$\frac{f(z) q(z|\phi + \delta) - f(z) q(z|\phi)}{\delta} = f(z) \partial_\phi q(x|\phi + \theta)$$ for some $\theta$ in the interval $[-\delta, \delta]$. Then find an integrable bound function for this derivative. In short: (1): Yes, this seems to me as if it is one of these examples where you need to pull the differentiation into the integral. My question is why the rewrite in equation (1) is even needed. Let us assume that you directly approximite the lhs. Who tells you that this approximation is any good?? We have results of the form ''We can approximize the expected value $E[W]$ of a random value $W$ by $\frac{1}{L} \sum_{i=1}^L w_i \cdot f_W(w_i)$ this and that good if we have a sufficient amount of samples $w_1, ..., w_L$.'' So we could use these results on $\partial_\phi E_{q(z|\phi)}[f(Z)]$ but only if we know that this weird expression (the derivative of a random variable that somehow depends on a second parameter in this parameter) is an expected value of a random variable again and by pulling the derivative into the integral you do precisely that: Realize that this is the normal expectation of a random variable again, namely $E[f(Z)\cdot \partial_{q(z|\phi} \log q(z|\phi)]$. In short: you need to rewrite (1) to (2) in order to see that the approximation is any good. On your (3): Even in all the usual well known theorems (like the central limit theorem, the proof that the mean is a consistent estimator, etc) you need to divide the sum by the number of samples, otherwise the sum does not have a chance to converge but just vanishes towards infinity.
Gradient of the expectation of a function w.r.t. distribution parameters
Without knowing anything in partuclar about auto-encoders: (1) $E_{q(z|\phi)}[f(Z)]$ this notation is not really 'standard' but usually means the expression $$ E_{q(z|\phi)}[f(Z)] = \int_Z f(z) q(z|\
Gradient of the expectation of a function w.r.t. distribution parameters Without knowing anything in partuclar about auto-encoders: (1) $E_{q(z|\phi)}[f(Z)]$ this notation is not really 'standard' but usually means the expression $$ E_{q(z|\phi)}[f(Z)] = \int_Z f(z) q(z|\phi) dz $$ I.e. it is a quirky way of writing the (factorization) of the conditional expectation $E[f(Z)|\Phi=\phi]$ where the common distribution $f_{Z|\Phi}(z|\phi)$ is given by $q(z|\phi)$. Now we want to proceed like this: $$\partial_\phi E_{q(z|\phi)}[f(Z)] = \partial_\phi \int_Z f(z) q(z|\phi) dz = \int_Z f(z) \partial_\phi q(z|\phi) dz$$ It is mathematically not clear ad hoc that you may do this (and there are examples where this in general, i.e. $\partial_\phi \int f(x,\phi) dx = \int \partial_\phi f(x,\phi) dx$ is false!). The reason is that one needs to verify some assumptions that allows us to interchange two limits (differentiation and integration) but in probability theory these assumptions are usually met or assumed in turn. The assumption more precisely is that we can bound the functions $$ \frac{f(z) q(z|\phi + \delta) - f(z) q(z|\phi)}{\delta}$$ uniformly in all $z$ and $\delta$ ($\delta$ being close to $0$) by a single function that is still integrable (then we can use the Lebesgue dominated convergence theorem in order to interchange the limits). In your case it will (probably) work like this: Use the mean value theorem to write $$\frac{f(z) q(z|\phi + \delta) - f(z) q(z|\phi)}{\delta} = f(z) \partial_\phi q(x|\phi + \theta)$$ for some $\theta$ in the interval $[-\delta, \delta]$. Then find an integrable bound function for this derivative. In short: (1): Yes, this seems to me as if it is one of these examples where you need to pull the differentiation into the integral. My question is why the rewrite in equation (1) is even needed. Let us assume that you directly approximite the lhs. Who tells you that this approximation is any good?? We have results of the form ''We can approximize the expected value $E[W]$ of a random value $W$ by $\frac{1}{L} \sum_{i=1}^L w_i \cdot f_W(w_i)$ this and that good if we have a sufficient amount of samples $w_1, ..., w_L$.'' So we could use these results on $\partial_\phi E_{q(z|\phi)}[f(Z)]$ but only if we know that this weird expression (the derivative of a random variable that somehow depends on a second parameter in this parameter) is an expected value of a random variable again and by pulling the derivative into the integral you do precisely that: Realize that this is the normal expectation of a random variable again, namely $E[f(Z)\cdot \partial_{q(z|\phi} \log q(z|\phi)]$. In short: you need to rewrite (1) to (2) in order to see that the approximation is any good. On your (3): Even in all the usual well known theorems (like the central limit theorem, the proof that the mean is a consistent estimator, etc) you need to divide the sum by the number of samples, otherwise the sum does not have a chance to converge but just vanishes towards infinity.
Gradient of the expectation of a function w.r.t. distribution parameters Without knowing anything in partuclar about auto-encoders: (1) $E_{q(z|\phi)}[f(Z)]$ this notation is not really 'standard' but usually means the expression $$ E_{q(z|\phi)}[f(Z)] = \int_Z f(z) q(z|\
35,335
Gradient of the expectation of a function w.r.t. distribution parameters
I don't know if this is too late but I would like to add my two cents. Let consider the simple case where $\phi$ and $z$ are 1 dimensional $\nabla_{\phi}\mathbb{E}_{q(z|\phi)}[f(z)] = \lim_{\delta \rightarrow 0} \frac{\int_{z=-\infty}^{z=\infty}f(z)q(z|\phi + \delta)dz \ - \int_{z=-\infty}^{z=\infty}f(z)q(z|\phi)dz}{\delta} = \lim_{\delta \rightarrow 0} \frac{\int_{z=-\infty}^{z=\infty}f(z)[q(z|\phi+\delta) - q(z|\phi)]dz}{\delta} \quad (4) $ If you want to approximate $\int_{z=-\infty}^{z=\infty}f(z)q(z|\phi)dz \approx \frac{1}{L}\sum_i f(z_i)q(z_i|\phi) \quad (5)$ then in order to use Eq. (4), you need to guarantee that the variance of RHS in Eq. (5) much smaller than $\delta$. This way you have to work with $d\delta^2$ while in Eq. 2, you only have to work with $d\delta$. Your method will require $n^2$ samples to achieve the same error with the method in Eq. 2.
Gradient of the expectation of a function w.r.t. distribution parameters
I don't know if this is too late but I would like to add my two cents. Let consider the simple case where $\phi$ and $z$ are 1 dimensional $\nabla_{\phi}\mathbb{E}_{q(z|\phi)}[f(z)] = \lim_{\delta \ri
Gradient of the expectation of a function w.r.t. distribution parameters I don't know if this is too late but I would like to add my two cents. Let consider the simple case where $\phi$ and $z$ are 1 dimensional $\nabla_{\phi}\mathbb{E}_{q(z|\phi)}[f(z)] = \lim_{\delta \rightarrow 0} \frac{\int_{z=-\infty}^{z=\infty}f(z)q(z|\phi + \delta)dz \ - \int_{z=-\infty}^{z=\infty}f(z)q(z|\phi)dz}{\delta} = \lim_{\delta \rightarrow 0} \frac{\int_{z=-\infty}^{z=\infty}f(z)[q(z|\phi+\delta) - q(z|\phi)]dz}{\delta} \quad (4) $ If you want to approximate $\int_{z=-\infty}^{z=\infty}f(z)q(z|\phi)dz \approx \frac{1}{L}\sum_i f(z_i)q(z_i|\phi) \quad (5)$ then in order to use Eq. (4), you need to guarantee that the variance of RHS in Eq. (5) much smaller than $\delta$. This way you have to work with $d\delta^2$ while in Eq. 2, you only have to work with $d\delta$. Your method will require $n^2$ samples to achieve the same error with the method in Eq. 2.
Gradient of the expectation of a function w.r.t. distribution parameters I don't know if this is too late but I would like to add my two cents. Let consider the simple case where $\phi$ and $z$ are 1 dimensional $\nabla_{\phi}\mathbb{E}_{q(z|\phi)}[f(z)] = \lim_{\delta \ri
35,336
Is there a mathematical definition of non-collapsibility?
Yes, there is, for instance, you can find one in Pearl, definition 6.5.1. Consider any functional $g[P(x, y)]$ of the joint distribution of $X$ and $Y$. We say $g$ is collapsible on $Z$ if: $$E_z\left[g[P(x, y|z)]\right] = g[P(x, y)]$$ We can see that collapsibility must make reference to not only $P(Y,X)$ but at least two more things: (i) a measure of association of $X$ and $Y$; and, (ii) a third variable $Z$. Note that if $g[P(x, y|z)]$ is constant across Z, the definition reduces to checking $g[P(x, y|z)] = g[P(x, y)]$, Greenland and Pearl call this simple collapsibility (see reference in the end). We will use this case below, since it reflects the case of the coefficient changes you refer to. With this in mind, we see that we need to assess when certain measures are collapsible with respect to certain variables --- and while the collapsibility of some measures might vary depending on the specific parameterization of the joint distribution, we can still say something about the collapsibility of some measures even without specifying $P(Y, X)$. For instance, let's take the logit link. The logit coefficients aim to estimate odds ratios, so to better understand the collapsibility of the logit coefficients we can investigate the collapsibility of the odds ratio. Let's write the Z specific odds ratio as: $$ \text{OR}(yx|z) = \frac{P(y_1|x_1, z)p(y_0|x_0, z)}{p(y_1|x_0, z)p(y_0|x_1, z)} $$ Suppose that it is constant across $Z$. Then we would say the z specific odds ratio is (simply) collapsible over $Z$ if $\text{OR}(yx|z) = \text{OR}(yx)$. Note that if $Y \perp Z|X$ then: $$ \text{OR}(yx|z) = \frac{P(y_1|x_1, z)p(y_0|x_0, z)}{p(y_1|x_0, z)p(y_0|x_1, z)} =\frac{P(y_1|x_1)p(y_0|x_0)}{p(y_1|x_0)p(y_0|x_1)} = \text{OR}(yx) $$ Thus the odds ratio is collapsible when $Z$ is independent of $Y$ given $X$. Therefore, we should expect the coefficient of $X$ in a logistic regression not to change when adding $Z$ in this case. Since the odds ratio is symmetric, if $X \perp Z|Y$ we also have collapsibility of the odds ratio, that is: $$ \begin{align} \text{OR}(yx|z) &= \frac{P(y_1|x_1, z)p(y_0|x_0, z)}{p(y_1|x_0, z)p(y_0|x_1, z)} =\frac{P(x_1|y_1, z)p(x_0|y_0, z)}{p(x_1|y_0, z)p(x_0|y_1, z)} \\ &=\frac{P(x_1|y_1)p(x_0|y_0)}{p(x_1|y_0)p(x_0|y_1)} = \text{OR}(yx) \end{align} $$ We can also see that we should not expect it to be collapsible over $Z$ with the condition $X \perp Z$ only. Thus, if $Z$ is independent of $X$ given $Y$ we should expect the coefficient of $X$ in a logistic regression to be unchanged by the inclusion of $Z$, but if we can only guarantee $Z \perp X$ we should not expect that. Note we are talking about when the associational measure Z specific odds ratio of $X$ and $Y$ is collapsible over $Z$. You could estimate $P(y|x,z)$ with other (non) parametric methods other than a GLM with logit link. If you then compute the Z specific odds ratio, what we said above about when we should expect it to be collapsible would still be valid, regardless of how $P(y|x,z)$ was obtained. It is true, however, that we are providing sufficient conditions here, and specific parameterizations of the joint distribution might have cases where we should not expect a measure to be collapsible but in that case it is. As to the risk ratio, assume it is constant across $Z$ and write the Z-specific RR as: $$ \text{RR}(yx|z) = \frac{P(y_1|x_1, z)}{P(y_1|x_0, z)} = k $$ Thus $P(y_1|x_1, z) = kP(y_1|x_0, z)$. If $X \perp Z$: $$ \begin{align} \text{RR}(yx) &= \frac{P(y_1|x_1)}{P(y_1|x_0)} = \frac{\sum_{z}P(y_1|x_1, z)p(z|x_1)}{\sum_{z}P(y_1|x_0,z)P(z|x_0)}\\ &= \frac{\sum_{z}P(y_1|x_1, z)p(z)}{\sum_{z}P(y_1|x_0,z)P(z)} = \frac{\sum_{z}kP(y_1|x_0, z)p(z)}{\sum_{z}P(y_1|x_0,z)P(z)}\\ &= k\frac{\sum_{z}P(y_1|x_0, z)p(z)}{\sum_{z}P(y_1|x_0,z)P(z)} = k = \text{RR}(yx|z) \end{align} $$ Thus the constant Z-specific RR would be collapsible with $X\perp Z$ and, for example, we would not expect the log-link coefficient of $X$ to change by adding $Z$ in this case. As a final remark, when $X \perp Z$, even though the Z specific odds ratio is not collapsible, the odds ratio using standardized probabilities would still be collapsible, since $$ \sum_{z}P(y|x, z)P(z) = \sum_{z}\frac{P(y,x, z)}{P(x|z)} = \sum_{z}\frac{P(y,x, z)}{P(x)} =\frac{P(y,x)}{P(x)} = P(y|x) $$ In fact, $Y \perp Z |X$ or $X\perp Z$ are sufficient conditions for the collapsibility of standardized measures. You might find this paper by Greenland and Pearl useful.
Is there a mathematical definition of non-collapsibility?
Yes, there is, for instance, you can find one in Pearl, definition 6.5.1. Consider any functional $g[P(x, y)]$ of the joint distribution of $X$ and $Y$. We say $g$ is collapsible on $Z$ if: $$E_z\left
Is there a mathematical definition of non-collapsibility? Yes, there is, for instance, you can find one in Pearl, definition 6.5.1. Consider any functional $g[P(x, y)]$ of the joint distribution of $X$ and $Y$. We say $g$ is collapsible on $Z$ if: $$E_z\left[g[P(x, y|z)]\right] = g[P(x, y)]$$ We can see that collapsibility must make reference to not only $P(Y,X)$ but at least two more things: (i) a measure of association of $X$ and $Y$; and, (ii) a third variable $Z$. Note that if $g[P(x, y|z)]$ is constant across Z, the definition reduces to checking $g[P(x, y|z)] = g[P(x, y)]$, Greenland and Pearl call this simple collapsibility (see reference in the end). We will use this case below, since it reflects the case of the coefficient changes you refer to. With this in mind, we see that we need to assess when certain measures are collapsible with respect to certain variables --- and while the collapsibility of some measures might vary depending on the specific parameterization of the joint distribution, we can still say something about the collapsibility of some measures even without specifying $P(Y, X)$. For instance, let's take the logit link. The logit coefficients aim to estimate odds ratios, so to better understand the collapsibility of the logit coefficients we can investigate the collapsibility of the odds ratio. Let's write the Z specific odds ratio as: $$ \text{OR}(yx|z) = \frac{P(y_1|x_1, z)p(y_0|x_0, z)}{p(y_1|x_0, z)p(y_0|x_1, z)} $$ Suppose that it is constant across $Z$. Then we would say the z specific odds ratio is (simply) collapsible over $Z$ if $\text{OR}(yx|z) = \text{OR}(yx)$. Note that if $Y \perp Z|X$ then: $$ \text{OR}(yx|z) = \frac{P(y_1|x_1, z)p(y_0|x_0, z)}{p(y_1|x_0, z)p(y_0|x_1, z)} =\frac{P(y_1|x_1)p(y_0|x_0)}{p(y_1|x_0)p(y_0|x_1)} = \text{OR}(yx) $$ Thus the odds ratio is collapsible when $Z$ is independent of $Y$ given $X$. Therefore, we should expect the coefficient of $X$ in a logistic regression not to change when adding $Z$ in this case. Since the odds ratio is symmetric, if $X \perp Z|Y$ we also have collapsibility of the odds ratio, that is: $$ \begin{align} \text{OR}(yx|z) &= \frac{P(y_1|x_1, z)p(y_0|x_0, z)}{p(y_1|x_0, z)p(y_0|x_1, z)} =\frac{P(x_1|y_1, z)p(x_0|y_0, z)}{p(x_1|y_0, z)p(x_0|y_1, z)} \\ &=\frac{P(x_1|y_1)p(x_0|y_0)}{p(x_1|y_0)p(x_0|y_1)} = \text{OR}(yx) \end{align} $$ We can also see that we should not expect it to be collapsible over $Z$ with the condition $X \perp Z$ only. Thus, if $Z$ is independent of $X$ given $Y$ we should expect the coefficient of $X$ in a logistic regression to be unchanged by the inclusion of $Z$, but if we can only guarantee $Z \perp X$ we should not expect that. Note we are talking about when the associational measure Z specific odds ratio of $X$ and $Y$ is collapsible over $Z$. You could estimate $P(y|x,z)$ with other (non) parametric methods other than a GLM with logit link. If you then compute the Z specific odds ratio, what we said above about when we should expect it to be collapsible would still be valid, regardless of how $P(y|x,z)$ was obtained. It is true, however, that we are providing sufficient conditions here, and specific parameterizations of the joint distribution might have cases where we should not expect a measure to be collapsible but in that case it is. As to the risk ratio, assume it is constant across $Z$ and write the Z-specific RR as: $$ \text{RR}(yx|z) = \frac{P(y_1|x_1, z)}{P(y_1|x_0, z)} = k $$ Thus $P(y_1|x_1, z) = kP(y_1|x_0, z)$. If $X \perp Z$: $$ \begin{align} \text{RR}(yx) &= \frac{P(y_1|x_1)}{P(y_1|x_0)} = \frac{\sum_{z}P(y_1|x_1, z)p(z|x_1)}{\sum_{z}P(y_1|x_0,z)P(z|x_0)}\\ &= \frac{\sum_{z}P(y_1|x_1, z)p(z)}{\sum_{z}P(y_1|x_0,z)P(z)} = \frac{\sum_{z}kP(y_1|x_0, z)p(z)}{\sum_{z}P(y_1|x_0,z)P(z)}\\ &= k\frac{\sum_{z}P(y_1|x_0, z)p(z)}{\sum_{z}P(y_1|x_0,z)P(z)} = k = \text{RR}(yx|z) \end{align} $$ Thus the constant Z-specific RR would be collapsible with $X\perp Z$ and, for example, we would not expect the log-link coefficient of $X$ to change by adding $Z$ in this case. As a final remark, when $X \perp Z$, even though the Z specific odds ratio is not collapsible, the odds ratio using standardized probabilities would still be collapsible, since $$ \sum_{z}P(y|x, z)P(z) = \sum_{z}\frac{P(y,x, z)}{P(x|z)} = \sum_{z}\frac{P(y,x, z)}{P(x)} =\frac{P(y,x)}{P(x)} = P(y|x) $$ In fact, $Y \perp Z |X$ or $X\perp Z$ are sufficient conditions for the collapsibility of standardized measures. You might find this paper by Greenland and Pearl useful.
Is there a mathematical definition of non-collapsibility? Yes, there is, for instance, you can find one in Pearl, definition 6.5.1. Consider any functional $g[P(x, y)]$ of the joint distribution of $X$ and $Y$. We say $g$ is collapsible on $Z$ if: $$E_z\left
35,337
References on number of features to use in Random Forest Regression
According to Elements of Statistical Learning (section 15.3): Recommended default values are $m = p/3$ for regression problems and $m = \sqrt{p}$ for classification problems (attributed to Breiman) The best value of $m$ depends on the problem, so $m$ should be treated as a tuning parameter. As discussed by Breiman (2001), the generalization error of a random forest decreases with the generalization error of the individual trees, and with the correlation between trees. Subsampling features is a way to decorrelate the trees. Increasing $m$ makes individual trees more powerful, but also increases their correlation. The optimal value of $m$ achieves a tradeoff between these two opposing effects, and typically lies somewhere in the middle of the range. He states that, in regression problems (compared to classification problems), the generalization error of individual trees decreases more slowly with $m$, and the correlation between trees increases more slowly. So, a larger value of $m$ is needed. This would explain why the commonly recommended default values for $m$ scale faster with $p$ for regression problems than classification problems. However, I didn't see an explicit recommendation for $m = p/3$ in this paper. Regarding scikit-learn's default setting of $m=p$: As mentioned above, subsampling features is one of the essential properties of random forests, and improves their performance by decorrelating the trees. Setting $m=p$ would remove this benefit, and would make the model equivalent to simple bagged trees. Breiman (2001) showed that this gives inferior performance on regression problems. Someone on the scikit-learn github page you linked claimed that $m=p$ is indeed recommended. However, the paper they cite is about 'extremely randomized trees', not standard random forests. Extremely randomized trees choose completely random split points, whereas random forests optimize the split point. As above, good performance requires a balance between strengthening the individual trees and injecting randomness to decorrelate them. Because extremely randomized trees inject a higher degree of randomness in the split points, it makes sense that they would benefit by compensating with searching over more features to split on. Conversely, random forests fully optimize the split points, so it makes sense that they would benefit by subsampling features to increase randomness. References: Breiman (2001). Random Forests. Hastie, Tibshirani, Friedman (2009). The Elements of Statistical Learning.
References on number of features to use in Random Forest Regression
According to Elements of Statistical Learning (section 15.3): Recommended default values are $m = p/3$ for regression problems and $m = \sqrt{p}$ for classification problems (attributed to Breiman) T
References on number of features to use in Random Forest Regression According to Elements of Statistical Learning (section 15.3): Recommended default values are $m = p/3$ for regression problems and $m = \sqrt{p}$ for classification problems (attributed to Breiman) The best value of $m$ depends on the problem, so $m$ should be treated as a tuning parameter. As discussed by Breiman (2001), the generalization error of a random forest decreases with the generalization error of the individual trees, and with the correlation between trees. Subsampling features is a way to decorrelate the trees. Increasing $m$ makes individual trees more powerful, but also increases their correlation. The optimal value of $m$ achieves a tradeoff between these two opposing effects, and typically lies somewhere in the middle of the range. He states that, in regression problems (compared to classification problems), the generalization error of individual trees decreases more slowly with $m$, and the correlation between trees increases more slowly. So, a larger value of $m$ is needed. This would explain why the commonly recommended default values for $m$ scale faster with $p$ for regression problems than classification problems. However, I didn't see an explicit recommendation for $m = p/3$ in this paper. Regarding scikit-learn's default setting of $m=p$: As mentioned above, subsampling features is one of the essential properties of random forests, and improves their performance by decorrelating the trees. Setting $m=p$ would remove this benefit, and would make the model equivalent to simple bagged trees. Breiman (2001) showed that this gives inferior performance on regression problems. Someone on the scikit-learn github page you linked claimed that $m=p$ is indeed recommended. However, the paper they cite is about 'extremely randomized trees', not standard random forests. Extremely randomized trees choose completely random split points, whereas random forests optimize the split point. As above, good performance requires a balance between strengthening the individual trees and injecting randomness to decorrelate them. Because extremely randomized trees inject a higher degree of randomness in the split points, it makes sense that they would benefit by compensating with searching over more features to split on. Conversely, random forests fully optimize the split points, so it makes sense that they would benefit by subsampling features to increase randomness. References: Breiman (2001). Random Forests. Hastie, Tibshirani, Friedman (2009). The Elements of Statistical Learning.
References on number of features to use in Random Forest Regression According to Elements of Statistical Learning (section 15.3): Recommended default values are $m = p/3$ for regression problems and $m = \sqrt{p}$ for classification problems (attributed to Breiman) T
35,338
How does poisson regression handle zeros anyway?
The Poisson model is $$y = \exp \left(\alpha + \beta \cdot x + \varepsilon \right).$$ The way you get an outcome of zero is when the index $\alpha + \beta \cdot x + \varepsilon$ is large and negative. The coefficients do not come from a regression of logged outcome on the covariates, but from maximization of the log likelihood. You can also use this model on non-integer outcomes, though that is more controversial. You can learn more about this model from this blog post, including the zeros issue and a comparison to logged outcome regression.
How does poisson regression handle zeros anyway?
The Poisson model is $$y = \exp \left(\alpha + \beta \cdot x + \varepsilon \right).$$ The way you get an outcome of zero is when the index $\alpha + \beta \cdot x + \varepsilon$ is large and negative.
How does poisson regression handle zeros anyway? The Poisson model is $$y = \exp \left(\alpha + \beta \cdot x + \varepsilon \right).$$ The way you get an outcome of zero is when the index $\alpha + \beta \cdot x + \varepsilon$ is large and negative. The coefficients do not come from a regression of logged outcome on the covariates, but from maximization of the log likelihood. You can also use this model on non-integer outcomes, though that is more controversial. You can learn more about this model from this blog post, including the zeros issue and a comparison to logged outcome regression.
How does poisson regression handle zeros anyway? The Poisson model is $$y = \exp \left(\alpha + \beta \cdot x + \varepsilon \right).$$ The way you get an outcome of zero is when the index $\alpha + \beta \cdot x + \varepsilon$ is large and negative.
35,339
How does poisson regression handle zeros anyway?
The poisson regression model is that the logarithm of the expected values can be modeled by a linear combination of predictors. The expected values of y are not 0, even though there may be 0 counts in the real data. The expectation is a positive real number.
How does poisson regression handle zeros anyway?
The poisson regression model is that the logarithm of the expected values can be modeled by a linear combination of predictors. The expected values of y are not 0, even though there may be 0 counts in
How does poisson regression handle zeros anyway? The poisson regression model is that the logarithm of the expected values can be modeled by a linear combination of predictors. The expected values of y are not 0, even though there may be 0 counts in the real data. The expectation is a positive real number.
How does poisson regression handle zeros anyway? The poisson regression model is that the logarithm of the expected values can be modeled by a linear combination of predictors. The expected values of y are not 0, even though there may be 0 counts in
35,340
Model with admissible estimator(s) that are not the Bayes estimator for any choice of prior?
Some results about Bayes and admissibility: If the Bayes risk is finite, there exists an admissible Bayes estimator, while if the Bayes risk is infinite there is no reason for the associated Bayes estimator(s) to be admissible. I cannot think of a case when all priors would have an infinite Bayes risk since the set of priors contain Dirac masses [complete class] If an estimator is admissible and the parameter set $\Theta$ is finite, then this estimator is Bayes [Blyth's theorem] If $\Theta$ is open, if the risk function $R(\theta,\delta)$ is continuous in $\theta$, and if $\delta$ is a limit of Bayes estimators in the sense that$$\lim_n\dfrac{R(\pi_n,\delta)-\min_\xi R(\pi_n,\xi)}{\pi_n(\Theta)}=0$$ then the estimator $\delta$ is admissible [Stein's theorem] If the support of the sampling density $f(\cdot|\theta)$ does not depend on $\theta$, if the loss function $L(\theta,d)$ is continuous and strictly convex in d for every $\theta$ and diverges at infinity, then every admissible estimator is a limit of Bayes estimators, corresponding to priors on a finite set The maximum likelihood estimator of the mean in the Normal mean problem, $x\sim \mathcal{N}(\theta,1)$, $\delta_0(x)=x$, is admissible under squared error loss, while not Bayes under quadratic loss but only generalised Bayes [Duanmu and Roy, 2016] For exponential families, under suitable conditions, every admissible estimator is generalized Bayes. [Farrell, 1968] "In problems of testing statistical hypotheses, there exist examples of admissible tests that cannot be generalised Bayes procedures. Although we believe the same to be true of some estimation problems, we do not have a conclusive example of an admissible estimator that is not a generalised Bayes estimator." (All statements except 6 are available in my book, as well as Jim Berger's and Peter Hoff's.) After digging further, I found these two exercises in Larry Brown's Fundamentals of Statistical Exponential Families:
Model with admissible estimator(s) that are not the Bayes estimator for any choice of prior?
Some results about Bayes and admissibility: If the Bayes risk is finite, there exists an admissible Bayes estimator, while if the Bayes risk is infinite there is no reason for the associated Bayes es
Model with admissible estimator(s) that are not the Bayes estimator for any choice of prior? Some results about Bayes and admissibility: If the Bayes risk is finite, there exists an admissible Bayes estimator, while if the Bayes risk is infinite there is no reason for the associated Bayes estimator(s) to be admissible. I cannot think of a case when all priors would have an infinite Bayes risk since the set of priors contain Dirac masses [complete class] If an estimator is admissible and the parameter set $\Theta$ is finite, then this estimator is Bayes [Blyth's theorem] If $\Theta$ is open, if the risk function $R(\theta,\delta)$ is continuous in $\theta$, and if $\delta$ is a limit of Bayes estimators in the sense that$$\lim_n\dfrac{R(\pi_n,\delta)-\min_\xi R(\pi_n,\xi)}{\pi_n(\Theta)}=0$$ then the estimator $\delta$ is admissible [Stein's theorem] If the support of the sampling density $f(\cdot|\theta)$ does not depend on $\theta$, if the loss function $L(\theta,d)$ is continuous and strictly convex in d for every $\theta$ and diverges at infinity, then every admissible estimator is a limit of Bayes estimators, corresponding to priors on a finite set The maximum likelihood estimator of the mean in the Normal mean problem, $x\sim \mathcal{N}(\theta,1)$, $\delta_0(x)=x$, is admissible under squared error loss, while not Bayes under quadratic loss but only generalised Bayes [Duanmu and Roy, 2016] For exponential families, under suitable conditions, every admissible estimator is generalized Bayes. [Farrell, 1968] "In problems of testing statistical hypotheses, there exist examples of admissible tests that cannot be generalised Bayes procedures. Although we believe the same to be true of some estimation problems, we do not have a conclusive example of an admissible estimator that is not a generalised Bayes estimator." (All statements except 6 are available in my book, as well as Jim Berger's and Peter Hoff's.) After digging further, I found these two exercises in Larry Brown's Fundamentals of Statistical Exponential Families:
Model with admissible estimator(s) that are not the Bayes estimator for any choice of prior? Some results about Bayes and admissibility: If the Bayes risk is finite, there exists an admissible Bayes estimator, while if the Bayes risk is infinite there is no reason for the associated Bayes es
35,341
Is the MAP the maximum value of the posterior or its mode?
In Bayesian statistics, a maximum a posteriori probability (MAP) estimate is an estimate of an unknown quantity, that equals the mode of the posterior distribution. This is correct. As far as I understand it, the mode of a distribution depends on how I construct its histogram (or KDE). This looks to me to be in contradiction with the above definition, where the MAP is the maximum θ value found for the sampled f(θ∣x) and does not depend on anything else. You are confusing theoretical quantities with random/sampling based ones. The posterior is defined by the likelihood and prior. That is $f(θ∣x) = \frac{L(\theta)\pi(\theta)}{\int_{\Theta} L(\theta')\pi(\theta') d \theta' }$ where $L(\theta)$, $\pi(\theta)$ are the likelihood and prior, respectively. This is a unique function in $\theta$. In practice it is common to sample from this distribution, and if that's the case, then you're introducing random error. Usually when this is done, it is the only option because, say, the normalizing constant will not be available. Popular strategies obtain samples from $f(\theta|x)$ and only require that the user is able to evaluate the un-normalized posterior $L(\theta)\pi(\theta)$. Even though this is only an approximation because it is indeed based on random draws, there are results that guarantee the convergence of your estimators, so the error is tolerable as long as you run your simulations for long enough.
Is the MAP the maximum value of the posterior or its mode?
In Bayesian statistics, a maximum a posteriori probability (MAP) estimate is an estimate of an unknown quantity, that equals the mode of the posterior distribution. This is correct. As far as I
Is the MAP the maximum value of the posterior or its mode? In Bayesian statistics, a maximum a posteriori probability (MAP) estimate is an estimate of an unknown quantity, that equals the mode of the posterior distribution. This is correct. As far as I understand it, the mode of a distribution depends on how I construct its histogram (or KDE). This looks to me to be in contradiction with the above definition, where the MAP is the maximum θ value found for the sampled f(θ∣x) and does not depend on anything else. You are confusing theoretical quantities with random/sampling based ones. The posterior is defined by the likelihood and prior. That is $f(θ∣x) = \frac{L(\theta)\pi(\theta)}{\int_{\Theta} L(\theta')\pi(\theta') d \theta' }$ where $L(\theta)$, $\pi(\theta)$ are the likelihood and prior, respectively. This is a unique function in $\theta$. In practice it is common to sample from this distribution, and if that's the case, then you're introducing random error. Usually when this is done, it is the only option because, say, the normalizing constant will not be available. Popular strategies obtain samples from $f(\theta|x)$ and only require that the user is able to evaluate the un-normalized posterior $L(\theta)\pi(\theta)$. Even though this is only an approximation because it is indeed based on random draws, there are results that guarantee the convergence of your estimators, so the error is tolerable as long as you run your simulations for long enough.
Is the MAP the maximum value of the posterior or its mode? In Bayesian statistics, a maximum a posteriori probability (MAP) estimate is an estimate of an unknown quantity, that equals the mode of the posterior distribution. This is correct. As far as I
35,342
Is the MAP the maximum value of the posterior or its mode?
The mode of distribution is either the value with more probability (for discrete random variable) or the point with highest probability density value (for continuous random variables). So yes, the mode of the a posteriori distribution is the MAP estimate. Note that, when constructing a histogram, you don't know the real distribution, which means the "mode" you find is just an estimate of what interval has the most probability associated.
Is the MAP the maximum value of the posterior or its mode?
The mode of distribution is either the value with more probability (for discrete random variable) or the point with highest probability density value (for continuous random variables). So yes, the mod
Is the MAP the maximum value of the posterior or its mode? The mode of distribution is either the value with more probability (for discrete random variable) or the point with highest probability density value (for continuous random variables). So yes, the mode of the a posteriori distribution is the MAP estimate. Note that, when constructing a histogram, you don't know the real distribution, which means the "mode" you find is just an estimate of what interval has the most probability associated.
Is the MAP the maximum value of the posterior or its mode? The mode of distribution is either the value with more probability (for discrete random variable) or the point with highest probability density value (for continuous random variables). So yes, the mod
35,343
Comparing two regressions models by looking at $R^2$
Are $u$ the residuals; is the second model also supposed to have residuals? Choosing whether to log-transform the response variable should be based on the type of relationship you expect between the explanatory and response variable. The explained variance ($R^2$) can be low or high despite the relationship being logarithmic. About R-squared $R^2$ is not a model selection criterium because it does not take into account the degrees of freedom used by the model (i.e. the number of parameters). However, since these models have the same number of parameters, this would not be a problem. More important is that they describe something completely different: At first glance I thought that since $R^2$ explains us how close the explained variation is to the total variation This is true, $R^2$ is the amount of variance in the response variable that is explained by the model. However, the $R^2$ of the first model describes the variance explained of $Y$, which is something else than in the second model ($\ln(Y)$). This is probably why you found that they cannot be compared this way: ESS from your question is Explained Sum of Squares.
Comparing two regressions models by looking at $R^2$
Are $u$ the residuals; is the second model also supposed to have residuals? Choosing whether to log-transform the response variable should be based on the type of relationship you expect between the
Comparing two regressions models by looking at $R^2$ Are $u$ the residuals; is the second model also supposed to have residuals? Choosing whether to log-transform the response variable should be based on the type of relationship you expect between the explanatory and response variable. The explained variance ($R^2$) can be low or high despite the relationship being logarithmic. About R-squared $R^2$ is not a model selection criterium because it does not take into account the degrees of freedom used by the model (i.e. the number of parameters). However, since these models have the same number of parameters, this would not be a problem. More important is that they describe something completely different: At first glance I thought that since $R^2$ explains us how close the explained variation is to the total variation This is true, $R^2$ is the amount of variance in the response variable that is explained by the model. However, the $R^2$ of the first model describes the variance explained of $Y$, which is something else than in the second model ($\ln(Y)$). This is probably why you found that they cannot be compared this way: ESS from your question is Explained Sum of Squares.
Comparing two regressions models by looking at $R^2$ Are $u$ the residuals; is the second model also supposed to have residuals? Choosing whether to log-transform the response variable should be based on the type of relationship you expect between the
35,344
Comparing two regressions models by looking at $R^2$
If the only two choices are either a log transformation or no transformation of the dependent variable, then to get the AIC values on an equal footing and allow for a comparison one could perform the linear regression on the untransformed dependent variable and on the log-transformed dependent variable multiplied by the geometric mean. First (using R for this example) generate some data with a model that's linear in the logs of the dependent variable: set.seed(12345) x = c(1:10) y = exp(1 + 0.2*x + 0.2*rnorm(10)) Fit a linear regression on $y$ given $x$: lm.y = lm(y ~ x) AIC(lm.y) # 41.72051 Now fit a linear regression on the geometric mean times the log of $y$ given $x$: lm.logy = lm(I(mean(log(y))*log(y)) ~ x) AIC(lm.logy) # 9.189641 The difference in the AIC values is around 32 which would suggest that taking the logs would produce a better model. (Not necessarily a good model, but a better model.) If the choice of the transformation is on some unknown power (rather than just "knowing" that either a log transformation or no transformation are the only two options), then that power should be estimated simultaneously with the regression parameters. See Box-Cox transformations.
Comparing two regressions models by looking at $R^2$
If the only two choices are either a log transformation or no transformation of the dependent variable, then to get the AIC values on an equal footing and allow for a comparison one could perform the
Comparing two regressions models by looking at $R^2$ If the only two choices are either a log transformation or no transformation of the dependent variable, then to get the AIC values on an equal footing and allow for a comparison one could perform the linear regression on the untransformed dependent variable and on the log-transformed dependent variable multiplied by the geometric mean. First (using R for this example) generate some data with a model that's linear in the logs of the dependent variable: set.seed(12345) x = c(1:10) y = exp(1 + 0.2*x + 0.2*rnorm(10)) Fit a linear regression on $y$ given $x$: lm.y = lm(y ~ x) AIC(lm.y) # 41.72051 Now fit a linear regression on the geometric mean times the log of $y$ given $x$: lm.logy = lm(I(mean(log(y))*log(y)) ~ x) AIC(lm.logy) # 9.189641 The difference in the AIC values is around 32 which would suggest that taking the logs would produce a better model. (Not necessarily a good model, but a better model.) If the choice of the transformation is on some unknown power (rather than just "knowing" that either a log transformation or no transformation are the only two options), then that power should be estimated simultaneously with the regression parameters. See Box-Cox transformations.
Comparing two regressions models by looking at $R^2$ If the only two choices are either a log transformation or no transformation of the dependent variable, then to get the AIC values on an equal footing and allow for a comparison one could perform the
35,345
Incremental learning with decision trees (scikit-learn)
Scikit-learn only offers implementations of the most common Decision Tree Algorithms (D3, C4.5, C5.0 and CART). These depend on having the whole dataset in memory, so there is no way to use partial-fit on them. You could only learn multiple decision trees on small subsets of your data and arrange them into a random forest. There are some other algorithms for inducing Decision Trees that work with on-disk or streaming data. I think the most known algorithms are SLIQ, SPRINT and HOEFFDING Trees (see this paper). While none of them seem to be implemented in any of the common machine learning frameworks (afaik), you can find some stand-alone python implementations on github. And if you are using Spark, they have some Decision Tree algorithms for big data too. PS: btw, how are you storing 3Tb of data in one pandas dataframe? (Are you using PyTables?)
Incremental learning with decision trees (scikit-learn)
Scikit-learn only offers implementations of the most common Decision Tree Algorithms (D3, C4.5, C5.0 and CART). These depend on having the whole dataset in memory, so there is no way to use partial-fi
Incremental learning with decision trees (scikit-learn) Scikit-learn only offers implementations of the most common Decision Tree Algorithms (D3, C4.5, C5.0 and CART). These depend on having the whole dataset in memory, so there is no way to use partial-fit on them. You could only learn multiple decision trees on small subsets of your data and arrange them into a random forest. There are some other algorithms for inducing Decision Trees that work with on-disk or streaming data. I think the most known algorithms are SLIQ, SPRINT and HOEFFDING Trees (see this paper). While none of them seem to be implemented in any of the common machine learning frameworks (afaik), you can find some stand-alone python implementations on github. And if you are using Spark, they have some Decision Tree algorithms for big data too. PS: btw, how are you storing 3Tb of data in one pandas dataframe? (Are you using PyTables?)
Incremental learning with decision trees (scikit-learn) Scikit-learn only offers implementations of the most common Decision Tree Algorithms (D3, C4.5, C5.0 and CART). These depend on having the whole dataset in memory, so there is no way to use partial-fi
35,346
In causal inference in statistics, how do you interpret the consistency assumption in mathematical terms?
Let me use $X$ for the treatment, $Y$ for the observed outcome and $Y(x)$ for the potential outcome under $X = x$. Consistency means that for an individual $i$, his observed outcome $Y_i$ when $X_i = x$ is his potential outcome $Y_{i}(x)$. Or, more formally: $$X_i = x \implies Y_i(x) = Y_i$$ When the treatment is binary ($X \in \{0,1\}$) consistency translates to the well known equation: $$ Y_i = X_i Y_i(1) +(1-X_i)Y_i(0) $$ In an informal way, that's what people intend to convey when stating that the "way" $X$ is assigned doesn't matter, that is, that there aren't multiple versions of the treatment. For if there were multiple potential outcomes to the same $x$, when you see $X_i = x$, then which potential outcome is the observed outcome $Y_i$? And if it doesn't matter how the treatment is assigned, then when $X_i = x$, $Y_i(x)$ is well defined and usually assumed to be equal to $Y_i$ (but note that, even without multiple versions of the treatment, you still need to assume that $X_i = x \implies Y_i(x) = Y_i$). What would happen without consistency? Consistency is what connects the potential outcomes with the observed data. That is, it's consistency that allows us writing things like: $$ E[Y(x)|X = x] = E[Y|X =x] $$ Which transforms expressions of counterfactual quantities $Y(x)$ into expressions of observed quantities $Y$. Without consistency, all of your potential outcomes data would be "missing". To make this clear, consider again a binary treatment. If consistency holds , when $X=1$ you observe $Y_i = Y(1)$ and when $X = 0$ you observe $Y_i = Y_i(0)$. The other two potential outcomes are unobserved, so your potential outcomes table would look like this: \begin{array} {|r|r|r|r|} \hline &Y_i(1) & Y_i(0) \\ \hline X_i=1 &Y_i &unobserved\\ \hline X_i=0 & unobserved & Y_i\\ \hline \end{array} If consistency did not hold, this is what you would get --- you don't observe any potential outcome: \begin{array} {|r|r|r|r|} \hline &Y_i(1) & Y_i(0) \\ \hline X_i=1 &unobserved &unobserved\\ \hline X_i=0 & unobserved & unobserved\\ \hline \end{array} Consistency, potential outcomes,axioms of counterfactuals and structural causal models In some of the potential outcomes literature, consistency is not explicitly defined, and casually considered together with other substantive assumptions such as SUTVA. In the axiomatization of counterfactuals, consistency is seen as a corollary of the axiom of composition. However, once you properly define a structural causal model (SCM) and you define counterfactuals as derived from interventional submodels, consistency is simply a natural consequence that automatically holds for all SCMs (see Gales and Pearl and also Pearl's Causality, Chapter 7). Finally, whether consistency really "holds" in your model when compared to the real world is a practical/modeling issue. That is, to make any inference, you always need consistency, so what you are question is not the rule, but modeling assumptions. For example, do you think you have properly defined the treatment assignment $X$? Or are there more relevant things in the assignment of $X$ that would matter for the outcome that you didn't model? These are the questions you need to think about to judge whether your model is a good approximation for the problem you are investigating.
In causal inference in statistics, how do you interpret the consistency assumption in mathematical t
Let me use $X$ for the treatment, $Y$ for the observed outcome and $Y(x)$ for the potential outcome under $X = x$. Consistency means that for an individual $i$, his observed outcome $Y_i$ when $X_i =
In causal inference in statistics, how do you interpret the consistency assumption in mathematical terms? Let me use $X$ for the treatment, $Y$ for the observed outcome and $Y(x)$ for the potential outcome under $X = x$. Consistency means that for an individual $i$, his observed outcome $Y_i$ when $X_i = x$ is his potential outcome $Y_{i}(x)$. Or, more formally: $$X_i = x \implies Y_i(x) = Y_i$$ When the treatment is binary ($X \in \{0,1\}$) consistency translates to the well known equation: $$ Y_i = X_i Y_i(1) +(1-X_i)Y_i(0) $$ In an informal way, that's what people intend to convey when stating that the "way" $X$ is assigned doesn't matter, that is, that there aren't multiple versions of the treatment. For if there were multiple potential outcomes to the same $x$, when you see $X_i = x$, then which potential outcome is the observed outcome $Y_i$? And if it doesn't matter how the treatment is assigned, then when $X_i = x$, $Y_i(x)$ is well defined and usually assumed to be equal to $Y_i$ (but note that, even without multiple versions of the treatment, you still need to assume that $X_i = x \implies Y_i(x) = Y_i$). What would happen without consistency? Consistency is what connects the potential outcomes with the observed data. That is, it's consistency that allows us writing things like: $$ E[Y(x)|X = x] = E[Y|X =x] $$ Which transforms expressions of counterfactual quantities $Y(x)$ into expressions of observed quantities $Y$. Without consistency, all of your potential outcomes data would be "missing". To make this clear, consider again a binary treatment. If consistency holds , when $X=1$ you observe $Y_i = Y(1)$ and when $X = 0$ you observe $Y_i = Y_i(0)$. The other two potential outcomes are unobserved, so your potential outcomes table would look like this: \begin{array} {|r|r|r|r|} \hline &Y_i(1) & Y_i(0) \\ \hline X_i=1 &Y_i &unobserved\\ \hline X_i=0 & unobserved & Y_i\\ \hline \end{array} If consistency did not hold, this is what you would get --- you don't observe any potential outcome: \begin{array} {|r|r|r|r|} \hline &Y_i(1) & Y_i(0) \\ \hline X_i=1 &unobserved &unobserved\\ \hline X_i=0 & unobserved & unobserved\\ \hline \end{array} Consistency, potential outcomes,axioms of counterfactuals and structural causal models In some of the potential outcomes literature, consistency is not explicitly defined, and casually considered together with other substantive assumptions such as SUTVA. In the axiomatization of counterfactuals, consistency is seen as a corollary of the axiom of composition. However, once you properly define a structural causal model (SCM) and you define counterfactuals as derived from interventional submodels, consistency is simply a natural consequence that automatically holds for all SCMs (see Gales and Pearl and also Pearl's Causality, Chapter 7). Finally, whether consistency really "holds" in your model when compared to the real world is a practical/modeling issue. That is, to make any inference, you always need consistency, so what you are question is not the rule, but modeling assumptions. For example, do you think you have properly defined the treatment assignment $X$? Or are there more relevant things in the assignment of $X$ that would matter for the outcome that you didn't model? These are the questions you need to think about to judge whether your model is a good approximation for the problem you are investigating.
In causal inference in statistics, how do you interpret the consistency assumption in mathematical t Let me use $X$ for the treatment, $Y$ for the observed outcome and $Y(x)$ for the potential outcome under $X = x$. Consistency means that for an individual $i$, his observed outcome $Y_i$ when $X_i =
35,347
How to calculate a partial expected value of beta distribution (mean of a truncated beta)?
Note that the formula you have near the top there for the beta median ($\frac{\alpha-\frac13}{\alpha+\beta-\frac23}$) is approximate. You should be able to compute an effectively "exact" numerical median with the inverse cdf (quantile function) of the beta distribution in Python (for a $\text{beta}(2,3)$ I get a median of around $0.3857$ while that approximate formula gives $0.3846$). This mean of a truncated distribution is pretty straightforward with a beta. For a positive random variable we have $E(X|X<k) = \int_0^k x\,f(x)\, dx / \int_0^k f(x)\, dx$ where in this case $f$ is the density of a beta with parameters $\alpha$ and $\beta$ (which I'll now write as $f(x;\alpha,\beta)$): $f(x;\alpha,\beta)=\frac{1}{B(\alpha,\beta)} x^{\alpha-1} (1-x)^{\beta-1}\,,\:0<x<1,\alpha,\beta>0$ Hence $x\,f(x) = \frac{B(\alpha+1,\beta)}{B(\alpha,\beta)} f(x;\alpha+1,\beta)=\frac{\alpha}{\alpha+\beta} f(x;\alpha+1,\beta)$ So $E(X|X<k) = \frac{\alpha}{\alpha+\beta} \int_0^k f(x;\alpha+1,\beta)\, dx / \int_0^k f(x;\alpha,\beta)\,dx$ Now the two integrals are just beta CDFs which you have available in Python already. With $\alpha=2,\beta=3,k=0.4$ we get $E(X|X<0.4)\approx 0.24195$. This is consistent with simulation ($10^6$ simulations gave $\approx 0.24194$). For the median, I get $F^{-1}(\frac12 F(0.4;2,3);2,3)\approx 0.25040$, which is again consistent with simulation ($10^6$ simulations gave $\approx 0.25038$). The two are pretty close in this case but that's not a general result; they may sometimes be more substantially different.
How to calculate a partial expected value of beta distribution (mean of a truncated beta)?
Note that the formula you have near the top there for the beta median ($\frac{\alpha-\frac13}{\alpha+\beta-\frac23}$) is approximate. You should be able to compute an effectively "exact" numerical med
How to calculate a partial expected value of beta distribution (mean of a truncated beta)? Note that the formula you have near the top there for the beta median ($\frac{\alpha-\frac13}{\alpha+\beta-\frac23}$) is approximate. You should be able to compute an effectively "exact" numerical median with the inverse cdf (quantile function) of the beta distribution in Python (for a $\text{beta}(2,3)$ I get a median of around $0.3857$ while that approximate formula gives $0.3846$). This mean of a truncated distribution is pretty straightforward with a beta. For a positive random variable we have $E(X|X<k) = \int_0^k x\,f(x)\, dx / \int_0^k f(x)\, dx$ where in this case $f$ is the density of a beta with parameters $\alpha$ and $\beta$ (which I'll now write as $f(x;\alpha,\beta)$): $f(x;\alpha,\beta)=\frac{1}{B(\alpha,\beta)} x^{\alpha-1} (1-x)^{\beta-1}\,,\:0<x<1,\alpha,\beta>0$ Hence $x\,f(x) = \frac{B(\alpha+1,\beta)}{B(\alpha,\beta)} f(x;\alpha+1,\beta)=\frac{\alpha}{\alpha+\beta} f(x;\alpha+1,\beta)$ So $E(X|X<k) = \frac{\alpha}{\alpha+\beta} \int_0^k f(x;\alpha+1,\beta)\, dx / \int_0^k f(x;\alpha,\beta)\,dx$ Now the two integrals are just beta CDFs which you have available in Python already. With $\alpha=2,\beta=3,k=0.4$ we get $E(X|X<0.4)\approx 0.24195$. This is consistent with simulation ($10^6$ simulations gave $\approx 0.24194$). For the median, I get $F^{-1}(\frac12 F(0.4;2,3);2,3)\approx 0.25040$, which is again consistent with simulation ($10^6$ simulations gave $\approx 0.25038$). The two are pretty close in this case but that's not a general result; they may sometimes be more substantially different.
How to calculate a partial expected value of beta distribution (mean of a truncated beta)? Note that the formula you have near the top there for the beta median ($\frac{\alpha-\frac13}{\alpha+\beta-\frac23}$) is approximate. You should be able to compute an effectively "exact" numerical med
35,348
How to calculate a partial expected value of beta distribution (mean of a truncated beta)?
For people who just want a scipy one-liner, it is also possible to use the expect function: from scipy.stats import beta as B start = 0 end = 0.4 a=2 b=3 print(B(a, b, loc=0, scale=1).expect(lb=start,ub=end,conditional=True)) 0.24195121951219523 This has the advantage of being (slightly) more readable, and more general However, it seems significantly slower (~4X slower) than the answer of @Glen_b Code used to generate the figure : from scipy.stats import beta as B from datetime import datetime import time import matplotlib.pyplot as plt N_tests = 10000 start = 0 end = 0.4 a = 2 b = 3 for i in range(N_tests): t1 = datetime.now() value = B(a=a, b=b, loc=0, scale=1).expect(lb=start,ub=end,conditional=True) t2 = datetime.now() list_times1.append((t2 - t1).total_seconds()) for i in range(N_tests): t1 = datetime.now() value = (a/(a+b)) * B(a+1,b).cdf(end) / B(a,b).cdf(end) t2 = datetime.now() list_times2.append((t2 - t1).total_seconds()) _ = plt.hist(list_times2,bins=100,label="scipy cdf",density=True) _ = plt.hist(list_times1,bins=100,label="scipy expect",density=True) plt.xlabel("Time taken") plt.ylabel("Number of occurences") plt.title("Distribution of the execution times for 10000 computations") plt.legend() plt.savefig("expected_partial_beta.png") plt.show()
How to calculate a partial expected value of beta distribution (mean of a truncated beta)?
For people who just want a scipy one-liner, it is also possible to use the expect function: from scipy.stats import beta as B start = 0 end = 0.4 a=2 b=3 print(B(a, b, loc=0, scale=1).expect(lb=star
How to calculate a partial expected value of beta distribution (mean of a truncated beta)? For people who just want a scipy one-liner, it is also possible to use the expect function: from scipy.stats import beta as B start = 0 end = 0.4 a=2 b=3 print(B(a, b, loc=0, scale=1).expect(lb=start,ub=end,conditional=True)) 0.24195121951219523 This has the advantage of being (slightly) more readable, and more general However, it seems significantly slower (~4X slower) than the answer of @Glen_b Code used to generate the figure : from scipy.stats import beta as B from datetime import datetime import time import matplotlib.pyplot as plt N_tests = 10000 start = 0 end = 0.4 a = 2 b = 3 for i in range(N_tests): t1 = datetime.now() value = B(a=a, b=b, loc=0, scale=1).expect(lb=start,ub=end,conditional=True) t2 = datetime.now() list_times1.append((t2 - t1).total_seconds()) for i in range(N_tests): t1 = datetime.now() value = (a/(a+b)) * B(a+1,b).cdf(end) / B(a,b).cdf(end) t2 = datetime.now() list_times2.append((t2 - t1).total_seconds()) _ = plt.hist(list_times2,bins=100,label="scipy cdf",density=True) _ = plt.hist(list_times1,bins=100,label="scipy expect",density=True) plt.xlabel("Time taken") plt.ylabel("Number of occurences") plt.title("Distribution of the execution times for 10000 computations") plt.legend() plt.savefig("expected_partial_beta.png") plt.show()
How to calculate a partial expected value of beta distribution (mean of a truncated beta)? For people who just want a scipy one-liner, it is also possible to use the expect function: from scipy.stats import beta as B start = 0 end = 0.4 a=2 b=3 print(B(a, b, loc=0, scale=1).expect(lb=star
35,349
The expected number of unique elements drawn with replacement
The solution to this problem makes use of a classic technique in probability, which is to begin by defining a set of so-called indicator (i.e. binary-valued) random variables, and then to use linearity of expectation. We begin by defining for each of the $n$ bins the random variable $$ \begin{align*} I_j = \begin{cases} 1 & \text{if we draw at least one ball from the } j\text{th bin} \\ 0 & \text{otherwise}. \end{cases} \end{align*} $$ Letting $X$ be the random variable denoting the number of different colored balls we draw, we have $$ X = \sum_{j=1}^n I_j. $$ Now using linearity of expectation, $$ \mathbb{E}[X] = \mathbb{E}\left[\sum_{j=1}^n I_j\right] = \sum_{j=1}^n \mathbb{E}[I_j]. $$ It remains to compute $\mathbb{E}[I_j]$ for $j = 1,\dots,n$. Note that for any $j$ $$ \begin{align*} \mathbb{E}[I_j] & = P(I_j = 1) \\ & = P(\text{draw at least one ball from bin } j) \\ & = 1 - P(\text{draw zero balls from bin } j) \\ & = 1 - \left(\frac{n-1}{n}\right)^k. \end{align*} $$ So the expected number of unique colors is $$ \mathbb{E}[X] = n\left[ 1 - \left(\frac{n-1}{n}\right)^k \right] $$ Note that the answer you provide is a close approximation since $$ \left(\frac{n-1}{n}\right)^k = \left(1 - \frac{1}{n}\right)^{k} = \left(1 - \frac{1}{n}\right)^{n\cdot\frac{k}{n}} \approx e^{-k/n}. $$
The expected number of unique elements drawn with replacement
The solution to this problem makes use of a classic technique in probability, which is to begin by defining a set of so-called indicator (i.e. binary-valued) random variables, and then to use linearit
The expected number of unique elements drawn with replacement The solution to this problem makes use of a classic technique in probability, which is to begin by defining a set of so-called indicator (i.e. binary-valued) random variables, and then to use linearity of expectation. We begin by defining for each of the $n$ bins the random variable $$ \begin{align*} I_j = \begin{cases} 1 & \text{if we draw at least one ball from the } j\text{th bin} \\ 0 & \text{otherwise}. \end{cases} \end{align*} $$ Letting $X$ be the random variable denoting the number of different colored balls we draw, we have $$ X = \sum_{j=1}^n I_j. $$ Now using linearity of expectation, $$ \mathbb{E}[X] = \mathbb{E}\left[\sum_{j=1}^n I_j\right] = \sum_{j=1}^n \mathbb{E}[I_j]. $$ It remains to compute $\mathbb{E}[I_j]$ for $j = 1,\dots,n$. Note that for any $j$ $$ \begin{align*} \mathbb{E}[I_j] & = P(I_j = 1) \\ & = P(\text{draw at least one ball from bin } j) \\ & = 1 - P(\text{draw zero balls from bin } j) \\ & = 1 - \left(\frac{n-1}{n}\right)^k. \end{align*} $$ So the expected number of unique colors is $$ \mathbb{E}[X] = n\left[ 1 - \left(\frac{n-1}{n}\right)^k \right] $$ Note that the answer you provide is a close approximation since $$ \left(\frac{n-1}{n}\right)^k = \left(1 - \frac{1}{n}\right)^{k} = \left(1 - \frac{1}{n}\right)^{n\cdot\frac{k}{n}} \approx e^{-k/n}. $$
The expected number of unique elements drawn with replacement The solution to this problem makes use of a classic technique in probability, which is to begin by defining a set of so-called indicator (i.e. binary-valued) random variables, and then to use linearit
35,350
Proof of Convergence for SARSA/Q-Learning Algorithm
The SARSA algorithm is a stochastic approximation to the Bellman equations for Markov Decision Processes. One way of writing the Bellman equation for $q_{\pi}(s,a)$ is: $$q_{\pi}(s,a) = \sum_{s',r}p(s',r|s,a)( r + \gamma \sum_{a'}\pi(a'|s') q_{\pi}(s',a'))$$ Where $p(s',r|s,a)$ is the probability of transition to state $s'$ with reward $r$ given current state $s$ and action $a$. In Dynamic Programming solutions to MDPs, the Bellman equation is used directly as an update mechanism that converges to correct values for $q_{\pi}(s,a)$. For estimating the value of a fixed policy, this works because the only stationary points of these updates are when the two sides are equal, and there is one equation for each $q_{\pi}(s,a)$ relating it linearly to one or more other $q_{\pi}(s',a')$, so it has a computable solution. When you add the search for an optimal solution, such as in SARSA, then the policy $\pi$ changes. There is a proof that changing the policy to pick the action $\pi'(s) = argmax_a q_{\pi}(s,a)$ will always either improve the policy or be optimal. This is called the Policy Improvement Theorem, and is based on the inequality $v_{\pi}(s) \le q_{\pi}(s,\pi'(s))$ - there is an extension to the theorem that covers $\epsilon$-greedy policies used in learners such as Monte Carlo Control or SARSA. TD learning, including SARSA and Q-Learning, uses the ideas of Dynamic Programming in a sample-based environment where the equalities are true in expectation. But essentially you can see how the update $q_{\pi}(s,a) = \sum_{s',r}p(s',r|s,a)( r + \gamma \sum_{a'}\pi(a'|s') q_{\pi}(s',a'))$ has turned into SARSA's update: The weighted sum over state transition and reward probabilities happens in expectation as you take many samples. So $Q(S,A) = \mathbb{E}[ \text{Sampled}(R) + \gamma \sum_{a'}\pi(a'|S') q_{\pi}(S',a')]$ (technically you have to sample R and S' together) Likewise the weighting of the current policy happens in expectation. So $Q(S,A) = \mathbb{E}[ \text{Sampled}(R + \gamma Q(S',A'))]$ To change this expectation into an incremental update, allowing for non-stationarity as the policy improves over time, we add a learning rate and move each estimate towards the latest sampled value: $Q(S,A) = Q(S,A) +\alpha[R + \gamma Q(S',A') - Q(S,A)]$ For a more thorough explanation of the building blocks of algorithms like SARSA and Q-Learning, you can read Reinforcement Learning: An Introduction. Or for a more concise and mathematically rigorous approach you can read Algorithms for Reinforcement Learning.
Proof of Convergence for SARSA/Q-Learning Algorithm
The SARSA algorithm is a stochastic approximation to the Bellman equations for Markov Decision Processes. One way of writing the Bellman equation for $q_{\pi}(s,a)$ is: $$q_{\pi}(s,a) = \sum_{s',r}p(s
Proof of Convergence for SARSA/Q-Learning Algorithm The SARSA algorithm is a stochastic approximation to the Bellman equations for Markov Decision Processes. One way of writing the Bellman equation for $q_{\pi}(s,a)$ is: $$q_{\pi}(s,a) = \sum_{s',r}p(s',r|s,a)( r + \gamma \sum_{a'}\pi(a'|s') q_{\pi}(s',a'))$$ Where $p(s',r|s,a)$ is the probability of transition to state $s'$ with reward $r$ given current state $s$ and action $a$. In Dynamic Programming solutions to MDPs, the Bellman equation is used directly as an update mechanism that converges to correct values for $q_{\pi}(s,a)$. For estimating the value of a fixed policy, this works because the only stationary points of these updates are when the two sides are equal, and there is one equation for each $q_{\pi}(s,a)$ relating it linearly to one or more other $q_{\pi}(s',a')$, so it has a computable solution. When you add the search for an optimal solution, such as in SARSA, then the policy $\pi$ changes. There is a proof that changing the policy to pick the action $\pi'(s) = argmax_a q_{\pi}(s,a)$ will always either improve the policy or be optimal. This is called the Policy Improvement Theorem, and is based on the inequality $v_{\pi}(s) \le q_{\pi}(s,\pi'(s))$ - there is an extension to the theorem that covers $\epsilon$-greedy policies used in learners such as Monte Carlo Control or SARSA. TD learning, including SARSA and Q-Learning, uses the ideas of Dynamic Programming in a sample-based environment where the equalities are true in expectation. But essentially you can see how the update $q_{\pi}(s,a) = \sum_{s',r}p(s',r|s,a)( r + \gamma \sum_{a'}\pi(a'|s') q_{\pi}(s',a'))$ has turned into SARSA's update: The weighted sum over state transition and reward probabilities happens in expectation as you take many samples. So $Q(S,A) = \mathbb{E}[ \text{Sampled}(R) + \gamma \sum_{a'}\pi(a'|S') q_{\pi}(S',a')]$ (technically you have to sample R and S' together) Likewise the weighting of the current policy happens in expectation. So $Q(S,A) = \mathbb{E}[ \text{Sampled}(R + \gamma Q(S',A'))]$ To change this expectation into an incremental update, allowing for non-stationarity as the policy improves over time, we add a learning rate and move each estimate towards the latest sampled value: $Q(S,A) = Q(S,A) +\alpha[R + \gamma Q(S',A') - Q(S,A)]$ For a more thorough explanation of the building blocks of algorithms like SARSA and Q-Learning, you can read Reinforcement Learning: An Introduction. Or for a more concise and mathematically rigorous approach you can read Algorithms for Reinforcement Learning.
Proof of Convergence for SARSA/Q-Learning Algorithm The SARSA algorithm is a stochastic approximation to the Bellman equations for Markov Decision Processes. One way of writing the Bellman equation for $q_{\pi}(s,a)$ is: $$q_{\pi}(s,a) = \sum_{s',r}p(s
35,351
Poisson regression with strong pattern in residuals
I would not begin by transforming the response variable (DV). I'd start by considering whether you have the right link function or whether you should transform some x's (independent variables). If you expect the ticketCount to be proportional to some of those predictors (I sure would), you might either want to use an identity link or enter the logs of some relevant predictors, possibly putting them in as offsets; the choice would depend on whether you see the way that the IVs would relate to the response as additive or multiplicative on the untransformed ticketCount scale. There's other things you could consider, but careful consideration of the relationship between the DV and IVs is central to choosing a good model. Here's an example of simulated Poisson data where the simulation used an identity link (i.e. $E(Y)$ is linear in $x$ -- in fact proportional to it in this case) while the fit used the default log-link: That's reasonably consistent with what you see. As soon as I saw your plot my first thought was "maybe an identity link was needed" and then after looking at your variable names that seemed like it might make a lot of sense; I'd have probably tried the identity link first. Here's what I get when I use my two proposed solutions: You can see that both of them solved the lack of fit problem, but there's some heteroskedasticity in the case where I fitted a different link to what I used to generate the data (this is as expected). # example code included as requested #(assumes we have already used `par` to get 1x2 grid for plots like above) # generate data x=runif(1000,1,20) y=rpois(1000,33*x) #fit (incorrect in this case) log-link function pfit=glm(y~x,family=poisson) # first plot plot(x,y) plot(pfit,which=1) #shows bowed appearance # identity link (correct in this case) # generalizes to additive in predictors pfiti=glm(y~x,family=poisson(link="identity")) # log link, log predictor, suits *multiplicative* model # and general case is in powers - could fit a model like # E(Y) = a . X1 . X2 . X3^b3 . X4^b4 using offsets pfitl=glm(y~log(x),family=poisson) # second plot plot(pfiti,which=1) plot(pfitl,which=1)
Poisson regression with strong pattern in residuals
I would not begin by transforming the response variable (DV). I'd start by considering whether you have the right link function or whether you should transform some x's (independent variables). If yo
Poisson regression with strong pattern in residuals I would not begin by transforming the response variable (DV). I'd start by considering whether you have the right link function or whether you should transform some x's (independent variables). If you expect the ticketCount to be proportional to some of those predictors (I sure would), you might either want to use an identity link or enter the logs of some relevant predictors, possibly putting them in as offsets; the choice would depend on whether you see the way that the IVs would relate to the response as additive or multiplicative on the untransformed ticketCount scale. There's other things you could consider, but careful consideration of the relationship between the DV and IVs is central to choosing a good model. Here's an example of simulated Poisson data where the simulation used an identity link (i.e. $E(Y)$ is linear in $x$ -- in fact proportional to it in this case) while the fit used the default log-link: That's reasonably consistent with what you see. As soon as I saw your plot my first thought was "maybe an identity link was needed" and then after looking at your variable names that seemed like it might make a lot of sense; I'd have probably tried the identity link first. Here's what I get when I use my two proposed solutions: You can see that both of them solved the lack of fit problem, but there's some heteroskedasticity in the case where I fitted a different link to what I used to generate the data (this is as expected). # example code included as requested #(assumes we have already used `par` to get 1x2 grid for plots like above) # generate data x=runif(1000,1,20) y=rpois(1000,33*x) #fit (incorrect in this case) log-link function pfit=glm(y~x,family=poisson) # first plot plot(x,y) plot(pfit,which=1) #shows bowed appearance # identity link (correct in this case) # generalizes to additive in predictors pfiti=glm(y~x,family=poisson(link="identity")) # log link, log predictor, suits *multiplicative* model # and general case is in powers - could fit a model like # E(Y) = a . X1 . X2 . X3^b3 . X4^b4 using offsets pfitl=glm(y~log(x),family=poisson) # second plot plot(pfiti,which=1) plot(pfitl,which=1)
Poisson regression with strong pattern in residuals I would not begin by transforming the response variable (DV). I'd start by considering whether you have the right link function or whether you should transform some x's (independent variables). If yo
35,352
Poisson regression with strong pattern in residuals
Surely ticketcount with a maximum possible value of capacity can only at best be approximately Poisson. Would it perhaps be more logical to model this as binomial with of ticketcount out of capacity? If it were not for this being clearly a potential inappropriate distribution, I would have wondered about whether you might have been ignoring (or not had available to you) important predictive variables leading to overdispersion - that you might partially account for by using any explanatory variables you have or by allowing for overdispersion (e.g. by using a negative binomial model - or in case of a binomial model a beta-binomial model or some other random effects model).
Poisson regression with strong pattern in residuals
Surely ticketcount with a maximum possible value of capacity can only at best be approximately Poisson. Would it perhaps be more logical to model this as binomial with of ticketcount out of capacity?
Poisson regression with strong pattern in residuals Surely ticketcount with a maximum possible value of capacity can only at best be approximately Poisson. Would it perhaps be more logical to model this as binomial with of ticketcount out of capacity? If it were not for this being clearly a potential inappropriate distribution, I would have wondered about whether you might have been ignoring (or not had available to you) important predictive variables leading to overdispersion - that you might partially account for by using any explanatory variables you have or by allowing for overdispersion (e.g. by using a negative binomial model - or in case of a binomial model a beta-binomial model or some other random effects model).
Poisson regression with strong pattern in residuals Surely ticketcount with a maximum possible value of capacity can only at best be approximately Poisson. Would it perhaps be more logical to model this as binomial with of ticketcount out of capacity?
35,353
Linear regression with changing variance
This sounds like a special case of heteroscedasticity. There are two issues: What estimator should you use in the presence of heteroscedasticity? How should you calculate your standard errors? The most straightforward thing to do is run a regular regression but use heteroscedastic robust standard errors. As @Glen_b suggests in the comments though, you probably can do better than this by efficiently exploiting known structure on your problem. What estimator to use? You could just run a normal regression. In the presence of heteroscedasticity, the regular ordinary least squares (OLS) estimator is still consistent. In layman's terms, OLS still works given enough data. But OLS is not efficient. You could run weighted least squares, an application of generalized least squares. The loose idea is to give more weight to observations with low variance error terms. Since you probably don't know ex-ante how the variance of the error term varies with $x$, you probably have to do something like feasible gls. If you run a regular OLS regression, you should not use the usual standard errors based upon assumptions of homoscedasticity. Instead you should use heteroscedastic robust standard errors. Any stats package can do this.
Linear regression with changing variance
This sounds like a special case of heteroscedasticity. There are two issues: What estimator should you use in the presence of heteroscedasticity? How should you calculate your standard errors? The m
Linear regression with changing variance This sounds like a special case of heteroscedasticity. There are two issues: What estimator should you use in the presence of heteroscedasticity? How should you calculate your standard errors? The most straightforward thing to do is run a regular regression but use heteroscedastic robust standard errors. As @Glen_b suggests in the comments though, you probably can do better than this by efficiently exploiting known structure on your problem. What estimator to use? You could just run a normal regression. In the presence of heteroscedasticity, the regular ordinary least squares (OLS) estimator is still consistent. In layman's terms, OLS still works given enough data. But OLS is not efficient. You could run weighted least squares, an application of generalized least squares. The loose idea is to give more weight to observations with low variance error terms. Since you probably don't know ex-ante how the variance of the error term varies with $x$, you probably have to do something like feasible gls. If you run a regular OLS regression, you should not use the usual standard errors based upon assumptions of homoscedasticity. Instead you should use heteroscedastic robust standard errors. Any stats package can do this.
Linear regression with changing variance This sounds like a special case of heteroscedasticity. There are two issues: What estimator should you use in the presence of heteroscedasticity? How should you calculate your standard errors? The m
35,354
Linear regression with changing variance
Your data violate the assumption of homoscedasticity. You can use a regression method that produces standard errors that are robust to heteroscedasticity. What software are you using to run your regression? If you are using R, you can use the sandwich package to estimate robust standard errors.
Linear regression with changing variance
Your data violate the assumption of homoscedasticity. You can use a regression method that produces standard errors that are robust to heteroscedasticity. What software are you using to run your regre
Linear regression with changing variance Your data violate the assumption of homoscedasticity. You can use a regression method that produces standard errors that are robust to heteroscedasticity. What software are you using to run your regression? If you are using R, you can use the sandwich package to estimate robust standard errors.
Linear regression with changing variance Your data violate the assumption of homoscedasticity. You can use a regression method that produces standard errors that are robust to heteroscedasticity. What software are you using to run your regre
35,355
Linear regression with changing variance
Machine learning guy here -- as much as I love the stats folks ML usually wins the day in real-world applications, and heteroscedasticity is one such common occurrence. A more general solution that is non-parametric and works for this and other (even highly) nonlinear regression problems is to just use quantile regression with a bagged decision tree. You can follow some links at Matlab to learn more (their examples are easily transferable to Python or R).
Linear regression with changing variance
Machine learning guy here -- as much as I love the stats folks ML usually wins the day in real-world applications, and heteroscedasticity is one such common occurrence. A more general solution that i
Linear regression with changing variance Machine learning guy here -- as much as I love the stats folks ML usually wins the day in real-world applications, and heteroscedasticity is one such common occurrence. A more general solution that is non-parametric and works for this and other (even highly) nonlinear regression problems is to just use quantile regression with a bagged decision tree. You can follow some links at Matlab to learn more (their examples are easily transferable to Python or R).
Linear regression with changing variance Machine learning guy here -- as much as I love the stats folks ML usually wins the day in real-world applications, and heteroscedasticity is one such common occurrence. A more general solution that i
35,356
Why can't this function be used as a loss function?
The loss function in the original post seems like a 0-1 loss divided by $N$, which is in fact the ultimate goal of most of classification settings. Actually, 0-1 loss divided by $N$ is equivalent to the accuracy metric. What your friend said is that it is difficult to use 0-1 loss directly for training a model. This is true for many reasons, but mostly because the loss is not differentiable. Many other loss functions used in classification, for example the likelihood of data, can be viewed as approximations of 0-1 loss. However, since the 0-1 loss is so intuitive and straightforward, the loss function is often measured during the training and assessing models. For me, I would love to print out both likelihood and 0-1 loss.
Why can't this function be used as a loss function?
The loss function in the original post seems like a 0-1 loss divided by $N$, which is in fact the ultimate goal of most of classification settings. Actually, 0-1 loss divided by $N$ is equivalent to t
Why can't this function be used as a loss function? The loss function in the original post seems like a 0-1 loss divided by $N$, which is in fact the ultimate goal of most of classification settings. Actually, 0-1 loss divided by $N$ is equivalent to the accuracy metric. What your friend said is that it is difficult to use 0-1 loss directly for training a model. This is true for many reasons, but mostly because the loss is not differentiable. Many other loss functions used in classification, for example the likelihood of data, can be viewed as approximations of 0-1 loss. However, since the 0-1 loss is so intuitive and straightforward, the loss function is often measured during the training and assessing models. For me, I would love to print out both likelihood and 0-1 loss.
Why can't this function be used as a loss function? The loss function in the original post seems like a 0-1 loss divided by $N$, which is in fact the ultimate goal of most of classification settings. Actually, 0-1 loss divided by $N$ is equivalent to t
35,357
Why can't this function be used as a loss function?
A loss function must be differentiable to perform gradient descent. It seems like you're trying to measure some sort of 1-accuracy (e.g., the proportion of incorrectly labeled samples). This doesn't have a derivative, so you can't use it. Instead, use cross entropy.
Why can't this function be used as a loss function?
A loss function must be differentiable to perform gradient descent. It seems like you're trying to measure some sort of 1-accuracy (e.g., the proportion of incorrectly labeled samples). This doesn't
Why can't this function be used as a loss function? A loss function must be differentiable to perform gradient descent. It seems like you're trying to measure some sort of 1-accuracy (e.g., the proportion of incorrectly labeled samples). This doesn't have a derivative, so you can't use it. Instead, use cross entropy.
Why can't this function be used as a loss function? A loss function must be differentiable to perform gradient descent. It seems like you're trying to measure some sort of 1-accuracy (e.g., the proportion of incorrectly labeled samples). This doesn't
35,358
Normalizing all the variarbles vs. using scale=TRUE option in prcomp in R
No difference. Type debug(prcomp) before running prcomp. The third line of the function reads: x <- scale(x, center = center, scale = scale.); ie. you will either scale within the function if you set scale = TRUE during function call or you will have the scaling done originally by you. Having said that, when applying PCA in general it is a good idea to scale your variables. Otherwise the magnitude to certain variables dominates the associations between the variables in the sample. Unless all your variables are recorded in the same scale and/or the difference in variable magnitudes are of interest I would suggest you normalise your data prior to PCA. This issue has been revisited multiple time within CV eg. 1, 2, 3.
Normalizing all the variarbles vs. using scale=TRUE option in prcomp in R
No difference. Type debug(prcomp) before running prcomp. The third line of the function reads: x <- scale(x, center = center, scale = scale.); ie. you will either scale within the function if you set
Normalizing all the variarbles vs. using scale=TRUE option in prcomp in R No difference. Type debug(prcomp) before running prcomp. The third line of the function reads: x <- scale(x, center = center, scale = scale.); ie. you will either scale within the function if you set scale = TRUE during function call or you will have the scaling done originally by you. Having said that, when applying PCA in general it is a good idea to scale your variables. Otherwise the magnitude to certain variables dominates the associations between the variables in the sample. Unless all your variables are recorded in the same scale and/or the difference in variable magnitudes are of interest I would suggest you normalise your data prior to PCA. This issue has been revisited multiple time within CV eg. 1, 2, 3.
Normalizing all the variarbles vs. using scale=TRUE option in prcomp in R No difference. Type debug(prcomp) before running prcomp. The third line of the function reads: x <- scale(x, center = center, scale = scale.); ie. you will either scale within the function if you set
35,359
Normalizing all the variarbles vs. using scale=TRUE option in prcomp in R
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. Using the correlation matrix is equivalent to standardizing each of the variables (to mean 0 and standard deviation 1). In general, PCA with and without standardizing will give different results. Especially when the scales are different. scale=TRUE bases the PCA on the correlation matrix and FALSE on the covariance matrix For example: #my data set.seed(1) x<-rnorm(10,50,4) y<-rnorm(10,50,7) df<-data.frame(x,y) PCA based on covariance matrix and on Correlation matrix PCA_df.cov <- prcomp(df, scale=FALSE) PCA_df.corr <- prcomp(df, scale=TRUE)
Normalizing all the variarbles vs. using scale=TRUE option in prcomp in R
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.
Normalizing all the variarbles vs. using scale=TRUE option in prcomp in R 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. Using the correlation matrix is equivalent to standardizing each of the variables (to mean 0 and standard deviation 1). In general, PCA with and without standardizing will give different results. Especially when the scales are different. scale=TRUE bases the PCA on the correlation matrix and FALSE on the covariance matrix For example: #my data set.seed(1) x<-rnorm(10,50,4) y<-rnorm(10,50,7) df<-data.frame(x,y) PCA based on covariance matrix and on Correlation matrix PCA_df.cov <- prcomp(df, scale=FALSE) PCA_df.corr <- prcomp(df, scale=TRUE)
Normalizing all the variarbles vs. using scale=TRUE option in prcomp in R 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.
35,360
How can I convert a lognormal distribution into a normal distribution?
By definition, a random variable $Z$ has a Lognormal distribution when $\log Z$ has a Normal distribution. This means there are numbers $\sigma\gt 0$ and $\mu$ for which the density function of $X = (\log(Z) - \mu)/\sigma$ is $$\phi(x) = \frac{1}{\sqrt{2\pi}} e^{-x^2/2}.$$ The density of $Z$ itself is obtained by substituting $(\log(z)-\mu)/\sigma$ for $x$ in the density element $\phi(x)\mathrm{d}z$: $$\eqalign{ f(z;\mu,\sigma)\mathrm{d}z &= \phi\left(\frac{\log(z) - \mu}{\sigma}\right)\mathrm{d}\left(\frac{\log(z) - \mu}{\sigma}\right) \\ &=\frac{1}{z\,\sigma}\phi\left(\frac{\log(z) - \mu}{\sigma}\right)\mathrm{d}z. }$$ For $z \gt 0$, this is the PDF of a Normal$(\mu,\sigma)$ distribution applied to $\log(z)$, but divided by $z$. That division resulted from the (nonlinear) effect of the logarithm on $\mathrm{d}z$: namely, $$\mathrm{d}\log z = \frac{1}{z}\mathrm{d}z.$$ Apply this to fitting your data: estimate $\mu$ and $\sigma$ by fitting a Normal distribution to the logarithms of the data and plug them into $f$. It's that simple. As an example, here is a histogram of $200$ values drawn independently from a Lognormal distribution. On it is plotted, in red, the graph of $f(z;\hat\mu,\hat\sigma)$ where $\hat \mu$ is the mean of the logs and $\hat \sigma$ is the estimated standard deviation of the logs. You might like to study the (simple) R code that produced these data and the plot. n <- 200 # Amount of data to generate mu <- -2 sigma <- 0.4 # # Generate data according to a lognormal distribution. # set.seed(17) z <- exp(rnorm(n, mu, sigma)) # # Fit the data. # y <- log(z) mu.hat <- mean(y) sigma.hat <- sd(y) # # Plot a histogram and superimpose the fitted PDF. # hist(z, freq=FALSE, breaks=25) phi <- function(x, mu, sigma) exp(-0.5 * ((x-mu)/sigma)^2) / (sigma * sqrt(2*pi)) curve(phi(log(x), mu.hat, sigma.hat) / x, add=TRUE, col="Red", lwd=2) This analysis appears to have addressed all the questions. Because it isn't clear what you mean by a "Chi Square analysis," let me finish with a warning: if you mean to compute a chi-squared statistic from a histogram of the data and obtain a p-value from it using a chi-squared distribution, then there are many pitfalls to beware. Read and study the account at https://stats.stackexchange.com/a/17148/919 and especially note the need to (a) establish the bin cutpoints independent of the data and (b) estimate $\mu$ and $\sigma$ by means of Maximum Likelihood based on the bin counts alone (rather than the actual data).
How can I convert a lognormal distribution into a normal distribution?
By definition, a random variable $Z$ has a Lognormal distribution when $\log Z$ has a Normal distribution. This means there are numbers $\sigma\gt 0$ and $\mu$ for which the density function of $X =
How can I convert a lognormal distribution into a normal distribution? By definition, a random variable $Z$ has a Lognormal distribution when $\log Z$ has a Normal distribution. This means there are numbers $\sigma\gt 0$ and $\mu$ for which the density function of $X = (\log(Z) - \mu)/\sigma$ is $$\phi(x) = \frac{1}{\sqrt{2\pi}} e^{-x^2/2}.$$ The density of $Z$ itself is obtained by substituting $(\log(z)-\mu)/\sigma$ for $x$ in the density element $\phi(x)\mathrm{d}z$: $$\eqalign{ f(z;\mu,\sigma)\mathrm{d}z &= \phi\left(\frac{\log(z) - \mu}{\sigma}\right)\mathrm{d}\left(\frac{\log(z) - \mu}{\sigma}\right) \\ &=\frac{1}{z\,\sigma}\phi\left(\frac{\log(z) - \mu}{\sigma}\right)\mathrm{d}z. }$$ For $z \gt 0$, this is the PDF of a Normal$(\mu,\sigma)$ distribution applied to $\log(z)$, but divided by $z$. That division resulted from the (nonlinear) effect of the logarithm on $\mathrm{d}z$: namely, $$\mathrm{d}\log z = \frac{1}{z}\mathrm{d}z.$$ Apply this to fitting your data: estimate $\mu$ and $\sigma$ by fitting a Normal distribution to the logarithms of the data and plug them into $f$. It's that simple. As an example, here is a histogram of $200$ values drawn independently from a Lognormal distribution. On it is plotted, in red, the graph of $f(z;\hat\mu,\hat\sigma)$ where $\hat \mu$ is the mean of the logs and $\hat \sigma$ is the estimated standard deviation of the logs. You might like to study the (simple) R code that produced these data and the plot. n <- 200 # Amount of data to generate mu <- -2 sigma <- 0.4 # # Generate data according to a lognormal distribution. # set.seed(17) z <- exp(rnorm(n, mu, sigma)) # # Fit the data. # y <- log(z) mu.hat <- mean(y) sigma.hat <- sd(y) # # Plot a histogram and superimpose the fitted PDF. # hist(z, freq=FALSE, breaks=25) phi <- function(x, mu, sigma) exp(-0.5 * ((x-mu)/sigma)^2) / (sigma * sqrt(2*pi)) curve(phi(log(x), mu.hat, sigma.hat) / x, add=TRUE, col="Red", lwd=2) This analysis appears to have addressed all the questions. Because it isn't clear what you mean by a "Chi Square analysis," let me finish with a warning: if you mean to compute a chi-squared statistic from a histogram of the data and obtain a p-value from it using a chi-squared distribution, then there are many pitfalls to beware. Read and study the account at https://stats.stackexchange.com/a/17148/919 and especially note the need to (a) establish the bin cutpoints independent of the data and (b) estimate $\mu$ and $\sigma$ by means of Maximum Likelihood based on the bin counts alone (rather than the actual data).
How can I convert a lognormal distribution into a normal distribution? By definition, a random variable $Z$ has a Lognormal distribution when $\log Z$ has a Normal distribution. This means there are numbers $\sigma\gt 0$ and $\mu$ for which the density function of $X =
35,361
How can I convert a lognormal distribution into a normal distribution?
NO, to transform lognormal data to normal you just take the log. That is what the name is saying, "log (of data) is normal". But you cannot just apply the log to the parameters of the lognormal to get the parameters of the normal. Log is a non-linear transformation, so relationship will be more complicated , but is well explained here: https://en.wikipedia.org/wiki/Log-normal_distribution
How can I convert a lognormal distribution into a normal distribution?
NO, to transform lognormal data to normal you just take the log. That is what the name is saying, "log (of data) is normal". But you cannot just apply the log to the parameters of the lognormal to g
How can I convert a lognormal distribution into a normal distribution? NO, to transform lognormal data to normal you just take the log. That is what the name is saying, "log (of data) is normal". But you cannot just apply the log to the parameters of the lognormal to get the parameters of the normal. Log is a non-linear transformation, so relationship will be more complicated , but is well explained here: https://en.wikipedia.org/wiki/Log-normal_distribution
How can I convert a lognormal distribution into a normal distribution? NO, to transform lognormal data to normal you just take the log. That is what the name is saying, "log (of data) is normal". But you cannot just apply the log to the parameters of the lognormal to g
35,362
How can I convert a lognormal distribution into a normal distribution?
I just stumbled into this post. I just want to give my 2 cents here: You can transform the distribution by change of variable: So transforming norm to log norm you use the following formula: Y=EXP(X) <=> LN(Y) = X Applying change of variable: pdf(y) = pdf(x) * dy/dx <=> pdf(y) = Norm(ln(x)) / x So you want the log norm from the norm, you do the following: Y=LN(X) <=> EXP(Y) = X Applying change of variable: pdf(y) = pdf(x) * dy/dx <=> pdf(y) = LogNorm(Exp(x)) * exp(x) I hope this helps
How can I convert a lognormal distribution into a normal distribution?
I just stumbled into this post. I just want to give my 2 cents here: You can transform the distribution by change of variable: So transforming norm to log norm you use the following formula: Y=EXP(X)
How can I convert a lognormal distribution into a normal distribution? I just stumbled into this post. I just want to give my 2 cents here: You can transform the distribution by change of variable: So transforming norm to log norm you use the following formula: Y=EXP(X) <=> LN(Y) = X Applying change of variable: pdf(y) = pdf(x) * dy/dx <=> pdf(y) = Norm(ln(x)) / x So you want the log norm from the norm, you do the following: Y=LN(X) <=> EXP(Y) = X Applying change of variable: pdf(y) = pdf(x) * dy/dx <=> pdf(y) = LogNorm(Exp(x)) * exp(x) I hope this helps
How can I convert a lognormal distribution into a normal distribution? I just stumbled into this post. I just want to give my 2 cents here: You can transform the distribution by change of variable: So transforming norm to log norm you use the following formula: Y=EXP(X)
35,363
What is the distribution of the sample variance for a Poisson random variable?
The distribution of the sample variance is slightly tricky, particularly because of the way the sample mean comes into it. Note that it has a discrete distribution, by taking deviations from the sample mean, the sizes of the positive and negative deviations will vary from sample to sample and will generally not be of the same sizes (e.g. imagine with $n=10$ that the mean is $1.9$; then deviations ($x_i-\bar{x}$) for value above the mean, will be $0.1$ or $1.1$ or $2.1$, while those below will be $-0.9$ or $-1.9$; but in the next sample the mean might be $1.7$, so the deviations will be values like $0.3$ or $-1.7$) the squaring makes both the deviations above and below the mean of different sizes even within one sample (consider deviations about the mean of -1.9, -0.9, 0.1, 1.1, 2.1; their squares are 3.61, 0.81, 0.01, 1.21 and 4.41, so the gaps between adjacent values of those jump in different increments ... and then these are "averaged" - but with n-1 denominator - to produce a sample variance) As a result you have a discrete distribution over a pretty complicated set of values (this set is countably infinite in size). The set of values taken also varies with sample size (n=3 yields a different set of possible values than n=10). Here's an example via simulation (though the simulation is so large that the distribution displayed is essentially the population cdf -- it's accurate to within about a pixel): We can clearly see "clumpiness" in the distribution - uneven spacing, as well as an intermingled jumble of large and small probabilities. The distributions are of course different at different values of $n$ and the Poisson mean, but the general impression (a clumpy discrete distribution, with uneven spacing and irregular progression of probabilities) is - unsurprisingly - similar across a range of values. The issue is even trickier if you want to back out some form of confidence interval for the population variance, since I am pretty sure you won't have a pivotal quantity to work with. However, you might be able to get somewhere via approximation. The upper tail in particular is a fair bit smoother than the lower tail and might be amenable to a continuous approximation. It looks like either large $\lambda$ or large samples will give smooth outcomes that may have scaled chi-square approximations.
What is the distribution of the sample variance for a Poisson random variable?
The distribution of the sample variance is slightly tricky, particularly because of the way the sample mean comes into it. Note that it has a discrete distribution, by taking deviations from the samp
What is the distribution of the sample variance for a Poisson random variable? The distribution of the sample variance is slightly tricky, particularly because of the way the sample mean comes into it. Note that it has a discrete distribution, by taking deviations from the sample mean, the sizes of the positive and negative deviations will vary from sample to sample and will generally not be of the same sizes (e.g. imagine with $n=10$ that the mean is $1.9$; then deviations ($x_i-\bar{x}$) for value above the mean, will be $0.1$ or $1.1$ or $2.1$, while those below will be $-0.9$ or $-1.9$; but in the next sample the mean might be $1.7$, so the deviations will be values like $0.3$ or $-1.7$) the squaring makes both the deviations above and below the mean of different sizes even within one sample (consider deviations about the mean of -1.9, -0.9, 0.1, 1.1, 2.1; their squares are 3.61, 0.81, 0.01, 1.21 and 4.41, so the gaps between adjacent values of those jump in different increments ... and then these are "averaged" - but with n-1 denominator - to produce a sample variance) As a result you have a discrete distribution over a pretty complicated set of values (this set is countably infinite in size). The set of values taken also varies with sample size (n=3 yields a different set of possible values than n=10). Here's an example via simulation (though the simulation is so large that the distribution displayed is essentially the population cdf -- it's accurate to within about a pixel): We can clearly see "clumpiness" in the distribution - uneven spacing, as well as an intermingled jumble of large and small probabilities. The distributions are of course different at different values of $n$ and the Poisson mean, but the general impression (a clumpy discrete distribution, with uneven spacing and irregular progression of probabilities) is - unsurprisingly - similar across a range of values. The issue is even trickier if you want to back out some form of confidence interval for the population variance, since I am pretty sure you won't have a pivotal quantity to work with. However, you might be able to get somewhere via approximation. The upper tail in particular is a fair bit smoother than the lower tail and might be amenable to a continuous approximation. It looks like either large $\lambda$ or large samples will give smooth outcomes that may have scaled chi-square approximations.
What is the distribution of the sample variance for a Poisson random variable? The distribution of the sample variance is slightly tricky, particularly because of the way the sample mean comes into it. Note that it has a discrete distribution, by taking deviations from the samp
35,364
Autocovariance, Autocorrelation and Autocorrelation coefficient
Q1: Say you have observations over time on a variable $\{x_t\}, t=\{1,...,T\}$. If they are generated from a second-order stationary stochastic process (Click) you may apply the following techniques to find the first autocovariance and the first autocorrelation coefficient. Calculate the covariance of observations $x_t, \forall t>1$ and $x_{t-1}$, this gives the first autocovariance. This generalizes: $Cov(x_t,x_{t-n})$ is the n-th autocovariance. If you divide the autocovariance by the variance of the $x_t$ you obtain the autocorrelation coefficient: $\rho_1=\frac{Cov(x_t,x_{t-1})}{Var(x_t)}$. Autocorrelation is the property of the variable $x_t$ indicated by the autocorrelation coefficient, which tells you how much the realization $x_t$ depends on the last realization $x_{t-1}$. This naturally leads into the idea of an autoregressive process. For example an autoregressive process of order 1 is given by $x_t=\rho_1 x_{t-1}+\epsilon_t$, where $\epsilon_t$ is a standard-normal random variable. So, $x_{t-1}$ will contribute to $x_t$ according to the parameter $\rho_1$. Click Q2: You can piece it together from the answer to Q1. The lag-operator shifts the period on a variable like $x_t$ to a previous period. For example, $L(x_t)=x_{t-1}$, where $L()$ is the one-period lag-operator. You can find the estimate of $\rho_1$ by running a linear regression of present values of your variable on their realizations one period back.
Autocovariance, Autocorrelation and Autocorrelation coefficient
Q1: Say you have observations over time on a variable $\{x_t\}, t=\{1,...,T\}$. If they are generated from a second-order stationary stochastic process (Click) you may apply the following techniques t
Autocovariance, Autocorrelation and Autocorrelation coefficient Q1: Say you have observations over time on a variable $\{x_t\}, t=\{1,...,T\}$. If they are generated from a second-order stationary stochastic process (Click) you may apply the following techniques to find the first autocovariance and the first autocorrelation coefficient. Calculate the covariance of observations $x_t, \forall t>1$ and $x_{t-1}$, this gives the first autocovariance. This generalizes: $Cov(x_t,x_{t-n})$ is the n-th autocovariance. If you divide the autocovariance by the variance of the $x_t$ you obtain the autocorrelation coefficient: $\rho_1=\frac{Cov(x_t,x_{t-1})}{Var(x_t)}$. Autocorrelation is the property of the variable $x_t$ indicated by the autocorrelation coefficient, which tells you how much the realization $x_t$ depends on the last realization $x_{t-1}$. This naturally leads into the idea of an autoregressive process. For example an autoregressive process of order 1 is given by $x_t=\rho_1 x_{t-1}+\epsilon_t$, where $\epsilon_t$ is a standard-normal random variable. So, $x_{t-1}$ will contribute to $x_t$ according to the parameter $\rho_1$. Click Q2: You can piece it together from the answer to Q1. The lag-operator shifts the period on a variable like $x_t$ to a previous period. For example, $L(x_t)=x_{t-1}$, where $L()$ is the one-period lag-operator. You can find the estimate of $\rho_1$ by running a linear regression of present values of your variable on their realizations one period back.
Autocovariance, Autocorrelation and Autocorrelation coefficient Q1: Say you have observations over time on a variable $\{x_t\}, t=\{1,...,T\}$. If they are generated from a second-order stationary stochastic process (Click) you may apply the following techniques t
35,365
Autocovariance, Autocorrelation and Autocorrelation coefficient
Disclaimer: This is meant to be an intuitive explanation without going into mathematical details, given that the original question seemed fairly elementary. To understand the difference between auto-covariance and auto-correlation, it helps to understand the difference between covariance and correlation. Covariance is a measure of how much two paired variables v1 and v2 vary in the same way/direction. It is positive when v1 is above its mean at the same time that v2 is above its mean and/or v1 is below its mean at the same time that v2 is below its mean. It is negative when the opposite happens, i.e. whenever v1 is above its mean, v2 is below its mean and vice versa. It is important to note that covariance only gives you an idea of the direction of the relationship but its hard to interpret the magnitude of the relation, since it is very dependent on the units that are used. (For instance, if your variables are in cm and then you transform it into inches, the absolute value of the covariance will be very different. Correlation addresses this by scaling the covariance, and putting it into the interval between -1 and 1. Correlation of 1 means your two variables are perfectly positively correlated, -1 means they are perfectly negatively correlated (whenever v1 goes up, v2 goes down), 0 means that there is no correlation at all. Now, for time-series, the "auto-" prefix indicates that you calculate the covariance and correlation between one variable at time t1 and the the same variable at a later time t1+k. E.g. for k=1, you calculate the covariance and correlation between one time and the next time. The k indicates the difference or lag between the time points, e.g. if you had monthly data, with k=12 you would inspect the relationship between the variables in the first year and the following year. The auto-correlation coefficients then give you the auto-correlation for each lag k. Comparing the coefficients for different lags can tell you if there is seasonality in the data - e.g. temperatures tend to change with seasons, so you would expect a higher autocorrelation coefficient at around k=12 for monthly data.
Autocovariance, Autocorrelation and Autocorrelation coefficient
Disclaimer: This is meant to be an intuitive explanation without going into mathematical details, given that the original question seemed fairly elementary. To understand the difference between auto-c
Autocovariance, Autocorrelation and Autocorrelation coefficient Disclaimer: This is meant to be an intuitive explanation without going into mathematical details, given that the original question seemed fairly elementary. To understand the difference between auto-covariance and auto-correlation, it helps to understand the difference between covariance and correlation. Covariance is a measure of how much two paired variables v1 and v2 vary in the same way/direction. It is positive when v1 is above its mean at the same time that v2 is above its mean and/or v1 is below its mean at the same time that v2 is below its mean. It is negative when the opposite happens, i.e. whenever v1 is above its mean, v2 is below its mean and vice versa. It is important to note that covariance only gives you an idea of the direction of the relationship but its hard to interpret the magnitude of the relation, since it is very dependent on the units that are used. (For instance, if your variables are in cm and then you transform it into inches, the absolute value of the covariance will be very different. Correlation addresses this by scaling the covariance, and putting it into the interval between -1 and 1. Correlation of 1 means your two variables are perfectly positively correlated, -1 means they are perfectly negatively correlated (whenever v1 goes up, v2 goes down), 0 means that there is no correlation at all. Now, for time-series, the "auto-" prefix indicates that you calculate the covariance and correlation between one variable at time t1 and the the same variable at a later time t1+k. E.g. for k=1, you calculate the covariance and correlation between one time and the next time. The k indicates the difference or lag between the time points, e.g. if you had monthly data, with k=12 you would inspect the relationship between the variables in the first year and the following year. The auto-correlation coefficients then give you the auto-correlation for each lag k. Comparing the coefficients for different lags can tell you if there is seasonality in the data - e.g. temperatures tend to change with seasons, so you would expect a higher autocorrelation coefficient at around k=12 for monthly data.
Autocovariance, Autocorrelation and Autocorrelation coefficient Disclaimer: This is meant to be an intuitive explanation without going into mathematical details, given that the original question seemed fairly elementary. To understand the difference between auto-c
35,366
Why there is no transition probability in Q-Learning (reinforcement learning)?
Algorithms that don't learn the state-transition probability function are called model-free. One of the main problems with model-based algorithms is that there are often many states, and a naïve model is quadratic in the number of states. That imposes a huge data requirement. Q-learning is model-free. It does not learn a state-transition probability function.
Why there is no transition probability in Q-Learning (reinforcement learning)?
Algorithms that don't learn the state-transition probability function are called model-free. One of the main problems with model-based algorithms is that there are often many states, and a naïve mode
Why there is no transition probability in Q-Learning (reinforcement learning)? Algorithms that don't learn the state-transition probability function are called model-free. One of the main problems with model-based algorithms is that there are often many states, and a naïve model is quadratic in the number of states. That imposes a huge data requirement. Q-learning is model-free. It does not learn a state-transition probability function.
Why there is no transition probability in Q-Learning (reinforcement learning)? Algorithms that don't learn the state-transition probability function are called model-free. One of the main problems with model-based algorithms is that there are often many states, and a naïve mode
35,367
Why there is no transition probability in Q-Learning (reinforcement learning)?
For clarity, I think you should replace $max_a(Q', a)$ with $max_a(Q(S', a))$ as there is only one action-value function, we are just evaluating Q on actions in the next state. This notation also hints at where the $p(s'|s, a)$ lies. Intuitively, $p(s'|s, a)$ is a property of the environment. We do not control how it works but simply sample from it. Before we call this update we first have to take an action A while in state S. The process of doing this gives us a reward and sends us to the next state. That next state that you land in is drawn from $p(s'|s, a)$ by it's definition. So in the Q-learning update we essentially assume $p(s'|s, a)$ is 1 because that is where we ended up. This is ok because it's an iterative method where we are estimating the optimal action-value function without knowing the full dynamics of the environment and more specifically the value of $p(s|s', a)$. If you happen to have a model of the environment that gives you this information you can change the update to include it by simply changing the return to $\gamma p(S'|S, A)max_a(Q(S', a))$.
Why there is no transition probability in Q-Learning (reinforcement learning)?
For clarity, I think you should replace $max_a(Q', a)$ with $max_a(Q(S', a))$ as there is only one action-value function, we are just evaluating Q on actions in the next state. This notation also hint
Why there is no transition probability in Q-Learning (reinforcement learning)? For clarity, I think you should replace $max_a(Q', a)$ with $max_a(Q(S', a))$ as there is only one action-value function, we are just evaluating Q on actions in the next state. This notation also hints at where the $p(s'|s, a)$ lies. Intuitively, $p(s'|s, a)$ is a property of the environment. We do not control how it works but simply sample from it. Before we call this update we first have to take an action A while in state S. The process of doing this gives us a reward and sends us to the next state. That next state that you land in is drawn from $p(s'|s, a)$ by it's definition. So in the Q-learning update we essentially assume $p(s'|s, a)$ is 1 because that is where we ended up. This is ok because it's an iterative method where we are estimating the optimal action-value function without knowing the full dynamics of the environment and more specifically the value of $p(s|s', a)$. If you happen to have a model of the environment that gives you this information you can change the update to include it by simply changing the return to $\gamma p(S'|S, A)max_a(Q(S', a))$.
Why there is no transition probability in Q-Learning (reinforcement learning)? For clarity, I think you should replace $max_a(Q', a)$ with $max_a(Q(S', a))$ as there is only one action-value function, we are just evaluating Q on actions in the next state. This notation also hint
35,368
Why there is no transition probability in Q-Learning (reinforcement learning)?
In addition to the above, Q-Learning is a model-free algorithm,that means that our agent just know the states what the environment gives to it. In other words, if an agent selects and performs an action, next state is determined by the environment only and gives to the agent. For that reason, the agent do not think about the state-transition probabilities.
Why there is no transition probability in Q-Learning (reinforcement learning)?
In addition to the above, Q-Learning is a model-free algorithm,that means that our agent just know the states what the environment gives to it. In other words, if an agent selects and performs an acti
Why there is no transition probability in Q-Learning (reinforcement learning)? In addition to the above, Q-Learning is a model-free algorithm,that means that our agent just know the states what the environment gives to it. In other words, if an agent selects and performs an action, next state is determined by the environment only and gives to the agent. For that reason, the agent do not think about the state-transition probabilities.
Why there is no transition probability in Q-Learning (reinforcement learning)? In addition to the above, Q-Learning is a model-free algorithm,that means that our agent just know the states what the environment gives to it. In other words, if an agent selects and performs an acti
35,369
Equation for the variance inflation factors
Assume all $X$ variables are standardized by the correlation transformation, like you mentioned, unit length scaled version of $\mathbf{X}$. The standardized model does not change the correlation between $X$ variables. $VIF$ can be calculated when standardized transformation of the original linear model is made. Let's denote the design matrix after standardized transformation as \begin{align*} \mathbf{X^*} = \begin{bmatrix} 1& X_{11}& \ldots &X_{1,p-1} \\ 1& X_{21}& \ldots &X_{2,p-1} \\ \vdots & \vdots & \vdots & \vdots \\ 1& X_{n1}& \ldots &X_{n,p-1} \\ \end{bmatrix}. \end{align*} Then \begin{align*} \mathbf{X^{*'}X^*} = \begin{bmatrix} n & \mathbf{0}' \\ \mathbf{0} & \mathbf{r}_{XX} \end{bmatrix}, \end{align*} where $\mathbf{r}_{XX}$ is the correlation matrix of $X$ variables. We also know that \begin{align*} \sigma^2\{\hat{\beta}\} & = \sigma^2 (\mathbf{X^{*'}X^*})^{-1}\\ & = \sigma^2 \begin{bmatrix} \frac{1}{n} & \mathbf{0}' \\ \mathbf{0} & \mathbf{r}^{-1}_{XX}. \end{bmatrix}\\ \end{align*} $VIF_k$ for $k=1,2,\ldots,p-1$ is the $k$-th diagonal term of $\mathbf{r}^{-1}_{XX}$. We only need to prove this for $k = 1$ because you can permute the rows and columns of $r_{XX}$ to get the result for other $k$. Let's define: \begin{align*} \mathbf{X}_{(-1)} = \begin{bmatrix} X_{12}&\ldots&X_{1,p-1} \\X_{22}&\ldots&X_{2,p-1}\\ \vdots & \vdots & \vdots \\ X_{n2}&\ldots&X_{n,p-1} \\ \end{bmatrix}, \mathbf{X}_1 = \begin{bmatrix} X_{11} \\ X_{21} \\ \vdots \\ X_{n1} \\ \end{bmatrix}. \end{align*} Note that both matrices are different from design matrices. Since we only care about the coefficients of $X$ variables, the $1$-vector of a design matrix can be ignored in our calculation. Hence, by using Schur's complement, \begin{align*} r^{-1}_{XX} (1,1) & = (r_{11} - r_{1\mathbf{X}_{(-1)}} r^{-1}_{\mathbf{X}_{(-1)}\mathbf{X}_{(-1)}} r_{\mathbf{X}_{(-1)}1})^{-1} \\ & = (r_{11} - [r_{1\mathbf{X}_{(-1)}} r^{-1}_{\mathbf{X}_{(-1)}\mathbf{X}_{(-1)}}] r_{\mathbf{X}_{(-1)}\mathbf{X}_{(-1)}} [r^{-1}_{\mathbf{X}_{(-1)}\mathbf{X}_{(-1)}} r_{\mathbf{X}_{(-1)}1}])^{-1} \\ & = (1-\beta_{1\mathbf{X}_{(-1)}}' \mathbf{X}_{(-1)}' \mathbf{X}_{(-1)} \beta_{1\mathbf{X}_{(-1)}} )^{-1}, \end{align*} where $\beta_{1\mathbf{X}_{(-1)}}$ is the regression coefficients of $X_1$ on $X_2, \ldots, X_{p-1}$ except the intercept. In fact, the intercept should be the origin, since all $X$ variables are standardized with mean zero. On the other hand, (it would be more straightforward if we can write everything in explicit matrix form) \begin{align*} R_1^2 & = \frac{SSR}{SSTO} = \frac{\beta_{1\mathbf{X}_{(-1)}}' \mathbf{X}_{(-1)}' \mathbf{X}_{(-1)} \beta_{1\mathbf{X}_{(-1)}}}{1} \\ & = \beta_{1\mathbf{X}_{(-1)}}' \mathbf{X}_{(-1)}' \mathbf{X}_{(-1)} \beta_{1\mathbf{X}_{(-1)}}. \end{align*} Therefore \begin{align*} VIF_1 = r^{-1}_{XX} (1,1) = \frac{1}{1-R_1^2}. \end{align*}
Equation for the variance inflation factors
Assume all $X$ variables are standardized by the correlation transformation, like you mentioned, unit length scaled version of $\mathbf{X}$. The standardized model does not change the correlation betw
Equation for the variance inflation factors Assume all $X$ variables are standardized by the correlation transformation, like you mentioned, unit length scaled version of $\mathbf{X}$. The standardized model does not change the correlation between $X$ variables. $VIF$ can be calculated when standardized transformation of the original linear model is made. Let's denote the design matrix after standardized transformation as \begin{align*} \mathbf{X^*} = \begin{bmatrix} 1& X_{11}& \ldots &X_{1,p-1} \\ 1& X_{21}& \ldots &X_{2,p-1} \\ \vdots & \vdots & \vdots & \vdots \\ 1& X_{n1}& \ldots &X_{n,p-1} \\ \end{bmatrix}. \end{align*} Then \begin{align*} \mathbf{X^{*'}X^*} = \begin{bmatrix} n & \mathbf{0}' \\ \mathbf{0} & \mathbf{r}_{XX} \end{bmatrix}, \end{align*} where $\mathbf{r}_{XX}$ is the correlation matrix of $X$ variables. We also know that \begin{align*} \sigma^2\{\hat{\beta}\} & = \sigma^2 (\mathbf{X^{*'}X^*})^{-1}\\ & = \sigma^2 \begin{bmatrix} \frac{1}{n} & \mathbf{0}' \\ \mathbf{0} & \mathbf{r}^{-1}_{XX}. \end{bmatrix}\\ \end{align*} $VIF_k$ for $k=1,2,\ldots,p-1$ is the $k$-th diagonal term of $\mathbf{r}^{-1}_{XX}$. We only need to prove this for $k = 1$ because you can permute the rows and columns of $r_{XX}$ to get the result for other $k$. Let's define: \begin{align*} \mathbf{X}_{(-1)} = \begin{bmatrix} X_{12}&\ldots&X_{1,p-1} \\X_{22}&\ldots&X_{2,p-1}\\ \vdots & \vdots & \vdots \\ X_{n2}&\ldots&X_{n,p-1} \\ \end{bmatrix}, \mathbf{X}_1 = \begin{bmatrix} X_{11} \\ X_{21} \\ \vdots \\ X_{n1} \\ \end{bmatrix}. \end{align*} Note that both matrices are different from design matrices. Since we only care about the coefficients of $X$ variables, the $1$-vector of a design matrix can be ignored in our calculation. Hence, by using Schur's complement, \begin{align*} r^{-1}_{XX} (1,1) & = (r_{11} - r_{1\mathbf{X}_{(-1)}} r^{-1}_{\mathbf{X}_{(-1)}\mathbf{X}_{(-1)}} r_{\mathbf{X}_{(-1)}1})^{-1} \\ & = (r_{11} - [r_{1\mathbf{X}_{(-1)}} r^{-1}_{\mathbf{X}_{(-1)}\mathbf{X}_{(-1)}}] r_{\mathbf{X}_{(-1)}\mathbf{X}_{(-1)}} [r^{-1}_{\mathbf{X}_{(-1)}\mathbf{X}_{(-1)}} r_{\mathbf{X}_{(-1)}1}])^{-1} \\ & = (1-\beta_{1\mathbf{X}_{(-1)}}' \mathbf{X}_{(-1)}' \mathbf{X}_{(-1)} \beta_{1\mathbf{X}_{(-1)}} )^{-1}, \end{align*} where $\beta_{1\mathbf{X}_{(-1)}}$ is the regression coefficients of $X_1$ on $X_2, \ldots, X_{p-1}$ except the intercept. In fact, the intercept should be the origin, since all $X$ variables are standardized with mean zero. On the other hand, (it would be more straightforward if we can write everything in explicit matrix form) \begin{align*} R_1^2 & = \frac{SSR}{SSTO} = \frac{\beta_{1\mathbf{X}_{(-1)}}' \mathbf{X}_{(-1)}' \mathbf{X}_{(-1)} \beta_{1\mathbf{X}_{(-1)}}}{1} \\ & = \beta_{1\mathbf{X}_{(-1)}}' \mathbf{X}_{(-1)}' \mathbf{X}_{(-1)} \beta_{1\mathbf{X}_{(-1)}}. \end{align*} Therefore \begin{align*} VIF_1 = r^{-1}_{XX} (1,1) = \frac{1}{1-R_1^2}. \end{align*}
Equation for the variance inflation factors Assume all $X$ variables are standardized by the correlation transformation, like you mentioned, unit length scaled version of $\mathbf{X}$. The standardized model does not change the correlation betw
35,370
Variance of gradient as e.g. in SGD
I gave this issue some more thoughts and came to the following conclusion: Most of the papers that deal with variance reduction for SGD (methods such as SVRG, SAGA, and SAG) actually mean the 1-norm of the variance of the gradients (trace of cov-matrix) when they write $\operatorname{Var}(g)$. Assuming that the stochastic gradients $g \in \mathbb{R}^p$ are unbiased estimator of the true gradient we have: \begin{equation} \begin{aligned} \| \text{diag}(\operatorname{Cov}(g))\|_1= \|\operatorname{Var}(g)\|_1=&|\operatorname{E}(g^1-\nabla f^1)^2|+...+ |\operatorname{E}(g^p-\nabla f^p)^2| \\ =& \operatorname{E}((g^1-\nabla f^1)^2+...+(g^p-\nabla f^p)^2) \\=&\operatorname{E}(\|g-\nabla f\|_2^2)\\=&\operatorname{E}(\|g\|^2)-\|\nabla f\|^2\\=&\operatorname{E}(\|g\|^2)-\|\operatorname{E}(g) \|^2\\ \overset{def}{=}& \operatorname{Var}(g) \end{aligned} \end{equation}
Variance of gradient as e.g. in SGD
I gave this issue some more thoughts and came to the following conclusion: Most of the papers that deal with variance reduction for SGD (methods such as SVRG, SAGA, and SAG) actually mean the 1-norm o
Variance of gradient as e.g. in SGD I gave this issue some more thoughts and came to the following conclusion: Most of the papers that deal with variance reduction for SGD (methods such as SVRG, SAGA, and SAG) actually mean the 1-norm of the variance of the gradients (trace of cov-matrix) when they write $\operatorname{Var}(g)$. Assuming that the stochastic gradients $g \in \mathbb{R}^p$ are unbiased estimator of the true gradient we have: \begin{equation} \begin{aligned} \| \text{diag}(\operatorname{Cov}(g))\|_1= \|\operatorname{Var}(g)\|_1=&|\operatorname{E}(g^1-\nabla f^1)^2|+...+ |\operatorname{E}(g^p-\nabla f^p)^2| \\ =& \operatorname{E}((g^1-\nabla f^1)^2+...+(g^p-\nabla f^p)^2) \\=&\operatorname{E}(\|g-\nabla f\|_2^2)\\=&\operatorname{E}(\|g\|^2)-\|\nabla f\|^2\\=&\operatorname{E}(\|g\|^2)-\|\operatorname{E}(g) \|^2\\ \overset{def}{=}& \operatorname{Var}(g) \end{aligned} \end{equation}
Variance of gradient as e.g. in SGD I gave this issue some more thoughts and came to the following conclusion: Most of the papers that deal with variance reduction for SGD (methods such as SVRG, SAGA, and SAG) actually mean the 1-norm o
35,371
In MLE for continuous rv, why is it ok to evaluate a pdf at a point?
Intuitively, @dsaxton's answer provides the correct logic. Let me just "translate" it to math language. Suppose the sample $Y_1, \ldots, Y_n \text{ i.i.d.} \sim f_\theta(y)$, $\theta \in \Theta$, where $\Theta$ is the parameter space and $f_\theta(\cdot)$ are density functions. After a vector of observations $y = (y_1, \ldots, y_n)'$ has been made, the maximum likelihood principle aims to look for an estimator $\hat{\theta} \in \Theta$ such that for any $\delta > 0$, the probability \begin{equation} P_{\hat{\theta}}[(Y_1, \ldots, Y_n) \in (y_1 - \delta, y_1 + \delta) \times \cdots \times (y_n - \delta, y_n + \delta)] \tag{1} \end{equation} is the maximum over $\theta \in \Theta$, which suggests us considering the quantity \begin{equation} L(\theta, \delta) \equiv P_{\theta}[(Y_1, \ldots, Y_n) \in (y_1 - \delta, y_1 + \delta) \times \cdots \times (y_n - \delta, y_n + \delta)], \quad \theta \in \Theta.\tag{2} \end{equation} Note that from the statistical inference point of view, the probability in $(2)$ should be viewed as a function of $\theta$. We now simplify $(2)$ by invoking the i.i.d. assumption and that $P_\theta$ has density $f_\theta$. Clearly, $$L(\theta, \delta) = \prod_{i = 1}^n P_\theta[y_i - \delta < Y_i < y_i + \delta] = \prod_{i = 1}^n \int_{y_i - \delta}^{y_i + \delta}f_\theta(y) dy. \tag{3}$$ What we need to show, thus answer your question is: if $\hat{\theta}$ maximizes $L(\theta, \delta)$ with respect to $\theta \in \Theta$ for any $\delta > 0$, then it also maximizes the so-called likelihood function $$L(\theta) = \prod_{i = 1}^n f_{\theta}(y_i). \tag{4}$$ So let's start with assuming for any $\delta > 0$, $$L(\hat{\theta}, \delta) \geq L(\theta, \delta), \quad \forall \theta \in \Theta. \tag{5}$$ Divide both sides of $(5)$ by $(2\delta)^n$, then let $\delta \downarrow 0$ gives $$\prod_{i = 1}^n f_{\hat{\theta}}(y_i) \geq \prod_{i = 1}^n f_{\theta}(y_i), \quad \forall \theta \in \Theta,$$ which is precisely $L(\hat{\theta}) \geq L(\theta), \forall \theta \in \Theta$. In other words, maximizing the so-called likelihood function $(4)$ (which is a product of densities) is a necessary condition of carrying out the maximum likelihood principle. From this point of view, the form of densities multiplication makes sense. Above is just my own interpretation, any comment or critic is very welcomed.
In MLE for continuous rv, why is it ok to evaluate a pdf at a point?
Intuitively, @dsaxton's answer provides the correct logic. Let me just "translate" it to math language. Suppose the sample $Y_1, \ldots, Y_n \text{ i.i.d.} \sim f_\theta(y)$, $\theta \in \Theta$, wher
In MLE for continuous rv, why is it ok to evaluate a pdf at a point? Intuitively, @dsaxton's answer provides the correct logic. Let me just "translate" it to math language. Suppose the sample $Y_1, \ldots, Y_n \text{ i.i.d.} \sim f_\theta(y)$, $\theta \in \Theta$, where $\Theta$ is the parameter space and $f_\theta(\cdot)$ are density functions. After a vector of observations $y = (y_1, \ldots, y_n)'$ has been made, the maximum likelihood principle aims to look for an estimator $\hat{\theta} \in \Theta$ such that for any $\delta > 0$, the probability \begin{equation} P_{\hat{\theta}}[(Y_1, \ldots, Y_n) \in (y_1 - \delta, y_1 + \delta) \times \cdots \times (y_n - \delta, y_n + \delta)] \tag{1} \end{equation} is the maximum over $\theta \in \Theta$, which suggests us considering the quantity \begin{equation} L(\theta, \delta) \equiv P_{\theta}[(Y_1, \ldots, Y_n) \in (y_1 - \delta, y_1 + \delta) \times \cdots \times (y_n - \delta, y_n + \delta)], \quad \theta \in \Theta.\tag{2} \end{equation} Note that from the statistical inference point of view, the probability in $(2)$ should be viewed as a function of $\theta$. We now simplify $(2)$ by invoking the i.i.d. assumption and that $P_\theta$ has density $f_\theta$. Clearly, $$L(\theta, \delta) = \prod_{i = 1}^n P_\theta[y_i - \delta < Y_i < y_i + \delta] = \prod_{i = 1}^n \int_{y_i - \delta}^{y_i + \delta}f_\theta(y) dy. \tag{3}$$ What we need to show, thus answer your question is: if $\hat{\theta}$ maximizes $L(\theta, \delta)$ with respect to $\theta \in \Theta$ for any $\delta > 0$, then it also maximizes the so-called likelihood function $$L(\theta) = \prod_{i = 1}^n f_{\theta}(y_i). \tag{4}$$ So let's start with assuming for any $\delta > 0$, $$L(\hat{\theta}, \delta) \geq L(\theta, \delta), \quad \forall \theta \in \Theta. \tag{5}$$ Divide both sides of $(5)$ by $(2\delta)^n$, then let $\delta \downarrow 0$ gives $$\prod_{i = 1}^n f_{\hat{\theta}}(y_i) \geq \prod_{i = 1}^n f_{\theta}(y_i), \quad \forall \theta \in \Theta,$$ which is precisely $L(\hat{\theta}) \geq L(\theta), \forall \theta \in \Theta$. In other words, maximizing the so-called likelihood function $(4)$ (which is a product of densities) is a necessary condition of carrying out the maximum likelihood principle. From this point of view, the form of densities multiplication makes sense. Above is just my own interpretation, any comment or critic is very welcomed.
In MLE for continuous rv, why is it ok to evaluate a pdf at a point? Intuitively, @dsaxton's answer provides the correct logic. Let me just "translate" it to math language. Suppose the sample $Y_1, \ldots, Y_n \text{ i.i.d.} \sim f_\theta(y)$, $\theta \in \Theta$, wher
35,372
In MLE for continuous rv, why is it ok to evaluate a pdf at a point?
It's not "incorrect" to look at a density function at a specific point. If it were, what's the point of the function? What you may have heard is that a density function at a given point is not to be interpreted as a probability, but that doesn't make it unimportant. The density function tells you how "tightly packed" probability is around a certain point, or how likely a random variable is to be close to the given value, and this idea extends to random samples as well. In the case of maximum likelihood estimation what we're doing then is finding a value for a parameter that causes the sample to belong to a "neighborhood" of high probability, relative to other regions of the sample space.
In MLE for continuous rv, why is it ok to evaluate a pdf at a point?
It's not "incorrect" to look at a density function at a specific point. If it were, what's the point of the function? What you may have heard is that a density function at a given point is not to be
In MLE for continuous rv, why is it ok to evaluate a pdf at a point? It's not "incorrect" to look at a density function at a specific point. If it were, what's the point of the function? What you may have heard is that a density function at a given point is not to be interpreted as a probability, but that doesn't make it unimportant. The density function tells you how "tightly packed" probability is around a certain point, or how likely a random variable is to be close to the given value, and this idea extends to random samples as well. In the case of maximum likelihood estimation what we're doing then is finding a value for a parameter that causes the sample to belong to a "neighborhood" of high probability, relative to other regions of the sample space.
In MLE for continuous rv, why is it ok to evaluate a pdf at a point? It's not "incorrect" to look at a density function at a specific point. If it were, what's the point of the function? What you may have heard is that a density function at a given point is not to be
35,373
Is this a Monte Carlo simulation?
This is a Monte Carlo simulation, though I doubt it's doing what you want, and really is of no practical use. What you are comparing is 10000 single sample studies and determining how many of these individual observed values are on average higher. So, it's probably better to conceptualize your code as the following less efficient code: runs <- 10000 result <- logical(runs) for(i in 1:runs){ a <- rnorm(1, mean = 0) b <- rnorm(1, mean = 0) result[i] <- a > b } mc.p.value <- mean(result) The above code, when the distributions are equal, should show that $a$ is higher than $b$ 50% of the time, but this type of result is essentially useless in practice because you would only have $N=2$, and statistical inferences are not applicable (i.e., there is no variance within each group available to quantify sampling uncertainty). What you are missing is comparing two summary statistics of interest to determine their sampling properties, which is generally the topic of statistical inference and requires at least a minimum number of data points to quantify some form of sampling uncertainty. As it stands this is generally a standard independent $t$-test set-up. So, you could compare a number of things, such as how often the first group mean is higher than the second, how often a $t$-test gives a $p < \alpha$ result (or analogously, how often the $|t|$ ratio is greater than the cut-off), and so on. E.g., If $n=20$ for each group and the distributions are equal in the population then runs <- 10000 n <- 20 alpha <- .05 result.p <- result.mean <- numeric(runs) for(i in 1:runs){ a <- rnorm(n, mean = 0) b <- rnorm(n, mean = 0) result.mean[i] <- mean(a) > mean(b) result.p[i] <- t.test(a, b)$p.value } mc.p.value <- mean(result.p < alpha) mc.a_gt_b.value <- mean(result.mean) Playing around with the other parameters, such as changing the first group mean to 1, will change the nature of the simulation (changing it from a Type I error simulation, as it is now, to a power study).
Is this a Monte Carlo simulation?
This is a Monte Carlo simulation, though I doubt it's doing what you want, and really is of no practical use. What you are comparing is 10000 single sample studies and determining how many of these in
Is this a Monte Carlo simulation? This is a Monte Carlo simulation, though I doubt it's doing what you want, and really is of no practical use. What you are comparing is 10000 single sample studies and determining how many of these individual observed values are on average higher. So, it's probably better to conceptualize your code as the following less efficient code: runs <- 10000 result <- logical(runs) for(i in 1:runs){ a <- rnorm(1, mean = 0) b <- rnorm(1, mean = 0) result[i] <- a > b } mc.p.value <- mean(result) The above code, when the distributions are equal, should show that $a$ is higher than $b$ 50% of the time, but this type of result is essentially useless in practice because you would only have $N=2$, and statistical inferences are not applicable (i.e., there is no variance within each group available to quantify sampling uncertainty). What you are missing is comparing two summary statistics of interest to determine their sampling properties, which is generally the topic of statistical inference and requires at least a minimum number of data points to quantify some form of sampling uncertainty. As it stands this is generally a standard independent $t$-test set-up. So, you could compare a number of things, such as how often the first group mean is higher than the second, how often a $t$-test gives a $p < \alpha$ result (or analogously, how often the $|t|$ ratio is greater than the cut-off), and so on. E.g., If $n=20$ for each group and the distributions are equal in the population then runs <- 10000 n <- 20 alpha <- .05 result.p <- result.mean <- numeric(runs) for(i in 1:runs){ a <- rnorm(n, mean = 0) b <- rnorm(n, mean = 0) result.mean[i] <- mean(a) > mean(b) result.p[i] <- t.test(a, b)$p.value } mc.p.value <- mean(result.p < alpha) mc.a_gt_b.value <- mean(result.mean) Playing around with the other parameters, such as changing the first group mean to 1, will change the nature of the simulation (changing it from a Type I error simulation, as it is now, to a power study).
Is this a Monte Carlo simulation? This is a Monte Carlo simulation, though I doubt it's doing what you want, and really is of no practical use. What you are comparing is 10000 single sample studies and determining how many of these in
35,374
Deep Learning: Use L2 and Dropout Regularization Simultaneously?
The paper {1} that introduced dropout combined dropout with L2: We found that dropout combined with max-norm regularization gives the lowest generalization error. {1} Srivastava, Nitish, Geoffrey E. Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdinov. "Dropout: a simple way to prevent neural networks from overfitting." Journal of Machine Learning Research 15, no. 1 (2014): 1929-1958. http://jmlr.org/papers/volume15/srivastava14a.old/srivastava14a.pdf
Deep Learning: Use L2 and Dropout Regularization Simultaneously?
The paper {1} that introduced dropout combined dropout with L2: We found that dropout combined with max-norm regularization gives the lowest generalization error. {1} Srivastava, Nitish, Geoffr
Deep Learning: Use L2 and Dropout Regularization Simultaneously? The paper {1} that introduced dropout combined dropout with L2: We found that dropout combined with max-norm regularization gives the lowest generalization error. {1} Srivastava, Nitish, Geoffrey E. Hinton, Alex Krizhevsky, Ilya Sutskever, and Ruslan Salakhutdinov. "Dropout: a simple way to prevent neural networks from overfitting." Journal of Machine Learning Research 15, no. 1 (2014): 1929-1958. http://jmlr.org/papers/volume15/srivastava14a.old/srivastava14a.pdf
Deep Learning: Use L2 and Dropout Regularization Simultaneously? The paper {1} that introduced dropout combined dropout with L2: We found that dropout combined with max-norm regularization gives the lowest generalization error. {1} Srivastava, Nitish, Geoffr
35,375
If $X_n ∼ N(0, 1/n)$, then why is $\sqrt{n}X_n ∼ N(0, 1)$?
Because the variance is a second-order moment, related to squaring, so a factor gets squared. More precisely, since the expectation is a linear operation, in general, if you have a centered $d$-order moment (yours is a $2$-order moment): $$\mu_{d}(X)=\operatorname {E} \left[X^{d}\right]=\int _{-\infty }^{\infty }x^{d}\,dF(x)\,$$ multiplying $X$ by a constant results in getting that constant outside the integral, affected with power $d$ (as long as the integral is properly defined): $$\mu_{d}(aX) = a^d \mu_{d}(X)\,.$$ So if you multiply $X$ by $\sqrt{n}$, the variance (power of two moment) of $X$ is multiplied by $(\sqrt{n})^2$. The mean is a first-order moment, so you would multiply it by $\sqrt{n}$, and as it is $0$ for $X$, the resulting variable still has zero mean.
If $X_n ∼ N(0, 1/n)$, then why is $\sqrt{n}X_n ∼ N(0, 1)$?
Because the variance is a second-order moment, related to squaring, so a factor gets squared. More precisely, since the expectation is a linear operation, in general, if you have a centered $d$-orde
If $X_n ∼ N(0, 1/n)$, then why is $\sqrt{n}X_n ∼ N(0, 1)$? Because the variance is a second-order moment, related to squaring, so a factor gets squared. More precisely, since the expectation is a linear operation, in general, if you have a centered $d$-order moment (yours is a $2$-order moment): $$\mu_{d}(X)=\operatorname {E} \left[X^{d}\right]=\int _{-\infty }^{\infty }x^{d}\,dF(x)\,$$ multiplying $X$ by a constant results in getting that constant outside the integral, affected with power $d$ (as long as the integral is properly defined): $$\mu_{d}(aX) = a^d \mu_{d}(X)\,.$$ So if you multiply $X$ by $\sqrt{n}$, the variance (power of two moment) of $X$ is multiplied by $(\sqrt{n})^2$. The mean is a first-order moment, so you would multiply it by $\sqrt{n}$, and as it is $0$ for $X$, the resulting variable still has zero mean.
If $X_n ∼ N(0, 1/n)$, then why is $\sqrt{n}X_n ∼ N(0, 1)$? Because the variance is a second-order moment, related to squaring, so a factor gets squared. More precisely, since the expectation is a linear operation, in general, if you have a centered $d$-orde
35,376
If $X_n ∼ N(0, 1/n)$, then why is $\sqrt{n}X_n ∼ N(0, 1)$?
Suppose $X\sim N(\mu, \sigma^{2})$. Then, \begin{eqnarray*} X-\mu &\sim& N(0, \sigma^{2})\\ \frac{X-\mu}{\sigma}&\sim&N(0,1). \end{eqnarray*} Similarly, if $X_{1},X_{2},\cdots X_{n}$ is a random sample from $N(\mu,\sigma^{2})$, then the sample mean, \begin{eqnarray*} \bar{X}=\frac{1}{n}\sum_{i=1}^{n}X_{i}&\sim & N\left(\mu,\frac{\sigma^{2}}{n}\right)\\ \bar{X}-\mu &\sim& N\left(0,\frac{\sigma^{2}}{n}\right)\\ \frac{\sqrt{n}(\bar{X}-\mu)}{\sigma}&\sim&N(0,1) \end{eqnarray*}
If $X_n ∼ N(0, 1/n)$, then why is $\sqrt{n}X_n ∼ N(0, 1)$?
Suppose $X\sim N(\mu, \sigma^{2})$. Then, \begin{eqnarray*} X-\mu &\sim& N(0, \sigma^{2})\\ \frac{X-\mu}{\sigma}&\sim&N(0,1). \end{eqnarray*} Similarly, if $X_{1},X_{2},\cdots X_{n}$ is a random sampl
If $X_n ∼ N(0, 1/n)$, then why is $\sqrt{n}X_n ∼ N(0, 1)$? Suppose $X\sim N(\mu, \sigma^{2})$. Then, \begin{eqnarray*} X-\mu &\sim& N(0, \sigma^{2})\\ \frac{X-\mu}{\sigma}&\sim&N(0,1). \end{eqnarray*} Similarly, if $X_{1},X_{2},\cdots X_{n}$ is a random sample from $N(\mu,\sigma^{2})$, then the sample mean, \begin{eqnarray*} \bar{X}=\frac{1}{n}\sum_{i=1}^{n}X_{i}&\sim & N\left(\mu,\frac{\sigma^{2}}{n}\right)\\ \bar{X}-\mu &\sim& N\left(0,\frac{\sigma^{2}}{n}\right)\\ \frac{\sqrt{n}(\bar{X}-\mu)}{\sigma}&\sim&N(0,1) \end{eqnarray*}
If $X_n ∼ N(0, 1/n)$, then why is $\sqrt{n}X_n ∼ N(0, 1)$? Suppose $X\sim N(\mu, \sigma^{2})$. Then, \begin{eqnarray*} X-\mu &\sim& N(0, \sigma^{2})\\ \frac{X-\mu}{\sigma}&\sim&N(0,1). \end{eqnarray*} Similarly, if $X_{1},X_{2},\cdots X_{n}$ is a random sampl
35,377
Setting up simulation algorithm to check calibration of Bayesian posterior probabilities
Simulation results will depend on how the parameter is sampled in the simulation. I don't think there is any dispute over whether the posterior probabilities will be calibrated (in the frequency sense) if the prior probabilities are, so I suspect a simulation will not convince anyone of anything new. Anyway, in the sequential sampling case mentioned in the question (third paragraph) can be simulated "as is" by drawing $\mu$ from the prior, drawing samples given this $\mu$ until $p(\mu>0\mid \textrm{samples})>0.95$ or some other termination criterion occurs (another termination criterion is needed since there is positive probability that the running posterior probability will never exceed $0.95$). Then, for every $p(\mu>0\mid \textrm{samples})>0.95$ claim, check whether the underlying sampled $\mu$-parameter is positive and count the number of true positives vs. false positives. So, for $i=1,2,\ldots$: Sample $\mu_i \sim N(\gamma, \tau^2)$ For $j=1,\ldots^\ast$: Sample $y_{i,j} \sim N(\mu_i, \sigma^2)$ Compute $p_{i,j} := P(\mu_i>0 \mid y_{i,1:j})$ If $p_{i,j}>0.95$ If $\mu_i>0$, increment true positive counter If $\mu_i\leq0$, increment false positive counter Break from the inner for loop $\ast$ some other breaking condition, such as $j\geq j_{\max}$ The ratio of true positives to all positives will be at least $0.95$, which demonstrates calibration of the $P(\mu>0 \mid D)>0.95$ claims. A slow-and-dirty Python implementation (bugs very possible + there is a potential stopping bias in that I debugged until I saw the expected calibration property holding). # (C) Juho Kokkala 2016 # MIT License import numpy as np np.random.seed(1) N = 10000 max_samples = 50 gamma = 0.1 tau = 2 sigma = 1 truehits = 0 falsehits = 0 p_positivemus = [] while truehits + falsehits < N: # Sample the parameter from prior mu = np.random.normal(gamma, tau) # For sequential updating of posterior gamma_post = gamma tau2_post = tau**2 for j in range(max_samples): # Sample data y_j = np.random.normal(mu, sigma) gamma_post = ( (gamma_post/(tau2_post) + y_j/(sigma**2)) / (1/tau2_post + 1/sigma**2) ) tau2_post = 1 / (1/tau2_post + 1/sigma**2) p_positivemu = 1 - stats.norm.cdf(0, loc=gamma_post, scale=np.sqrt(tau2_post)) if p_positivemu > 0.95: p_positivemus.append(p_positivemu) if mu>0: truehits += 1 else: falsehits +=1 if (truehits+falsehits)%1000 == 0: print(truehits / (truehits+falsehits)) print(truehits+falsehits) break print(truehits / (truehits+falsehits)) print(np.mean(p_positivemus)) I got $0.9807$ for the proportion of true positives to all claims. This is over $0.95$ as the posterior probability will not hit exactly $0.95$. For this reason the code tracks also the mean "claimed" posterior probability, for which I got $0.9804$. One could also change the prior parameters $\gamma,\tau$ for every $i$ to demonstrate a calibration "over all inferences" (if the priors are calibrated). On the other hand, one could perform the posterior updates starting from "wrong" prior hyperparameters (different than what are used in drawing the ground-truth parameter), in which case the calibration might not hold.
Setting up simulation algorithm to check calibration of Bayesian posterior probabilities
Simulation results will depend on how the parameter is sampled in the simulation. I don't think there is any dispute over whether the posterior probabilities will be calibrated (in the frequency sense
Setting up simulation algorithm to check calibration of Bayesian posterior probabilities Simulation results will depend on how the parameter is sampled in the simulation. I don't think there is any dispute over whether the posterior probabilities will be calibrated (in the frequency sense) if the prior probabilities are, so I suspect a simulation will not convince anyone of anything new. Anyway, in the sequential sampling case mentioned in the question (third paragraph) can be simulated "as is" by drawing $\mu$ from the prior, drawing samples given this $\mu$ until $p(\mu>0\mid \textrm{samples})>0.95$ or some other termination criterion occurs (another termination criterion is needed since there is positive probability that the running posterior probability will never exceed $0.95$). Then, for every $p(\mu>0\mid \textrm{samples})>0.95$ claim, check whether the underlying sampled $\mu$-parameter is positive and count the number of true positives vs. false positives. So, for $i=1,2,\ldots$: Sample $\mu_i \sim N(\gamma, \tau^2)$ For $j=1,\ldots^\ast$: Sample $y_{i,j} \sim N(\mu_i, \sigma^2)$ Compute $p_{i,j} := P(\mu_i>0 \mid y_{i,1:j})$ If $p_{i,j}>0.95$ If $\mu_i>0$, increment true positive counter If $\mu_i\leq0$, increment false positive counter Break from the inner for loop $\ast$ some other breaking condition, such as $j\geq j_{\max}$ The ratio of true positives to all positives will be at least $0.95$, which demonstrates calibration of the $P(\mu>0 \mid D)>0.95$ claims. A slow-and-dirty Python implementation (bugs very possible + there is a potential stopping bias in that I debugged until I saw the expected calibration property holding). # (C) Juho Kokkala 2016 # MIT License import numpy as np np.random.seed(1) N = 10000 max_samples = 50 gamma = 0.1 tau = 2 sigma = 1 truehits = 0 falsehits = 0 p_positivemus = [] while truehits + falsehits < N: # Sample the parameter from prior mu = np.random.normal(gamma, tau) # For sequential updating of posterior gamma_post = gamma tau2_post = tau**2 for j in range(max_samples): # Sample data y_j = np.random.normal(mu, sigma) gamma_post = ( (gamma_post/(tau2_post) + y_j/(sigma**2)) / (1/tau2_post + 1/sigma**2) ) tau2_post = 1 / (1/tau2_post + 1/sigma**2) p_positivemu = 1 - stats.norm.cdf(0, loc=gamma_post, scale=np.sqrt(tau2_post)) if p_positivemu > 0.95: p_positivemus.append(p_positivemu) if mu>0: truehits += 1 else: falsehits +=1 if (truehits+falsehits)%1000 == 0: print(truehits / (truehits+falsehits)) print(truehits+falsehits) break print(truehits / (truehits+falsehits)) print(np.mean(p_positivemus)) I got $0.9807$ for the proportion of true positives to all claims. This is over $0.95$ as the posterior probability will not hit exactly $0.95$. For this reason the code tracks also the mean "claimed" posterior probability, for which I got $0.9804$. One could also change the prior parameters $\gamma,\tau$ for every $i$ to demonstrate a calibration "over all inferences" (if the priors are calibrated). On the other hand, one could perform the posterior updates starting from "wrong" prior hyperparameters (different than what are used in drawing the ground-truth parameter), in which case the calibration might not hold.
Setting up simulation algorithm to check calibration of Bayesian posterior probabilities Simulation results will depend on how the parameter is sampled in the simulation. I don't think there is any dispute over whether the posterior probabilities will be calibrated (in the frequency sense
35,378
Setting up simulation algorithm to check calibration of Bayesian posterior probabilities
Expanding on the excellent answer by @juho-kokkala and using R here are the results. For a prior distribution for the population mean mu I used an equal mixture of two normals with mean zero, one of them very skeptical about large means. ## Posterior density for a normal data distribution and for ## a mixture of two normal priors with mixing proportions wt and 1-wt ## and means mu1 mu2 and variances v1 an ## Adapted for LearnBayes package normal.normal.mix function ## Produces a list of 3 functions. The posterior density and cum. prob. ## function can be called with a vector of posterior means and variances ## if the first argument x is a scalar mixpost <- function(stat, vstat, mu1=0, mu2=0, v1, v2, wt) { if(length(stat) + length(vstat) != 2) stop('improper arguments') probs <- c(wt, 1. - wt) prior.mean <- c(mu1, mu2) prior.var <- c(v1, v2) post.precision <- 1. / prior.var + 1. / vstat post.var <- 1. / post.precision post.mean <- (stat / vstat + prior.mean / prior.var) / post.precision pwt <- dnorm(stat, prior.mean, sqrt(vstat + prior.var)) pwt <- probs * pwt / sum(probs * pwt) dMix <- function(x, pwt, post.mean, post.var) pwt[1] * dnorm(x, mean=post.mean[1], sd=sqrt(post.var[1])) + pwt[2] * dnorm(x, mean=post.mean[2], sd=sqrt(post.var[2])) formals(dMix) <- z <- list(x=NULL, pwt=pwt, post.mean=post.mean, post.var=post.var) pMix <- function(x, pwt, post.mean, post.var) pwt[1] * pnorm(x, mean=post.mean[1], sd=sqrt(post.var[1])) + pwt[2] * pnorm(x, mean=post.mean[2], sd=sqrt(post.var[2])) formals(pMix) <- z priorMix <- function(x, mu1, mu2, v1, v2, wt) wt * dnorm(x, mean=mu1, sd=sqrt(v1)) + (1. - wt) * dnorm(x, mean=mu2, sd=sqrt(v2)) formals(priorMix) <- list(x=NULL, mu1=mu1, mu2=mu2, v1=v1, v2=v2, wt=wt) list(priorMix=priorMix, dMix=dMix, pMix=pMix) } ## mixposts handles the case where the posterior distribution function ## is to be evaluated at a scalar x for a vector of point estimates and ## variances of the statistic of interest ## If generates a single function mixposts <- function(stat, vstat, mu1=0, mu2=0, v1, v2, wt) { post.precision1 <- 1. / v1 + 1. / vstat post.var1 <- 1. / post.precision1 post.mean1 <- (stat / vstat + mu1 / v1) / post.precision1 post.precision2 <- 1. / v2 + 1. / vstat post.var2 <- 1. / post.precision2 post.mean2 <- (stat / vstat + mu2 / v2) / post.precision2 pwt1 <- dnorm(stat, mean=mu1, sd=sqrt(vstat + v1)) pwt2 <- dnorm(stat, mean=mu2, sd=sqrt(vstat + v2)) pwt <- wt * pwt1 / (wt * pwt1 + (1. - wt) * pwt2) pMix <- function(x, post.mean1, post.mean2, post.var1, post.var2, pwt) pwt * pnorm(x, mean=post.mean1, sd=sqrt(post.var1)) + (1. - pwt) * pnorm(x, mean=post.mean2, sd=sqrt(post.var2)) formals(pMix) <- list(x=NULL, post.mean1=post.mean1, post.mean2=post.mean2, post.var1=post.var1, post.var2=post.var2, pwt=pwt) pMix } ## Compute proportion mu > 0 in trials for ## which posterior prob(mu > 0) > 0.95, and also use a loess smoother ## to estimate prob(mu > 0) as a function of the final post prob ## In sequential analyses of observations 1, 2, ..., N, the final ## posterior prob is the post prob at the final sample size if the ## prob never exceeds 0.95, otherwise it is the post prob the first ## time it exceeds 0.95 sim <- function(N, prior.mu=0, prior.sd, wt, mucut=0, postcut=0.95, nsim=1000, plprior=TRUE) { prior.mu <- rep(prior.mu, length=2) prior.sd <- rep(prior.sd, length=2) sd1 <- prior.sd[1]; sd2 <- prior.sd[2] v1 <- sd1 ^ 2 v2 <- sd2 ^ 2 if(plprior) { pdensity <- mixpost(1, 1, mu1=prior.mu[1], mu2=prior.mu[2], v1=v1, v2=v2, wt=wt)$priorMix x <- seq(-3, 3, length=200) plot(x, pdensity(x), type='l', xlab=expression(mu), ylab='Prior Density') title(paste(wt, 1 - wt, 'Mixture of Zero Mean Normals\nWith SD=', round(sd1, 3), 'and', round(sd2, 3))) } j <- 1 : N Mu <- Post <- numeric(nsim) stopped <- integer(nsim) for(i in 1 : nsim) { # See http://stats.stackexchange.com/questions/70855 component <- sample(1 : 2, size=1, prob=c(wt, 1. - wt)) mu <- prior.mu[component] + rnorm(1) * prior.sd[component] # mu <- rnorm(1, mean=prior.mu, sd=prior.sd) if only 1 component Mu[i] <- mu y <- rnorm(N, mean=mu, sd=1) ybar <- cumsum(y) / j pcdf <- mixposts(ybar, 1. / j, mu1=prior.mu[1], mu2=prior.mu[2], v1=v1, v2=v2, wt=wt) if(i==1) print(body(pcdf)) post <- 1. - pcdf(mucut) Post[i] <- if(max(post) < postcut) post[N] else post[min(which(post >= postcut))] stopped[i] <- if(max(post) < postcut) N else min(which(post >= postcut)) } list(mu=Mu, post=Post, stopped=stopped) } # Take prior on mu to be a mixture of two normal densities both with mean zero # One has SD so that Prob(mu > 1) = 0.1 # The second has SD so that Prob(mu > 0.25) = 0.05 prior.sd <- c(1 / qnorm(1 - 0.1), 0.25 / qnorm(1 - 0.05)) prior.sd set.seed(2) z <- sim(500, prior.mu=0, prior.sd=prior.sd, wt=0.5, postcut=0.95, nsim=10000) mu <- z$mu post <- z$post st <- z$stopped plot(mu, post) abline(v=0, col=gray(.8)); abline(h=0.95, col=gray(.8)) hist(mu[post >= 0.95], nclass=25) k <- post >= 0.95 mean(k) # 0.44 of trials stopped with post >= 0.95 mean(st) # 313 average sample size mean(mu[k] > 0) # 0.963 of trials with post >= 0.95 actually had mu > 0 mean(post[k]) # 0.961 mean posterior prob. when stopped early w <- lowess(post, mu > 0, iter=0) # perfect calibration of post probs plot(w, type='n', # even if stopped early xlab=expression(paste('Posterior Probability ', mu > 0, ' Upon Stopping')), ylab=expression(paste('Proportion of Trials with ', mu > 0))) abline(a=0, b=1, lwd=6, col=gray(.85)) lines(w)
Setting up simulation algorithm to check calibration of Bayesian posterior probabilities
Expanding on the excellent answer by @juho-kokkala and using R here are the results. For a prior distribution for the population mean mu I used an equal mixture of two normals with mean zero, one of
Setting up simulation algorithm to check calibration of Bayesian posterior probabilities Expanding on the excellent answer by @juho-kokkala and using R here are the results. For a prior distribution for the population mean mu I used an equal mixture of two normals with mean zero, one of them very skeptical about large means. ## Posterior density for a normal data distribution and for ## a mixture of two normal priors with mixing proportions wt and 1-wt ## and means mu1 mu2 and variances v1 an ## Adapted for LearnBayes package normal.normal.mix function ## Produces a list of 3 functions. The posterior density and cum. prob. ## function can be called with a vector of posterior means and variances ## if the first argument x is a scalar mixpost <- function(stat, vstat, mu1=0, mu2=0, v1, v2, wt) { if(length(stat) + length(vstat) != 2) stop('improper arguments') probs <- c(wt, 1. - wt) prior.mean <- c(mu1, mu2) prior.var <- c(v1, v2) post.precision <- 1. / prior.var + 1. / vstat post.var <- 1. / post.precision post.mean <- (stat / vstat + prior.mean / prior.var) / post.precision pwt <- dnorm(stat, prior.mean, sqrt(vstat + prior.var)) pwt <- probs * pwt / sum(probs * pwt) dMix <- function(x, pwt, post.mean, post.var) pwt[1] * dnorm(x, mean=post.mean[1], sd=sqrt(post.var[1])) + pwt[2] * dnorm(x, mean=post.mean[2], sd=sqrt(post.var[2])) formals(dMix) <- z <- list(x=NULL, pwt=pwt, post.mean=post.mean, post.var=post.var) pMix <- function(x, pwt, post.mean, post.var) pwt[1] * pnorm(x, mean=post.mean[1], sd=sqrt(post.var[1])) + pwt[2] * pnorm(x, mean=post.mean[2], sd=sqrt(post.var[2])) formals(pMix) <- z priorMix <- function(x, mu1, mu2, v1, v2, wt) wt * dnorm(x, mean=mu1, sd=sqrt(v1)) + (1. - wt) * dnorm(x, mean=mu2, sd=sqrt(v2)) formals(priorMix) <- list(x=NULL, mu1=mu1, mu2=mu2, v1=v1, v2=v2, wt=wt) list(priorMix=priorMix, dMix=dMix, pMix=pMix) } ## mixposts handles the case where the posterior distribution function ## is to be evaluated at a scalar x for a vector of point estimates and ## variances of the statistic of interest ## If generates a single function mixposts <- function(stat, vstat, mu1=0, mu2=0, v1, v2, wt) { post.precision1 <- 1. / v1 + 1. / vstat post.var1 <- 1. / post.precision1 post.mean1 <- (stat / vstat + mu1 / v1) / post.precision1 post.precision2 <- 1. / v2 + 1. / vstat post.var2 <- 1. / post.precision2 post.mean2 <- (stat / vstat + mu2 / v2) / post.precision2 pwt1 <- dnorm(stat, mean=mu1, sd=sqrt(vstat + v1)) pwt2 <- dnorm(stat, mean=mu2, sd=sqrt(vstat + v2)) pwt <- wt * pwt1 / (wt * pwt1 + (1. - wt) * pwt2) pMix <- function(x, post.mean1, post.mean2, post.var1, post.var2, pwt) pwt * pnorm(x, mean=post.mean1, sd=sqrt(post.var1)) + (1. - pwt) * pnorm(x, mean=post.mean2, sd=sqrt(post.var2)) formals(pMix) <- list(x=NULL, post.mean1=post.mean1, post.mean2=post.mean2, post.var1=post.var1, post.var2=post.var2, pwt=pwt) pMix } ## Compute proportion mu > 0 in trials for ## which posterior prob(mu > 0) > 0.95, and also use a loess smoother ## to estimate prob(mu > 0) as a function of the final post prob ## In sequential analyses of observations 1, 2, ..., N, the final ## posterior prob is the post prob at the final sample size if the ## prob never exceeds 0.95, otherwise it is the post prob the first ## time it exceeds 0.95 sim <- function(N, prior.mu=0, prior.sd, wt, mucut=0, postcut=0.95, nsim=1000, plprior=TRUE) { prior.mu <- rep(prior.mu, length=2) prior.sd <- rep(prior.sd, length=2) sd1 <- prior.sd[1]; sd2 <- prior.sd[2] v1 <- sd1 ^ 2 v2 <- sd2 ^ 2 if(plprior) { pdensity <- mixpost(1, 1, mu1=prior.mu[1], mu2=prior.mu[2], v1=v1, v2=v2, wt=wt)$priorMix x <- seq(-3, 3, length=200) plot(x, pdensity(x), type='l', xlab=expression(mu), ylab='Prior Density') title(paste(wt, 1 - wt, 'Mixture of Zero Mean Normals\nWith SD=', round(sd1, 3), 'and', round(sd2, 3))) } j <- 1 : N Mu <- Post <- numeric(nsim) stopped <- integer(nsim) for(i in 1 : nsim) { # See http://stats.stackexchange.com/questions/70855 component <- sample(1 : 2, size=1, prob=c(wt, 1. - wt)) mu <- prior.mu[component] + rnorm(1) * prior.sd[component] # mu <- rnorm(1, mean=prior.mu, sd=prior.sd) if only 1 component Mu[i] <- mu y <- rnorm(N, mean=mu, sd=1) ybar <- cumsum(y) / j pcdf <- mixposts(ybar, 1. / j, mu1=prior.mu[1], mu2=prior.mu[2], v1=v1, v2=v2, wt=wt) if(i==1) print(body(pcdf)) post <- 1. - pcdf(mucut) Post[i] <- if(max(post) < postcut) post[N] else post[min(which(post >= postcut))] stopped[i] <- if(max(post) < postcut) N else min(which(post >= postcut)) } list(mu=Mu, post=Post, stopped=stopped) } # Take prior on mu to be a mixture of two normal densities both with mean zero # One has SD so that Prob(mu > 1) = 0.1 # The second has SD so that Prob(mu > 0.25) = 0.05 prior.sd <- c(1 / qnorm(1 - 0.1), 0.25 / qnorm(1 - 0.05)) prior.sd set.seed(2) z <- sim(500, prior.mu=0, prior.sd=prior.sd, wt=0.5, postcut=0.95, nsim=10000) mu <- z$mu post <- z$post st <- z$stopped plot(mu, post) abline(v=0, col=gray(.8)); abline(h=0.95, col=gray(.8)) hist(mu[post >= 0.95], nclass=25) k <- post >= 0.95 mean(k) # 0.44 of trials stopped with post >= 0.95 mean(st) # 313 average sample size mean(mu[k] > 0) # 0.963 of trials with post >= 0.95 actually had mu > 0 mean(post[k]) # 0.961 mean posterior prob. when stopped early w <- lowess(post, mu > 0, iter=0) # perfect calibration of post probs plot(w, type='n', # even if stopped early xlab=expression(paste('Posterior Probability ', mu > 0, ' Upon Stopping')), ylab=expression(paste('Proportion of Trials with ', mu > 0))) abline(a=0, b=1, lwd=6, col=gray(.85)) lines(w)
Setting up simulation algorithm to check calibration of Bayesian posterior probabilities Expanding on the excellent answer by @juho-kokkala and using R here are the results. For a prior distribution for the population mean mu I used an equal mixture of two normals with mean zero, one of
35,379
Why is the Kalman Filter a specific case of a (dynamic) Bayesian network?
The remark is not referring to continuous-time--continuous-observation Kalman-Bucy filters, but to discrete-time Kalman filters. The confusion seems to be only due to the OP not knowing about the discrete-time version (which in my experience is most commonly meant when 'Kalman filter' is mentioned). See, for example, the Wikipedia article 'Kalman filter' or [1]. In the discrete-time case, the state-space of the nodes is indeed not discrete but $\mathbb{R}^m$ for the measurements and $\mathbb{R}^n$ for the observations. There are however other Bayesian networks with continuous state-space (for the variables) and Gaussian conditional distributions, too [e.g. 2]. The discrete-time linear-Gaussian dynamic-system model can be written as a dynamic Bayesian network as follows. Time-slice $k$ consists of nodes $\mathbf{x}_k$ and $\mathbf{y}_k$ and there is an edge pointing from $\mathbf{x}_k$ to $\mathbf{y}_k$. The intertemporal edges are from $\mathbf{x}_k$ to $\mathbf{x}_{k+1}$. The conditional probability distributions are $\mathbf{y}_k \mid \mathbf{x}_{k+1} \sim \mathrm{N}(\mathbf{A}_k\,\mathbf{x}_k,\mathbf{Q}_k)$ and $\mathbf{y}_{k} \mid \mathbf{x}_k \sim \mathrm{N}(\mathbf{H}_k \, \mathbf{x}_k, \mathbf{R}_k)$ where all quantities except $\mathbf{x},\mathbf{y}$ are known matrices. The Kalman filter is then an algorithm for sequentially updating the distributions of $\mathbb{x}_k$ given observed $\mathbb{y}_1,\ldots,\mathbb{y}_k$ in this dynamic Bayesian network. The only probability theory required is computing conditional distributions of (finite-dimensional) multivariate Gaussian distributions. Caveat: There exists also something called 'Continuous-time Bayesian networks'[3] but I'm not aware of any connection between them and the Kalman-Bucy filter's model. References [1]: Simo Särkkä (2013). Bayesian Filtering and Smoothing. Cambridge University Press. Section 4.3. Available on the author's webpage. (Conflict-of-interest disclaimer: the author was my PhD advisor) [2]: F.V. Jensen (2001), Bayesian Networks and Decision Graphs, Springer (p. 69) (Curiously,this book p. 65 claims that a "Kalman filter" is any hidden Markov model with only one variable having intertemporal 'relatives' but this is definitely nonstandard usage) [3]: Nodelman, U., Shelton, C. R., & Koller, D. (2002, August). Continuous time Bayesian networks. In Proceedings of the Eighteenth conference on Uncertainty in artificial intelligence (pp. 378-387).
Why is the Kalman Filter a specific case of a (dynamic) Bayesian network?
The remark is not referring to continuous-time--continuous-observation Kalman-Bucy filters, but to discrete-time Kalman filters. The confusion seems to be only due to the OP not knowing about the disc
Why is the Kalman Filter a specific case of a (dynamic) Bayesian network? The remark is not referring to continuous-time--continuous-observation Kalman-Bucy filters, but to discrete-time Kalman filters. The confusion seems to be only due to the OP not knowing about the discrete-time version (which in my experience is most commonly meant when 'Kalman filter' is mentioned). See, for example, the Wikipedia article 'Kalman filter' or [1]. In the discrete-time case, the state-space of the nodes is indeed not discrete but $\mathbb{R}^m$ for the measurements and $\mathbb{R}^n$ for the observations. There are however other Bayesian networks with continuous state-space (for the variables) and Gaussian conditional distributions, too [e.g. 2]. The discrete-time linear-Gaussian dynamic-system model can be written as a dynamic Bayesian network as follows. Time-slice $k$ consists of nodes $\mathbf{x}_k$ and $\mathbf{y}_k$ and there is an edge pointing from $\mathbf{x}_k$ to $\mathbf{y}_k$. The intertemporal edges are from $\mathbf{x}_k$ to $\mathbf{x}_{k+1}$. The conditional probability distributions are $\mathbf{y}_k \mid \mathbf{x}_{k+1} \sim \mathrm{N}(\mathbf{A}_k\,\mathbf{x}_k,\mathbf{Q}_k)$ and $\mathbf{y}_{k} \mid \mathbf{x}_k \sim \mathrm{N}(\mathbf{H}_k \, \mathbf{x}_k, \mathbf{R}_k)$ where all quantities except $\mathbf{x},\mathbf{y}$ are known matrices. The Kalman filter is then an algorithm for sequentially updating the distributions of $\mathbb{x}_k$ given observed $\mathbb{y}_1,\ldots,\mathbb{y}_k$ in this dynamic Bayesian network. The only probability theory required is computing conditional distributions of (finite-dimensional) multivariate Gaussian distributions. Caveat: There exists also something called 'Continuous-time Bayesian networks'[3] but I'm not aware of any connection between them and the Kalman-Bucy filter's model. References [1]: Simo Särkkä (2013). Bayesian Filtering and Smoothing. Cambridge University Press. Section 4.3. Available on the author's webpage. (Conflict-of-interest disclaimer: the author was my PhD advisor) [2]: F.V. Jensen (2001), Bayesian Networks and Decision Graphs, Springer (p. 69) (Curiously,this book p. 65 claims that a "Kalman filter" is any hidden Markov model with only one variable having intertemporal 'relatives' but this is definitely nonstandard usage) [3]: Nodelman, U., Shelton, C. R., & Koller, D. (2002, August). Continuous time Bayesian networks. In Proceedings of the Eighteenth conference on Uncertainty in artificial intelligence (pp. 378-387).
Why is the Kalman Filter a specific case of a (dynamic) Bayesian network? The remark is not referring to continuous-time--continuous-observation Kalman-Bucy filters, but to discrete-time Kalman filters. The confusion seems to be only due to the OP not knowing about the disc
35,380
the turning point test
This assumes the distribution of $y_i$ is absolutely continuous. For sequence of length $n$, let $X_i$ denote the indicator random variable that there is a turning point on $i,i+1,i+2$. Then the number of turning points is: $T_n=X_1+\cdots+X_{n-2}$. Focus on $X_1$. The chance of a turning point on $1,2,3$ is equivalent to the order statistics $y_1<y_2$ and $y_3<y_2$ or $y_1>y_2$ and $y_3>y_2$. Since order statistics for iid absolutely continuous random variables are the same as order statistics for uniform permutations, there are only four permutations that contribute: $132$,$231$,$312$,$213$, giving $4/3!=2/3$ probability: $$E[T_n]=(n-2)E[X_1]=\frac{2(n-2)}{3}.$$ For calculating the variance, it will suffice to find $E[T_n^2]$. Notice that $X_i,X_j$ are independent for $|i-j|\geq 2$. So break the covariances into $E[X_iX_j]$ for $|i-j|<2$ and otherwise. For say $X_1,X_2$, there are two options: \ / \ and / \ / which contribute, so there are 8 permutations: $4132,4231,3142,3241,\cdots$ $$E[X_1X_2]=\frac{8}{4!}=1/3.$$ Thus: \begin{align*} E[T_n^2]&=\sum_{i=1}^{n-2} E[X_1^2]+2\sum_{i<j,|i-j|\geq 2}E[X_iX_j]+2\sum_{i=1}^{n-3}E[X_iX_{i+1}]\\ &=\frac{2}{3}(n-2)+[(n-2)^2-(n-2)-(n-3)]E[X_1]^2+(n-3)\frac{2}{3}, \end{align*} simplifying which gives: $$E[T_n^2]-E[T_n]^2=\frac{2}{9}(2n^2-10n+13).$$ Double check the above arithmetic. I think your variance is wrong because if you plug in $n=3$, you get $19/90$, whereas I get $2/9$, and for $n=3$ there's only $X_1$: $$E[X_1^2]-E[X_1]^2=2/3-(2/3)^2=2/9$$
the turning point test
This assumes the distribution of $y_i$ is absolutely continuous. For sequence of length $n$, let $X_i$ denote the indicator random variable that there is a turning point on $i,i+1,i+2$. Then the numb
the turning point test This assumes the distribution of $y_i$ is absolutely continuous. For sequence of length $n$, let $X_i$ denote the indicator random variable that there is a turning point on $i,i+1,i+2$. Then the number of turning points is: $T_n=X_1+\cdots+X_{n-2}$. Focus on $X_1$. The chance of a turning point on $1,2,3$ is equivalent to the order statistics $y_1<y_2$ and $y_3<y_2$ or $y_1>y_2$ and $y_3>y_2$. Since order statistics for iid absolutely continuous random variables are the same as order statistics for uniform permutations, there are only four permutations that contribute: $132$,$231$,$312$,$213$, giving $4/3!=2/3$ probability: $$E[T_n]=(n-2)E[X_1]=\frac{2(n-2)}{3}.$$ For calculating the variance, it will suffice to find $E[T_n^2]$. Notice that $X_i,X_j$ are independent for $|i-j|\geq 2$. So break the covariances into $E[X_iX_j]$ for $|i-j|<2$ and otherwise. For say $X_1,X_2$, there are two options: \ / \ and / \ / which contribute, so there are 8 permutations: $4132,4231,3142,3241,\cdots$ $$E[X_1X_2]=\frac{8}{4!}=1/3.$$ Thus: \begin{align*} E[T_n^2]&=\sum_{i=1}^{n-2} E[X_1^2]+2\sum_{i<j,|i-j|\geq 2}E[X_iX_j]+2\sum_{i=1}^{n-3}E[X_iX_{i+1}]\\ &=\frac{2}{3}(n-2)+[(n-2)^2-(n-2)-(n-3)]E[X_1]^2+(n-3)\frac{2}{3}, \end{align*} simplifying which gives: $$E[T_n^2]-E[T_n]^2=\frac{2}{9}(2n^2-10n+13).$$ Double check the above arithmetic. I think your variance is wrong because if you plug in $n=3$, you get $19/90$, whereas I get $2/9$, and for $n=3$ there's only $X_1$: $$E[X_1^2]-E[X_1]^2=2/3-(2/3)^2=2/9$$
the turning point test This assumes the distribution of $y_i$ is absolutely continuous. For sequence of length $n$, let $X_i$ denote the indicator random variable that there is a turning point on $i,i+1,i+2$. Then the numb
35,381
the turning point test
I think the solution provided by Alex is incorrect. I cheat a bit and used R help. First we will write a program to evaluate the different probabilites of the sequences. > findMifne <- function(x) { + d.x <- sign(diff(x)) + n <- length(d.x) + temp.vec <- rep(F, n + 1) + for (i in 2:n) { + temp.vec[i] <- ifelse(d.x[i] == d.x[i-1],F,T) + } + return(temp.vec) + } > > temp.list <- do.call('rbind', permn(1:5)) > mat.logic <- t(apply(temp.list, 1, findMifne)) > mean(mat.logic[,2] + mat.logic[,4] == 2) [1] 0.45 > > > temp.list <- do.call('rbind', permn(1:4)) > mat.logic <- t(apply(temp.list, 1, findMifne)) > mean((mat.logic[,2] + mat.logic[,3]) == 2) [1] 0.4166667 So $X_i$ and $X_{i+2}$ are correlated. $P(X_{i+2} * X_{i} = 1) = 54 / 120$ and $Cov(X_{i+2} * X_{i}) = \frac{1}{180}$, $P(X_{i+1} * X_{i} = 1) = 10 / 24$, and covariance $Cov(X_{i+1} * X_{i}) = -\frac{1}{36}$. We are left to find the variance of the summation: $Var(T) = (n-2)Var(I_i) + 2(n-3)Cov(I_i,I_{i+1}) + 2(n-4)Cov(I_i,I_{i+2}) = \frac{2n-4}{9} -\frac{n-3}{18}+\frac{n-4}{90}=\frac{16n-29}{90}$
the turning point test
I think the solution provided by Alex is incorrect. I cheat a bit and used R help. First we will write a program to evaluate the different probabilites of the sequences. > findMifne <- function(x) {
the turning point test I think the solution provided by Alex is incorrect. I cheat a bit and used R help. First we will write a program to evaluate the different probabilites of the sequences. > findMifne <- function(x) { + d.x <- sign(diff(x)) + n <- length(d.x) + temp.vec <- rep(F, n + 1) + for (i in 2:n) { + temp.vec[i] <- ifelse(d.x[i] == d.x[i-1],F,T) + } + return(temp.vec) + } > > temp.list <- do.call('rbind', permn(1:5)) > mat.logic <- t(apply(temp.list, 1, findMifne)) > mean(mat.logic[,2] + mat.logic[,4] == 2) [1] 0.45 > > > temp.list <- do.call('rbind', permn(1:4)) > mat.logic <- t(apply(temp.list, 1, findMifne)) > mean((mat.logic[,2] + mat.logic[,3]) == 2) [1] 0.4166667 So $X_i$ and $X_{i+2}$ are correlated. $P(X_{i+2} * X_{i} = 1) = 54 / 120$ and $Cov(X_{i+2} * X_{i}) = \frac{1}{180}$, $P(X_{i+1} * X_{i} = 1) = 10 / 24$, and covariance $Cov(X_{i+1} * X_{i}) = -\frac{1}{36}$. We are left to find the variance of the summation: $Var(T) = (n-2)Var(I_i) + 2(n-3)Cov(I_i,I_{i+1}) + 2(n-4)Cov(I_i,I_{i+2}) = \frac{2n-4}{9} -\frac{n-3}{18}+\frac{n-4}{90}=\frac{16n-29}{90}$
the turning point test I think the solution provided by Alex is incorrect. I cheat a bit and used R help. First we will write a program to evaluate the different probabilites of the sequences. > findMifne <- function(x) {
35,382
When does Least Square Regression (LSQ) line equal to Least Absolute Deviation (LAD) line?
Some hints to help you gain some insight Make up or generate some data consistent with the conditions in the question. Try $x_1=0, y_1=0$ and $x_2..x_{10}=1$ (choosing some values for $y_i$, $i=2,...,10$). Where do the lines pass relative to the first point? Now start as above but try placing $y_i$, $i=2,...,10$ at say 1,2,3,4,5,6,7,8,9 respectively. Where do the lines go? Now place $y_i$, $i=2,...,10$ at say 1,2,3,4,5,6,7,8,99 respectively. Where do the lines go? What is special/interesting about the fitted values for the two lines at $x=1$? (If it's not clear try some other values for $y_{10}$.) Can you prove this is the case more generally? This ultimately brings us to a slightly simpler question, which relates to when means and medians are equal in the univariate case. (There's a simple, obvious condition that's sufficient, but not necessary.) There are a number of posts on site that discuss the other case. There are some interesting examples here
When does Least Square Regression (LSQ) line equal to Least Absolute Deviation (LAD) line?
Some hints to help you gain some insight Make up or generate some data consistent with the conditions in the question. Try $x_1=0, y_1=0$ and $x_2..x_{10}=1$ (choosing some values for $y_i$, $i=2,...
When does Least Square Regression (LSQ) line equal to Least Absolute Deviation (LAD) line? Some hints to help you gain some insight Make up or generate some data consistent with the conditions in the question. Try $x_1=0, y_1=0$ and $x_2..x_{10}=1$ (choosing some values for $y_i$, $i=2,...,10$). Where do the lines pass relative to the first point? Now start as above but try placing $y_i$, $i=2,...,10$ at say 1,2,3,4,5,6,7,8,9 respectively. Where do the lines go? Now place $y_i$, $i=2,...,10$ at say 1,2,3,4,5,6,7,8,99 respectively. Where do the lines go? What is special/interesting about the fitted values for the two lines at $x=1$? (If it's not clear try some other values for $y_{10}$.) Can you prove this is the case more generally? This ultimately brings us to a slightly simpler question, which relates to when means and medians are equal in the univariate case. (There's a simple, obvious condition that's sufficient, but not necessary.) There are a number of posts on site that discuss the other case. There are some interesting examples here
When does Least Square Regression (LSQ) line equal to Least Absolute Deviation (LAD) line? Some hints to help you gain some insight Make up or generate some data consistent with the conditions in the question. Try $x_1=0, y_1=0$ and $x_2..x_{10}=1$ (choosing some values for $y_i$, $i=2,...
35,383
What is the purpose of a neural network activation function?
Is it correct to say that the non-linear activation function's main purpose is to allow the neural network's decision boundary to be non-linear? Yes. Neural networks compose several functions in layers: the output of a previous layer is the input to the next layer. If you compose linear functions, these functions are all linear. So the result of stacking several linear functions together is a linear function. Showing this is simple algebra: $$ \begin{align} \hat{y} &= W_2(W_1x + b_1)+b_2 \\ &= \underbrace{W_2W_1}_W x+\underbrace{W_2b_1+b_2}_b \\ &= Wx+b \end{align} $$ On the other hand, using a nonlinear function makes the map from the input to the output nonlinear.$$ \hat{y} = f(W_2 f(W_1x + b_1)+b_2) \\ $$ For some activation function $f$, such as $\tanh$ or ReLU, this cannot be rewritten as a single linear operation on $x$. Any model which minimizes a loss $L(y,\hat{y})$ over parameters $W_1,W_2,b_1,b_2$ is equivalent to a model which minimizes the same loss over parameters $W,b$. In the case that the loss is the square error loss, this is exactly the same as an OLS model. If you are estimating this model and observe a discrepancy between an OLS solution and a neural network optimized using gradient descent, it's probably due to either or both of two facts (1) gradient descent is not an effective optimizer for certain problems; (2) the problem is ill-conditioned. For more information, see Reflections on Random Kitchen Sinks Do we need gradient descent to find the coefficients of a linear regression model? Why use gradient descent for linear regression, when a closed-form math solution is available? This isn't unique to classification problems, either. If you have some sort of regression problem (such as an output that can take on any real number), then using nonlinear activation functions is necessary to model a nonlinear relationship between the inputs and outputs. For example, a ReLU function's output is either 0 or positive. If the unit is 0, it is effectively "off," so the inputs to the unit are not propagated forward from that function. If the unit is on, the input data is reflected in subsequent layers through that unit. ReLU itself is not linear, and neither is the composition of several layers of several ReLU functions. So the mapping from inputs to classification outcomes is not linear either.
What is the purpose of a neural network activation function?
Is it correct to say that the non-linear activation function's main purpose is to allow the neural network's decision boundary to be non-linear? Yes. Neural networks compose several functions in laye
What is the purpose of a neural network activation function? Is it correct to say that the non-linear activation function's main purpose is to allow the neural network's decision boundary to be non-linear? Yes. Neural networks compose several functions in layers: the output of a previous layer is the input to the next layer. If you compose linear functions, these functions are all linear. So the result of stacking several linear functions together is a linear function. Showing this is simple algebra: $$ \begin{align} \hat{y} &= W_2(W_1x + b_1)+b_2 \\ &= \underbrace{W_2W_1}_W x+\underbrace{W_2b_1+b_2}_b \\ &= Wx+b \end{align} $$ On the other hand, using a nonlinear function makes the map from the input to the output nonlinear.$$ \hat{y} = f(W_2 f(W_1x + b_1)+b_2) \\ $$ For some activation function $f$, such as $\tanh$ or ReLU, this cannot be rewritten as a single linear operation on $x$. Any model which minimizes a loss $L(y,\hat{y})$ over parameters $W_1,W_2,b_1,b_2$ is equivalent to a model which minimizes the same loss over parameters $W,b$. In the case that the loss is the square error loss, this is exactly the same as an OLS model. If you are estimating this model and observe a discrepancy between an OLS solution and a neural network optimized using gradient descent, it's probably due to either or both of two facts (1) gradient descent is not an effective optimizer for certain problems; (2) the problem is ill-conditioned. For more information, see Reflections on Random Kitchen Sinks Do we need gradient descent to find the coefficients of a linear regression model? Why use gradient descent for linear regression, when a closed-form math solution is available? This isn't unique to classification problems, either. If you have some sort of regression problem (such as an output that can take on any real number), then using nonlinear activation functions is necessary to model a nonlinear relationship between the inputs and outputs. For example, a ReLU function's output is either 0 or positive. If the unit is 0, it is effectively "off," so the inputs to the unit are not propagated forward from that function. If the unit is on, the input data is reflected in subsequent layers through that unit. ReLU itself is not linear, and neither is the composition of several layers of several ReLU functions. So the mapping from inputs to classification outcomes is not linear either.
What is the purpose of a neural network activation function? Is it correct to say that the non-linear activation function's main purpose is to allow the neural network's decision boundary to be non-linear? Yes. Neural networks compose several functions in laye
35,384
What is the purpose of a neural network activation function?
Without activation function many layers would be equivalent to a single layer, as each layer (without an activation function) can be represented by a matrix and a product of many matrices is still a matrix: $$ M = M_1 M_2 \cdots M_n$$
What is the purpose of a neural network activation function?
Without activation function many layers would be equivalent to a single layer, as each layer (without an activation function) can be represented by a matrix and a product of many matrices is still a m
What is the purpose of a neural network activation function? Without activation function many layers would be equivalent to a single layer, as each layer (without an activation function) can be represented by a matrix and a product of many matrices is still a matrix: $$ M = M_1 M_2 \cdots M_n$$
What is the purpose of a neural network activation function? Without activation function many layers would be equivalent to a single layer, as each layer (without an activation function) can be represented by a matrix and a product of many matrices is still a m
35,385
What is the purpose of a neural network activation function?
Role of activation function in neural network: Before moving towards activation function one must have the basic understanding of neurons in the neural network. So what does an artificial neuron do? Simply put, it calculates a weighted sum of its input, adds a bias and then decides whether it should be activated or not. So consider a neuron. $$ Y = \sum (\textit{weight} \cdot \textit{input}) + \textit{bias} $$ Now, the value of $Y$ can be anything ranging from $-\infty$ to $+\infty$. The neuron really doesn’t know the bounds of the value. So how do we decide whether the neuron should activated or not We decided to add activation functions for this purpose. To check the $Y$ value produced by a neuron and decide whether outside connections should consider this neuron as  activated or not.
What is the purpose of a neural network activation function?
Role of activation function in neural network: Before moving towards activation function one must have the basic understanding of neurons in the neural network. So what does an artificial neuron do? S
What is the purpose of a neural network activation function? Role of activation function in neural network: Before moving towards activation function one must have the basic understanding of neurons in the neural network. So what does an artificial neuron do? Simply put, it calculates a weighted sum of its input, adds a bias and then decides whether it should be activated or not. So consider a neuron. $$ Y = \sum (\textit{weight} \cdot \textit{input}) + \textit{bias} $$ Now, the value of $Y$ can be anything ranging from $-\infty$ to $+\infty$. The neuron really doesn’t know the bounds of the value. So how do we decide whether the neuron should activated or not We decided to add activation functions for this purpose. To check the $Y$ value produced by a neuron and decide whether outside connections should consider this neuron as  activated or not.
What is the purpose of a neural network activation function? Role of activation function in neural network: Before moving towards activation function one must have the basic understanding of neurons in the neural network. So what does an artificial neuron do? S
35,386
What is the purpose of a neural network activation function?
A non-linear activation function and a 2-layer Neural Network can approximate any function. That is why we need to introduce non-linearity, cause we can better approximate.
What is the purpose of a neural network activation function?
A non-linear activation function and a 2-layer Neural Network can approximate any function. That is why we need to introduce non-linearity, cause we can better approximate.
What is the purpose of a neural network activation function? A non-linear activation function and a 2-layer Neural Network can approximate any function. That is why we need to introduce non-linearity, cause we can better approximate.
What is the purpose of a neural network activation function? A non-linear activation function and a 2-layer Neural Network can approximate any function. That is why we need to introduce non-linearity, cause we can better approximate.
35,387
What is the purpose of a neural network activation function?
Let me try to answer this without giving any equations. Q) What is the purpose of a neural network having a non-linear activation function? It is not necessary to add non-linear activation function to a neural net if the situation being modelled is linear. However in reality, complicated relationships cannot be represented by a straight line. Most real-world problems are non-linear. In order to help the model converge upon the solution for such cases, we need to bring in an element of non-linearity. One of the ways this can be done is to add functions/layers that are non-linear. Now the model has more power to find solutions Q) Is it correct to say that the non-linear activation function's main purpose is to allow the neural network's decision boundary to be non-linear? Yes that is the only purpose as explained above. The decision boundary now need not be a simple straight line but can be a circle or any other complicated shape. Now that you have provided the model with great deal of flexibility to 'fit' solutions, you should be careful and take precautions against overfitting
What is the purpose of a neural network activation function?
Let me try to answer this without giving any equations. Q) What is the purpose of a neural network having a non-linear activation function? It is not necessary to add non-linear activation function to
What is the purpose of a neural network activation function? Let me try to answer this without giving any equations. Q) What is the purpose of a neural network having a non-linear activation function? It is not necessary to add non-linear activation function to a neural net if the situation being modelled is linear. However in reality, complicated relationships cannot be represented by a straight line. Most real-world problems are non-linear. In order to help the model converge upon the solution for such cases, we need to bring in an element of non-linearity. One of the ways this can be done is to add functions/layers that are non-linear. Now the model has more power to find solutions Q) Is it correct to say that the non-linear activation function's main purpose is to allow the neural network's decision boundary to be non-linear? Yes that is the only purpose as explained above. The decision boundary now need not be a simple straight line but can be a circle or any other complicated shape. Now that you have provided the model with great deal of flexibility to 'fit' solutions, you should be careful and take precautions against overfitting
What is the purpose of a neural network activation function? Let me try to answer this without giving any equations. Q) What is the purpose of a neural network having a non-linear activation function? It is not necessary to add non-linear activation function to
35,388
Truncated normal distribution over a union of intervals
What you are describing is not truncated normal distribution per se, but its probability density function and cumulative distribution functions can be easily calculated the same way as in general we deal with truncated distributions, so you need to divide them by the leftover area under the curve i.e. by $$\int_{ a < x \le b ~\cup ~ c < x \le d} f(x) dx \\ = [F(b)-F(a)] + [F(d)-F(c)] $$ where $f(x)$ is non-truncated density and $F(x)$ is non-truncated cdf. This can be generalized to any number of such intervals. Density of such distribution is $$ g(x) = \begin{cases} \frac{f(x)}{F(b)-F(a) + F(d)-F(c)} & \text{for } a < x \le b ~\cup ~ c < x \le d \\ 0 & \text{otherwise} \end{cases} $$ To convince yourself, you can easily verify this result via simple simulation (see below). set.seed(123) m <- 0 s <- 1 a <- -2 b <- -1 c <- 1 d <- 2 x <- rnorm(1e5, m, s) y <- x[(x > a & x <= b) | (x > c & x <= d)] g <- function(x, mean = 0, sd = 1, a, b, c, d) { ifelse((x > a & x <= b) | (x > c & x <= d), dnorm(x, mean = mean, sd = sd) / ((pnorm(b, mean = mean, sd = sd) - pnorm(a, mean = mean, sd = sd)) + (pnorm(d, mean = mean, sd = sd) - pnorm(c, mean = mean, sd = sd))), 0) } xx <- seq(-4, 4, by = 0.01) hist(y, 100, xlim = c(-4, 4), freq = FALSE) lines(xx, g(xx, m, s, a, b, c, d), col = "red")
Truncated normal distribution over a union of intervals
What you are describing is not truncated normal distribution per se, but its probability density function and cumulative distribution functions can be easily calculated the same way as in general we d
Truncated normal distribution over a union of intervals What you are describing is not truncated normal distribution per se, but its probability density function and cumulative distribution functions can be easily calculated the same way as in general we deal with truncated distributions, so you need to divide them by the leftover area under the curve i.e. by $$\int_{ a < x \le b ~\cup ~ c < x \le d} f(x) dx \\ = [F(b)-F(a)] + [F(d)-F(c)] $$ where $f(x)$ is non-truncated density and $F(x)$ is non-truncated cdf. This can be generalized to any number of such intervals. Density of such distribution is $$ g(x) = \begin{cases} \frac{f(x)}{F(b)-F(a) + F(d)-F(c)} & \text{for } a < x \le b ~\cup ~ c < x \le d \\ 0 & \text{otherwise} \end{cases} $$ To convince yourself, you can easily verify this result via simple simulation (see below). set.seed(123) m <- 0 s <- 1 a <- -2 b <- -1 c <- 1 d <- 2 x <- rnorm(1e5, m, s) y <- x[(x > a & x <= b) | (x > c & x <= d)] g <- function(x, mean = 0, sd = 1, a, b, c, d) { ifelse((x > a & x <= b) | (x > c & x <= d), dnorm(x, mean = mean, sd = sd) / ((pnorm(b, mean = mean, sd = sd) - pnorm(a, mean = mean, sd = sd)) + (pnorm(d, mean = mean, sd = sd) - pnorm(c, mean = mean, sd = sd))), 0) } xx <- seq(-4, 4, by = 0.01) hist(y, 100, xlim = c(-4, 4), freq = FALSE) lines(xx, g(xx, m, s, a, b, c, d), col = "red")
Truncated normal distribution over a union of intervals What you are describing is not truncated normal distribution per se, but its probability density function and cumulative distribution functions can be easily calculated the same way as in general we d
35,389
How to use time dependent covariates with cox regression in R
Its hard without seeing your data, so I'll try making it generic. First of all, the two main ways that a data frame should look like for the use in the survival package: The bare-bones ID - a unique variable to identify each unit of analysis (e.g., patient, country, organization) Event - a binary variable to indicate the occurrence of the event tested (e.g., death, , revolution, bankruptcy) Time - Time until event or until information ends (right-censoring). The Cox model is best used with continuous time, but when the study is over the course of years (especially regarding countries) monthly spells can do. (Oftentimes) Some covariates Lets use a made-up model of trying to find the hazard for countries falling into civil war (the event) over ten years (in monthly spells). Using a single covariate (previousCivilWar) which is not time-dependent: # the first country was censored before an event and the second # experienced the event after 8 years id time event prevCivilWar 1 120 0 0 2 96 1 1 Adding time-dependent covariates: Method 1 Covariate - In this case you need to know the original value, and whether it changed and to what - and if so, when (at what spell). Changing the time variable to start and end - when needed to indicate the time of change for (any of the) covariates Here we will add the binary variable to indicate >40% poverty is40pov: id time1 time2 event prevCivilWar is40pov 1 0 80 0 0 0 1 80 120 0 0 1 2 0 24 0 1 0 2 24 60 0 1 1 2 60 96 1 1 1 When using time-dependent covariates we need to specify the exact time frame until any change in any covariate occurs. Note that the times need to overlap. If a certain subject has no changes in any covariates, than one row suffices. Method 2 - best for continuously changing covariates This will include $k$ rows per unique ID as there are spells ($k$ rows if censored, or less if the event happened before). So, if you have a database with information on a certain time frame studied, decide on the spell-length that makes sense to you (which makes theoretical sense): If the covariates change on an hourly basis - make it hourly, etc... Once you have decided on the spell-length (e.g., month) and the total time (e.g., ten years) than each ID will have <=$120$ spells. If you need, create the longitudinal dataset with empty (NA, 0, or whatever) data, for the time-dependent covariates, and make two extra utility columns for dates/times of each spell. Then you can access the database and fetch the specific values for your covariates at those dates/times and fill it in. It is OK if certain rows have no changes in covariates. You will end up with something like: # The variable pov is the poverty percent of population and measured monthly id time1 time2 event prevCivilWar pov 1 0 1 0 0 0.34 1 1 2 0 0 0.34 ... 1 79 80 0 0 0.43 ... 1 119 120 1 0 0.41 2 0 1 0 1 0.25 ... 2 23 24 0 1 0.42 ... 2 95 96 1 1 0.58 For more info on time-dependent covariates and coefficients, see Therneau, Crowson and Atkinson's 2016 Vignette.
How to use time dependent covariates with cox regression in R
Its hard without seeing your data, so I'll try making it generic. First of all, the two main ways that a data frame should look like for the use in the survival package: The bare-bones ID - a unique
How to use time dependent covariates with cox regression in R Its hard without seeing your data, so I'll try making it generic. First of all, the two main ways that a data frame should look like for the use in the survival package: The bare-bones ID - a unique variable to identify each unit of analysis (e.g., patient, country, organization) Event - a binary variable to indicate the occurrence of the event tested (e.g., death, , revolution, bankruptcy) Time - Time until event or until information ends (right-censoring). The Cox model is best used with continuous time, but when the study is over the course of years (especially regarding countries) monthly spells can do. (Oftentimes) Some covariates Lets use a made-up model of trying to find the hazard for countries falling into civil war (the event) over ten years (in monthly spells). Using a single covariate (previousCivilWar) which is not time-dependent: # the first country was censored before an event and the second # experienced the event after 8 years id time event prevCivilWar 1 120 0 0 2 96 1 1 Adding time-dependent covariates: Method 1 Covariate - In this case you need to know the original value, and whether it changed and to what - and if so, when (at what spell). Changing the time variable to start and end - when needed to indicate the time of change for (any of the) covariates Here we will add the binary variable to indicate >40% poverty is40pov: id time1 time2 event prevCivilWar is40pov 1 0 80 0 0 0 1 80 120 0 0 1 2 0 24 0 1 0 2 24 60 0 1 1 2 60 96 1 1 1 When using time-dependent covariates we need to specify the exact time frame until any change in any covariate occurs. Note that the times need to overlap. If a certain subject has no changes in any covariates, than one row suffices. Method 2 - best for continuously changing covariates This will include $k$ rows per unique ID as there are spells ($k$ rows if censored, or less if the event happened before). So, if you have a database with information on a certain time frame studied, decide on the spell-length that makes sense to you (which makes theoretical sense): If the covariates change on an hourly basis - make it hourly, etc... Once you have decided on the spell-length (e.g., month) and the total time (e.g., ten years) than each ID will have <=$120$ spells. If you need, create the longitudinal dataset with empty (NA, 0, or whatever) data, for the time-dependent covariates, and make two extra utility columns for dates/times of each spell. Then you can access the database and fetch the specific values for your covariates at those dates/times and fill it in. It is OK if certain rows have no changes in covariates. You will end up with something like: # The variable pov is the poverty percent of population and measured monthly id time1 time2 event prevCivilWar pov 1 0 1 0 0 0.34 1 1 2 0 0 0.34 ... 1 79 80 0 0 0.43 ... 1 119 120 1 0 0.41 2 0 1 0 1 0.25 ... 2 23 24 0 1 0.42 ... 2 95 96 1 1 0.58 For more info on time-dependent covariates and coefficients, see Therneau, Crowson and Atkinson's 2016 Vignette.
How to use time dependent covariates with cox regression in R Its hard without seeing your data, so I'll try making it generic. First of all, the two main ways that a data frame should look like for the use in the survival package: The bare-bones ID - a unique
35,390
In a mixed effects model, how do you determine when the slope and intercept should be independent?
I'm just responding in case this might be useful for anyone else. OPEN QUESTION Turns out, I still have not found a clear resource that distinguishes between these two options in a theoretical manner - i.e. distinguishes between them not as an optimization but as being different model structures that are best suited for capturing different kinds of experimental designs. Ideally, you should be able to rely upon your knowledge of the properties / structure of the study / data sample / data elicitation technique - and, make decisions about the random effects model before you have looked at the data. After all, random effects should be determined a priori based on the theoretical assumptions. That part of the question remains unanswered in a satisfactory manner What are the theory-driven / experimental design based features that should allows us to determine whether Option 1 or Option 2 is the appropriate choice. OPTION 1: random slope-intercept with no constraints (G)LMER---|[ m.1 ]|---[Y ~ 1 + B + (1 + B | A)]| OPTION 2: random slope-intercept with uncorrelated random effects (G)LMER---|[ m.2 ]|---[Y ~ 1 + B + (1 | A) + (0 + B | A)]| PARTIAL SOLUTION IN PRACTICE However, I did find a a tutorial by Douglas Bates that may help. Around slide 73 onwards, he covers this topic. Essentially, this response is inspired by and often reproduces those slides. If you would like more detail, head there. 1. Inspect Your Random Effects Plots Bates suggest that if visual inspection of the data plots gives you "little indication of a systematic relationship between a subject’s random effect for slope and his/her random effect for the intercept," we may want to consider using a model with uncorrelated random effects. 2. MODEL COMPARISON 2(a) Build Option 2 from above First, we construct the model with the uncorrelated random effects. To express this we use two random-effects terms with the same grouping factor and different left-hand sides. TWO GROUPING FACTORS: (1 | A)-----------[Random Intercept] (0 + B | A)-------[Random Slope, no intercept] Since the distinct random effects terms are modeled as being independent, by design, this imposes the constraint that the random intercept (1) from above is independent of the slope (2) conditional on A. 2(b) Compare the models using ANOVA Using ANOVA for model comparison Model m.1 represents the unconstrained random intercept-slope model associated with Option 1 from above Model m.2 represents Option 2 where the intercept & slope are independent conditional on A Model m.1 contains m.2 in the sense that: If the parameter values for model m.1 were constrained so as to force the correlation (and, hence the covariance) to be zero and we could get the model to re-fit, we would get m.2 Use a likelihood ratio test to determine if m.1 adds something substantial and statistically significant; If not, use the preference for parsimonious models (i.e. "smaller is better") and prefer the simpler, more constrained model; Since the value 0 to which the correlation is constrained is not on the boundary of the allowable parameter values, a likelihood ratio test and a reference distribution of a χ2 on 1 degree of freedom is suitable. 3. Likelihood ratio tests on variance component As for the case of a covariance, we can fit the model with and without the variance component and compare the quality of the fits. The likelihood ratio is a reasonable test statistic for the comparison but the “asymptotic” reference distribution of a χ2 does not apply because the parameter value being tested is on the boundary. The p-value computed using the χ2 reference distribution should be conservative (i.e. greater than the p-value that would be obtained through simulation). 4. References and Resources For additional resources, please see the following two useful links: Barr, D. J., Levy, R., Scheepers, C., & Tily, H. J. (2013). Random effects structure for confirmatory hypothesis testing: Keep it maximal. Journal of Memory and Language, 68(3) Also, search the subsequent article by Barr ("Random effects structure for testing interactions in linear mixed-effects models") if you are testing any interactions in your models).
In a mixed effects model, how do you determine when the slope and intercept should be independent?
I'm just responding in case this might be useful for anyone else. OPEN QUESTION Turns out, I still have not found a clear resource that distinguishes between these two options in a theoretical manner
In a mixed effects model, how do you determine when the slope and intercept should be independent? I'm just responding in case this might be useful for anyone else. OPEN QUESTION Turns out, I still have not found a clear resource that distinguishes between these two options in a theoretical manner - i.e. distinguishes between them not as an optimization but as being different model structures that are best suited for capturing different kinds of experimental designs. Ideally, you should be able to rely upon your knowledge of the properties / structure of the study / data sample / data elicitation technique - and, make decisions about the random effects model before you have looked at the data. After all, random effects should be determined a priori based on the theoretical assumptions. That part of the question remains unanswered in a satisfactory manner What are the theory-driven / experimental design based features that should allows us to determine whether Option 1 or Option 2 is the appropriate choice. OPTION 1: random slope-intercept with no constraints (G)LMER---|[ m.1 ]|---[Y ~ 1 + B + (1 + B | A)]| OPTION 2: random slope-intercept with uncorrelated random effects (G)LMER---|[ m.2 ]|---[Y ~ 1 + B + (1 | A) + (0 + B | A)]| PARTIAL SOLUTION IN PRACTICE However, I did find a a tutorial by Douglas Bates that may help. Around slide 73 onwards, he covers this topic. Essentially, this response is inspired by and often reproduces those slides. If you would like more detail, head there. 1. Inspect Your Random Effects Plots Bates suggest that if visual inspection of the data plots gives you "little indication of a systematic relationship between a subject’s random effect for slope and his/her random effect for the intercept," we may want to consider using a model with uncorrelated random effects. 2. MODEL COMPARISON 2(a) Build Option 2 from above First, we construct the model with the uncorrelated random effects. To express this we use two random-effects terms with the same grouping factor and different left-hand sides. TWO GROUPING FACTORS: (1 | A)-----------[Random Intercept] (0 + B | A)-------[Random Slope, no intercept] Since the distinct random effects terms are modeled as being independent, by design, this imposes the constraint that the random intercept (1) from above is independent of the slope (2) conditional on A. 2(b) Compare the models using ANOVA Using ANOVA for model comparison Model m.1 represents the unconstrained random intercept-slope model associated with Option 1 from above Model m.2 represents Option 2 where the intercept & slope are independent conditional on A Model m.1 contains m.2 in the sense that: If the parameter values for model m.1 were constrained so as to force the correlation (and, hence the covariance) to be zero and we could get the model to re-fit, we would get m.2 Use a likelihood ratio test to determine if m.1 adds something substantial and statistically significant; If not, use the preference for parsimonious models (i.e. "smaller is better") and prefer the simpler, more constrained model; Since the value 0 to which the correlation is constrained is not on the boundary of the allowable parameter values, a likelihood ratio test and a reference distribution of a χ2 on 1 degree of freedom is suitable. 3. Likelihood ratio tests on variance component As for the case of a covariance, we can fit the model with and without the variance component and compare the quality of the fits. The likelihood ratio is a reasonable test statistic for the comparison but the “asymptotic” reference distribution of a χ2 does not apply because the parameter value being tested is on the boundary. The p-value computed using the χ2 reference distribution should be conservative (i.e. greater than the p-value that would be obtained through simulation). 4. References and Resources For additional resources, please see the following two useful links: Barr, D. J., Levy, R., Scheepers, C., & Tily, H. J. (2013). Random effects structure for confirmatory hypothesis testing: Keep it maximal. Journal of Memory and Language, 68(3) Also, search the subsequent article by Barr ("Random effects structure for testing interactions in linear mixed-effects models") if you are testing any interactions in your models).
In a mixed effects model, how do you determine when the slope and intercept should be independent? I'm just responding in case this might be useful for anyone else. OPEN QUESTION Turns out, I still have not found a clear resource that distinguishes between these two options in a theoretical manner
35,391
In a mixed effects model, how do you determine when the slope and intercept should be independent?
The following is a rule of thumb. I think the default choice should be a model where the slope and the intercept covary ((1 + A | B)). Unless you have a theoretical or technical reason to exclude the possibility of covariance, it just makes in most cases a lot of sense to at least allow for the possibility. I wouldn't be able to come up with a theoretical reason, but a technical reason could be that you don't have enough data to estimate the covariance. On the other hand, even in such cases, estimating a covariance will likely improve the estimate of the random slopes and intercepts. I'd be suspicious, or at least interested in finding out why it happens, if your crossvalidation or ANOVA or other "hard" measure (perhaps try WAIC?) is better for the model without covariance.
In a mixed effects model, how do you determine when the slope and intercept should be independent?
The following is a rule of thumb. I think the default choice should be a model where the slope and the intercept covary ((1 + A | B)). Unless you have a theoretical or technical reason to exclude the
In a mixed effects model, how do you determine when the slope and intercept should be independent? The following is a rule of thumb. I think the default choice should be a model where the slope and the intercept covary ((1 + A | B)). Unless you have a theoretical or technical reason to exclude the possibility of covariance, it just makes in most cases a lot of sense to at least allow for the possibility. I wouldn't be able to come up with a theoretical reason, but a technical reason could be that you don't have enough data to estimate the covariance. On the other hand, even in such cases, estimating a covariance will likely improve the estimate of the random slopes and intercepts. I'd be suspicious, or at least interested in finding out why it happens, if your crossvalidation or ANOVA or other "hard" measure (perhaps try WAIC?) is better for the model without covariance.
In a mixed effects model, how do you determine when the slope and intercept should be independent? The following is a rule of thumb. I think the default choice should be a model where the slope and the intercept covary ((1 + A | B)). Unless you have a theoretical or technical reason to exclude the
35,392
In a mixed effects model, how do you determine when the slope and intercept should be independent?
I think I may have an additional piece of information that can be used to help you. In the world of econometrics and more precisely, in the world of panel data estimation (the way econometritians call longitudinal/repeated measures data). The test that I present to you is the Hausman specification test. The theoretical framework is to test, in terms of the estimator's consistency, if a random-effects model is preferred to a fixed-effects. The approaches that I've used are more similar to your answer, but this can be one more idea for you. Here are a few resources: Wikipedia article A nice video explaining the test Some slides on the test Chapter 10 on Woodridge's Econometric Analysis of Cross Section and Panel Data
In a mixed effects model, how do you determine when the slope and intercept should be independent?
I think I may have an additional piece of information that can be used to help you. In the world of econometrics and more precisely, in the world of panel data estimation (the way econometritians call
In a mixed effects model, how do you determine when the slope and intercept should be independent? I think I may have an additional piece of information that can be used to help you. In the world of econometrics and more precisely, in the world of panel data estimation (the way econometritians call longitudinal/repeated measures data). The test that I present to you is the Hausman specification test. The theoretical framework is to test, in terms of the estimator's consistency, if a random-effects model is preferred to a fixed-effects. The approaches that I've used are more similar to your answer, but this can be one more idea for you. Here are a few resources: Wikipedia article A nice video explaining the test Some slides on the test Chapter 10 on Woodridge's Econometric Analysis of Cross Section and Panel Data
In a mixed effects model, how do you determine when the slope and intercept should be independent? I think I may have an additional piece of information that can be used to help you. In the world of econometrics and more precisely, in the world of panel data estimation (the way econometritians call
35,393
Calculating the adjusted rand index?
Basically: nij is across the diagonal (i.e., when i = j) ai is the row sums bj is the column sums Using wikipedia, we have the formula: $ARI = \frac{ \sum_{ij} \binom{n_{ij}}{2} - [\sum_i \binom{a_i}{2} \sum_j \binom{b_j}{2}] / \binom{n}{2} }{ \frac{1}{2} [\sum_i \binom{a_i}{2} + \sum_j \binom{b_j}{2}] - [\sum_i \binom{a_i}{2} \sum_j \binom{b_j}{2}] / \binom{n}{2} }$ Let's assume we have the table: x1 x2 x3 Sums y1 1 1 0 2 y2 1 2 1 4 y3 0 0 4 4 Sums 2 3 5 Breaking into components: $\sum_{ij} \binom{n_{ij}}{2} = \binom{1}{2} + \binom{2}{2} + \binom{4}{2} = 7$ $\sum_i \binom{a_i}{2} = \binom{2}{2} + \binom{4}{2} + \binom{4}{2} = 13$ $\sum_j \binom{b_j}{2} = \binom{2}{2} + \binom{3}{2} + \binom{5}{2} = 14$ So, then $ARI = \frac{7 - 13*14/45}{(13 + 14)/2 - 13*14/45} = 0.313$ Confirming this result in R: library(cluster) x <- c(1, 1, 2, 2, 2, 2, 3, 3, 3, 3) y <- c(1, 2, 1, 2, 2, 3, 3, 3, 3, 3) adjustedRandIndex(x, y) # .313
Calculating the adjusted rand index?
Basically: nij is across the diagonal (i.e., when i = j) ai is the row sums bj is the column sums Using wikipedia, we have the formula: $ARI = \frac{ \sum_{ij} \binom{n_{ij}}{2} - [\sum_i \binom{a_i
Calculating the adjusted rand index? Basically: nij is across the diagonal (i.e., when i = j) ai is the row sums bj is the column sums Using wikipedia, we have the formula: $ARI = \frac{ \sum_{ij} \binom{n_{ij}}{2} - [\sum_i \binom{a_i}{2} \sum_j \binom{b_j}{2}] / \binom{n}{2} }{ \frac{1}{2} [\sum_i \binom{a_i}{2} + \sum_j \binom{b_j}{2}] - [\sum_i \binom{a_i}{2} \sum_j \binom{b_j}{2}] / \binom{n}{2} }$ Let's assume we have the table: x1 x2 x3 Sums y1 1 1 0 2 y2 1 2 1 4 y3 0 0 4 4 Sums 2 3 5 Breaking into components: $\sum_{ij} \binom{n_{ij}}{2} = \binom{1}{2} + \binom{2}{2} + \binom{4}{2} = 7$ $\sum_i \binom{a_i}{2} = \binom{2}{2} + \binom{4}{2} + \binom{4}{2} = 13$ $\sum_j \binom{b_j}{2} = \binom{2}{2} + \binom{3}{2} + \binom{5}{2} = 14$ So, then $ARI = \frac{7 - 13*14/45}{(13 + 14)/2 - 13*14/45} = 0.313$ Confirming this result in R: library(cluster) x <- c(1, 1, 2, 2, 2, 2, 3, 3, 3, 3) y <- c(1, 2, 1, 2, 2, 3, 3, 3, 3, 3) adjustedRandIndex(x, y) # .313
Calculating the adjusted rand index? Basically: nij is across the diagonal (i.e., when i = j) ai is the row sums bj is the column sums Using wikipedia, we have the formula: $ARI = \frac{ \sum_{ij} \binom{n_{ij}}{2} - [\sum_i \binom{a_i
35,394
Calculating the adjusted rand index?
The answer by dmartin is nice to get some insight. To actually have a few lines of code (in octave/matlab): function [RI ARI] = adjustedrandindex(A) N=sum(sum(A)); R=sum(A,2); C=sum(A,1); a=sum(sum(bincoeff(A,2))); b0=sum(bincoeff(R,2)); b=b0 - a; c0=sum(bincoeff(C,2)); c=c0 - a; S=bincoeff(N,2); d=S - (a + b + c); RI=(a+d)/S; ARI=(a-b0*c0/S)/((b0+c0)/2-b0*c0/S); end Copyrights hereby: public domain. B = 1 1 0 1 2 1 0 0 4 [RI ARI] = adjustedrandindex(B) RI = 0.71111 ARI = 0.31257 Permutations of B should lead to the same RI and ARI: [RI ARI] = adjustedrandindex(B(:,randperm(size(B,2)))) RI = 0.71111 ARI = 0.31257
Calculating the adjusted rand index?
The answer by dmartin is nice to get some insight. To actually have a few lines of code (in octave/matlab): function [RI ARI] = adjustedrandindex(A)
Calculating the adjusted rand index? The answer by dmartin is nice to get some insight. To actually have a few lines of code (in octave/matlab): function [RI ARI] = adjustedrandindex(A) N=sum(sum(A)); R=sum(A,2); C=sum(A,1); a=sum(sum(bincoeff(A,2))); b0=sum(bincoeff(R,2)); b=b0 - a; c0=sum(bincoeff(C,2)); c=c0 - a; S=bincoeff(N,2); d=S - (a + b + c); RI=(a+d)/S; ARI=(a-b0*c0/S)/((b0+c0)/2-b0*c0/S); end Copyrights hereby: public domain. B = 1 1 0 1 2 1 0 0 4 [RI ARI] = adjustedrandindex(B) RI = 0.71111 ARI = 0.31257 Permutations of B should lead to the same RI and ARI: [RI ARI] = adjustedrandindex(B(:,randperm(size(B,2)))) RI = 0.71111 ARI = 0.31257
Calculating the adjusted rand index? The answer by dmartin is nice to get some insight. To actually have a few lines of code (in octave/matlab): function [RI ARI] = adjustedrandindex(A)
35,395
Curse of dimensionality: why is it a problem that most points are near the edge?
The problem is that "the edge" is not just one place in $d$-dimensional space. "The edge" is a big part of your volume, and the volume of "the edge" grows very quickly. Thus, even if more and more training data points lie near "the edge", the density of training data will still decrease very quickly as $d$ increases. As a little visualization, consider a two-dimensional square with sides of length 2, and inscribe a circle of radius 1 within it. Let's call the area of the square outside the circle "the edge". "The edge" has area $\frac{4-\pi}{4}$, and it consists of four disjoint pieces. Now consider the same situation in three dimensions. Then in four. And so forth. You can show that the volume of "the edge" will take up as much of the volume of the $d$-dimensional cube as we want, if we just increase $d$ sufficiently. "The edge" is not disjoint any more for $d\geq 3$, but your training data will get lost in it. Alternatively, draw $n$ points randomly and uniformly distributed in the $d$-dimensional unit cube, for increasing $d$, and check on the average pairwise distance. You will see that this distance increases quickly with $d$. How quickly will you need to increase $n$ with $d$ for this average distance to stay constant? Very quickly indeed. Bottom line: "the more training points nearby" is where your argument goes astray. In high dimensions, there are very few points nearby.
Curse of dimensionality: why is it a problem that most points are near the edge?
The problem is that "the edge" is not just one place in $d$-dimensional space. "The edge" is a big part of your volume, and the volume of "the edge" grows very quickly. Thus, even if more and more tra
Curse of dimensionality: why is it a problem that most points are near the edge? The problem is that "the edge" is not just one place in $d$-dimensional space. "The edge" is a big part of your volume, and the volume of "the edge" grows very quickly. Thus, even if more and more training data points lie near "the edge", the density of training data will still decrease very quickly as $d$ increases. As a little visualization, consider a two-dimensional square with sides of length 2, and inscribe a circle of radius 1 within it. Let's call the area of the square outside the circle "the edge". "The edge" has area $\frac{4-\pi}{4}$, and it consists of four disjoint pieces. Now consider the same situation in three dimensions. Then in four. And so forth. You can show that the volume of "the edge" will take up as much of the volume of the $d$-dimensional cube as we want, if we just increase $d$ sufficiently. "The edge" is not disjoint any more for $d\geq 3$, but your training data will get lost in it. Alternatively, draw $n$ points randomly and uniformly distributed in the $d$-dimensional unit cube, for increasing $d$, and check on the average pairwise distance. You will see that this distance increases quickly with $d$. How quickly will you need to increase $n$ with $d$ for this average distance to stay constant? Very quickly indeed. Bottom line: "the more training points nearby" is where your argument goes astray. In high dimensions, there are very few points nearby.
Curse of dimensionality: why is it a problem that most points are near the edge? The problem is that "the edge" is not just one place in $d$-dimensional space. "The edge" is a big part of your volume, and the volume of "the edge" grows very quickly. Thus, even if more and more tra
35,396
Curse of dimensionality: why is it a problem that most points are near the edge?
And the more training points nearby max's answer touches on the primary point but I just wanted to point out that the above quote was your erroring assumption, give some more intuition about how points all end up on the edge and point out how this causes sparsity issues. The erroring assumption is that the edge is small. It is not. It is massive in high dimensions. The proportion of volume within the 0.1% of the radius that is closest to the surface of the unit ball goes to 100% exponentially as the number of dimensions grows. An algebraic/probabilistic way to look at is that to be in the middle you need to have low values for all dimensions simultaneously. To be at the edge you just need to have a high value for one dimension. As the number of dimensions grow the chances of at last one dimension having a high value goes to 100%. If each dimension could only have values of 0 or 1 there would still be possible values in n dimensions. And you consider all of those as regions if we allow continuous values. This creates issues with sparsity. Most regions of the space don't exist in your training dataset. If you choose points at random almost no points will be near your training dataset. But a few of those regions will be in your test dataset.
Curse of dimensionality: why is it a problem that most points are near the edge?
And the more training points nearby max's answer touches on the primary point but I just wanted to point out that the above quote was your erroring assumption, give some more intuition about how poin
Curse of dimensionality: why is it a problem that most points are near the edge? And the more training points nearby max's answer touches on the primary point but I just wanted to point out that the above quote was your erroring assumption, give some more intuition about how points all end up on the edge and point out how this causes sparsity issues. The erroring assumption is that the edge is small. It is not. It is massive in high dimensions. The proportion of volume within the 0.1% of the radius that is closest to the surface of the unit ball goes to 100% exponentially as the number of dimensions grows. An algebraic/probabilistic way to look at is that to be in the middle you need to have low values for all dimensions simultaneously. To be at the edge you just need to have a high value for one dimension. As the number of dimensions grow the chances of at last one dimension having a high value goes to 100%. If each dimension could only have values of 0 or 1 there would still be possible values in n dimensions. And you consider all of those as regions if we allow continuous values. This creates issues with sparsity. Most regions of the space don't exist in your training dataset. If you choose points at random almost no points will be near your training dataset. But a few of those regions will be in your test dataset.
Curse of dimensionality: why is it a problem that most points are near the edge? And the more training points nearby max's answer touches on the primary point but I just wanted to point out that the above quote was your erroring assumption, give some more intuition about how poin
35,397
Weibull Survival Model with Time Varying Covariates in R
The flexurv package can do this: https://cran.r-project.org/web/packages/flexsurv/index.html Just call the flexsurvreg function instead of survreg.
Weibull Survival Model with Time Varying Covariates in R
The flexurv package can do this: https://cran.r-project.org/web/packages/flexsurv/index.html Just call the flexsurvreg function instead of survreg.
Weibull Survival Model with Time Varying Covariates in R The flexurv package can do this: https://cran.r-project.org/web/packages/flexsurv/index.html Just call the flexsurvreg function instead of survreg.
Weibull Survival Model with Time Varying Covariates in R The flexurv package can do this: https://cran.r-project.org/web/packages/flexsurv/index.html Just call the flexsurvreg function instead of survreg.
35,398
Weibull Survival Model with Time Varying Covariates in R
You can do it with Survival package by the following : Srv <- Surv(start, stop, fail, type="interval" ) and then you can use Srv in your model as : output <- survreg(Surv(start, stop, fail) ~ gdppc + [...] + cluster(name), data = mydata, dist="weibull") Hope this can help :)
Weibull Survival Model with Time Varying Covariates in R
You can do it with Survival package by the following : Srv <- Surv(start, stop, fail, type="interval" ) and then you can use Srv in your model as : output <- survreg(Surv(start, stop, fail) ~ gdppc +
Weibull Survival Model with Time Varying Covariates in R You can do it with Survival package by the following : Srv <- Surv(start, stop, fail, type="interval" ) and then you can use Srv in your model as : output <- survreg(Surv(start, stop, fail) ~ gdppc + [...] + cluster(name), data = mydata, dist="weibull") Hope this can help :)
Weibull Survival Model with Time Varying Covariates in R You can do it with Survival package by the following : Srv <- Surv(start, stop, fail, type="interval" ) and then you can use Srv in your model as : output <- survreg(Surv(start, stop, fail) ~ gdppc +
35,399
Weibull Survival Model with Time Varying Covariates in R
This can also be achieved with the aftreg command from the eha package. To obtain the same parametrisation normally used by the survreg command from the survival package, and also by the flexsurvreg command from the flexsurv package, the param option must be set to "LifeExp", as explained in the package's documentation. An adaptation of your code would therefore be as follows: output <- aftreg(Surv(start, stop, fail) ~ gdppc + [...] + cluster(name), data = mydata, dist="weibull", param="lifeExp") One advantage of the eha::aftreg command is that it is compatible with stargazer and thus its output can be easily exported to LaTeX format.
Weibull Survival Model with Time Varying Covariates in R
This can also be achieved with the aftreg command from the eha package. To obtain the same parametrisation normally used by the survreg command from the survival package, and also by the flexsurvreg c
Weibull Survival Model with Time Varying Covariates in R This can also be achieved with the aftreg command from the eha package. To obtain the same parametrisation normally used by the survreg command from the survival package, and also by the flexsurvreg command from the flexsurv package, the param option must be set to "LifeExp", as explained in the package's documentation. An adaptation of your code would therefore be as follows: output <- aftreg(Surv(start, stop, fail) ~ gdppc + [...] + cluster(name), data = mydata, dist="weibull", param="lifeExp") One advantage of the eha::aftreg command is that it is compatible with stargazer and thus its output can be easily exported to LaTeX format.
Weibull Survival Model with Time Varying Covariates in R This can also be achieved with the aftreg command from the eha package. To obtain the same parametrisation normally used by the survreg command from the survival package, and also by the flexsurvreg c
35,400
Does number of layers in neural network corresponds to degree of the approximation function?
It can be true that more layers/depth can yield more nonlinearity, but I do not think using the analogy of a polynomial's degree is a perfect analogy and it's certainly not mathematical fact. You can look at deep net regression a few different ways: learning a nonlinear function. In this sense, it is very natural to think in terms of degrees and polynomials. Another sense is that learning using neural networks involves learning a partition of the domain into sub-domains, and on each sub-domain we approximate the function with a linear superposition or a deep composition of simpler functions. In this sense, we measure representational capacity in terms of how many sub-domains we can learn. Of course, these concepts may not be orthogonal, but they emphasize different aspects. The polynomial degree analogy feels a lot like interpolation to me while I believe the philosophy (and recent theory) with deep net representational capacity is more about partitioning or learning regions. There's a couple of different angles to your question. If you are asking why is a single hidden layer NN is a Universal Function Approximator, that's a mathematical question, and the proof is available, for example see Cybenko's proof for sigmoidal nonlinearities. One key quote from Cybenko's paper is the following: "that networks with one internal layer and an arbitrary continuous sigmoidal function can approximate continuous functions wih arbitrary precision providing that no constraints are placed on the number of nodes or the size of the weights" So to approximate a continuous function $f$ with a single hidden layer NN to some given precision $\epsilon$ may require an extremely wide architecture, despite being incredibly shallow. Meaning, we have many many many different sigmoidal activation functions. By allowing ourselves to have possibly many such sigmoidal activation functions, i.e. the wide architecture, we are allowing ourselves to have a much more intricate partition of our domain, which increases our approximation accuracy. There's some further ways to break down the Universal approximation theorem. For example, it requires the activation function be nonconstant, bounded, and monotonically-increasing continuous function. Take the case of the sigmoidal activation, which asymptotes out to 0 as $x \rightarrow -\infty$ and to 1 as $x \rightarrow +\infty$. One of the original motivations for using the sigmoidal activation was that it can act like a switch. Allowing the weights to have arbitrary magnitude, i.e. no hard limit on the size of the parameter values, we can effectively shift sigmoids into their "off" states with very negative values and shift sigmoids into their "on" states with very positive values. And training a single hidden layer corresponds to learning a good configuration of parameters. By allowing for the weights to have unbounded size (both in the negative and positive sense), we can interpret the single hidden layer NN as partitioning the domain into sub-spaces where a specific configuration of the sigmoidals are "on" and contribute to the function approximation and the others are switched "off." Now if we allow ourselves to have a ton of these sigmoids, you start to get some intuition as to why the sigmoidal Universal Approximation Theorem is true. One question that I believe has motivated researchers is: how efficient is this? In particular: how does representational capacity scale with the number of hidden units for single hidden layer neural networks? For deeper architectures? I believe recent work by Yoshua Bengio and his collaborators have taken these ideas further with the wildly successful ReLU $f(x) = \max(0, x)$ and a generalization called the Maxout activation functions. These ReLU and Maxout networks tend to have multiple layers and are not shallow. Please see the following How to understand the geometric intuition of the inner workings of neural networks? for a more detailed explanation. But roughly speaking, they proved that Maxout networks learn an exponential number of linear regions. In particular, the number of linear regions learned scales exponentially with the number of layers. So perhaps thinking about degree in terms of polynomials is not the best analogy, but it's better to think about depth in terms of how it scales with the number of regions (size of the partition) our network can learn. In contrast to single hidden layer NN, if the general principle is that representational capacity scales with depth, then we would require an extremely wide and shallow architecture and on a per-parameter basis, this may be very inefficient compared to a deeper network.
Does number of layers in neural network corresponds to degree of the approximation function?
It can be true that more layers/depth can yield more nonlinearity, but I do not think using the analogy of a polynomial's degree is a perfect analogy and it's certainly not mathematical fact. You can
Does number of layers in neural network corresponds to degree of the approximation function? It can be true that more layers/depth can yield more nonlinearity, but I do not think using the analogy of a polynomial's degree is a perfect analogy and it's certainly not mathematical fact. You can look at deep net regression a few different ways: learning a nonlinear function. In this sense, it is very natural to think in terms of degrees and polynomials. Another sense is that learning using neural networks involves learning a partition of the domain into sub-domains, and on each sub-domain we approximate the function with a linear superposition or a deep composition of simpler functions. In this sense, we measure representational capacity in terms of how many sub-domains we can learn. Of course, these concepts may not be orthogonal, but they emphasize different aspects. The polynomial degree analogy feels a lot like interpolation to me while I believe the philosophy (and recent theory) with deep net representational capacity is more about partitioning or learning regions. There's a couple of different angles to your question. If you are asking why is a single hidden layer NN is a Universal Function Approximator, that's a mathematical question, and the proof is available, for example see Cybenko's proof for sigmoidal nonlinearities. One key quote from Cybenko's paper is the following: "that networks with one internal layer and an arbitrary continuous sigmoidal function can approximate continuous functions wih arbitrary precision providing that no constraints are placed on the number of nodes or the size of the weights" So to approximate a continuous function $f$ with a single hidden layer NN to some given precision $\epsilon$ may require an extremely wide architecture, despite being incredibly shallow. Meaning, we have many many many different sigmoidal activation functions. By allowing ourselves to have possibly many such sigmoidal activation functions, i.e. the wide architecture, we are allowing ourselves to have a much more intricate partition of our domain, which increases our approximation accuracy. There's some further ways to break down the Universal approximation theorem. For example, it requires the activation function be nonconstant, bounded, and monotonically-increasing continuous function. Take the case of the sigmoidal activation, which asymptotes out to 0 as $x \rightarrow -\infty$ and to 1 as $x \rightarrow +\infty$. One of the original motivations for using the sigmoidal activation was that it can act like a switch. Allowing the weights to have arbitrary magnitude, i.e. no hard limit on the size of the parameter values, we can effectively shift sigmoids into their "off" states with very negative values and shift sigmoids into their "on" states with very positive values. And training a single hidden layer corresponds to learning a good configuration of parameters. By allowing for the weights to have unbounded size (both in the negative and positive sense), we can interpret the single hidden layer NN as partitioning the domain into sub-spaces where a specific configuration of the sigmoidals are "on" and contribute to the function approximation and the others are switched "off." Now if we allow ourselves to have a ton of these sigmoids, you start to get some intuition as to why the sigmoidal Universal Approximation Theorem is true. One question that I believe has motivated researchers is: how efficient is this? In particular: how does representational capacity scale with the number of hidden units for single hidden layer neural networks? For deeper architectures? I believe recent work by Yoshua Bengio and his collaborators have taken these ideas further with the wildly successful ReLU $f(x) = \max(0, x)$ and a generalization called the Maxout activation functions. These ReLU and Maxout networks tend to have multiple layers and are not shallow. Please see the following How to understand the geometric intuition of the inner workings of neural networks? for a more detailed explanation. But roughly speaking, they proved that Maxout networks learn an exponential number of linear regions. In particular, the number of linear regions learned scales exponentially with the number of layers. So perhaps thinking about degree in terms of polynomials is not the best analogy, but it's better to think about depth in terms of how it scales with the number of regions (size of the partition) our network can learn. In contrast to single hidden layer NN, if the general principle is that representational capacity scales with depth, then we would require an extremely wide and shallow architecture and on a per-parameter basis, this may be very inefficient compared to a deeper network.
Does number of layers in neural network corresponds to degree of the approximation function? It can be true that more layers/depth can yield more nonlinearity, but I do not think using the analogy of a polynomial's degree is a perfect analogy and it's certainly not mathematical fact. You can