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 |
|---|---|---|---|---|---|---|
25,001 | How to avoid log(0) term in regression | The smaller the constant is that you add the larger the outlier is that you will create:
So it is hard to justify any constant here. You might consider a transformation that has no problem with 0s, for example a third order polynomial. | How to avoid log(0) term in regression | The smaller the constant is that you add the larger the outlier is that you will create:
So it is hard to justify any constant here. You might consider a transformation that has no problem with 0s, | How to avoid log(0) term in regression
The smaller the constant is that you add the larger the outlier is that you will create:
So it is hard to justify any constant here. You might consider a transformation that has no problem with 0s, for example a third order polynomial. | How to avoid log(0) term in regression
The smaller the constant is that you add the larger the outlier is that you will create:
So it is hard to justify any constant here. You might consider a transformation that has no problem with 0s, |
25,002 | How to avoid log(0) term in regression | Why do you want to plot logarithms? What's wrong with plotting the variables as they are?
One reason to work with logs is when an assumed generating distribution is log-normal, for example.
Another would be that the numbers represent scale parameters or are used multiplicatively, in which case the space in which they lie is naturally logarithmic (for the same reason that the Jeffreys prior of a scale variable is logarithmic).
Neither of these are the case. I think the right answer here is don't do it. First come up with a data-generating model, and then use your data in a way that is consistent with that.
It sounds like what you're trying to do is to add as many functions of the inputs as possible so that you get a "great fit". Why don't you add any of these functions: http://en.wikipedia.org/wiki/List_of_mathematical_functions ? Oh, you probably think many of those are ridiculous, like the Ackermann function. Why are they ridiculous? Each function of the input you add is essentially your hypothesis of a relationship. It's hard for either of us to imagine that $y$ is a function of Euler's totient function applied to $x$. This is why I'm against $y$ being a function of $\log x$. It seems equally ridiculous to me unless you explain this hypothesis to me.
Probably the only thing you're going to get by continually adding functions of the inputs is an overfitted model. If you want a model that actually validates well, you need to make good guesses and have enough data to learn a model. The more guesses you make, the more parameters you'll have, the more data you'll need. | How to avoid log(0) term in regression | Why do you want to plot logarithms? What's wrong with plotting the variables as they are?
One reason to work with logs is when an assumed generating distribution is log-normal, for example.
Another w | How to avoid log(0) term in regression
Why do you want to plot logarithms? What's wrong with plotting the variables as they are?
One reason to work with logs is when an assumed generating distribution is log-normal, for example.
Another would be that the numbers represent scale parameters or are used multiplicatively, in which case the space in which they lie is naturally logarithmic (for the same reason that the Jeffreys prior of a scale variable is logarithmic).
Neither of these are the case. I think the right answer here is don't do it. First come up with a data-generating model, and then use your data in a way that is consistent with that.
It sounds like what you're trying to do is to add as many functions of the inputs as possible so that you get a "great fit". Why don't you add any of these functions: http://en.wikipedia.org/wiki/List_of_mathematical_functions ? Oh, you probably think many of those are ridiculous, like the Ackermann function. Why are they ridiculous? Each function of the input you add is essentially your hypothesis of a relationship. It's hard for either of us to imagine that $y$ is a function of Euler's totient function applied to $x$. This is why I'm against $y$ being a function of $\log x$. It seems equally ridiculous to me unless you explain this hypothesis to me.
Probably the only thing you're going to get by continually adding functions of the inputs is an overfitted model. If you want a model that actually validates well, you need to make good guesses and have enough data to learn a model. The more guesses you make, the more parameters you'll have, the more data you'll need. | How to avoid log(0) term in regression
Why do you want to plot logarithms? What's wrong with plotting the variables as they are?
One reason to work with logs is when an assumed generating distribution is log-normal, for example.
Another w |
25,003 | How to avoid log(0) term in regression | It's hard to say with so few details about your data and only six observations, but maybe your problem lies in your Y variable (bounded between zero and one) and not in your X. Take a look at the following approach using the two-parameter log-logistic function from the drc package:
X<-c(1.000, 0.063, 0.031, 0.012, 0.005, 0.000)
Y<-c(1.000, 1.000, 1.000, 0.961, 0.884, 0.000)
library(drc)
mod1<-drm(Y ~ X, fct=LL.2())
summary(mod1)
#Model fitted: Log-logistic (ED50 as parameter) with lower limit at 0 and upper limit at 1 (2 parms)
#
#Parameter estimates:
#
# Estimate Std. Error t-value p-value
#b:(Intercept) -1.5131e+00 1.4894e-01 -1.0159e+01 0.0005
#e:(Intercept) 1.3134e-03 1.8925e-04 6.9401e+00 0.0023
#
#Residual standard error:
#
# 0.005071738 (4 degrees of freedom)
plot(X,Y)
lines(seq(0, 1, 0.001), predict(mod1, data.frame(X=seq(0, 1, 0.001)))) | How to avoid log(0) term in regression | It's hard to say with so few details about your data and only six observations, but maybe your problem lies in your Y variable (bounded between zero and one) and not in your X. Take a look at the foll | How to avoid log(0) term in regression
It's hard to say with so few details about your data and only six observations, but maybe your problem lies in your Y variable (bounded between zero and one) and not in your X. Take a look at the following approach using the two-parameter log-logistic function from the drc package:
X<-c(1.000, 0.063, 0.031, 0.012, 0.005, 0.000)
Y<-c(1.000, 1.000, 1.000, 0.961, 0.884, 0.000)
library(drc)
mod1<-drm(Y ~ X, fct=LL.2())
summary(mod1)
#Model fitted: Log-logistic (ED50 as parameter) with lower limit at 0 and upper limit at 1 (2 parms)
#
#Parameter estimates:
#
# Estimate Std. Error t-value p-value
#b:(Intercept) -1.5131e+00 1.4894e-01 -1.0159e+01 0.0005
#e:(Intercept) 1.3134e-03 1.8925e-04 6.9401e+00 0.0023
#
#Residual standard error:
#
# 0.005071738 (4 degrees of freedom)
plot(X,Y)
lines(seq(0, 1, 0.001), predict(mod1, data.frame(X=seq(0, 1, 0.001)))) | How to avoid log(0) term in regression
It's hard to say with so few details about your data and only six observations, but maybe your problem lies in your Y variable (bounded between zero and one) and not in your X. Take a look at the foll |
25,004 | How to avoid log(0) term in regression | Looking at the plot of y vs x, the functional form appears to be y = 1 - exp(-alpha x), with a very high alpha. This is close to but not quite a step function and you will need a large number of polynomials to fit this data (think in terms of exp(x) = 1 + x +x^2/2! + . + x^n/n! + ...). Rearranging terms, we get exp(-alpha x) = 1-y. If you take logs now, this gives -alpha x = log(1-y). You could define a new variable z = log(1-y) and try to find the alpha that best fits the data. You still have the issue of how to handle y = 1. I do not know the context of your problem but my impression is that you would have to think about y asymptotically approaching 1 as x approaches 1 and but y never actually reaches 1.
Thinking about this some more, I wonder if the data is actually from a Weibull distribution y = 1 - exp(-alpha x^beta). Rearranging terms, we get beta log(x) = log(-log(1-y)) - log(alpha) and we can use OLS to get alpha and beta. The issue of handling y = 1 remains. | How to avoid log(0) term in regression | Looking at the plot of y vs x, the functional form appears to be y = 1 - exp(-alpha x), with a very high alpha. This is close to but not quite a step function and you will need a large number of polyn | How to avoid log(0) term in regression
Looking at the plot of y vs x, the functional form appears to be y = 1 - exp(-alpha x), with a very high alpha. This is close to but not quite a step function and you will need a large number of polynomials to fit this data (think in terms of exp(x) = 1 + x +x^2/2! + . + x^n/n! + ...). Rearranging terms, we get exp(-alpha x) = 1-y. If you take logs now, this gives -alpha x = log(1-y). You could define a new variable z = log(1-y) and try to find the alpha that best fits the data. You still have the issue of how to handle y = 1. I do not know the context of your problem but my impression is that you would have to think about y asymptotically approaching 1 as x approaches 1 and but y never actually reaches 1.
Thinking about this some more, I wonder if the data is actually from a Weibull distribution y = 1 - exp(-alpha x^beta). Rearranging terms, we get beta log(x) = log(-log(1-y)) - log(alpha) and we can use OLS to get alpha and beta. The issue of handling y = 1 remains. | How to avoid log(0) term in regression
Looking at the plot of y vs x, the functional form appears to be y = 1 - exp(-alpha x), with a very high alpha. This is close to but not quite a step function and you will need a large number of polyn |
25,005 | z-score and Normal Distribution | Technically, z-scoring does not depend on any distributional assumptions, such as normality. It's just a way of describing how far observations are from the mean, no matter what the distribution happens to be. So no harm in z-scoring non-normal variables.
The main caveat is that z-scores tend to be more informative for distributions that are at least approximately symmetric about the mean (which includes normal distributions, but also many others), and less informative for highly skewed distributions. The reason is because in skewed distributions, two observations that lie on opposite side of the mean can have the same absolute z-score despite one being much more/less probable than the other. | z-score and Normal Distribution | Technically, z-scoring does not depend on any distributional assumptions, such as normality. It's just a way of describing how far observations are from the mean, no matter what the distribution happe | z-score and Normal Distribution
Technically, z-scoring does not depend on any distributional assumptions, such as normality. It's just a way of describing how far observations are from the mean, no matter what the distribution happens to be. So no harm in z-scoring non-normal variables.
The main caveat is that z-scores tend to be more informative for distributions that are at least approximately symmetric about the mean (which includes normal distributions, but also many others), and less informative for highly skewed distributions. The reason is because in skewed distributions, two observations that lie on opposite side of the mean can have the same absolute z-score despite one being much more/less probable than the other. | z-score and Normal Distribution
Technically, z-scoring does not depend on any distributional assumptions, such as normality. It's just a way of describing how far observations are from the mean, no matter what the distribution happe |
25,006 | z-score and Normal Distribution | Not exactly, z-score is just a form a transformation. What it does is replacing the measurement unit with "number of standard deviations" away from the mean. Hence, it's a convenient tool when someone wants to compare two variables that are measured in different units.
What you mentioned about normal distribution is not really a condition for using z-score, but an additional perk to z-score interpretation. When a distribution is normal, approximately 68% of the data will be between -1 to 1 SD, 95% between -2 to 2 SD, and 99.7% between -3 to 3 SD. (see image here). The same, however, cannot be said for non-normal distributions. | z-score and Normal Distribution | Not exactly, z-score is just a form a transformation. What it does is replacing the measurement unit with "number of standard deviations" away from the mean. Hence, it's a convenient tool when someone | z-score and Normal Distribution
Not exactly, z-score is just a form a transformation. What it does is replacing the measurement unit with "number of standard deviations" away from the mean. Hence, it's a convenient tool when someone wants to compare two variables that are measured in different units.
What you mentioned about normal distribution is not really a condition for using z-score, but an additional perk to z-score interpretation. When a distribution is normal, approximately 68% of the data will be between -1 to 1 SD, 95% between -2 to 2 SD, and 99.7% between -3 to 3 SD. (see image here). The same, however, cannot be said for non-normal distributions. | z-score and Normal Distribution
Not exactly, z-score is just a form a transformation. What it does is replacing the measurement unit with "number of standard deviations" away from the mean. Hence, it's a convenient tool when someone |
25,007 | z-score and Normal Distribution | Z Score Formula = (x – μ) / ơ
There is no relation distribution with z-score. To find out z score you just need three things. data point(x), mean(μ) and standard deviation(ơ). It does not limit to any specific distribution. To transform any data point to a z-score is called standardization and z-score has no unit. | z-score and Normal Distribution | Z Score Formula = (x – μ) / ơ
There is no relation distribution with z-score. To find out z score you just need three things. data point(x), mean(μ) and standard deviation(ơ). It does not limit to an | z-score and Normal Distribution
Z Score Formula = (x – μ) / ơ
There is no relation distribution with z-score. To find out z score you just need three things. data point(x), mean(μ) and standard deviation(ơ). It does not limit to any specific distribution. To transform any data point to a z-score is called standardization and z-score has no unit. | z-score and Normal Distribution
Z Score Formula = (x – μ) / ơ
There is no relation distribution with z-score. To find out z score you just need three things. data point(x), mean(μ) and standard deviation(ơ). It does not limit to an |
25,008 | z-score and Normal Distribution | I still makes sense to approximate the data as normal in certain instances...for most instances you would need to use substitute non-parametric tests such is Mann-Whitney etc.Also statisticians substitute Z scores with T scores to get more valid estimation read more about Z tables and z score... | z-score and Normal Distribution | I still makes sense to approximate the data as normal in certain instances...for most instances you would need to use substitute non-parametric tests such is Mann-Whitney etc.Also statisticians substi | z-score and Normal Distribution
I still makes sense to approximate the data as normal in certain instances...for most instances you would need to use substitute non-parametric tests such is Mann-Whitney etc.Also statisticians substitute Z scores with T scores to get more valid estimation read more about Z tables and z score... | z-score and Normal Distribution
I still makes sense to approximate the data as normal in certain instances...for most instances you would need to use substitute non-parametric tests such is Mann-Whitney etc.Also statisticians substi |
25,009 | Exponential of a standard normal random variable | Remember that the moment generating function of a normal random variable $Z\sim\textrm{N}(\mu,\sigma^2)$ is $\varphi_Z(t)=\mathrm{E}[e^{tZ}]=e^{\mu t + \sigma^2 t^2/2}$, and use that $\mathrm{E}[e^Z]=\varphi_Z(1)$.
Expanding a little bit
The following proposition, motivated by Huber's comment bellow, shows how this technique extends to the multivariate case.
Propositon. Let $(Z_1,\dots,Z_k)$ be a normal random vector with mean vector $m$ and covariance matrix $\Sigma=(\sigma_{ij})$. For the lognormal random vector $(U_1,\dots,U_k)=(e^{Z_1},\dots,e^{Z_k})$ we have $\mathrm{E}[U_i]=e^{m_i +\frac{1}{2}\sigma_{ii}}$ and $\mathrm{Cov}[U_i,U_j]=\mathrm{E}[U_i]\,\mathrm{E}[U_j](e^{\sigma_{ij}}-1)$, for $i,j=1,\dots,k$.
Proof. For $a=(a_1,\dots,a_k)^\top\in\mathbb{R}^k$, we have
$$
\mathrm{E}\!\left[\prod_{i=1}^k U_i^{a_i} \right] = \mathrm{E}\!\left[\prod_{i=1}^k e^{a_i Z_i} \right] = \mathrm{E}\!\left[e^{a^\top Z}\right] = e^{a^\top m +\frac{1}{2}a^\top\Sigma\,a} \, , \quad (*)
$$
in which we used the expression of the moment generating function of $(Z_1,\dots,Z_k)$. For $i=1,\dots,k$, choose $a\in\mathbb{R}^k$ such that its $i$-th component is equal to one and the other components are equal to zero. It follows from $(*)$ that $\mathrm{E}[U_i]=e^{m_i +\frac{1}{2}\sigma_{ii}}$. Now, for $i,j=1,\dots,k$, take $a\in\mathbb{R}^k$ such that its $i$-th and $j$-th components are equal to one and the others are equal to zero. It follows from $(*)$ that
$$
\mathrm{E}[U_i\,U_j]=e^{m_i+m_j+\frac{1}{2}\sigma_{ii}+\sigma_{ij}+\frac{1}{2}\sigma_{jj}}=\mathrm{E}[U_i]\,\mathrm{E}[U_j]\,e^{\sigma_{ij}}
$$
and
$$
\mathrm{Cov}[U_i,U_j]=\mathrm{E}[U_i\,U_j] - \mathrm{E}[U_i]\,\mathrm{E}[U_j] =\mathrm{E}[U_i]\,\mathrm{E}[U_j](e^{\sigma_{ij}}-1) \, .
$$ | Exponential of a standard normal random variable | Remember that the moment generating function of a normal random variable $Z\sim\textrm{N}(\mu,\sigma^2)$ is $\varphi_Z(t)=\mathrm{E}[e^{tZ}]=e^{\mu t + \sigma^2 t^2/2}$, and use that $\mathrm{E}[e^Z]= | Exponential of a standard normal random variable
Remember that the moment generating function of a normal random variable $Z\sim\textrm{N}(\mu,\sigma^2)$ is $\varphi_Z(t)=\mathrm{E}[e^{tZ}]=e^{\mu t + \sigma^2 t^2/2}$, and use that $\mathrm{E}[e^Z]=\varphi_Z(1)$.
Expanding a little bit
The following proposition, motivated by Huber's comment bellow, shows how this technique extends to the multivariate case.
Propositon. Let $(Z_1,\dots,Z_k)$ be a normal random vector with mean vector $m$ and covariance matrix $\Sigma=(\sigma_{ij})$. For the lognormal random vector $(U_1,\dots,U_k)=(e^{Z_1},\dots,e^{Z_k})$ we have $\mathrm{E}[U_i]=e^{m_i +\frac{1}{2}\sigma_{ii}}$ and $\mathrm{Cov}[U_i,U_j]=\mathrm{E}[U_i]\,\mathrm{E}[U_j](e^{\sigma_{ij}}-1)$, for $i,j=1,\dots,k$.
Proof. For $a=(a_1,\dots,a_k)^\top\in\mathbb{R}^k$, we have
$$
\mathrm{E}\!\left[\prod_{i=1}^k U_i^{a_i} \right] = \mathrm{E}\!\left[\prod_{i=1}^k e^{a_i Z_i} \right] = \mathrm{E}\!\left[e^{a^\top Z}\right] = e^{a^\top m +\frac{1}{2}a^\top\Sigma\,a} \, , \quad (*)
$$
in which we used the expression of the moment generating function of $(Z_1,\dots,Z_k)$. For $i=1,\dots,k$, choose $a\in\mathbb{R}^k$ such that its $i$-th component is equal to one and the other components are equal to zero. It follows from $(*)$ that $\mathrm{E}[U_i]=e^{m_i +\frac{1}{2}\sigma_{ii}}$. Now, for $i,j=1,\dots,k$, take $a\in\mathbb{R}^k$ such that its $i$-th and $j$-th components are equal to one and the others are equal to zero. It follows from $(*)$ that
$$
\mathrm{E}[U_i\,U_j]=e^{m_i+m_j+\frac{1}{2}\sigma_{ii}+\sigma_{ij}+\frac{1}{2}\sigma_{jj}}=\mathrm{E}[U_i]\,\mathrm{E}[U_j]\,e^{\sigma_{ij}}
$$
and
$$
\mathrm{Cov}[U_i,U_j]=\mathrm{E}[U_i\,U_j] - \mathrm{E}[U_i]\,\mathrm{E}[U_j] =\mathrm{E}[U_i]\,\mathrm{E}[U_j](e^{\sigma_{ij}}-1) \, .
$$ | Exponential of a standard normal random variable
Remember that the moment generating function of a normal random variable $Z\sim\textrm{N}(\mu,\sigma^2)$ is $\varphi_Z(t)=\mathrm{E}[e^{tZ}]=e^{\mu t + \sigma^2 t^2/2}$, and use that $\mathrm{E}[e^Z]= |
25,010 | Exponential of a standard normal random variable | As @Glen_b mentions for self-study problems please show an attempt. Here is how you would get started:
$\begin{align*}
\text{E}\left[e^Z\right] &= \dfrac{1}{\sqrt{2\pi}}\int_{-\infty}^\infty e^z e^{-z^2/2}dz \\
&= \dfrac{1}{\sqrt{2\pi}}\int_{-\infty}^\infty e^{-z^2/2 + z}dz \\
&= \dfrac{1}{\sqrt{2\pi}}\int_{-\infty}^\infty e^{\tfrac{-1}{2}(z^2 - 2z)}dz \\
&=
\end{align*}$
Now try completeing the square in the exponential so you get an integral that looks like it is the PDF of a normal distribution with known mean and variance. The answer will be $e^{1/2}$ | Exponential of a standard normal random variable | As @Glen_b mentions for self-study problems please show an attempt. Here is how you would get started:
$\begin{align*}
\text{E}\left[e^Z\right] &= \dfrac{1}{\sqrt{2\pi}}\int_{-\infty}^\infty e^z e^{-z | Exponential of a standard normal random variable
As @Glen_b mentions for self-study problems please show an attempt. Here is how you would get started:
$\begin{align*}
\text{E}\left[e^Z\right] &= \dfrac{1}{\sqrt{2\pi}}\int_{-\infty}^\infty e^z e^{-z^2/2}dz \\
&= \dfrac{1}{\sqrt{2\pi}}\int_{-\infty}^\infty e^{-z^2/2 + z}dz \\
&= \dfrac{1}{\sqrt{2\pi}}\int_{-\infty}^\infty e^{\tfrac{-1}{2}(z^2 - 2z)}dz \\
&=
\end{align*}$
Now try completeing the square in the exponential so you get an integral that looks like it is the PDF of a normal distribution with known mean and variance. The answer will be $e^{1/2}$ | Exponential of a standard normal random variable
As @Glen_b mentions for self-study problems please show an attempt. Here is how you would get started:
$\begin{align*}
\text{E}\left[e^Z\right] &= \dfrac{1}{\sqrt{2\pi}}\int_{-\infty}^\infty e^z e^{-z |
25,011 | Exponential of a standard normal random variable | How do I prove that $e^Z$ has a mean of $e^{0.5}$?
You can do it via integration, it's quite straightforward - you combine the $\exp$ terms into one exponent, complete the square and identify the density (which integrates to 1) leaving just a constant out the front.
An alternative is to do it via the MGF, which makes it trivial.
Also what is the pdf of $\exp(Z)$?
You just use straight up change of variable, keeping in mind the Jacobian. Or you can do it from first principles (Let $Y=\exp(Z)$ then $P(Y\leq y) = P(\exp(Z)\leq y) = ...$)
You get a particular case of the lognormal density. | Exponential of a standard normal random variable | How do I prove that $e^Z$ has a mean of $e^{0.5}$?
You can do it via integration, it's quite straightforward - you combine the $\exp$ terms into one exponent, complete the square and identify the de | Exponential of a standard normal random variable
How do I prove that $e^Z$ has a mean of $e^{0.5}$?
You can do it via integration, it's quite straightforward - you combine the $\exp$ terms into one exponent, complete the square and identify the density (which integrates to 1) leaving just a constant out the front.
An alternative is to do it via the MGF, which makes it trivial.
Also what is the pdf of $\exp(Z)$?
You just use straight up change of variable, keeping in mind the Jacobian. Or you can do it from first principles (Let $Y=\exp(Z)$ then $P(Y\leq y) = P(\exp(Z)\leq y) = ...$)
You get a particular case of the lognormal density. | Exponential of a standard normal random variable
How do I prove that $e^Z$ has a mean of $e^{0.5}$?
You can do it via integration, it's quite straightforward - you combine the $\exp$ terms into one exponent, complete the square and identify the de |
25,012 | Does Newman's network modularity work for signed, weighted graphs? | The straightforward generalization of the modularity for weighted networks does not work if those weights are signed. By straightforward, I mean: just using the weight matrix instead of the adjacency one, like Newman does, for instance, in (Newman 2004). You need a specific version, such as that cited by BenjaminLind, or that of (Gomez et al. 2009).
In both articles, they explain the reason for this. In summary: the modularity relies on the fact some normalized degrees (or strengths in the case of weighted networks) can be considered as probabilities. The probability a link exists between nodes $i$ and $j$ is estimated using $p_ip_j=w_iw_j/(2w)^2$, where $w_i$ and $w_j$ are the respective strengths of nodes $i$ and $j$ and $w$ is the total strength over all the network nodes. If some weights are negative, then the original normalization doesn't guarantee having values in $[0,1]$ anymore, so the above $p_ip_j$ quantity cannot be considered as a probability.
To solve this problem, Gomez et al. consider positive and negative links separately. They obtain two distinct modularity values: one for positive links, one for negative ones. They substract the latter from the former to get the overall modularity. | Does Newman's network modularity work for signed, weighted graphs? | The straightforward generalization of the modularity for weighted networks does not work if those weights are signed. By straightforward, I mean: just using the weight matrix instead of the adjacency | Does Newman's network modularity work for signed, weighted graphs?
The straightforward generalization of the modularity for weighted networks does not work if those weights are signed. By straightforward, I mean: just using the weight matrix instead of the adjacency one, like Newman does, for instance, in (Newman 2004). You need a specific version, such as that cited by BenjaminLind, or that of (Gomez et al. 2009).
In both articles, they explain the reason for this. In summary: the modularity relies on the fact some normalized degrees (or strengths in the case of weighted networks) can be considered as probabilities. The probability a link exists between nodes $i$ and $j$ is estimated using $p_ip_j=w_iw_j/(2w)^2$, where $w_i$ and $w_j$ are the respective strengths of nodes $i$ and $j$ and $w$ is the total strength over all the network nodes. If some weights are negative, then the original normalization doesn't guarantee having values in $[0,1]$ anymore, so the above $p_ip_j$ quantity cannot be considered as a probability.
To solve this problem, Gomez et al. consider positive and negative links separately. They obtain two distinct modularity values: one for positive links, one for negative ones. They substract the latter from the former to get the overall modularity. | Does Newman's network modularity work for signed, weighted graphs?
The straightforward generalization of the modularity for weighted networks does not work if those weights are signed. By straightforward, I mean: just using the weight matrix instead of the adjacency |
25,013 | Does Newman's network modularity work for signed, weighted graphs? | Yes, it can. Spin-glass models for community detection can compute modularity from weighted, signed graphs. You'll want Traag and Bruggeman "Community detection in networks with positive and negative links" as a reference. The function "spinglass.community()" in igraph can find the communities and return the graph's modularity. | Does Newman's network modularity work for signed, weighted graphs? | Yes, it can. Spin-glass models for community detection can compute modularity from weighted, signed graphs. You'll want Traag and Bruggeman "Community detection in networks with positive and negative | Does Newman's network modularity work for signed, weighted graphs?
Yes, it can. Spin-glass models for community detection can compute modularity from weighted, signed graphs. You'll want Traag and Bruggeman "Community detection in networks with positive and negative links" as a reference. The function "spinglass.community()" in igraph can find the communities and return the graph's modularity. | Does Newman's network modularity work for signed, weighted graphs?
Yes, it can. Spin-glass models for community detection can compute modularity from weighted, signed graphs. You'll want Traag and Bruggeman "Community detection in networks with positive and negative |
25,014 | Does Newman's network modularity work for signed, weighted graphs? | We have pointed out the problem of Modularity[-alike] functions with signed networks in this paper. They tend to ignore the positive density of communities more as the absolute number of negative links in the network increases.
Also, here is our open source java project for weighted-signed networks, which is based on Constant Potts Model (similar to Modularity), fast Louvain algorithm, and community evaluation based on an extension of Map Equation.
Esmailian, P. and Jalili, M., 2015. Community detection in signed networks: the role of negative ties in different scales. Scientific reports, 5, p.14339 | Does Newman's network modularity work for signed, weighted graphs? | We have pointed out the problem of Modularity[-alike] functions with signed networks in this paper. They tend to ignore the positive density of communities more as the absolute number of negative link | Does Newman's network modularity work for signed, weighted graphs?
We have pointed out the problem of Modularity[-alike] functions with signed networks in this paper. They tend to ignore the positive density of communities more as the absolute number of negative links in the network increases.
Also, here is our open source java project for weighted-signed networks, which is based on Constant Potts Model (similar to Modularity), fast Louvain algorithm, and community evaluation based on an extension of Map Equation.
Esmailian, P. and Jalili, M., 2015. Community detection in signed networks: the role of negative ties in different scales. Scientific reports, 5, p.14339 | Does Newman's network modularity work for signed, weighted graphs?
We have pointed out the problem of Modularity[-alike] functions with signed networks in this paper. They tend to ignore the positive density of communities more as the absolute number of negative link |
25,015 | Intuitive understanding covariance, cross-covariance, auto-/cross-correliation and power spectrum density | Covariance, as you might guess from the name, indicates the tendency of two variables to co-vary or "move" together. If cov($X$, $Y$) is positive, then larger values of $X$ are associated with larger values of $Y$ and smaller values of $X$ are associated with smaller values of $Y$. If the covariance is negative, the opposite holds: small $X$s are associated with larger $Y$s and vice versa. For example, we'd expect to see a high covariance between salary and years of experience, but a low or negative covariance between weight and top running speed.
Covariance is scale-dependent (e.g., you'll get a different covariance if weight is measured in kilograms or pounds) and the units are a little strange (dollar-years and kilogram-meters-per-second in our two examples), so we often normalize covariances by dividing by $\sigma_x \cdot \sigma_y$ to get correlation. Correlation is unitless and ranges from -1 to 1, which makes it a handy measure of linear associations. (That linear bit is a very imporant caveat!)
Now, suppose we have a series of values that are somehow ordered; these are often, but not always, a time series. The auto-correlation function is the correlation between the value at position/time $t$ is with values at other positions $(t-1)$, $(t-2)$, etc. High autocorrelations may indicate that the series changes slowly, or, equivalently, that the present value is predictable from previous values. Although variance and covariance are scalars (i.e., single values), the auto-correlation is a vector--you get an autocorrelation value for each "lag" or "gap". White noise has a very flat autocorrelation function since it's random; natural images typically have broad spatial autocorrelations since nearby pixels are often of similar color and brightness. An echo might have a peak near the center (since the sounds are self-similar), a flat region during the silence, and then another peak that constitutes the echo itself.
Cross-correlation compares two series by shifting one of them relative to the other. Like auto-correlation, it produces a vector. The middle of the vector is just the correlation between $X$ and $Y$. The entry before that is correlation between a copy of $X$ shifted slightly one way and Y; the entry after the middle is the correlation between a copy of $X$ shifted slightly the other way and $Y$. (If you're familiar with convolution, this is very similar). If $X$ and $Y$ are (possibly-delayed) copies of each other, they'll have a cross-correlation function with a peak of 1.0 somewhere, with the location of the peak given by the delay.
The auto-covariance and cross-covariance functions are like their correlation equivalents, but unscaled; it's the same difference as between covariance and correlation.
A power spectral density tells you how the power of a signal is distributed over various frequencies. The PSD of pure tone (i.e., a sine wave) is flat except at the tone's frequency; Naturalistic signals and sounds have much more complicated PSDs with harmonics, overtones, resonance, etc. It's related to the other concepts because the Fourier transform of the autocorrelation function is the PSD. | Intuitive understanding covariance, cross-covariance, auto-/cross-correliation and power spectrum de | Covariance, as you might guess from the name, indicates the tendency of two variables to co-vary or "move" together. If cov($X$, $Y$) is positive, then larger values of $X$ are associated with larger | Intuitive understanding covariance, cross-covariance, auto-/cross-correliation and power spectrum density
Covariance, as you might guess from the name, indicates the tendency of two variables to co-vary or "move" together. If cov($X$, $Y$) is positive, then larger values of $X$ are associated with larger values of $Y$ and smaller values of $X$ are associated with smaller values of $Y$. If the covariance is negative, the opposite holds: small $X$s are associated with larger $Y$s and vice versa. For example, we'd expect to see a high covariance between salary and years of experience, but a low or negative covariance between weight and top running speed.
Covariance is scale-dependent (e.g., you'll get a different covariance if weight is measured in kilograms or pounds) and the units are a little strange (dollar-years and kilogram-meters-per-second in our two examples), so we often normalize covariances by dividing by $\sigma_x \cdot \sigma_y$ to get correlation. Correlation is unitless and ranges from -1 to 1, which makes it a handy measure of linear associations. (That linear bit is a very imporant caveat!)
Now, suppose we have a series of values that are somehow ordered; these are often, but not always, a time series. The auto-correlation function is the correlation between the value at position/time $t$ is with values at other positions $(t-1)$, $(t-2)$, etc. High autocorrelations may indicate that the series changes slowly, or, equivalently, that the present value is predictable from previous values. Although variance and covariance are scalars (i.e., single values), the auto-correlation is a vector--you get an autocorrelation value for each "lag" or "gap". White noise has a very flat autocorrelation function since it's random; natural images typically have broad spatial autocorrelations since nearby pixels are often of similar color and brightness. An echo might have a peak near the center (since the sounds are self-similar), a flat region during the silence, and then another peak that constitutes the echo itself.
Cross-correlation compares two series by shifting one of them relative to the other. Like auto-correlation, it produces a vector. The middle of the vector is just the correlation between $X$ and $Y$. The entry before that is correlation between a copy of $X$ shifted slightly one way and Y; the entry after the middle is the correlation between a copy of $X$ shifted slightly the other way and $Y$. (If you're familiar with convolution, this is very similar). If $X$ and $Y$ are (possibly-delayed) copies of each other, they'll have a cross-correlation function with a peak of 1.0 somewhere, with the location of the peak given by the delay.
The auto-covariance and cross-covariance functions are like their correlation equivalents, but unscaled; it's the same difference as between covariance and correlation.
A power spectral density tells you how the power of a signal is distributed over various frequencies. The PSD of pure tone (i.e., a sine wave) is flat except at the tone's frequency; Naturalistic signals and sounds have much more complicated PSDs with harmonics, overtones, resonance, etc. It's related to the other concepts because the Fourier transform of the autocorrelation function is the PSD. | Intuitive understanding covariance, cross-covariance, auto-/cross-correliation and power spectrum de
Covariance, as you might guess from the name, indicates the tendency of two variables to co-vary or "move" together. If cov($X$, $Y$) is positive, then larger values of $X$ are associated with larger |
25,016 | How much calculus is necessary to understand maximum likelihood estimation? | To expand on my comment - it depends. If you're only trying to comprehend the basics, being able to find extrema of functions gets you a fair way (though in many practical cases of MLE, the likelihood is maximized numerically, in which case you need some other skills as well as some basic calculus).
I'll leave aside the nice simple cases where you get explicit algebraic solutions. Even so, calculus is often very useful.
I'll assume independence throughout. Let's take the simplest possible case of 1-parameter optimization. First we'll look at a case where we can take derivatives and separate out a function of the parameter and a statistic.
Consider the $\rm{Gamma}(\alpha,1)$ density
$$
f_X(x;\alpha) = \frac{1}{\Gamma(\alpha)} x^{\alpha-1} \exp(-x); \,\,\, x>0;\,\,\alpha>0
$$
Then for a sample of size $n$, the likelihood is
$$
\mathcal{L}(\alpha; \mathbf{x}) = \prod_{i=1}^n f_X(x_i;\alpha)
$$
and so the log-likelihood is
$$
\mathcal{l}(\alpha; \mathbf{x}) = \sum_{i=1}^n \ln{f_X(x_i;\alpha)} \\
= \sum_{i=1}^n \ln{\left(\frac{1}{\Gamma(\alpha)} x_i^{\alpha-1} \exp(-x_i)\right)}\\
$$
$$
= \sum_{i=1}^n -\ln{\Gamma(\alpha)}+(\alpha-1)\ln{x_i} -x_i\\
$$
$$
= -n\ln{\Gamma(\alpha)}+(\alpha-1)S_x -n\bar{x}
$$
where $S_x=\sum_{i=1}^n\ln{x_i}$. Taking derivatives,
$$
\frac{d}{d\alpha}\mathcal{l}(\alpha; \mathbf{x}) = \frac{d}{d\alpha} \left(-n\ln{\Gamma(\alpha)}+(\alpha-1)S_x -n\bar{x}\right)\\
$$
$$
= -n\frac{\Gamma'(\alpha)}{{\Gamma(\alpha)}}+S_x\\
$$
$$
= -n\psi(\alpha)+S_x
$$
So if we set that to zero and try to solve for $\hat{\alpha}$, we can get this:
$$
\psi(\hat{\alpha})=\ln{G(\mathbf{x})}\\
$$
where $\psi(\cdot)$ is the digamma function and $G(\cdot)$ is the geometric mean. We must not forget that in general you can't just set the derivative to zero and be confident you will locate the argmax; you still have to show in some way that the solution is a maximum (in this case it is). More generally, you may get minima, or horizontal points of inflexion, and even if you have a local maximum, you may not have a global maximum (which I touch on near the end).
So our task is now to find the value of $\hat{\alpha}$ for which
$$
\psi(\hat{\alpha})=g
$$
where $g=\ln{G(\mathbf{x})}$.
This doesn't have a solution in terms of elementary functions, it must be calculated numerically; at least we were able to get a function of the parameter on one side and a function of the data on the other. There are various zero-finding algorithms that might be used if you don't have an explicit way of solving the equation (even if you are without derivatives, there's binary section, for example).
Often, it's not so nice as that. Consider the logistic density with unit scale:
$$
f(x; \mu) =\frac{1}{4} \operatorname{sech}^2\!\left(\frac{x-\mu}{2}\right).
$$
Neither the argmax of the likelihood nor of the log-likelihood function can be readily obtained algebraically - you have to use numerical optimization methods. In this case, the function is fairly well behaved and the Newton-Raphson method should usually suffice to locate the ML estimate of $\mu$. If the derivative was unavailable or if Newton-Raphson doesn't converge, other numerical optimization methods may be needed, such as golden-section (this is not intended to be an overview of the best available methods, just mentioning some methods you are more likely to encounter at a basic level).
More generally, you may not even be able to do that much. Consider a Cauchy with median $\theta$ and unit scale:
$$
f_X(x;\theta) = \frac{1}{\pi (1 + (x-\theta)^2)}\,.
$$
In general the likelihood here doesn't have a unique local maximum, but several local maxima. If you find a local maximum, there may be another, bigger one elsewhere. (Sometimes people focus on identifying the local maximum closest to the median, or some-such.)
It is easy for beginners to assume that if they find a concave turning point that they have the argmax of the function, but besides multiple modes (already discussed), there may be maxima that are not associated with turning points at all. Taking derivatives and setting them to zero is not sufficient; consider estimating the parameter for a uniform on $(0,\theta)$ for example.
In other cases, the parameter space may be discrete.
Sometimes finding the maximum may be quite involved.
And that's just a sampling of the issues with a single parameter. When you have multiple parameters, things get more involved again. | How much calculus is necessary to understand maximum likelihood estimation? | To expand on my comment - it depends. If you're only trying to comprehend the basics, being able to find extrema of functions gets you a fair way (though in many practical cases of MLE, the likelihood | How much calculus is necessary to understand maximum likelihood estimation?
To expand on my comment - it depends. If you're only trying to comprehend the basics, being able to find extrema of functions gets you a fair way (though in many practical cases of MLE, the likelihood is maximized numerically, in which case you need some other skills as well as some basic calculus).
I'll leave aside the nice simple cases where you get explicit algebraic solutions. Even so, calculus is often very useful.
I'll assume independence throughout. Let's take the simplest possible case of 1-parameter optimization. First we'll look at a case where we can take derivatives and separate out a function of the parameter and a statistic.
Consider the $\rm{Gamma}(\alpha,1)$ density
$$
f_X(x;\alpha) = \frac{1}{\Gamma(\alpha)} x^{\alpha-1} \exp(-x); \,\,\, x>0;\,\,\alpha>0
$$
Then for a sample of size $n$, the likelihood is
$$
\mathcal{L}(\alpha; \mathbf{x}) = \prod_{i=1}^n f_X(x_i;\alpha)
$$
and so the log-likelihood is
$$
\mathcal{l}(\alpha; \mathbf{x}) = \sum_{i=1}^n \ln{f_X(x_i;\alpha)} \\
= \sum_{i=1}^n \ln{\left(\frac{1}{\Gamma(\alpha)} x_i^{\alpha-1} \exp(-x_i)\right)}\\
$$
$$
= \sum_{i=1}^n -\ln{\Gamma(\alpha)}+(\alpha-1)\ln{x_i} -x_i\\
$$
$$
= -n\ln{\Gamma(\alpha)}+(\alpha-1)S_x -n\bar{x}
$$
where $S_x=\sum_{i=1}^n\ln{x_i}$. Taking derivatives,
$$
\frac{d}{d\alpha}\mathcal{l}(\alpha; \mathbf{x}) = \frac{d}{d\alpha} \left(-n\ln{\Gamma(\alpha)}+(\alpha-1)S_x -n\bar{x}\right)\\
$$
$$
= -n\frac{\Gamma'(\alpha)}{{\Gamma(\alpha)}}+S_x\\
$$
$$
= -n\psi(\alpha)+S_x
$$
So if we set that to zero and try to solve for $\hat{\alpha}$, we can get this:
$$
\psi(\hat{\alpha})=\ln{G(\mathbf{x})}\\
$$
where $\psi(\cdot)$ is the digamma function and $G(\cdot)$ is the geometric mean. We must not forget that in general you can't just set the derivative to zero and be confident you will locate the argmax; you still have to show in some way that the solution is a maximum (in this case it is). More generally, you may get minima, or horizontal points of inflexion, and even if you have a local maximum, you may not have a global maximum (which I touch on near the end).
So our task is now to find the value of $\hat{\alpha}$ for which
$$
\psi(\hat{\alpha})=g
$$
where $g=\ln{G(\mathbf{x})}$.
This doesn't have a solution in terms of elementary functions, it must be calculated numerically; at least we were able to get a function of the parameter on one side and a function of the data on the other. There are various zero-finding algorithms that might be used if you don't have an explicit way of solving the equation (even if you are without derivatives, there's binary section, for example).
Often, it's not so nice as that. Consider the logistic density with unit scale:
$$
f(x; \mu) =\frac{1}{4} \operatorname{sech}^2\!\left(\frac{x-\mu}{2}\right).
$$
Neither the argmax of the likelihood nor of the log-likelihood function can be readily obtained algebraically - you have to use numerical optimization methods. In this case, the function is fairly well behaved and the Newton-Raphson method should usually suffice to locate the ML estimate of $\mu$. If the derivative was unavailable or if Newton-Raphson doesn't converge, other numerical optimization methods may be needed, such as golden-section (this is not intended to be an overview of the best available methods, just mentioning some methods you are more likely to encounter at a basic level).
More generally, you may not even be able to do that much. Consider a Cauchy with median $\theta$ and unit scale:
$$
f_X(x;\theta) = \frac{1}{\pi (1 + (x-\theta)^2)}\,.
$$
In general the likelihood here doesn't have a unique local maximum, but several local maxima. If you find a local maximum, there may be another, bigger one elsewhere. (Sometimes people focus on identifying the local maximum closest to the median, or some-such.)
It is easy for beginners to assume that if they find a concave turning point that they have the argmax of the function, but besides multiple modes (already discussed), there may be maxima that are not associated with turning points at all. Taking derivatives and setting them to zero is not sufficient; consider estimating the parameter for a uniform on $(0,\theta)$ for example.
In other cases, the parameter space may be discrete.
Sometimes finding the maximum may be quite involved.
And that's just a sampling of the issues with a single parameter. When you have multiple parameters, things get more involved again. | How much calculus is necessary to understand maximum likelihood estimation?
To expand on my comment - it depends. If you're only trying to comprehend the basics, being able to find extrema of functions gets you a fair way (though in many practical cases of MLE, the likelihood |
25,017 | How much calculus is necessary to understand maximum likelihood estimation? | Yes. Of course, we are not talking about one-dimensional functions, but functions $\mathbb{R}^p \to \mathbb{R}$ to be maximized (viz., the likelihood), so this is slightly more advanced than the one-dimensional case.
Some facility with logarithms will definitely be helpful, since maximizing the logarithm of the likelihood is usually much easier than maximizing the likelihood itself.
Quite a lot more than simple MLE can be understood (information matrices etc.) if you can deal with second derivatives of $\mathbb{R}^p \to \mathbb{R}$ functions, i.e., the Hessian matrix. | How much calculus is necessary to understand maximum likelihood estimation? | Yes. Of course, we are not talking about one-dimensional functions, but functions $\mathbb{R}^p \to \mathbb{R}$ to be maximized (viz., the likelihood), so this is slightly more advanced than the one-d | How much calculus is necessary to understand maximum likelihood estimation?
Yes. Of course, we are not talking about one-dimensional functions, but functions $\mathbb{R}^p \to \mathbb{R}$ to be maximized (viz., the likelihood), so this is slightly more advanced than the one-dimensional case.
Some facility with logarithms will definitely be helpful, since maximizing the logarithm of the likelihood is usually much easier than maximizing the likelihood itself.
Quite a lot more than simple MLE can be understood (information matrices etc.) if you can deal with second derivatives of $\mathbb{R}^p \to \mathbb{R}$ functions, i.e., the Hessian matrix. | How much calculus is necessary to understand maximum likelihood estimation?
Yes. Of course, we are not talking about one-dimensional functions, but functions $\mathbb{R}^p \to \mathbb{R}$ to be maximized (viz., the likelihood), so this is slightly more advanced than the one-d |
25,018 | Possible extensions to the default diagnostic plots for lm (in R and in general)? | Package car has quite a lot of useful functions for diagnostic plots of linear and generalized linear models. Compared to vanilla R plots, they are often enhanced with additional information. I recommend you try example("<function>") on the following functions to see what the plots look like. All plots are described in detail in chapter 6 of Fox & Weisberg. 2011. An R Companion to Applied Regression. 2nd ed.
residualPlots() plots Pearson residuals against each predictor (scatterplots for numeric variables including a Lowess fit, boxplots for factors)
marginalModelPlots() displays scatterplots of the response variable against each numeric predictor, inluding a Lowess fit
avPlots() displays partial-regression plots: for each predictor, this is a scatterplot of a) the residuals from the regression of the response variable on all other predictors against b) the residuals from the regression of the predictor against all other predictors
qqPlot() for a quantile-quantile plot which includes a confidence envelope
influenceIndexPlot() displays each value for Cook's distance, hat-value, p-value for outlier test, and studentized residual in a spike-plot against the observation index
influencePlot() gives a bubble-plot of studentized residuals against hat-values, with the size of the bubble corresponding to Cook's distance, also see dfbetaPlots() and leveragePlots()
boxCox() displays a profile of the log-likelihood for the transformation parameter $\lambda$ in a Box-Cox power-transform
crPlots() is for component + residual plots, a variant of which are CERES plots (Combining conditional Expectations and RESiduals), provided by ceresPlots()
spreadLevelPlot() is for assessing non-constant error variance and displays absolute studentized residuals against fitted values
scatterplot() provides much-enhanced scatterplots inluding boxplots along the axes, confidence ellipses for the bivariate distribution, and prediction lines with confidence bands
scatter3d() is based on package rgl and displays interactive 3D-scatterplots including wire-mesh confidence ellipsoids and prediction planes, make sure to run example("scatter3d")
In addition, have a look at bplot() from package rms for another approach to illustrating the common distribution of three variables. | Possible extensions to the default diagnostic plots for lm (in R and in general)? | Package car has quite a lot of useful functions for diagnostic plots of linear and generalized linear models. Compared to vanilla R plots, they are often enhanced with additional information. I recomm | Possible extensions to the default diagnostic plots for lm (in R and in general)?
Package car has quite a lot of useful functions for diagnostic plots of linear and generalized linear models. Compared to vanilla R plots, they are often enhanced with additional information. I recommend you try example("<function>") on the following functions to see what the plots look like. All plots are described in detail in chapter 6 of Fox & Weisberg. 2011. An R Companion to Applied Regression. 2nd ed.
residualPlots() plots Pearson residuals against each predictor (scatterplots for numeric variables including a Lowess fit, boxplots for factors)
marginalModelPlots() displays scatterplots of the response variable against each numeric predictor, inluding a Lowess fit
avPlots() displays partial-regression plots: for each predictor, this is a scatterplot of a) the residuals from the regression of the response variable on all other predictors against b) the residuals from the regression of the predictor against all other predictors
qqPlot() for a quantile-quantile plot which includes a confidence envelope
influenceIndexPlot() displays each value for Cook's distance, hat-value, p-value for outlier test, and studentized residual in a spike-plot against the observation index
influencePlot() gives a bubble-plot of studentized residuals against hat-values, with the size of the bubble corresponding to Cook's distance, also see dfbetaPlots() and leveragePlots()
boxCox() displays a profile of the log-likelihood for the transformation parameter $\lambda$ in a Box-Cox power-transform
crPlots() is for component + residual plots, a variant of which are CERES plots (Combining conditional Expectations and RESiduals), provided by ceresPlots()
spreadLevelPlot() is for assessing non-constant error variance and displays absolute studentized residuals against fitted values
scatterplot() provides much-enhanced scatterplots inluding boxplots along the axes, confidence ellipses for the bivariate distribution, and prediction lines with confidence bands
scatter3d() is based on package rgl and displays interactive 3D-scatterplots including wire-mesh confidence ellipsoids and prediction planes, make sure to run example("scatter3d")
In addition, have a look at bplot() from package rms for another approach to illustrating the common distribution of three variables. | Possible extensions to the default diagnostic plots for lm (in R and in general)?
Package car has quite a lot of useful functions for diagnostic plots of linear and generalized linear models. Compared to vanilla R plots, they are often enhanced with additional information. I recomm |
25,019 | Possible extensions to the default diagnostic plots for lm (in R and in general)? | This answer focus on what's available in base R, rather than external packages, although I agree that Fox's package is worth to adopt.
The function influence() (or its wrapper, influence.measures()) returns most of what we need for model diagnostic, including jacknifed statistics. As stated in Chambers and Hastie's Statistical Models in S (Wadsworth & Brooks, 1992), it can be used in combination to summary.lm(). One of the example provided in the so-called "white book" (pp. 130-131) allows to compute standardized (residuals with equal variance) and studentized (the same with a different estimate for SE) residuals, DFBETAS (change in the coefficients scaled by the SE for the regression coefficients), DFFIT (change in the fitted value when observation is dropped), and DFFITS (the same, with unit variance) measures without much difficulty.
Based on your example, and defining the following objects:
lms <- summary(fit)
lmi <- influence(fit)
e <- residuals(fit)
s <- lms$sigma
xxi <- diag(lms$cov.unscaled)
si <- lmi$sigma
h <- lmi$hat
bi <- coef(fit) - coef(lmi)
we can compute the above quantities as follows:
std. residuals e / (s * (1-h)^.5
stud. residuals e / (si * (1-h)^.5
dfbetas bi / (si %o% xxi^.5
dffit h * e / (1-h)
dffits h^.5 * e / (si * (1-h))
(This is Table 4.1, p. 131.)
Chambers and Hastie give the following S/R code for computing DFBETAS:
dfbetas <- function(fit, lms = summary(fit), lmi = lm.influence(fit)) {
xxi <- diag(lms$cov.unscaled)
si <- lmi$sigma
bi <- coef(fit) - coef(lmi)
bi / (si %o% xxi^0.5)
}
Why do I mention that approach? Because, first, I find this is interesting from a pedagogical perspective (that's what I am using when teaching introductory statistics courses) as it allows to illustrate what can be computed from the output of a fitted linear model fitted in R (but the same would apply with any other statistical package). Second, as the above quantities will be returned as simple vectors or matrices in R, that also means that we can choose the graphics device we want---lattice or ggplot--- to display those statistics, or use them to enhance an existing plot (e.g., highlight DFFITS values in a scatterplot by varying point size cex). | Possible extensions to the default diagnostic plots for lm (in R and in general)? | This answer focus on what's available in base R, rather than external packages, although I agree that Fox's package is worth to adopt.
The function influence() (or its wrapper, influence.measures()) r | Possible extensions to the default diagnostic plots for lm (in R and in general)?
This answer focus on what's available in base R, rather than external packages, although I agree that Fox's package is worth to adopt.
The function influence() (or its wrapper, influence.measures()) returns most of what we need for model diagnostic, including jacknifed statistics. As stated in Chambers and Hastie's Statistical Models in S (Wadsworth & Brooks, 1992), it can be used in combination to summary.lm(). One of the example provided in the so-called "white book" (pp. 130-131) allows to compute standardized (residuals with equal variance) and studentized (the same with a different estimate for SE) residuals, DFBETAS (change in the coefficients scaled by the SE for the regression coefficients), DFFIT (change in the fitted value when observation is dropped), and DFFITS (the same, with unit variance) measures without much difficulty.
Based on your example, and defining the following objects:
lms <- summary(fit)
lmi <- influence(fit)
e <- residuals(fit)
s <- lms$sigma
xxi <- diag(lms$cov.unscaled)
si <- lmi$sigma
h <- lmi$hat
bi <- coef(fit) - coef(lmi)
we can compute the above quantities as follows:
std. residuals e / (s * (1-h)^.5
stud. residuals e / (si * (1-h)^.5
dfbetas bi / (si %o% xxi^.5
dffit h * e / (1-h)
dffits h^.5 * e / (si * (1-h))
(This is Table 4.1, p. 131.)
Chambers and Hastie give the following S/R code for computing DFBETAS:
dfbetas <- function(fit, lms = summary(fit), lmi = lm.influence(fit)) {
xxi <- diag(lms$cov.unscaled)
si <- lmi$sigma
bi <- coef(fit) - coef(lmi)
bi / (si %o% xxi^0.5)
}
Why do I mention that approach? Because, first, I find this is interesting from a pedagogical perspective (that's what I am using when teaching introductory statistics courses) as it allows to illustrate what can be computed from the output of a fitted linear model fitted in R (but the same would apply with any other statistical package). Second, as the above quantities will be returned as simple vectors or matrices in R, that also means that we can choose the graphics device we want---lattice or ggplot--- to display those statistics, or use them to enhance an existing plot (e.g., highlight DFFITS values in a scatterplot by varying point size cex). | Possible extensions to the default diagnostic plots for lm (in R and in general)?
This answer focus on what's available in base R, rather than external packages, although I agree that Fox's package is worth to adopt.
The function influence() (or its wrapper, influence.measures()) r |
25,020 | Use a trendline formula to get values for any given X with Excel | Use LINEST, as shown:
The method is to create new columns (C:E here) containing the variables in the fit. Perversely, LINEST returns the coefficients in the reverse order, as you can see from the calculation in the "Fit" column. An example prediction is shown outlined in blue: all the formulas are exactly the same as for the data.
Note that LINEST is an array formula: the answer will occupy p+1 cells in a row, where p is the number of variables (the last one is for the constant term). Such formulas are created by selecting all the output cells, pasting (or typing) the formula in the formula textbox, and pressing Ctrl-Shift-Enter (instead of the usual Enter). | Use a trendline formula to get values for any given X with Excel | Use LINEST, as shown:
The method is to create new columns (C:E here) containing the variables in the fit. Perversely, LINEST returns the coefficients in the reverse order, as you can see from the ca | Use a trendline formula to get values for any given X with Excel
Use LINEST, as shown:
The method is to create new columns (C:E here) containing the variables in the fit. Perversely, LINEST returns the coefficients in the reverse order, as you can see from the calculation in the "Fit" column. An example prediction is shown outlined in blue: all the formulas are exactly the same as for the data.
Note that LINEST is an array formula: the answer will occupy p+1 cells in a row, where p is the number of variables (the last one is for the constant term). Such formulas are created by selecting all the output cells, pasting (or typing) the formula in the formula textbox, and pressing Ctrl-Shift-Enter (instead of the usual Enter). | Use a trendline formula to get values for any given X with Excel
Use LINEST, as shown:
The method is to create new columns (C:E here) containing the variables in the fit. Perversely, LINEST returns the coefficients in the reverse order, as you can see from the ca |
25,021 | Use a trendline formula to get values for any given X with Excel | Try trend(known_y's, known_x's, new_x's, const).
Column A below is X. Column B is X^2 (the cell to the left squared). Column C is X^3 (two cells to the left cubed). The trend() formula is in Cell E24 where the cell references are shown in red.
The "known_y's" are in E3:E22
The "known_x's" are in A3:C22
The "new_x's" are in A24:C24
The "const" is left blank.
Cell A24 contains the new X, and is the cell to change to update the formula in E24
Cell B24 contains the X^2 formula (A24*A24) for the new X
Cell C24 contains the X^3 formula (A24*A24*A24) for the new X
If you change the values in E3:E22, the trend() function will update Cell E24 for your new input at Cell A24.
Edit ====================================
Kirk,
There's not much to the spreadsheet. I posted a "formula view" below.
The "known_x" values are in green in A3:C22
The "known_y" values are in green in E3:E22
The "new_x" values are in cells A24:C24, where B24 and C24 are the formulas as shown. And, cell E24 has the trend() formula. You enter your new "X" in cell A24.
That's all there is to it. | Use a trendline formula to get values for any given X with Excel | Try trend(known_y's, known_x's, new_x's, const).
Column A below is X. Column B is X^2 (the cell to the left squared). Column C is X^3 (two cells to the left cubed). The trend() formula is in Cell | Use a trendline formula to get values for any given X with Excel
Try trend(known_y's, known_x's, new_x's, const).
Column A below is X. Column B is X^2 (the cell to the left squared). Column C is X^3 (two cells to the left cubed). The trend() formula is in Cell E24 where the cell references are shown in red.
The "known_y's" are in E3:E22
The "known_x's" are in A3:C22
The "new_x's" are in A24:C24
The "const" is left blank.
Cell A24 contains the new X, and is the cell to change to update the formula in E24
Cell B24 contains the X^2 formula (A24*A24) for the new X
Cell C24 contains the X^3 formula (A24*A24*A24) for the new X
If you change the values in E3:E22, the trend() function will update Cell E24 for your new input at Cell A24.
Edit ====================================
Kirk,
There's not much to the spreadsheet. I posted a "formula view" below.
The "known_x" values are in green in A3:C22
The "known_y" values are in green in E3:E22
The "new_x" values are in cells A24:C24, where B24 and C24 are the formulas as shown. And, cell E24 has the trend() formula. You enter your new "X" in cell A24.
That's all there is to it. | Use a trendline formula to get values for any given X with Excel
Try trend(known_y's, known_x's, new_x's, const).
Column A below is X. Column B is X^2 (the cell to the left squared). Column C is X^3 (two cells to the left cubed). The trend() formula is in Cell |
25,022 | Building MATLAB and R interfaces to Ross Quinlan's C5.0 | That sounds like a great idea, especially as the page you link to shows that C5.0 is now under GPL.
I have some experience wrapping C/C++ software to R using Rcpp; I would be happy to help. | Building MATLAB and R interfaces to Ross Quinlan's C5.0 | That sounds like a great idea, especially as the page you link to shows that C5.0 is now under GPL.
I have some experience wrapping C/C++ software to R using Rcpp; I would be happy to help. | Building MATLAB and R interfaces to Ross Quinlan's C5.0
That sounds like a great idea, especially as the page you link to shows that C5.0 is now under GPL.
I have some experience wrapping C/C++ software to R using Rcpp; I would be happy to help. | Building MATLAB and R interfaces to Ross Quinlan's C5.0
That sounds like a great idea, especially as the page you link to shows that C5.0 is now under GPL.
I have some experience wrapping C/C++ software to R using Rcpp; I would be happy to help. |
25,023 | Building MATLAB and R interfaces to Ross Quinlan's C5.0 | Interfacing C/C++ code to MATLAB is pretty straightforward, all you have to do is create a MEX gateway function to handle the conversion of parameters and return parameters. I have experience in making MEX files to do this sort of thing and would be happy to help. | Building MATLAB and R interfaces to Ross Quinlan's C5.0 | Interfacing C/C++ code to MATLAB is pretty straightforward, all you have to do is create a MEX gateway function to handle the conversion of parameters and return parameters. I have experience in maki | Building MATLAB and R interfaces to Ross Quinlan's C5.0
Interfacing C/C++ code to MATLAB is pretty straightforward, all you have to do is create a MEX gateway function to handle the conversion of parameters and return parameters. I have experience in making MEX files to do this sort of thing and would be happy to help. | Building MATLAB and R interfaces to Ross Quinlan's C5.0
Interfacing C/C++ code to MATLAB is pretty straightforward, all you have to do is create a MEX gateway function to handle the conversion of parameters and return parameters. I have experience in maki |
25,024 | Building MATLAB and R interfaces to Ross Quinlan's C5.0 | UPDATE:
Now on CRAN:
http://cran.r-project.org/web/packages/C50/index.html
ORIGINAL:
We've been working on this for a bit now (starting with Cubist then working on C5.0).
If you'd like to contribute:
https://r-forge.r-project.org/projects/rulebasedmodels/
was created recently and we should be checking the initial code in.
We've had access to the Cubist sources for a while now (but there was an explicit agreement not to link it to other sw) and been debating the different options for incorporating the code, but I thin | Building MATLAB and R interfaces to Ross Quinlan's C5.0 | UPDATE:
Now on CRAN:
http://cran.r-project.org/web/packages/C50/index.html
ORIGINAL:
We've been working on this for a bit now (starting with Cubist then working on C5.0).
If you'd like to contribute:
| Building MATLAB and R interfaces to Ross Quinlan's C5.0
UPDATE:
Now on CRAN:
http://cran.r-project.org/web/packages/C50/index.html
ORIGINAL:
We've been working on this for a bit now (starting with Cubist then working on C5.0).
If you'd like to contribute:
https://r-forge.r-project.org/projects/rulebasedmodels/
was created recently and we should be checking the initial code in.
We've had access to the Cubist sources for a while now (but there was an explicit agreement not to link it to other sw) and been debating the different options for incorporating the code, but I thin | Building MATLAB and R interfaces to Ross Quinlan's C5.0
UPDATE:
Now on CRAN:
http://cran.r-project.org/web/packages/C50/index.html
ORIGINAL:
We've been working on this for a bit now (starting with Cubist then working on C5.0).
If you'd like to contribute:
|
25,025 | Building MATLAB and R interfaces to Ross Quinlan's C5.0 | The C5.0 (Linux) documentation is at http://rulequest.com/see5-unix.html | Building MATLAB and R interfaces to Ross Quinlan's C5.0 | The C5.0 (Linux) documentation is at http://rulequest.com/see5-unix.html | Building MATLAB and R interfaces to Ross Quinlan's C5.0
The C5.0 (Linux) documentation is at http://rulequest.com/see5-unix.html | Building MATLAB and R interfaces to Ross Quinlan's C5.0
The C5.0 (Linux) documentation is at http://rulequest.com/see5-unix.html |
25,026 | Is there a site to post my survey to so I can get a sample representative of the population? | For a high school project it will probably be difficult to gain a representative sample with your limited time and budget. I'd be somewhat skeptical an online vendor can achieve a random sample of anything. If I had to do it I think I would use the phone book and either call or go to the addresses to distribute the survey in your community. Although this isn't perfect (likley under-represents younger people, minorities, and people of lower socio-economic status) it makes the project more feasible in your situation (as opposed to conducting stratified sampling based on geographic regions). Both of these solutions are local samples, and would not get you a national sample. An agency I work for samples the local community based on parcel addresses and apartment listings obtained from the postal office (these sources of information are not always public though, and would require more front end work than opening up a phone book).
idclark is right and the General Social Survey has several variables addressing public opinion on global warming. You could either analyze that data directly (as it is open to the public) or if you are required to construct your own survey you could mimic the GSS's questions and then see how close your sample appears to be compared to the GSS. At the moment I am having a much easier time searching the GSS variable lists from the ICPSR archive than I am from the actual GSS website. You can actually conduct basic data analysis online at ICPSR of the GSS data (you can basically do frequencies and cross-tabulations). If all you need are frequencies this circumvents the need to use stat software such as SPSS or Stata.
Getting a representative sample is difficult not only because true populations which to construct your sample are sometimes hard to come by, but just as importantly not everybody you do sample responds to the survey. I wouldn't be fixated on a national sample either, I'm sure you can construct just as interesting questions to answer by estimating public opinion of the local community, school mates, teachers, etc. What I find interesting is in comparison (like say comparing your school teachers opinions to those of the students). You could also conduct an experiment via surveys (like say manipulate how you present arguments for or against global warming and see how people differ in their opinions of global warming). | Is there a site to post my survey to so I can get a sample representative of the population? | For a high school project it will probably be difficult to gain a representative sample with your limited time and budget. I'd be somewhat skeptical an online vendor can achieve a random sample of any | Is there a site to post my survey to so I can get a sample representative of the population?
For a high school project it will probably be difficult to gain a representative sample with your limited time and budget. I'd be somewhat skeptical an online vendor can achieve a random sample of anything. If I had to do it I think I would use the phone book and either call or go to the addresses to distribute the survey in your community. Although this isn't perfect (likley under-represents younger people, minorities, and people of lower socio-economic status) it makes the project more feasible in your situation (as opposed to conducting stratified sampling based on geographic regions). Both of these solutions are local samples, and would not get you a national sample. An agency I work for samples the local community based on parcel addresses and apartment listings obtained from the postal office (these sources of information are not always public though, and would require more front end work than opening up a phone book).
idclark is right and the General Social Survey has several variables addressing public opinion on global warming. You could either analyze that data directly (as it is open to the public) or if you are required to construct your own survey you could mimic the GSS's questions and then see how close your sample appears to be compared to the GSS. At the moment I am having a much easier time searching the GSS variable lists from the ICPSR archive than I am from the actual GSS website. You can actually conduct basic data analysis online at ICPSR of the GSS data (you can basically do frequencies and cross-tabulations). If all you need are frequencies this circumvents the need to use stat software such as SPSS or Stata.
Getting a representative sample is difficult not only because true populations which to construct your sample are sometimes hard to come by, but just as importantly not everybody you do sample responds to the survey. I wouldn't be fixated on a national sample either, I'm sure you can construct just as interesting questions to answer by estimating public opinion of the local community, school mates, teachers, etc. What I find interesting is in comparison (like say comparing your school teachers opinions to those of the students). You could also conduct an experiment via surveys (like say manipulate how you present arguments for or against global warming and see how people differ in their opinions of global warming). | Is there a site to post my survey to so I can get a sample representative of the population?
For a high school project it will probably be difficult to gain a representative sample with your limited time and budget. I'd be somewhat skeptical an online vendor can achieve a random sample of any |
25,027 | Is there a site to post my survey to so I can get a sample representative of the population? | Your best bet is mechanical turk, https://www.mturk.com/mturk/welcome. It will cost you some money, but not much. If your questions are short and can be done in ~ 1 min you can easily charge 10 cents or so per answer, so if you want 50 responses it will cost only $5. You can get the data formatted in .xml, which you can import into R or even (shudder) Excel. The people you sample will be much more varied than you'd get in a high school class. And you can ask for demographic info (age, gender, nationality, etc), as questions in your survey. Also making the survey is easy, just adjust amazon's templates.
See http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1601785 for more issues with the biases you mention, the WEIRD study. Also see why people at mech turk participate: http://behind-the-enemy-lines.blogspot.com/2008/09/why-people-participate-on-mechanical.html. | Is there a site to post my survey to so I can get a sample representative of the population? | Your best bet is mechanical turk, https://www.mturk.com/mturk/welcome. It will cost you some money, but not much. If your questions are short and can be done in ~ 1 min you can easily charge 10 cents | Is there a site to post my survey to so I can get a sample representative of the population?
Your best bet is mechanical turk, https://www.mturk.com/mturk/welcome. It will cost you some money, but not much. If your questions are short and can be done in ~ 1 min you can easily charge 10 cents or so per answer, so if you want 50 responses it will cost only $5. You can get the data formatted in .xml, which you can import into R or even (shudder) Excel. The people you sample will be much more varied than you'd get in a high school class. And you can ask for demographic info (age, gender, nationality, etc), as questions in your survey. Also making the survey is easy, just adjust amazon's templates.
See http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1601785 for more issues with the biases you mention, the WEIRD study. Also see why people at mech turk participate: http://behind-the-enemy-lines.blogspot.com/2008/09/why-people-participate-on-mechanical.html. | Is there a site to post my survey to so I can get a sample representative of the population?
Your best bet is mechanical turk, https://www.mturk.com/mturk/welcome. It will cost you some money, but not much. If your questions are short and can be done in ~ 1 min you can easily charge 10 cents |
25,028 | Is there a site to post my survey to so I can get a sample representative of the population? | I admire your ambition! To answer your question directly, I'm not familiar with any site. Perhaps a message board you're familiar with? Has your instructor addressed the issue of bias? It may be enough that you recognize the issue of bias in your sample and speak to how this will affect your survey. Most properly randomized nationally representative surveys have an N of somewhere between 1800 and 2300. The GSS probably has a few questions regarding global warming.
However, this will be inaccessible if you're not familiar with SPSS or Stata. I know others on here can help you better than I in regards to weighting responses to correct for bias. | Is there a site to post my survey to so I can get a sample representative of the population? | I admire your ambition! To answer your question directly, I'm not familiar with any site. Perhaps a message board you're familiar with? Has your instructor addressed the issue of bias? It may be enoug | Is there a site to post my survey to so I can get a sample representative of the population?
I admire your ambition! To answer your question directly, I'm not familiar with any site. Perhaps a message board you're familiar with? Has your instructor addressed the issue of bias? It may be enough that you recognize the issue of bias in your sample and speak to how this will affect your survey. Most properly randomized nationally representative surveys have an N of somewhere between 1800 and 2300. The GSS probably has a few questions regarding global warming.
However, this will be inaccessible if you're not familiar with SPSS or Stata. I know others on here can help you better than I in regards to weighting responses to correct for bias. | Is there a site to post my survey to so I can get a sample representative of the population?
I admire your ambition! To answer your question directly, I'm not familiar with any site. Perhaps a message board you're familiar with? Has your instructor addressed the issue of bias? It may be enoug |
25,029 | Is there a site to post my survey to so I can get a sample representative of the population? | a sample representative of population cannot be obtained through internet as you will only get people interested in answering your survey online, which will give you a biased sample. | Is there a site to post my survey to so I can get a sample representative of the population? | a sample representative of population cannot be obtained through internet as you will only get people interested in answering your survey online, which will give you a biased sample. | Is there a site to post my survey to so I can get a sample representative of the population?
a sample representative of population cannot be obtained through internet as you will only get people interested in answering your survey online, which will give you a biased sample. | Is there a site to post my survey to so I can get a sample representative of the population?
a sample representative of population cannot be obtained through internet as you will only get people interested in answering your survey online, which will give you a biased sample. |
25,030 | Is there a site to post my survey to so I can get a sample representative of the population? | Marketing people are using self-selected samples in online-surveys all the time, so they probably have methods for cleaning their data. Sadly, I don't have a good pointer right now to look for their methods. | Is there a site to post my survey to so I can get a sample representative of the population? | Marketing people are using self-selected samples in online-surveys all the time, so they probably have methods for cleaning their data. Sadly, I don't have a good pointer right now to look for their m | Is there a site to post my survey to so I can get a sample representative of the population?
Marketing people are using self-selected samples in online-surveys all the time, so they probably have methods for cleaning their data. Sadly, I don't have a good pointer right now to look for their methods. | Is there a site to post my survey to so I can get a sample representative of the population?
Marketing people are using self-selected samples in online-surveys all the time, so they probably have methods for cleaning their data. Sadly, I don't have a good pointer right now to look for their m |
25,031 | Is there a site to post my survey to so I can get a sample representative of the population? | Just a thought, but it might make sense to implement an inexpensive Google Ad Words campaign where at least the participants would be coming directly from Google search and you can somewhat control some sort of stratification. Of course, it is never possible to get a true sample.
Along these lines, there is some work being done nowadays to adjust for selection bias of Web Surveys via propensity scores. This is being done by some of the majors, including Harris.
http://www.amstat.org/sections/srms/proceedings/y2004/files/Jsm2004-000032.pdf
-Ralph Winters | Is there a site to post my survey to so I can get a sample representative of the population? | Just a thought, but it might make sense to implement an inexpensive Google Ad Words campaign where at least the participants would be coming directly from Google search and you can somewhat control so | Is there a site to post my survey to so I can get a sample representative of the population?
Just a thought, but it might make sense to implement an inexpensive Google Ad Words campaign where at least the participants would be coming directly from Google search and you can somewhat control some sort of stratification. Of course, it is never possible to get a true sample.
Along these lines, there is some work being done nowadays to adjust for selection bias of Web Surveys via propensity scores. This is being done by some of the majors, including Harris.
http://www.amstat.org/sections/srms/proceedings/y2004/files/Jsm2004-000032.pdf
-Ralph Winters | Is there a site to post my survey to so I can get a sample representative of the population?
Just a thought, but it might make sense to implement an inexpensive Google Ad Words campaign where at least the participants would be coming directly from Google search and you can somewhat control so |
25,032 | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | While I think aggregate is probably the solution you are seeking, if you are want to create an explicit list of all possible factor combinations, expand.grid will do that for you. e.g.
> expand.grid(height = seq(60, 80, 5), weight = seq(100, 300, 50),
sex = c("Male","Female"))
height weight sex
1 60 100 Male
2 65 100 Male
...
30 80 100 Female
31 60 150 Female
You could then loop over each row in the resulting data frame to pull out records from your original data. | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | While I think aggregate is probably the solution you are seeking, if you are want to create an explicit list of all possible factor combinations, expand.grid will do that for you. e.g.
> expand.grid(h | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
While I think aggregate is probably the solution you are seeking, if you are want to create an explicit list of all possible factor combinations, expand.grid will do that for you. e.g.
> expand.grid(height = seq(60, 80, 5), weight = seq(100, 300, 50),
sex = c("Male","Female"))
height weight sex
1 60 100 Male
2 65 100 Male
...
30 80 100 Female
31 60 150 Female
You could then loop over each row in the resulting data frame to pull out records from your original data. | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
While I think aggregate is probably the solution you are seeking, if you are want to create an explicit list of all possible factor combinations, expand.grid will do that for you. e.g.
> expand.grid(h |
25,033 | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | See aggregate and by. For example, from the help file for aggregate:
## Compute the averages according to region and the occurrence of more
## than 130 days of frost.
aggregate(state.x77,
list(Region = state.region,
Cold = state.x77[,"Frost"] > 130),
mean) | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | See aggregate and by. For example, from the help file for aggregate:
## Compute the averages according to region and the occurrence of more
## than 130 days of frost.
aggregate(state.x77,
list(R | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
See aggregate and by. For example, from the help file for aggregate:
## Compute the averages according to region and the occurrence of more
## than 130 days of frost.
aggregate(state.x77,
list(Region = state.region,
Cold = state.x77[,"Frost"] > 130),
mean) | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
See aggregate and by. For example, from the help file for aggregate:
## Compute the averages according to region and the occurrence of more
## than 130 days of frost.
aggregate(state.x77,
list(R |
25,034 | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | Here's the plyr solution, which has the advantage of returning multiple summary stats and producing a progress bar for long computes:
library(ez) #for a data set
data(ANT)
cell_stats = ddply(
.data = ANT #use the ANT data
, .variables = .(cue,flanker) #uses each combination of cue and flanker
, .fun = function(x){ #apply this function to each combin. of cue & flanker
to_return = data.frame(
, acc = mean(x$acc)
, mrt = mean(x$rt[x$acc==1])
)
return(to_return)
}
, .progress = 'text'
) | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | Here's the plyr solution, which has the advantage of returning multiple summary stats and producing a progress bar for long computes:
library(ez) #for a data set
data(ANT)
cell_stats = ddply(
.dat | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
Here's the plyr solution, which has the advantage of returning multiple summary stats and producing a progress bar for long computes:
library(ez) #for a data set
data(ANT)
cell_stats = ddply(
.data = ANT #use the ANT data
, .variables = .(cue,flanker) #uses each combination of cue and flanker
, .fun = function(x){ #apply this function to each combin. of cue & flanker
to_return = data.frame(
, acc = mean(x$acc)
, mrt = mean(x$rt[x$acc==1])
)
return(to_return)
}
, .progress = 'text'
) | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
Here's the plyr solution, which has the advantage of returning multiple summary stats and producing a progress bar for long computes:
library(ez) #for a data set
data(ANT)
cell_stats = ddply(
.dat |
25,035 | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | In addition to other suggestions you may find the describe.by() function in the psych package useful.
It can be used to show summary statistics on numeric variables across levels of a factor variable. | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | In addition to other suggestions you may find the describe.by() function in the psych package useful.
It can be used to show summary statistics on numeric variables across levels of a factor variable. | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
In addition to other suggestions you may find the describe.by() function in the psych package useful.
It can be used to show summary statistics on numeric variables across levels of a factor variable. | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
In addition to other suggestions you may find the describe.by() function in the psych package useful.
It can be used to show summary statistics on numeric variables across levels of a factor variable. |
25,036 | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | I personally like cast(), from the reshape package because of it's simplicity:
library(reshape)
cast(melt(tips), sex ~ smoker | variable, c(sd,mean, length)) | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | I personally like cast(), from the reshape package because of it's simplicity:
library(reshape)
cast(melt(tips), sex ~ smoker | variable, c(sd,mean, length)) | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
I personally like cast(), from the reshape package because of it's simplicity:
library(reshape)
cast(melt(tips), sex ~ smoker | variable, c(sd,mean, length)) | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
I personally like cast(), from the reshape package because of it's simplicity:
library(reshape)
cast(melt(tips), sex ~ smoker | variable, c(sd,mean, length)) |
25,037 | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | In library(doBy) there is also the summaryBy() function, e.g.
summaryBy(DV1 + DV2 ~ Height+Weight+Sex,data=my.data) | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed] | In library(doBy) there is also the summaryBy() function, e.g.
summaryBy(DV1 + DV2 ~ Height+Weight+Sex,data=my.data) | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
In library(doBy) there is also the summaryBy() function, e.g.
summaryBy(DV1 + DV2 ~ Height+Weight+Sex,data=my.data) | How to find summary statistics for all unique combinations of factors in a data.frame in R? [closed]
In library(doBy) there is also the summaryBy() function, e.g.
summaryBy(DV1 + DV2 ~ Height+Weight+Sex,data=my.data) |
25,038 | Forecast accuracy metric that involves prediction intervals | This is a good question. Unfortunately, while the academic forecasting literature is indeed (slowly) moving from an almost exclusive emphasis on point forecasts towards interval forecasts and predictive densities, there has been little work on evaluating interval forecasts. (EDIT: See the bottom of this answer for an update.)
As gung notes, whether or not a given 95% prediction interval contains the true actual is in principle a Bernoulli trial with $p=0.95$. Given enough PIs and realizations, you can in principle test the null hypothesis that the actual coverage probability is in fact at least 95%.
However, you will need to think about statistical power and sample sizes. It's probably best to decide beforehand what kind of deviation from the target coverage is still acceptable (is 92% OK? 90%?), then find the minimum sample size needed to detect a deviation that is this strong or stronger with a given probability, say $\beta=80\%$, which is standard. You can do this by a straightforward simulation: simulate $n$ Bernoulli trials with $p=0.92$, estimate $\hat{p}$ with a confidence interval for it, see whether it contains the value 95%, do this "often", and tweak $n$ until 95% is outside the CI in $\beta=80\%$ of your cases. Or use any Bernoulli power calculator.
OK, now that we have our sample size, you can batch your PIs and realizations in batches of this sample size, see how often your PIs contain the true realization, and start testing. Your batches can be the last $n$ PI/realizations of a single time series, or all the latest PIs/realizations of a large number of time series you are forecasting, or whatever.
This approach has the advantage of being rather easy to explain and to understand. Of course, if you have a large number of trials, even small deviations from the target coverage will be statistically significant, which is why you'll need to think about what deviation actually is significant from a business perspective, as per above.
Alternatively, quantile forecasts (say, a 2.5% and a 97.5% quantile forecast, to yield a 95% PI) arise naturally as optimal point forecasts under certain loss functions, which are parameterized based on the target quantile. This paper gives a nice overview. This may be an alternative to the Bernoulli tests above: find the correct loss function for your target upper and lower quantile, then evaluate the two endpoints of your PIs under these loss functions. However, the loss functions are rather abstract and not easily understood, especially for nontechnical audiences.
If you are comparing, say, multiple forecasting methods, you could first discard those whose PIs significantly underperform, based on Bernoulli hypothesis tests or loss functions, then assess the ones that passed this initial screening based on the width of their PIs. Among two PIs with the same correct coverage rate, the narrower one is usually better.
For a simple evaluation of PIs using null hypothesis significance tests, see this paper. There are also some far more elaborate schemes for evaluating PIs, which can also deal with serial dependence in deviations in coverage (maybe your financial PIs are good some part of the year, but bad at specific times), like this paper and that paper. Unfortunately, these require quite a large number of PI/realizations and so are likely only relevant for high-frequency financial data, like stock prices reported multiple times per day.
Finally, there has recently been some interest in going beyond PIs to the underlying predictive densities, which can be evaluated using (proper) scoring rules. Tilmann Gneiting has been very active in this area, and this paper of his gives a good introduction. However, even if you do decide to go deeper into predictive densities, scoring rules are again quite abstract and hard to communicate to a nontechnical audience.
EDIT - an update:
Your quality measure needs to balance coverage and length of the prediction intervals: yes, we want high coverage, but we also want short intervals.
There is a quality measure that does precisely this and has attractive properties: the interval score. Let $\ell$ and $u$ be the lower and the upper end of the prediction interval. The score is given by
$$ S(\ell,u,h) = (u-\ell)+\frac{2}{\alpha}(\ell-h)1(h<\ell)+\frac{2}{\alpha}(h-u)1(h>u). $$
Here $1$ is the indicator function, and $\alpha$ is the coverage your algorithm is aiming for. (You will need to prespecify this, based on what you plan on doing with the prediction interval. It makes no sense to aim for $\alpha=100\%$ coverage, because the resulting intervals will be too wide to be useful for anything.)
You can then average the interval score over many predictions. The lower the average score, the better. See Gneiting & Raftery (2007, JASA)] for a discussion and pointers to further literature. A scaled version of this score was used, for instance, in assessing predictions intervals in the recent M4 forecasting competition.
(Full disclosure: this was shamelessly cribbed from this answer of mine.) | Forecast accuracy metric that involves prediction intervals | This is a good question. Unfortunately, while the academic forecasting literature is indeed (slowly) moving from an almost exclusive emphasis on point forecasts towards interval forecasts and predicti | Forecast accuracy metric that involves prediction intervals
This is a good question. Unfortunately, while the academic forecasting literature is indeed (slowly) moving from an almost exclusive emphasis on point forecasts towards interval forecasts and predictive densities, there has been little work on evaluating interval forecasts. (EDIT: See the bottom of this answer for an update.)
As gung notes, whether or not a given 95% prediction interval contains the true actual is in principle a Bernoulli trial with $p=0.95$. Given enough PIs and realizations, you can in principle test the null hypothesis that the actual coverage probability is in fact at least 95%.
However, you will need to think about statistical power and sample sizes. It's probably best to decide beforehand what kind of deviation from the target coverage is still acceptable (is 92% OK? 90%?), then find the minimum sample size needed to detect a deviation that is this strong or stronger with a given probability, say $\beta=80\%$, which is standard. You can do this by a straightforward simulation: simulate $n$ Bernoulli trials with $p=0.92$, estimate $\hat{p}$ with a confidence interval for it, see whether it contains the value 95%, do this "often", and tweak $n$ until 95% is outside the CI in $\beta=80\%$ of your cases. Or use any Bernoulli power calculator.
OK, now that we have our sample size, you can batch your PIs and realizations in batches of this sample size, see how often your PIs contain the true realization, and start testing. Your batches can be the last $n$ PI/realizations of a single time series, or all the latest PIs/realizations of a large number of time series you are forecasting, or whatever.
This approach has the advantage of being rather easy to explain and to understand. Of course, if you have a large number of trials, even small deviations from the target coverage will be statistically significant, which is why you'll need to think about what deviation actually is significant from a business perspective, as per above.
Alternatively, quantile forecasts (say, a 2.5% and a 97.5% quantile forecast, to yield a 95% PI) arise naturally as optimal point forecasts under certain loss functions, which are parameterized based on the target quantile. This paper gives a nice overview. This may be an alternative to the Bernoulli tests above: find the correct loss function for your target upper and lower quantile, then evaluate the two endpoints of your PIs under these loss functions. However, the loss functions are rather abstract and not easily understood, especially for nontechnical audiences.
If you are comparing, say, multiple forecasting methods, you could first discard those whose PIs significantly underperform, based on Bernoulli hypothesis tests or loss functions, then assess the ones that passed this initial screening based on the width of their PIs. Among two PIs with the same correct coverage rate, the narrower one is usually better.
For a simple evaluation of PIs using null hypothesis significance tests, see this paper. There are also some far more elaborate schemes for evaluating PIs, which can also deal with serial dependence in deviations in coverage (maybe your financial PIs are good some part of the year, but bad at specific times), like this paper and that paper. Unfortunately, these require quite a large number of PI/realizations and so are likely only relevant for high-frequency financial data, like stock prices reported multiple times per day.
Finally, there has recently been some interest in going beyond PIs to the underlying predictive densities, which can be evaluated using (proper) scoring rules. Tilmann Gneiting has been very active in this area, and this paper of his gives a good introduction. However, even if you do decide to go deeper into predictive densities, scoring rules are again quite abstract and hard to communicate to a nontechnical audience.
EDIT - an update:
Your quality measure needs to balance coverage and length of the prediction intervals: yes, we want high coverage, but we also want short intervals.
There is a quality measure that does precisely this and has attractive properties: the interval score. Let $\ell$ and $u$ be the lower and the upper end of the prediction interval. The score is given by
$$ S(\ell,u,h) = (u-\ell)+\frac{2}{\alpha}(\ell-h)1(h<\ell)+\frac{2}{\alpha}(h-u)1(h>u). $$
Here $1$ is the indicator function, and $\alpha$ is the coverage your algorithm is aiming for. (You will need to prespecify this, based on what you plan on doing with the prediction interval. It makes no sense to aim for $\alpha=100\%$ coverage, because the resulting intervals will be too wide to be useful for anything.)
You can then average the interval score over many predictions. The lower the average score, the better. See Gneiting & Raftery (2007, JASA)] for a discussion and pointers to further literature. A scaled version of this score was used, for instance, in assessing predictions intervals in the recent M4 forecasting competition.
(Full disclosure: this was shamelessly cribbed from this answer of mine.) | Forecast accuracy metric that involves prediction intervals
This is a good question. Unfortunately, while the academic forecasting literature is indeed (slowly) moving from an almost exclusive emphasis on point forecasts towards interval forecasts and predicti |
25,039 | Forecast accuracy metric that involves prediction intervals | As nicely reflected in Stephan Kolassa's answer, there is a large academic literature on forecast evaluation. Let me add another idea from that literature, which I think matches your problem well.
Suppose your prediction interval has lower limit $p_l$ and upper limit $p_u$, and the goal is to design a central prediction interval at level $\alpha$ (i.e. you allow for $\alpha$/2 percent of the observations to fall below $p_l$, and for $\alpha$/2 percent to fall above $p_u$).
Given a realization $y$, a statistical score for the prediction interval is given by $$\text{Score} = (p_u - p_l) + \frac{2}{\alpha}(p_l - y)\mathbb{1}(y < p_l) + \frac{2}{\alpha}(y - p_u)\mathbb{1}(y > p_u),$$ where $\mathbb{1}$ is the indicator function; see Section 6.2 in Gneiting and Raftery ("Strictly Proper Scoring Rules, Prediction and Estimation", Journal of the American Statistical Association, 2007). Importantly, note that a smaller score corresponds to a better prediction interval.
The intuition behind the score formula is as follows: In the best of all worlds, we would want to have very short prediction intervals ($p_u$ only slightly larger than $p_l$), which nevertheless cover the realization $y$ ($p_l \le y \le p_u$). In this ideal world, the first summand of the score formula would be close to zero, whereas the second and third summands would be exactly zero.
Of course, in practice there is a tradeoff between producing short prediction intervals and actually covering the realization $y$. The score above strikes a balance between those two goals. | Forecast accuracy metric that involves prediction intervals | As nicely reflected in Stephan Kolassa's answer, there is a large academic literature on forecast evaluation. Let me add another idea from that literature, which I think matches your problem well.
Su | Forecast accuracy metric that involves prediction intervals
As nicely reflected in Stephan Kolassa's answer, there is a large academic literature on forecast evaluation. Let me add another idea from that literature, which I think matches your problem well.
Suppose your prediction interval has lower limit $p_l$ and upper limit $p_u$, and the goal is to design a central prediction interval at level $\alpha$ (i.e. you allow for $\alpha$/2 percent of the observations to fall below $p_l$, and for $\alpha$/2 percent to fall above $p_u$).
Given a realization $y$, a statistical score for the prediction interval is given by $$\text{Score} = (p_u - p_l) + \frac{2}{\alpha}(p_l - y)\mathbb{1}(y < p_l) + \frac{2}{\alpha}(y - p_u)\mathbb{1}(y > p_u),$$ where $\mathbb{1}$ is the indicator function; see Section 6.2 in Gneiting and Raftery ("Strictly Proper Scoring Rules, Prediction and Estimation", Journal of the American Statistical Association, 2007). Importantly, note that a smaller score corresponds to a better prediction interval.
The intuition behind the score formula is as follows: In the best of all worlds, we would want to have very short prediction intervals ($p_u$ only slightly larger than $p_l$), which nevertheless cover the realization $y$ ($p_l \le y \le p_u$). In this ideal world, the first summand of the score formula would be close to zero, whereas the second and third summands would be exactly zero.
Of course, in practice there is a tradeoff between producing short prediction intervals and actually covering the realization $y$. The score above strikes a balance between those two goals. | Forecast accuracy metric that involves prediction intervals
As nicely reflected in Stephan Kolassa's answer, there is a large academic literature on forecast evaluation. Let me add another idea from that literature, which I think matches your problem well.
Su |
25,040 | Forecast accuracy metric that involves prediction intervals | This seems like something you could accomplish with a dataframe--say you have your confidence intervals at each day--that is two columns, with day rows: an upper estimate, and a lower estimate. You could also just use the mean and std deviation of the gaussian with that day's confidence interval as your two columns for each day.
Then, you just store another column of actual measurements of product revenue.
Next, you load just the dates with estimation data and actual data, take the difference between the mean of the gaussian and the actual data, divide by the standard deviation, and use that number to 'rank' the effectiveness of your predictions.
If it is within ~2 standard deviations ($\frac{|predicted mean - actual|}{\sigma} \leq 2$), then it is within your confidence interval.
So the key problems are:
using a dataframe in R, storing the data (database, etc.), choosing the data properly...just the mechanics. | Forecast accuracy metric that involves prediction intervals | This seems like something you could accomplish with a dataframe--say you have your confidence intervals at each day--that is two columns, with day rows: an upper estimate, and a lower estimate. You c | Forecast accuracy metric that involves prediction intervals
This seems like something you could accomplish with a dataframe--say you have your confidence intervals at each day--that is two columns, with day rows: an upper estimate, and a lower estimate. You could also just use the mean and std deviation of the gaussian with that day's confidence interval as your two columns for each day.
Then, you just store another column of actual measurements of product revenue.
Next, you load just the dates with estimation data and actual data, take the difference between the mean of the gaussian and the actual data, divide by the standard deviation, and use that number to 'rank' the effectiveness of your predictions.
If it is within ~2 standard deviations ($\frac{|predicted mean - actual|}{\sigma} \leq 2$), then it is within your confidence interval.
So the key problems are:
using a dataframe in R, storing the data (database, etc.), choosing the data properly...just the mechanics. | Forecast accuracy metric that involves prediction intervals
This seems like something you could accomplish with a dataframe--say you have your confidence intervals at each day--that is two columns, with day rows: an upper estimate, and a lower estimate. You c |
25,041 | Forecast accuracy metric that involves prediction intervals | Maybe you could try with Winkler scores. Quote from A brief history of forecasting competitions:
For interval forecasting, Winkler scores (Winkler 1972) have been
widely used, but are not scale-free. The scaled version of Winkler
scores used to assess interval accuracy in the M4 competition seems
rather ad hoc and its properties are unknown. In any case, Askanazi et
al. (2018) argue that interval forecasts comparisons are problematic
in several ways and should be abandoned for density forecasts. | Forecast accuracy metric that involves prediction intervals | Maybe you could try with Winkler scores. Quote from A brief history of forecasting competitions:
For interval forecasting, Winkler scores (Winkler 1972) have been
widely used, but are not scale-free. | Forecast accuracy metric that involves prediction intervals
Maybe you could try with Winkler scores. Quote from A brief history of forecasting competitions:
For interval forecasting, Winkler scores (Winkler 1972) have been
widely used, but are not scale-free. The scaled version of Winkler
scores used to assess interval accuracy in the M4 competition seems
rather ad hoc and its properties are unknown. In any case, Askanazi et
al. (2018) argue that interval forecasts comparisons are problematic
in several ways and should be abandoned for density forecasts. | Forecast accuracy metric that involves prediction intervals
Maybe you could try with Winkler scores. Quote from A brief history of forecasting competitions:
For interval forecasting, Winkler scores (Winkler 1972) have been
widely used, but are not scale-free. |
25,042 | Simulate from a zero-inflated poisson distribution | You can get the probability of zero-inflation by
p <- predict(object, ..., type = "zero")
and the mean of the count distribution by
lambda <- predict(object, ..., type = "count")
See Appendix C of vignette("countreg", package = "pscl") for a few more details.
To simulate the distribution, you can either do it manually with
ifelse(rbinom(n, size = 1, prob = p) > 0, 0, rpois(n, lambda = lambda))
or you can use rzipois() from the VGAM package
library("VGAM")
rzipois(n, lambda = lambda, pstr0 = p)
which essentially also does an ifelse() as above but adds a few sanity checks etc. | Simulate from a zero-inflated poisson distribution | You can get the probability of zero-inflation by
p <- predict(object, ..., type = "zero")
and the mean of the count distribution by
lambda <- predict(object, ..., type = "count")
See Appendix C of v | Simulate from a zero-inflated poisson distribution
You can get the probability of zero-inflation by
p <- predict(object, ..., type = "zero")
and the mean of the count distribution by
lambda <- predict(object, ..., type = "count")
See Appendix C of vignette("countreg", package = "pscl") for a few more details.
To simulate the distribution, you can either do it manually with
ifelse(rbinom(n, size = 1, prob = p) > 0, 0, rpois(n, lambda = lambda))
or you can use rzipois() from the VGAM package
library("VGAM")
rzipois(n, lambda = lambda, pstr0 = p)
which essentially also does an ifelse() as above but adds a few sanity checks etc. | Simulate from a zero-inflated poisson distribution
You can get the probability of zero-inflation by
p <- predict(object, ..., type = "zero")
and the mean of the count distribution by
lambda <- predict(object, ..., type = "count")
See Appendix C of v |
25,043 | Independence of Sample mean and Sample range of Normal Distribution | This is evidently a self-study question, so I do not intend to deprive you of the satisfaction of developing your own answer. Moreover, I'm sure there are many possible solutions. But for guidance, consider these observations:
When a random variable $X$ is independent of other random variables $Y_1, \ldots, Y_m$, then $X$ is independent of any function of them, $f(Y_1, \ldots, Y_m)$. (See Functions of Independent Random Variables for more about this.)
Because the $X_i$ are jointly Normal, $X_1 + \cdots + X_n$ is independent of all the differences $Y_{ij} = X_i - X_j$, since their covariances are zero.
Because the range can be expressed as
$$X_{(n)} - X_{(1)} = \max_{i,j}(|X_i - X_j|) = \max_{i,j}(|Y_{ij}|)$$
you can exploit (1) and (2) to finish the proof.
For more intuition, a quick simulation might be of some help. The following shows the marginal and joint distribution of the mean and range in the case $n=3$, using $10,000$ independent datasets. The joint distribution clearly is not bivariate Normal, so the temptation to prove independence by means of a zero correlation--although a good idea--is bound to fail. However, a close analysis of these results ought to suggest that the conditional distribution of the range does not vary with the mean. (The appearance of some variation at the right and left is due to the paucity of outcomes with such extreme means.)
Here is the R code that produced these figures. It is easily modified to vary $n$, vary the simulation size, and to analyze the simulation results more extensively.
n <- 3; n.sim <- 1e4
sim <- apply(matrix(rnorm(n * n.sim), n), 2, function(y) c(mean(y), diff(range(y))))
par(mfrow=c(1,3))
hist(sim[1,], xlab="Mean", main="Histogram of Means")
hist(sim[2,], xlab="Range", main="Histogram of Ranges")
plot(sim[1,], sim[2,], pch=16, col="#00000020", xlab="Mean", ylab="Range") | Independence of Sample mean and Sample range of Normal Distribution | This is evidently a self-study question, so I do not intend to deprive you of the satisfaction of developing your own answer. Moreover, I'm sure there are many possible solutions. But for guidance, | Independence of Sample mean and Sample range of Normal Distribution
This is evidently a self-study question, so I do not intend to deprive you of the satisfaction of developing your own answer. Moreover, I'm sure there are many possible solutions. But for guidance, consider these observations:
When a random variable $X$ is independent of other random variables $Y_1, \ldots, Y_m$, then $X$ is independent of any function of them, $f(Y_1, \ldots, Y_m)$. (See Functions of Independent Random Variables for more about this.)
Because the $X_i$ are jointly Normal, $X_1 + \cdots + X_n$ is independent of all the differences $Y_{ij} = X_i - X_j$, since their covariances are zero.
Because the range can be expressed as
$$X_{(n)} - X_{(1)} = \max_{i,j}(|X_i - X_j|) = \max_{i,j}(|Y_{ij}|)$$
you can exploit (1) and (2) to finish the proof.
For more intuition, a quick simulation might be of some help. The following shows the marginal and joint distribution of the mean and range in the case $n=3$, using $10,000$ independent datasets. The joint distribution clearly is not bivariate Normal, so the temptation to prove independence by means of a zero correlation--although a good idea--is bound to fail. However, a close analysis of these results ought to suggest that the conditional distribution of the range does not vary with the mean. (The appearance of some variation at the right and left is due to the paucity of outcomes with such extreme means.)
Here is the R code that produced these figures. It is easily modified to vary $n$, vary the simulation size, and to analyze the simulation results more extensively.
n <- 3; n.sim <- 1e4
sim <- apply(matrix(rnorm(n * n.sim), n), 2, function(y) c(mean(y), diff(range(y))))
par(mfrow=c(1,3))
hist(sim[1,], xlab="Mean", main="Histogram of Means")
hist(sim[2,], xlab="Range", main="Histogram of Ranges")
plot(sim[1,], sim[2,], pch=16, col="#00000020", xlab="Mean", ylab="Range") | Independence of Sample mean and Sample range of Normal Distribution
This is evidently a self-study question, so I do not intend to deprive you of the satisfaction of developing your own answer. Moreover, I'm sure there are many possible solutions. But for guidance, |
25,044 | Independence of Sample mean and Sample range of Normal Distribution | This exercise is an immediate application of Basu's theorem.
To begin with, first note that $\bar{X}$ and $R$ are independent if and only if $\sigma^{-1}\bar{X}$ and $\sigma^{-1}R$ are independent, so we may assume $X_1, \ldots, X_n \text{ i.i.d.} \sim N(\mu, 1)$.
It is well-known that $\bar{X}$ is a sufficient and complete statistic for $\mu$, so according to Basu's theorem, to show that $\bar{X}$ and $R$ are independent, it remains to show $R$ is ancillary, i.e., $R$'s distribution is independent of $\mu$. This is easily seen by noticing
$$R = X_{(n)} - X_{(1)}= (X_{(n)} - \mu) - (X_{(1)} - \mu).$$
Clearly, the distribution of $(X_{(1)} - \mu, \ldots, X_{(n)} - \mu)$ is identical to the distribution of $(Z_{(1)}, \ldots, Z_{(n)})$, where $Z_1, \ldots, Z_n \text{ i.i.d.} \sim N(0, 1)$, which is distribution-constant. Consequently, the distribution of $R$ does not depend on $\mu$. This completes the proof. | Independence of Sample mean and Sample range of Normal Distribution | This exercise is an immediate application of Basu's theorem.
To begin with, first note that $\bar{X}$ and $R$ are independent if and only if $\sigma^{-1}\bar{X}$ and $\sigma^{-1}R$ are independent, so | Independence of Sample mean and Sample range of Normal Distribution
This exercise is an immediate application of Basu's theorem.
To begin with, first note that $\bar{X}$ and $R$ are independent if and only if $\sigma^{-1}\bar{X}$ and $\sigma^{-1}R$ are independent, so we may assume $X_1, \ldots, X_n \text{ i.i.d.} \sim N(\mu, 1)$.
It is well-known that $\bar{X}$ is a sufficient and complete statistic for $\mu$, so according to Basu's theorem, to show that $\bar{X}$ and $R$ are independent, it remains to show $R$ is ancillary, i.e., $R$'s distribution is independent of $\mu$. This is easily seen by noticing
$$R = X_{(n)} - X_{(1)}= (X_{(n)} - \mu) - (X_{(1)} - \mu).$$
Clearly, the distribution of $(X_{(1)} - \mu, \ldots, X_{(n)} - \mu)$ is identical to the distribution of $(Z_{(1)}, \ldots, Z_{(n)})$, where $Z_1, \ldots, Z_n \text{ i.i.d.} \sim N(0, 1)$, which is distribution-constant. Consequently, the distribution of $R$ does not depend on $\mu$. This completes the proof. | Independence of Sample mean and Sample range of Normal Distribution
This exercise is an immediate application of Basu's theorem.
To begin with, first note that $\bar{X}$ and $R$ are independent if and only if $\sigma^{-1}\bar{X}$ and $\sigma^{-1}R$ are independent, so |
25,045 | Independence of Sample mean and Sample range of Normal Distribution | A well-known property of the normal distribution is that the joint distribution of the differences $X_i-\overline X$, $i=1,2,\ldots,n-1$ is independent of the distribution of sample mean $\overline X$. This is also apparent from the independence of $\overline X=\frac{1}{n}\sum\limits_{i=1}^n X_i$ with the sample variance $\frac{1}{n-1}\sum\limits_{i=1}^n (X_i-\overline X)^2$, giving us $\operatorname{Cov}(X_i-\overline X,\overline X)=0$ for each $i$. The joint normality of $\overline X$ and $X_i-\overline X$ then implies their independence. Since the sample range $R=\max(X_i-\overline X)-\min(X_i-\overline X)$, $i=1,2,\ldots,n$ is a measurable function of $X_i-\overline X$ for each $i$, we can justify that $\overline X$ is independent of $R$.
An alternative proof of this result in line with @whuber's answer appears in this paper by J. Daly.
The argument provided in this article roughly goes along these lines:
We assume without loss of generality that $\mu=0$ and $\sigma^2=1$.
The joint characteristic function of $\overline X$ and the $\frac{n(n-1)}{2}$ differences $X_j-X_k$, $j<k$, is then
$$\varphi(t,t_{jk})=\frac{1}{(2\pi)^{n/2}}\int_{\mathbb{R^n}}\exp\left[-\frac{1}{2}\sum_{j=1}^nx_j^2+i\frac{t}{n}\sum_{j=1}^nx_j+i\sum_{1\le j<k\le n}t_{jk}(x_j-x_k)\right]\mathrm{d}\mathbf x$$
Completing the square in the exponent and further simplification leads to
$$\varphi(t,t_{jk})=\exp\left[-\frac{1}{2}\sum_{j=1}^n\left(\frac{t}{n}+\sum_{k=1}^n\left(t_{jk}-t_{kj}\right)\right)^2\right]$$
, which factors into the marginal characteristic functions
$$\varphi(t)\varphi(t_{jk})=\exp\left(-\frac{t^2}{2n}\right).\exp\left[-\frac{1}{2}\sum_{j=1}^n\left(\sum_{k=1}^n\left(t_{jk}-t_{kj}\right)\right)^2\right]$$
Thus the differences $X_j-X_k$ are jointly independent of $\overline X$.
Since the sample range $R=\max|X_j-X_k|$ is a measurable function of these differences, it follows that $\overline X$ and $R$ are independently distributed. | Independence of Sample mean and Sample range of Normal Distribution | A well-known property of the normal distribution is that the joint distribution of the differences $X_i-\overline X$, $i=1,2,\ldots,n-1$ is independent of the distribution of sample mean $\overline X$ | Independence of Sample mean and Sample range of Normal Distribution
A well-known property of the normal distribution is that the joint distribution of the differences $X_i-\overline X$, $i=1,2,\ldots,n-1$ is independent of the distribution of sample mean $\overline X$. This is also apparent from the independence of $\overline X=\frac{1}{n}\sum\limits_{i=1}^n X_i$ with the sample variance $\frac{1}{n-1}\sum\limits_{i=1}^n (X_i-\overline X)^2$, giving us $\operatorname{Cov}(X_i-\overline X,\overline X)=0$ for each $i$. The joint normality of $\overline X$ and $X_i-\overline X$ then implies their independence. Since the sample range $R=\max(X_i-\overline X)-\min(X_i-\overline X)$, $i=1,2,\ldots,n$ is a measurable function of $X_i-\overline X$ for each $i$, we can justify that $\overline X$ is independent of $R$.
An alternative proof of this result in line with @whuber's answer appears in this paper by J. Daly.
The argument provided in this article roughly goes along these lines:
We assume without loss of generality that $\mu=0$ and $\sigma^2=1$.
The joint characteristic function of $\overline X$ and the $\frac{n(n-1)}{2}$ differences $X_j-X_k$, $j<k$, is then
$$\varphi(t,t_{jk})=\frac{1}{(2\pi)^{n/2}}\int_{\mathbb{R^n}}\exp\left[-\frac{1}{2}\sum_{j=1}^nx_j^2+i\frac{t}{n}\sum_{j=1}^nx_j+i\sum_{1\le j<k\le n}t_{jk}(x_j-x_k)\right]\mathrm{d}\mathbf x$$
Completing the square in the exponent and further simplification leads to
$$\varphi(t,t_{jk})=\exp\left[-\frac{1}{2}\sum_{j=1}^n\left(\frac{t}{n}+\sum_{k=1}^n\left(t_{jk}-t_{kj}\right)\right)^2\right]$$
, which factors into the marginal characteristic functions
$$\varphi(t)\varphi(t_{jk})=\exp\left(-\frac{t^2}{2n}\right).\exp\left[-\frac{1}{2}\sum_{j=1}^n\left(\sum_{k=1}^n\left(t_{jk}-t_{kj}\right)\right)^2\right]$$
Thus the differences $X_j-X_k$ are jointly independent of $\overline X$.
Since the sample range $R=\max|X_j-X_k|$ is a measurable function of these differences, it follows that $\overline X$ and $R$ are independently distributed. | Independence of Sample mean and Sample range of Normal Distribution
A well-known property of the normal distribution is that the joint distribution of the differences $X_i-\overline X$, $i=1,2,\ldots,n-1$ is independent of the distribution of sample mean $\overline X$ |
25,046 | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrease for the first time? | If $\{X_i\}_{i\geq 1}$ is an exchangeable sequence of random variables and $$N=\min\,\{n:X_{n-1}>X_n\},$$ then $N\geq n$ if and ony if $X_1\leq X_2\leq\dots\leq X_{n-1}$. Therefore, $$\Pr(N\geq n) = \Pr(X_1\leq X_2\leq\dots\leq X_{n-1})=\frac{1}{(n-1)!}, \qquad (*)$$
by symmetry. Hence, $\mathrm{E}[N]=\sum_{n=1}^\infty \Pr(N\geq n)=e\approx 2.71828\dots$.
P.S. People asked about the proof of $(*)$. Since the sequence is exchangeable, it must be that, for any permutation $\pi:\{1,\dots,n-1\}\to\{1,\dots,n-1\}$, we have
$$
\Pr(X_1\leq X_2\leq\dots\leq X_{n-1}) = \Pr(X_{\pi(1)}\leq X_{\pi(2)}\leq\dots\leq X_{\pi(n-1)}).
$$
Since we have $(n-1)!$ possible permutations, the result follows. | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrea | If $\{X_i\}_{i\geq 1}$ is an exchangeable sequence of random variables and $$N=\min\,\{n:X_{n-1}>X_n\},$$ then $N\geq n$ if and ony if $X_1\leq X_2\leq\dots\leq X_{n-1}$. Therefore, $$\Pr(N\geq n) = \ | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrease for the first time?
If $\{X_i\}_{i\geq 1}$ is an exchangeable sequence of random variables and $$N=\min\,\{n:X_{n-1}>X_n\},$$ then $N\geq n$ if and ony if $X_1\leq X_2\leq\dots\leq X_{n-1}$. Therefore, $$\Pr(N\geq n) = \Pr(X_1\leq X_2\leq\dots\leq X_{n-1})=\frac{1}{(n-1)!}, \qquad (*)$$
by symmetry. Hence, $\mathrm{E}[N]=\sum_{n=1}^\infty \Pr(N\geq n)=e\approx 2.71828\dots$.
P.S. People asked about the proof of $(*)$. Since the sequence is exchangeable, it must be that, for any permutation $\pi:\{1,\dots,n-1\}\to\{1,\dots,n-1\}$, we have
$$
\Pr(X_1\leq X_2\leq\dots\leq X_{n-1}) = \Pr(X_{\pi(1)}\leq X_{\pi(2)}\leq\dots\leq X_{\pi(n-1)}).
$$
Since we have $(n-1)!$ possible permutations, the result follows. | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrea
If $\{X_i\}_{i\geq 1}$ is an exchangeable sequence of random variables and $$N=\min\,\{n:X_{n-1}>X_n\},$$ then $N\geq n$ if and ony if $X_1\leq X_2\leq\dots\leq X_{n-1}$. Therefore, $$\Pr(N\geq n) = \ |
25,047 | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrease for the first time? | As suggested by Silverfish, I'm posting the solution below.
\begin{align*}
P[N = i] & = P[X_1 \leq X_2 \dotsc \leq X_{i-1} > X_i] \\
& = P[X_1 \leq X_2 \dotsc \leq X_{i-1}] - P[X_1 \leq X_2 \dotsc \leq X_{i-1} \leq X_i] \\
& = \frac{1}{(i-1)!} - \frac{1}{i!}
\end{align*}
And
\begin{align*}
P[N \geq i] & = 1 - P[N < i] \\
& = 1 - \left(1 -\frac{1}{2!} + \frac{1}{2!} - \frac{1}{3!} + \cdots +\frac{1}{(i-2)!} - \frac{1}{(i-1)!}\right)\\
& = \frac{1}{(i-1)!} \\
\end{align*}
Thus $E[N] = \sum_{i = 1}^{\infty}P[N \geq i] = \sum_{i = 1}^{\infty}\frac{1}{(i-1)!} = e$. | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrea | As suggested by Silverfish, I'm posting the solution below.
\begin{align*}
P[N = i] & = P[X_1 \leq X_2 \dotsc \leq X_{i-1} > X_i] \\
& = P[X_1 \leq X_2 \dotsc \leq X_{i-1}] - P[X_1 \leq X_2 \dotsc \le | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrease for the first time?
As suggested by Silverfish, I'm posting the solution below.
\begin{align*}
P[N = i] & = P[X_1 \leq X_2 \dotsc \leq X_{i-1} > X_i] \\
& = P[X_1 \leq X_2 \dotsc \leq X_{i-1}] - P[X_1 \leq X_2 \dotsc \leq X_{i-1} \leq X_i] \\
& = \frac{1}{(i-1)!} - \frac{1}{i!}
\end{align*}
And
\begin{align*}
P[N \geq i] & = 1 - P[N < i] \\
& = 1 - \left(1 -\frac{1}{2!} + \frac{1}{2!} - \frac{1}{3!} + \cdots +\frac{1}{(i-2)!} - \frac{1}{(i-1)!}\right)\\
& = \frac{1}{(i-1)!} \\
\end{align*}
Thus $E[N] = \sum_{i = 1}^{\infty}P[N \geq i] = \sum_{i = 1}^{\infty}\frac{1}{(i-1)!} = e$. | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrea
As suggested by Silverfish, I'm posting the solution below.
\begin{align*}
P[N = i] & = P[X_1 \leq X_2 \dotsc \leq X_{i-1} > X_i] \\
& = P[X_1 \leq X_2 \dotsc \leq X_{i-1}] - P[X_1 \leq X_2 \dotsc \le |
25,048 | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrease for the first time? | An alternative argument: there is only one ordering of the $X_i$ which is increasing, out of the $n!$ possible permutations of $X_1, \dots, X_n$. We are interested in orderings which increase until the penultimate position, and then decrease: this requires the maximum to be in position $n-1$, and one of the $n-1$ other $X_i$ to be in the final position. Since there are $n-1$ ways to pick out one of the first $n-1$ terms in our ordered sequence and move it to the final position, then the probability is:
$$\Pr(N=n) = \frac{n-1}{n!}$$
Note $\Pr(N=2) = \frac{2-1}{2!} = \frac{1}{2}$, $\Pr(N=3) = \frac{3-1}{3!} = \frac{1}{3}$ and $\Pr(N=4) = \frac{4-1}{4!} = \frac{1}{8}$ so this is consistent with the results found by integration.
To find the expected value of $N$ we can use:
$$\mathbb{E}(N) = \sum_{n=2}^{\infty} n \Pr(N=n) = \sum_{n=2}^{\infty} \frac{n(n-1)}{n!} = \sum_{n=2}^{\infty} \frac{1}{(n-2)!}= \sum_{k=0}^{\infty} \frac{1}{k!} = e$$
(To make the summation more obvious I have used $k=n-2$; for readers unfamiliar with this sum, take the Taylor series $e^x = \sum_{k=0}^{\infty} \frac{x^k}{k!}$ and substitute $x=1$.)
We can check the result by simulation, here is some code in R:
firstDecrease <- function(x) {
counter <- 2
a <- runif(1)
b <- runif(1)
while(a < b){
counter <- counter + 1
a <- b
b <- runif(1)
}
return(counter)
}
mean(mapply(firstDecrease, 1:1e7))
This returned 2.718347, close enough to 2.71828 to satisfy me. | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrea | An alternative argument: there is only one ordering of the $X_i$ which is increasing, out of the $n!$ possible permutations of $X_1, \dots, X_n$. We are interested in orderings which increase until th | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrease for the first time?
An alternative argument: there is only one ordering of the $X_i$ which is increasing, out of the $n!$ possible permutations of $X_1, \dots, X_n$. We are interested in orderings which increase until the penultimate position, and then decrease: this requires the maximum to be in position $n-1$, and one of the $n-1$ other $X_i$ to be in the final position. Since there are $n-1$ ways to pick out one of the first $n-1$ terms in our ordered sequence and move it to the final position, then the probability is:
$$\Pr(N=n) = \frac{n-1}{n!}$$
Note $\Pr(N=2) = \frac{2-1}{2!} = \frac{1}{2}$, $\Pr(N=3) = \frac{3-1}{3!} = \frac{1}{3}$ and $\Pr(N=4) = \frac{4-1}{4!} = \frac{1}{8}$ so this is consistent with the results found by integration.
To find the expected value of $N$ we can use:
$$\mathbb{E}(N) = \sum_{n=2}^{\infty} n \Pr(N=n) = \sum_{n=2}^{\infty} \frac{n(n-1)}{n!} = \sum_{n=2}^{\infty} \frac{1}{(n-2)!}= \sum_{k=0}^{\infty} \frac{1}{k!} = e$$
(To make the summation more obvious I have used $k=n-2$; for readers unfamiliar with this sum, take the Taylor series $e^x = \sum_{k=0}^{\infty} \frac{x^k}{k!}$ and substitute $x=1$.)
We can check the result by simulation, here is some code in R:
firstDecrease <- function(x) {
counter <- 2
a <- runif(1)
b <- runif(1)
while(a < b){
counter <- counter + 1
a <- b
b <- runif(1)
}
return(counter)
}
mean(mapply(firstDecrease, 1:1e7))
This returned 2.718347, close enough to 2.71828 to satisfy me. | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrea
An alternative argument: there is only one ordering of the $X_i$ which is increasing, out of the $n!$ possible permutations of $X_1, \dots, X_n$. We are interested in orderings which increase until th |
25,049 | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrease for the first time? | EDIT: My answer is incorrect. I am leaving it as an example of how easy a seemingly simple question like this is to misinterpret.
I don't think your math is correct for the case $ P[N=4] $. We can check this via a simple simulation:
n=50000
flag <- rep(NA, n)
order <- 3
for (i in 1:n) {
x<-rnorm(100)
flag[i] <- all(x[order] < x[1:(order-1)])==T
}
sum(flag)/n
Gives us:
> sum(flag)/n
[1] 0.33326
Changing the order term to 4 get us:
> sum(flag)/n
[1] 0.25208
And 5:
> sum(flag)/n
[1] 0.2023
So if we trust our simulation results, it looks like the pattern is that $P[N = X] = \frac{1}{x}$. But this makes sense as well, since what you are really asking is what is the probability that any given observation in a subset of all your observations is the minimum observation (if we are assuming i.i.d. then we are assuming exchangability and so the order is arbitary). One of them has to be the minimum, and so really the question is what is probability that any observation selected at random is the minimum. This is just a simple binomial process. | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrea | EDIT: My answer is incorrect. I am leaving it as an example of how easy a seemingly simple question like this is to misinterpret.
I don't think your math is correct for the case $ P[N=4] $. We can che | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrease for the first time?
EDIT: My answer is incorrect. I am leaving it as an example of how easy a seemingly simple question like this is to misinterpret.
I don't think your math is correct for the case $ P[N=4] $. We can check this via a simple simulation:
n=50000
flag <- rep(NA, n)
order <- 3
for (i in 1:n) {
x<-rnorm(100)
flag[i] <- all(x[order] < x[1:(order-1)])==T
}
sum(flag)/n
Gives us:
> sum(flag)/n
[1] 0.33326
Changing the order term to 4 get us:
> sum(flag)/n
[1] 0.25208
And 5:
> sum(flag)/n
[1] 0.2023
So if we trust our simulation results, it looks like the pattern is that $P[N = X] = \frac{1}{x}$. But this makes sense as well, since what you are really asking is what is the probability that any given observation in a subset of all your observations is the minimum observation (if we are assuming i.i.d. then we are assuming exchangability and so the order is arbitary). One of them has to be the minimum, and so really the question is what is probability that any observation selected at random is the minimum. This is just a simple binomial process. | Suppose $X_1, X_2, \dotsc, X_n$ are i.i.d. random variables. When is the sequence expected to decrea
EDIT: My answer is incorrect. I am leaving it as an example of how easy a seemingly simple question like this is to misinterpret.
I don't think your math is correct for the case $ P[N=4] $. We can che |
25,050 | Evaluating a regression model | The link that you posted has many of the techniques that I would suggest, but additionally plotting learning curves can help. This can help you see not just the absolute performance, but can help you get a sense of how far from optimal performance you are.
Learning Curves: If you plot cross-validation (cv) error and training set error rates versus training set size, you can learn a lot. If the two curves approach each other with low error rate, then you are doing well.
If it looks like the curves are starting to approach each other and both heading/staying low, then you need more data.
If the cv curve remains high, but the training set curve remains low, then you have a high-variance situation. You can either get more data, or use regularization to improve generalization.
If the cv stays high and the training set curve comes up to meet it, then you have high bias. In this case, you want to add detail to your model. | Evaluating a regression model | The link that you posted has many of the techniques that I would suggest, but additionally plotting learning curves can help. This can help you see not just the absolute performance, but can help you | Evaluating a regression model
The link that you posted has many of the techniques that I would suggest, but additionally plotting learning curves can help. This can help you see not just the absolute performance, but can help you get a sense of how far from optimal performance you are.
Learning Curves: If you plot cross-validation (cv) error and training set error rates versus training set size, you can learn a lot. If the two curves approach each other with low error rate, then you are doing well.
If it looks like the curves are starting to approach each other and both heading/staying low, then you need more data.
If the cv curve remains high, but the training set curve remains low, then you have a high-variance situation. You can either get more data, or use regularization to improve generalization.
If the cv stays high and the training set curve comes up to meet it, then you have high bias. In this case, you want to add detail to your model. | Evaluating a regression model
The link that you posted has many of the techniques that I would suggest, but additionally plotting learning curves can help. This can help you see not just the absolute performance, but can help you |
25,051 | Evaluating a regression model | There is multiple ways to define performance criteria of model in estimation. Most of people use how good the model fit the data. So in case of regression it will be "how much of variance is explain by the model". However, you need to be careful with such regression when you are performing variable selection (for eg. by LASSO) you need to control for the number of parameter are included in the model. One can use cross-validated version of explained variance which presumably give unbiased estimate model performance. | Evaluating a regression model | There is multiple ways to define performance criteria of model in estimation. Most of people use how good the model fit the data. So in case of regression it will be "how much of variance is explain b | Evaluating a regression model
There is multiple ways to define performance criteria of model in estimation. Most of people use how good the model fit the data. So in case of regression it will be "how much of variance is explain by the model". However, you need to be careful with such regression when you are performing variable selection (for eg. by LASSO) you need to control for the number of parameter are included in the model. One can use cross-validated version of explained variance which presumably give unbiased estimate model performance. | Evaluating a regression model
There is multiple ways to define performance criteria of model in estimation. Most of people use how good the model fit the data. So in case of regression it will be "how much of variance is explain b |
25,052 | Evaluating a regression model | First of all, I think you should use the term "regression" or "prediction" instead of "estimation" - the latter rather refers to statistical inference for model parameters (assuming some parametric form), whereas you seem to be more concerned with predictive power for dependent variable. Now, from my consulting experience, most often used measures of model performance - apart from the simplest "distance metrics" you mention - are realtive mean absolute/squared error and $R^2$ coefficient for observed and predicted values. Of course you can use some custom loss functions, depending on a particular study/business context. | Evaluating a regression model | First of all, I think you should use the term "regression" or "prediction" instead of "estimation" - the latter rather refers to statistical inference for model parameters (assuming some parametric fo | Evaluating a regression model
First of all, I think you should use the term "regression" or "prediction" instead of "estimation" - the latter rather refers to statistical inference for model parameters (assuming some parametric form), whereas you seem to be more concerned with predictive power for dependent variable. Now, from my consulting experience, most often used measures of model performance - apart from the simplest "distance metrics" you mention - are realtive mean absolute/squared error and $R^2$ coefficient for observed and predicted values. Of course you can use some custom loss functions, depending on a particular study/business context. | Evaluating a regression model
First of all, I think you should use the term "regression" or "prediction" instead of "estimation" - the latter rather refers to statistical inference for model parameters (assuming some parametric fo |
25,053 | Evaluating a regression model | Referring to scikit-learn documentation (Python based package for machine learning), r2_score and explained_variance_score are popular choices. Unlike distance measures like mean_squared_error or mean_absolute_error, these metrics give an indication of how good or bad the prediction is (closer to 1 => better predictions). [By the way, if using distance measures, I would recommend RMSE (root mean square error) instead of just MSE (mean square error) so that the magnitude can be compared with the predictions]
Alternatively, you could also compute correlation coefficient between regressor predicted values and the true target variable values using Pearson's correlation coefficient (for linear models) or better go for Spearman's rank correlation coefficient (as this doesn't assume linear models and is less sensitive to outliers).
Learning curves suggested in John Yetter's reply is also a good method but the above mentioned metrics might be easier to assess the performance. | Evaluating a regression model | Referring to scikit-learn documentation (Python based package for machine learning), r2_score and explained_variance_score are popular choices. Unlike distance measures like mean_squared_error or mean | Evaluating a regression model
Referring to scikit-learn documentation (Python based package for machine learning), r2_score and explained_variance_score are popular choices. Unlike distance measures like mean_squared_error or mean_absolute_error, these metrics give an indication of how good or bad the prediction is (closer to 1 => better predictions). [By the way, if using distance measures, I would recommend RMSE (root mean square error) instead of just MSE (mean square error) so that the magnitude can be compared with the predictions]
Alternatively, you could also compute correlation coefficient between regressor predicted values and the true target variable values using Pearson's correlation coefficient (for linear models) or better go for Spearman's rank correlation coefficient (as this doesn't assume linear models and is less sensitive to outliers).
Learning curves suggested in John Yetter's reply is also a good method but the above mentioned metrics might be easier to assess the performance. | Evaluating a regression model
Referring to scikit-learn documentation (Python based package for machine learning), r2_score and explained_variance_score are popular choices. Unlike distance measures like mean_squared_error or mean |
25,054 | How can a t-test be statistically significant if the mean difference is almost 0? | I see no reason to believe you did something wrong just because the test was significant, even if the mean difference is very small. In a paired t-test, the significance will be driven by three things:
the magnitude of the mean difference
the amount of data you have
the standard deviation of the differences
Admittedly, your mean difference is very, very small. On the other hand, you do have a fair amount of data (N=335). The last factor is the standard deviation of the differences. I don't know what that is, but since you got a significant result, it is safe to assume it is small enough to overcome the small mean difference with the amount of data you have. For the sake of building an intuition, imagine that the paired difference for every observation in your study were 0.00017, then the standard deviation of the differences would be 0. Surely, it would be reasonable to conclude that the treatment led to a reduction (albeit a tiny one).
As @whuber notes in the comments below, it is worth pointing out that while 0.00017 seems like a very small number qua number, it isn't necessarily small in meaningful terms. To know that, we would need to know several things, firstly what the units are. If the units are very large (e.g., years, kilometers, etc.), what appears to be small could be meaningfully large, whereas if the units are small (e.g., seconds, centimeters, etc.), this difference seems even smaller. Second, even a small change can be important: imagine some kind of treatment (e.g., vaccine) that was very cheap, easy to administer to the whole populace, and had no side effects. It may well be worth doing even if it saved only a very few lives. | How can a t-test be statistically significant if the mean difference is almost 0? | I see no reason to believe you did something wrong just because the test was significant, even if the mean difference is very small. In a paired t-test, the significance will be driven by three thing | How can a t-test be statistically significant if the mean difference is almost 0?
I see no reason to believe you did something wrong just because the test was significant, even if the mean difference is very small. In a paired t-test, the significance will be driven by three things:
the magnitude of the mean difference
the amount of data you have
the standard deviation of the differences
Admittedly, your mean difference is very, very small. On the other hand, you do have a fair amount of data (N=335). The last factor is the standard deviation of the differences. I don't know what that is, but since you got a significant result, it is safe to assume it is small enough to overcome the small mean difference with the amount of data you have. For the sake of building an intuition, imagine that the paired difference for every observation in your study were 0.00017, then the standard deviation of the differences would be 0. Surely, it would be reasonable to conclude that the treatment led to a reduction (albeit a tiny one).
As @whuber notes in the comments below, it is worth pointing out that while 0.00017 seems like a very small number qua number, it isn't necessarily small in meaningful terms. To know that, we would need to know several things, firstly what the units are. If the units are very large (e.g., years, kilometers, etc.), what appears to be small could be meaningfully large, whereas if the units are small (e.g., seconds, centimeters, etc.), this difference seems even smaller. Second, even a small change can be important: imagine some kind of treatment (e.g., vaccine) that was very cheap, easy to administer to the whole populace, and had no side effects. It may well be worth doing even if it saved only a very few lives. | How can a t-test be statistically significant if the mean difference is almost 0?
I see no reason to believe you did something wrong just because the test was significant, even if the mean difference is very small. In a paired t-test, the significance will be driven by three thing |
25,055 | How can a t-test be statistically significant if the mean difference is almost 0? | To know if a difference is really large or small requires some measure of scale, the standard deviation is one measure of scale and is part of the t-test formula to account in part for that scale.
Consider if you are comparing the heights of 5 year olds to the heights of 20 year olds (humans, same geographic area, etc.). Intuition tells us that there is a practical difference there and if the heights are measured in inches or centimeters then the difference will look meaningful. But what if you convert the heights to kilometers? or light years? then the difference will be a very small number (but still different), but (barring round-off error) the t-test will give the same results whether the height is measured in inches, centimeters, or kilometers.
So a difference of 0.00017 may be huge depending on the scale of the measurements. | How can a t-test be statistically significant if the mean difference is almost 0? | To know if a difference is really large or small requires some measure of scale, the standard deviation is one measure of scale and is part of the t-test formula to account in part for that scale.
Con | How can a t-test be statistically significant if the mean difference is almost 0?
To know if a difference is really large or small requires some measure of scale, the standard deviation is one measure of scale and is part of the t-test formula to account in part for that scale.
Consider if you are comparing the heights of 5 year olds to the heights of 20 year olds (humans, same geographic area, etc.). Intuition tells us that there is a practical difference there and if the heights are measured in inches or centimeters then the difference will look meaningful. But what if you convert the heights to kilometers? or light years? then the difference will be a very small number (but still different), but (barring round-off error) the t-test will give the same results whether the height is measured in inches, centimeters, or kilometers.
So a difference of 0.00017 may be huge depending on the scale of the measurements. | How can a t-test be statistically significant if the mean difference is almost 0?
To know if a difference is really large or small requires some measure of scale, the standard deviation is one measure of scale and is part of the t-test formula to account in part for that scale.
Con |
25,056 | How can a t-test be statistically significant if the mean difference is almost 0? | If your critical $t$ is less than what you calculated, and assuming the test was appropriate for your particular kind of data (an important "if"), it seems your difference is statistically significant in the sense of unlikely to emerge at least as large in another, similar pair of samples selected randomly from the same populations if the null hypothesis of no difference is literally true of those populations. A significant $t$ in the appropriate context generally means that your observed difference is too reliably non-zero to support the null hypothesis that the data are not "any different at all". Even a difference of $\frac{17}{100,000}$ can be statistically significant from zero if every observed difference is between .00015–.00020. Observe!
pop1=rep(15:20* .00001, 56);pop2=rep(0,336) #Some fake samples of sample size = 336
t.test(pop1,pop2,paired=T) #Paired t-test with the following output...
$$t_{(335)}=187.55,p<2.2\times10^{-16}$$
Because these samples are very consistently different, the difference achieves statistical significance, even though they are of smaller scale than many of us are used to seeing in mundane, everyday numbers. In fact, you can scale down the data as much as you like by tacking as many zeros as your calculations can handle onto to the front of .00001 in my first line of R code. This will scale down the standard deviation of the differences as well; i.e., your differences will remain just as consistent, your $t$ will remain exactly the same, and so will its significance.
Maybe you'd be more interested in practical significance than in this literal sense of null hypothesis significance testing. Practical significance will depend much more on the meaning of your data in context than on statistical significance; it is not a purely statistical matter. I cited a useful example of this principle in an answer to a popular question here, Accommodating entrenched views of p-values:
One cannot conclude by size alone that an $r=.03$ is necessarily unimportant if it might pertain to a matter of life and death [(Rosenthal, Rubin, & Rosnow, 2000)].
This "matter of life and death" was the effect size of aspirin on heart attacks, basically – a powerful example of numerically small, much less consistent differences with practically important meaning. Many other questions with solid answers from which you might benefit deserve links here, including:
Why is "statistically significant" not enough?
practical vs statistical significance
Practical significance, especially with percents: "standard" measure and threshold
Reference
Rosenthal, R., Rosnow, R. L., & Rubin, D. B. (2000). Contrasts and effect sizes in behavioral research: A correlational approach. Cambridge University Press. | How can a t-test be statistically significant if the mean difference is almost 0? | If your critical $t$ is less than what you calculated, and assuming the test was appropriate for your particular kind of data (an important "if"), it seems your difference is statistically significant | How can a t-test be statistically significant if the mean difference is almost 0?
If your critical $t$ is less than what you calculated, and assuming the test was appropriate for your particular kind of data (an important "if"), it seems your difference is statistically significant in the sense of unlikely to emerge at least as large in another, similar pair of samples selected randomly from the same populations if the null hypothesis of no difference is literally true of those populations. A significant $t$ in the appropriate context generally means that your observed difference is too reliably non-zero to support the null hypothesis that the data are not "any different at all". Even a difference of $\frac{17}{100,000}$ can be statistically significant from zero if every observed difference is between .00015–.00020. Observe!
pop1=rep(15:20* .00001, 56);pop2=rep(0,336) #Some fake samples of sample size = 336
t.test(pop1,pop2,paired=T) #Paired t-test with the following output...
$$t_{(335)}=187.55,p<2.2\times10^{-16}$$
Because these samples are very consistently different, the difference achieves statistical significance, even though they are of smaller scale than many of us are used to seeing in mundane, everyday numbers. In fact, you can scale down the data as much as you like by tacking as many zeros as your calculations can handle onto to the front of .00001 in my first line of R code. This will scale down the standard deviation of the differences as well; i.e., your differences will remain just as consistent, your $t$ will remain exactly the same, and so will its significance.
Maybe you'd be more interested in practical significance than in this literal sense of null hypothesis significance testing. Practical significance will depend much more on the meaning of your data in context than on statistical significance; it is not a purely statistical matter. I cited a useful example of this principle in an answer to a popular question here, Accommodating entrenched views of p-values:
One cannot conclude by size alone that an $r=.03$ is necessarily unimportant if it might pertain to a matter of life and death [(Rosenthal, Rubin, & Rosnow, 2000)].
This "matter of life and death" was the effect size of aspirin on heart attacks, basically – a powerful example of numerically small, much less consistent differences with practically important meaning. Many other questions with solid answers from which you might benefit deserve links here, including:
Why is "statistically significant" not enough?
practical vs statistical significance
Practical significance, especially with percents: "standard" measure and threshold
Reference
Rosenthal, R., Rosnow, R. L., & Rubin, D. B. (2000). Contrasts and effect sizes in behavioral research: A correlational approach. Cambridge University Press. | How can a t-test be statistically significant if the mean difference is almost 0?
If your critical $t$ is less than what you calculated, and assuming the test was appropriate for your particular kind of data (an important "if"), it seems your difference is statistically significant |
25,057 | How can a t-test be statistically significant if the mean difference is almost 0? | Here is an example in R that shows the theoretical concepts in action. 10,000 trials of flipping a coin 10,000 times that has a probability of heads of .0001 compared to 10,000 trials of flipping a coin 10,000 times that has a probability of heads of .00011
t.test(rbinom(10000, 10000, .0001), rbinom(10000, 10000, .00011))
t = -8.0299, df = 19886.35, p-value = 1.03e-15
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-0.14493747 -0.08806253
sample estimates:
mean of x mean of y
0.9898 1.1063
The difference in the mean is relatively closed to 0 in terms of human perception, however it is very statistically different than 0. | How can a t-test be statistically significant if the mean difference is almost 0? | Here is an example in R that shows the theoretical concepts in action. 10,000 trials of flipping a coin 10,000 times that has a probability of heads of .0001 compared to 10,000 trials of flipping a c | How can a t-test be statistically significant if the mean difference is almost 0?
Here is an example in R that shows the theoretical concepts in action. 10,000 trials of flipping a coin 10,000 times that has a probability of heads of .0001 compared to 10,000 trials of flipping a coin 10,000 times that has a probability of heads of .00011
t.test(rbinom(10000, 10000, .0001), rbinom(10000, 10000, .00011))
t = -8.0299, df = 19886.35, p-value = 1.03e-15
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-0.14493747 -0.08806253
sample estimates:
mean of x mean of y
0.9898 1.1063
The difference in the mean is relatively closed to 0 in terms of human perception, however it is very statistically different than 0. | How can a t-test be statistically significant if the mean difference is almost 0?
Here is an example in R that shows the theoretical concepts in action. 10,000 trials of flipping a coin 10,000 times that has a probability of heads of .0001 compared to 10,000 trials of flipping a c |
25,058 | Are degrees of freedom in lmerTest::anova correct? They are very different from RM-ANOVA | I think that lmerTest is getting it right and ezanova is getting it wrong in this case.
the results from lmerTest agree with my intuition/understanding
two different computations in lmerTest (Satterthwaite and Kenward-Roger) agree
they also agree with nlme::lme
when I run it, ezanova gives a warning, which I don't entirely understand, but which should not be disregarded ...
Re-running example:
library(ez); library(lmerTest); library(nlme)
data(ANT)
ANT.2 <- subset(ANT, !error)
set.seed(101) ## for reproducibility
baseline.shift <- rnorm(length(unique(ANT.2$subnum)), 0, 50)
ANT.2$rt <- ANT.2$rt + baseline.shift[as.numeric(ANT.2$subnum)]
Figure out experimental design
with(ANT.2,table(subnum,group,direction))
So it looks like individuals (subnum) are placed in either control or treatment groups, and each is tested for both directions -- i.e. direction can be tested within individuals (denominator df is large), but group and group:direction can only be tested among individuals
(anova.ez <- ezANOVA(data = ANT.2, dv = .(rt), wid = .(subnum),
within = .(direction), between = .(group)))
## $ANOVA
## Effect DFn DFd F p p<.05 ges
## 2 group 1 18 2.4290721 0.13651174 0.1183150147
## 3 direction 1 18 0.9160571 0.35119193 0.0002852171
## 4 group:direction 1 18 4.9169156 0.03970473 * 0.0015289914
Here I get Warning: collapsing data to cell means. *IF* the requested effects are a subset of the full design, you must use the "within_full" argument, else results may be inaccurate. The denominator DF look a little funky (all equal to 18): I think they should be larger for direction and group:direction, which can be tested independently (but would be smaller if you added (direction|subnum) to the model)?
# similarly with lmer and lmerTest::anova
model <- lmer(rt ~ group * direction + (1 | subnum), data = ANT.2)
lmerTest::anova(model)
## Df Sum Sq Mean Sq F value Denom Pr(>F)
## group 1 12065.7 12065.7 2.4310 18 0.1364
## direction 1 1952.2 1952.2 0.3948 5169 0.5298
## group:direction 1 11552.2 11552.2 2.3299 5169 0.1270
the Df column here refers to the numerator df, Denom (second-to-last) gives the estimated denominator df; they agree with the classical intuition. More important, we also get different answers for the F values ...
We can also double-check with Kenward-Roger (very slow because it involves refitting the model several times)
lmerTest::anova(model,ddf="Kenward-Roger")
The results are identical.
For this example lme (from the nlme package) actually does a perfectly good job guessing the appropriate denominator df (the F and p-values are very slightly different):
model3 <- lme(rt ~ group * direction, random=~1|subnum, data = ANT.2)
anova(model3)[-1,]
## numDF denDF F-value p-value
## group 1 18 2.4334314 0.1362
## direction 1 5169 0.3937316 0.5304
## group:direction 1 5169 2.3298847 0.1270
If I fit an interaction between direction and subnum the df for direction and group:direction are much smaller (I would have thought they would be 18, but maybe I'm getting something wrong):
model2 <- lmer(rt ~ group * direction + (direction | subnum), data = ANT.2)
lmerTest::anova(model2)
## Df Sum Sq Mean Sq F value Denom Pr(>F)
## group 1 20334.7 20334.7 2.4302 17.995 0.1364
## direction 1 1804.3 1804.3 0.3649 124.784 0.5469
## group:direction 1 10616.6 10616.6 2.1418 124.784 0.1459 | Are degrees of freedom in lmerTest::anova correct? They are very different from RM-ANOVA | I think that lmerTest is getting it right and ezanova is getting it wrong in this case.
the results from lmerTest agree with my intuition/understanding
two different computations in lmerTest (Sattert | Are degrees of freedom in lmerTest::anova correct? They are very different from RM-ANOVA
I think that lmerTest is getting it right and ezanova is getting it wrong in this case.
the results from lmerTest agree with my intuition/understanding
two different computations in lmerTest (Satterthwaite and Kenward-Roger) agree
they also agree with nlme::lme
when I run it, ezanova gives a warning, which I don't entirely understand, but which should not be disregarded ...
Re-running example:
library(ez); library(lmerTest); library(nlme)
data(ANT)
ANT.2 <- subset(ANT, !error)
set.seed(101) ## for reproducibility
baseline.shift <- rnorm(length(unique(ANT.2$subnum)), 0, 50)
ANT.2$rt <- ANT.2$rt + baseline.shift[as.numeric(ANT.2$subnum)]
Figure out experimental design
with(ANT.2,table(subnum,group,direction))
So it looks like individuals (subnum) are placed in either control or treatment groups, and each is tested for both directions -- i.e. direction can be tested within individuals (denominator df is large), but group and group:direction can only be tested among individuals
(anova.ez <- ezANOVA(data = ANT.2, dv = .(rt), wid = .(subnum),
within = .(direction), between = .(group)))
## $ANOVA
## Effect DFn DFd F p p<.05 ges
## 2 group 1 18 2.4290721 0.13651174 0.1183150147
## 3 direction 1 18 0.9160571 0.35119193 0.0002852171
## 4 group:direction 1 18 4.9169156 0.03970473 * 0.0015289914
Here I get Warning: collapsing data to cell means. *IF* the requested effects are a subset of the full design, you must use the "within_full" argument, else results may be inaccurate. The denominator DF look a little funky (all equal to 18): I think they should be larger for direction and group:direction, which can be tested independently (but would be smaller if you added (direction|subnum) to the model)?
# similarly with lmer and lmerTest::anova
model <- lmer(rt ~ group * direction + (1 | subnum), data = ANT.2)
lmerTest::anova(model)
## Df Sum Sq Mean Sq F value Denom Pr(>F)
## group 1 12065.7 12065.7 2.4310 18 0.1364
## direction 1 1952.2 1952.2 0.3948 5169 0.5298
## group:direction 1 11552.2 11552.2 2.3299 5169 0.1270
the Df column here refers to the numerator df, Denom (second-to-last) gives the estimated denominator df; they agree with the classical intuition. More important, we also get different answers for the F values ...
We can also double-check with Kenward-Roger (very slow because it involves refitting the model several times)
lmerTest::anova(model,ddf="Kenward-Roger")
The results are identical.
For this example lme (from the nlme package) actually does a perfectly good job guessing the appropriate denominator df (the F and p-values are very slightly different):
model3 <- lme(rt ~ group * direction, random=~1|subnum, data = ANT.2)
anova(model3)[-1,]
## numDF denDF F-value p-value
## group 1 18 2.4334314 0.1362
## direction 1 5169 0.3937316 0.5304
## group:direction 1 5169 2.3298847 0.1270
If I fit an interaction between direction and subnum the df for direction and group:direction are much smaller (I would have thought they would be 18, but maybe I'm getting something wrong):
model2 <- lmer(rt ~ group * direction + (direction | subnum), data = ANT.2)
lmerTest::anova(model2)
## Df Sum Sq Mean Sq F value Denom Pr(>F)
## group 1 20334.7 20334.7 2.4302 17.995 0.1364
## direction 1 1804.3 1804.3 0.3649 124.784 0.5469
## group:direction 1 10616.6 10616.6 2.1418 124.784 0.1459 | Are degrees of freedom in lmerTest::anova correct? They are very different from RM-ANOVA
I think that lmerTest is getting it right and ezanova is getting it wrong in this case.
the results from lmerTest agree with my intuition/understanding
two different computations in lmerTest (Sattert |
25,059 | Are degrees of freedom in lmerTest::anova correct? They are very different from RM-ANOVA | I generally agree with Ben's analysis but let me add a couple of remarks and
a little intuition.
First, the overall results:
lmerTest results using the Satterthwaite method are correct
The Kenward-Roger method is also correct and agrees with Satterthwaite
Ben outlines the design in which subnum is nested in group while direction
and group:direction are crossed with subnum. This means that the natural
error term (i.e. the so-called "enclosing error stratum")
for group is subnum while the enclosing error stratum for the
other terms (including subnum) is the residuals.
This structure can be represented in a so-called factor-structure diagram:
names <- c(expression("[I]"[5169]^{5191}),
expression("[subnum]"[18]^{20}), expression(grp:dir[1]^{4}),
expression(dir[1]^{2}), expression(grp[1]^{2}), expression(0[1]^{1}))
x <- c(2, 4, 4, 6, 6, 8)
y <- c(5, 7, 5, 3, 7, 5)
plot(NA, NA, xlim=c(2, 8), ylim=c(2, 8), type="n", axes=F, xlab="", ylab="")
text(x, y, names) # Add text according to ’names’ vector
# Define coordinates for start (x0, y0) and end (x1, y1) of arrows:
x0 <- c(1.8, 1.8, 4.2, 4.2, 4.2, 6, 6) + .5
y0 <- c(5, 5, 7, 5, 5, 3, 7)
x1 <- c(2.7, 2.7, 5, 5, 5, 7.2, 7.2) + .5
y1 <- c(5, 7, 7, 3, 7, 5, 5)
arrows(x0, y0, x1, y1, length=0.1)
Here random terms are enclosed in brackets, 0 represents the overall mean
(or intercept), [I] represents the error term, the super-script numbers are
the number of levels and the sub-script numbers are the number of degrees of
freedom assuming a balanced design. The diagram indicates that the natural
error term (enclosing error stratum) for group is subnum and
that the numerator df for subnum, which equals the denominator df for group,
is 18: 20 minus 1 df for group and 1 df for the overall mean. A more comprehensive introduction to factor structure diagrams is available in chapter 2 here: https://02429.compute.dtu.dk/eBook.
If the data were exactly balanced we would be able to construct the F-tests from
a SSQ-decomposition as provided by anova.lm. Since the dataset is very-closely balanced we can obtain approximate F-tests as follows:
ANT.2 <- subset(ANT, !error)
set.seed(101)
baseline.shift <- rnorm(length(unique(ANT.2$subnum)), 0, 50)
ANT.2$rt <- ANT.2$rt + baseline.shift[as.numeric(ANT.2$subnum)]
fm <- lm(rt ~ group * direction + subnum, data=ANT.2)
(an <- anova(fm))
Analysis of Variance Table
Response: rt
Df Sum Sq Mean Sq F value Pr(>F)
group 1 994365 994365 200.5461 <2e-16 ***
direction 1 1568 1568 0.3163 0.5739
subnum 18 7576606 420923 84.8927 <2e-16 ***
group:direction 1 11561 11561 2.3316 0.1268
Residuals 5169 25629383 4958
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Here all F and p values are computed assuming that all terms have the residuals as their enclosing error stratum, and that is true for all but 'group'. The 'balanced-correct' F-test for group is instead:
F_group <- an["group", "Mean Sq"] / an["subnum", "Mean Sq"]
c(Fvalue=F_group, pvalue=pf(F_group, 1, 18, lower.tail = FALSE))
Fvalue pvalue
2.3623466 0.1416875
where we use the subnum MS instead of the Residuals MS in the F-value
denominator.
Note that these values match quite well with the Satterthwaite results:
model <- lmer(rt ~ group * direction + (1 | subnum), data = ANT.2)
anova(model, type=1)
Type I Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
group 12065.3 12065.3 1 18 2.4334 0.1362
direction 1951.8 1951.8 1 5169 0.3936 0.5304
group:direction 11552.2 11552.2 1 5169 2.3299 0.1270
Remaining differences are due to the data not being exactly balanced.
The OP compares anova.lm with anova.lmerModLmerTest, which is ok, but to compare like with like we have to use the same contrasts.
In this case there is a difference between anova.lm and anova.lmerModLmerTest since they produce Type I and III tests by default respectively, and for this dataset there is a
(small) difference between the Type I and III contrasts:
show_tests(anova(model, type=1))$group
(Intercept) groupTreatment directionright groupTreatment:directionright
groupTreatment 0 1 0.005202759 0.5013477
show_tests(anova(model, type=3))$group # type=3 is default
(Intercept) groupTreatment directionright groupTreatment:directionright
groupTreatment 0 1 0 0.5
If the data set had been completely balanced the type I contrasts would have
been the same as the type III contrasts (which are not affected by the observed
number of samples).
One last remark is that the 'slowness' of the Kenward-Roger method is not due to
model re-fitting, but because it involves computations with the marginal
variance-covariance matrix of the observations/residuals (5191x5191 in this case)
which is not the case for Satterthwaite's method.
Concerning model2
As for model2 the situation becomes more complex and I think it is easier to
start the discussion with another model where I have included the
'classical' interaction between subnum and direction:
model3 <- lmer(rt ~ group * direction + (1 | subnum) +
(1 | subnum:direction), data = ANT.2)
VarCorr(model3)
Groups Name Std.Dev.
subnum:direction (Intercept) 1.7008e-06
subnum (Intercept) 4.0100e+01
Residual 7.0415e+01
Because the variance associated with the interaction is essentially zero (in the
presence of the subnum random main-effect) the interaction
term has no effect on the calculation of denominator degrees of freedom, F-values and p-values:
anova(model3, type=1)
Type I Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
group 12065.3 12065.3 1 18 2.4334 0.1362
direction 1951.8 1951.8 1 5169 0.3936 0.5304
group:direction 11552.2 11552.2 1 5169 2.3299 0.1270
However, subnum:direction is the enclosing error stratum for subnum so if
we remove subnum all the associated SSQ falls back into subnum:direction
model4 <- lmer(rt ~ group * direction +
(1 | subnum:direction), data = ANT.2)
Now the natural error term for group, direction and group:direction is
subnum:direction and with nlevels(with(ANT.2, subnum:direction)) = 40 and
four parameters the denominator degrees of freedom for those terms should be
about 36:
anova(model4, type=1)
Type I Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
group 24004.5 24004.5 1 35.994 4.8325 0.03444 *
direction 50.6 50.6 1 35.994 0.0102 0.92020
group:direction 273.4 273.4 1 35.994 0.0551 0.81583
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
These F-tests can also be approximated with the 'balanced-correct' F-tests:
an4 <- anova(lm(rt ~ group*direction + subnum:direction, data=ANT.2))
an4[1:3, "F value"] <- an4[1:3, "Mean Sq"] / an4[4, "Mean Sq"]
an4[1:3, "Pr(>F)"] <- pf(an4[1:3, "F value"], 1, 36, lower.tail = FALSE)
an4
Analysis of Variance Table
Response: rt
Df Sum Sq Mean Sq F value Pr(>F)
group 1 994365 994365 4.6976 0.0369 *
direction 1 1568 1568 0.0074 0.9319
group:direction 1 10795 10795 0.0510 0.8226
direction:subnum 36 7620271 211674 42.6137 <2e-16 ***
Residuals 5151 25586484 4967
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
now turning to model2:
model2 <- lmer(rt ~ group * direction + (direction | subnum), data = ANT.2)
This model describes a rather complicated random-effect covariance structure
with a 2x2 variance-covariance matrix.
The default parameterization is not easy
to deal with and we are better of with a re-parameterization of the model:
model2 <- lmer(rt ~ group * direction + (0 + direction | subnum), data = ANT.2)
If we compare model2 to model4, they have equally many random-effects; 2 for
each subnum, i.e. 2*20=40 in total. While model4 stipulates a single variance
parameter for all 40 random effects, model2 stipulates that each subnum-pair of random effects has a bi-variate normal distribution with a 2x2 variance-covariance matrix the parameters of which are given by
VarCorr(model2)
Groups Name Std.Dev. Corr
subnum directionleft 38.880
directionright 41.324 1.000
Residual 70.405
This indicates over-fitting, but let's save that for another day. The important point here is that model4 is a special-case of model2 and that model is also a special case of model2. Loosely (and intuitively) speaking (direction | subnum) contains or captures the variation associated with the main effect subnum as well as the interaction direction:subnum. In terms of the random effects we can think of these two effects or structures as capturing variation between rows and rows-by-columns respectively:
head(ranef(model2)$subnum)
directionleft directionright
1 -25.453576 -27.053697
2 16.446105 17.479977
3 -47.828568 -50.835277
4 -1.980433 -2.104932
5 5.647213 6.002221
6 41.493591 44.102056
In this case these random effect estimates as well as the variance parameter
estimates both indicate that we really only have a random main effect
of subnum (variation between rows) present here.
What this all leads up to is that Satterthwaite denominator degrees of freedom in
anova(model2, type=1)
Type I Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
group 12059.8 12059.8 1 17.998 2.4329 0.1362
direction 1803.6 1803.6 1 125.135 0.3638 0.5475
group:direction 10616.6 10616.6 1 125.136 2.1418 0.1458
is a compromise between these main-effect and interaction structures: The group
DenDF remains at 18 (nested in subnum by design) but the direction and
group:direction DenDF are compromises between 36 (model4) and 5169
(model).
I don't think anything here indicates that the Satterthwaite approximation (or its implementation in lmerTest) is faulty.
The equivalent table with the Kenward-Roger method gives
anova(model2, type=1, ddf="Ken")
Type I Analysis of Variance Table with Kenward-Roger's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
group 12059.8 12059.8 1 18.000 2.4329 0.1362
direction 1803.2 1803.2 1 17.987 0.3638 0.5539
group:direction 10614.7 10614.7 1 17.987 2.1414 0.1606
It is not surprising that KR and Satterthwaite can differ but for all practical purposes the difference in p-values is minute. My analysis above indicates that the DenDF for direction and group:direction should not be smaller than ~36 and probably larger than that given that we basically only have the random main effect of direction present, so if anything I think this is an indication that the KR method gets the DenDF too low in this case. But keep in mind that the data don't really support the (group | direction) structure so the comparison is a little artificial - it would be more interesting if the model was actually supported. | Are degrees of freedom in lmerTest::anova correct? They are very different from RM-ANOVA | I generally agree with Ben's analysis but let me add a couple of remarks and
a little intuition.
First, the overall results:
lmerTest results using the Satterthwaite method are correct
The Kenward-Ro | Are degrees of freedom in lmerTest::anova correct? They are very different from RM-ANOVA
I generally agree with Ben's analysis but let me add a couple of remarks and
a little intuition.
First, the overall results:
lmerTest results using the Satterthwaite method are correct
The Kenward-Roger method is also correct and agrees with Satterthwaite
Ben outlines the design in which subnum is nested in group while direction
and group:direction are crossed with subnum. This means that the natural
error term (i.e. the so-called "enclosing error stratum")
for group is subnum while the enclosing error stratum for the
other terms (including subnum) is the residuals.
This structure can be represented in a so-called factor-structure diagram:
names <- c(expression("[I]"[5169]^{5191}),
expression("[subnum]"[18]^{20}), expression(grp:dir[1]^{4}),
expression(dir[1]^{2}), expression(grp[1]^{2}), expression(0[1]^{1}))
x <- c(2, 4, 4, 6, 6, 8)
y <- c(5, 7, 5, 3, 7, 5)
plot(NA, NA, xlim=c(2, 8), ylim=c(2, 8), type="n", axes=F, xlab="", ylab="")
text(x, y, names) # Add text according to ’names’ vector
# Define coordinates for start (x0, y0) and end (x1, y1) of arrows:
x0 <- c(1.8, 1.8, 4.2, 4.2, 4.2, 6, 6) + .5
y0 <- c(5, 5, 7, 5, 5, 3, 7)
x1 <- c(2.7, 2.7, 5, 5, 5, 7.2, 7.2) + .5
y1 <- c(5, 7, 7, 3, 7, 5, 5)
arrows(x0, y0, x1, y1, length=0.1)
Here random terms are enclosed in brackets, 0 represents the overall mean
(or intercept), [I] represents the error term, the super-script numbers are
the number of levels and the sub-script numbers are the number of degrees of
freedom assuming a balanced design. The diagram indicates that the natural
error term (enclosing error stratum) for group is subnum and
that the numerator df for subnum, which equals the denominator df for group,
is 18: 20 minus 1 df for group and 1 df for the overall mean. A more comprehensive introduction to factor structure diagrams is available in chapter 2 here: https://02429.compute.dtu.dk/eBook.
If the data were exactly balanced we would be able to construct the F-tests from
a SSQ-decomposition as provided by anova.lm. Since the dataset is very-closely balanced we can obtain approximate F-tests as follows:
ANT.2 <- subset(ANT, !error)
set.seed(101)
baseline.shift <- rnorm(length(unique(ANT.2$subnum)), 0, 50)
ANT.2$rt <- ANT.2$rt + baseline.shift[as.numeric(ANT.2$subnum)]
fm <- lm(rt ~ group * direction + subnum, data=ANT.2)
(an <- anova(fm))
Analysis of Variance Table
Response: rt
Df Sum Sq Mean Sq F value Pr(>F)
group 1 994365 994365 200.5461 <2e-16 ***
direction 1 1568 1568 0.3163 0.5739
subnum 18 7576606 420923 84.8927 <2e-16 ***
group:direction 1 11561 11561 2.3316 0.1268
Residuals 5169 25629383 4958
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Here all F and p values are computed assuming that all terms have the residuals as their enclosing error stratum, and that is true for all but 'group'. The 'balanced-correct' F-test for group is instead:
F_group <- an["group", "Mean Sq"] / an["subnum", "Mean Sq"]
c(Fvalue=F_group, pvalue=pf(F_group, 1, 18, lower.tail = FALSE))
Fvalue pvalue
2.3623466 0.1416875
where we use the subnum MS instead of the Residuals MS in the F-value
denominator.
Note that these values match quite well with the Satterthwaite results:
model <- lmer(rt ~ group * direction + (1 | subnum), data = ANT.2)
anova(model, type=1)
Type I Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
group 12065.3 12065.3 1 18 2.4334 0.1362
direction 1951.8 1951.8 1 5169 0.3936 0.5304
group:direction 11552.2 11552.2 1 5169 2.3299 0.1270
Remaining differences are due to the data not being exactly balanced.
The OP compares anova.lm with anova.lmerModLmerTest, which is ok, but to compare like with like we have to use the same contrasts.
In this case there is a difference between anova.lm and anova.lmerModLmerTest since they produce Type I and III tests by default respectively, and for this dataset there is a
(small) difference between the Type I and III contrasts:
show_tests(anova(model, type=1))$group
(Intercept) groupTreatment directionright groupTreatment:directionright
groupTreatment 0 1 0.005202759 0.5013477
show_tests(anova(model, type=3))$group # type=3 is default
(Intercept) groupTreatment directionright groupTreatment:directionright
groupTreatment 0 1 0 0.5
If the data set had been completely balanced the type I contrasts would have
been the same as the type III contrasts (which are not affected by the observed
number of samples).
One last remark is that the 'slowness' of the Kenward-Roger method is not due to
model re-fitting, but because it involves computations with the marginal
variance-covariance matrix of the observations/residuals (5191x5191 in this case)
which is not the case for Satterthwaite's method.
Concerning model2
As for model2 the situation becomes more complex and I think it is easier to
start the discussion with another model where I have included the
'classical' interaction between subnum and direction:
model3 <- lmer(rt ~ group * direction + (1 | subnum) +
(1 | subnum:direction), data = ANT.2)
VarCorr(model3)
Groups Name Std.Dev.
subnum:direction (Intercept) 1.7008e-06
subnum (Intercept) 4.0100e+01
Residual 7.0415e+01
Because the variance associated with the interaction is essentially zero (in the
presence of the subnum random main-effect) the interaction
term has no effect on the calculation of denominator degrees of freedom, F-values and p-values:
anova(model3, type=1)
Type I Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
group 12065.3 12065.3 1 18 2.4334 0.1362
direction 1951.8 1951.8 1 5169 0.3936 0.5304
group:direction 11552.2 11552.2 1 5169 2.3299 0.1270
However, subnum:direction is the enclosing error stratum for subnum so if
we remove subnum all the associated SSQ falls back into subnum:direction
model4 <- lmer(rt ~ group * direction +
(1 | subnum:direction), data = ANT.2)
Now the natural error term for group, direction and group:direction is
subnum:direction and with nlevels(with(ANT.2, subnum:direction)) = 40 and
four parameters the denominator degrees of freedom for those terms should be
about 36:
anova(model4, type=1)
Type I Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
group 24004.5 24004.5 1 35.994 4.8325 0.03444 *
direction 50.6 50.6 1 35.994 0.0102 0.92020
group:direction 273.4 273.4 1 35.994 0.0551 0.81583
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
These F-tests can also be approximated with the 'balanced-correct' F-tests:
an4 <- anova(lm(rt ~ group*direction + subnum:direction, data=ANT.2))
an4[1:3, "F value"] <- an4[1:3, "Mean Sq"] / an4[4, "Mean Sq"]
an4[1:3, "Pr(>F)"] <- pf(an4[1:3, "F value"], 1, 36, lower.tail = FALSE)
an4
Analysis of Variance Table
Response: rt
Df Sum Sq Mean Sq F value Pr(>F)
group 1 994365 994365 4.6976 0.0369 *
direction 1 1568 1568 0.0074 0.9319
group:direction 1 10795 10795 0.0510 0.8226
direction:subnum 36 7620271 211674 42.6137 <2e-16 ***
Residuals 5151 25586484 4967
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
now turning to model2:
model2 <- lmer(rt ~ group * direction + (direction | subnum), data = ANT.2)
This model describes a rather complicated random-effect covariance structure
with a 2x2 variance-covariance matrix.
The default parameterization is not easy
to deal with and we are better of with a re-parameterization of the model:
model2 <- lmer(rt ~ group * direction + (0 + direction | subnum), data = ANT.2)
If we compare model2 to model4, they have equally many random-effects; 2 for
each subnum, i.e. 2*20=40 in total. While model4 stipulates a single variance
parameter for all 40 random effects, model2 stipulates that each subnum-pair of random effects has a bi-variate normal distribution with a 2x2 variance-covariance matrix the parameters of which are given by
VarCorr(model2)
Groups Name Std.Dev. Corr
subnum directionleft 38.880
directionright 41.324 1.000
Residual 70.405
This indicates over-fitting, but let's save that for another day. The important point here is that model4 is a special-case of model2 and that model is also a special case of model2. Loosely (and intuitively) speaking (direction | subnum) contains or captures the variation associated with the main effect subnum as well as the interaction direction:subnum. In terms of the random effects we can think of these two effects or structures as capturing variation between rows and rows-by-columns respectively:
head(ranef(model2)$subnum)
directionleft directionright
1 -25.453576 -27.053697
2 16.446105 17.479977
3 -47.828568 -50.835277
4 -1.980433 -2.104932
5 5.647213 6.002221
6 41.493591 44.102056
In this case these random effect estimates as well as the variance parameter
estimates both indicate that we really only have a random main effect
of subnum (variation between rows) present here.
What this all leads up to is that Satterthwaite denominator degrees of freedom in
anova(model2, type=1)
Type I Analysis of Variance Table with Satterthwaite's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
group 12059.8 12059.8 1 17.998 2.4329 0.1362
direction 1803.6 1803.6 1 125.135 0.3638 0.5475
group:direction 10616.6 10616.6 1 125.136 2.1418 0.1458
is a compromise between these main-effect and interaction structures: The group
DenDF remains at 18 (nested in subnum by design) but the direction and
group:direction DenDF are compromises between 36 (model4) and 5169
(model).
I don't think anything here indicates that the Satterthwaite approximation (or its implementation in lmerTest) is faulty.
The equivalent table with the Kenward-Roger method gives
anova(model2, type=1, ddf="Ken")
Type I Analysis of Variance Table with Kenward-Roger's method
Sum Sq Mean Sq NumDF DenDF F value Pr(>F)
group 12059.8 12059.8 1 18.000 2.4329 0.1362
direction 1803.2 1803.2 1 17.987 0.3638 0.5539
group:direction 10614.7 10614.7 1 17.987 2.1414 0.1606
It is not surprising that KR and Satterthwaite can differ but for all practical purposes the difference in p-values is minute. My analysis above indicates that the DenDF for direction and group:direction should not be smaller than ~36 and probably larger than that given that we basically only have the random main effect of direction present, so if anything I think this is an indication that the KR method gets the DenDF too low in this case. But keep in mind that the data don't really support the (group | direction) structure so the comparison is a little artificial - it would be more interesting if the model was actually supported. | Are degrees of freedom in lmerTest::anova correct? They are very different from RM-ANOVA
I generally agree with Ben's analysis but let me add a couple of remarks and
a little intuition.
First, the overall results:
lmerTest results using the Satterthwaite method are correct
The Kenward-Ro |
25,060 | How to calculate 2D standard deviation, with 0 mean, bounded by limits | To characterize the amount of 2D dispersion around the centroid, you just want the (root) mean squared distance,
$$\hat\sigma=\text{RMS} = \sqrt{\frac{1}{n}\sum_i\left((x_i - \bar{x})^2 + (y_i - \bar{y})^2\right)}.$$
In this formula, $(x_i, y_i), i=1, 2, \ldots, n$ are the point coordinates and their centroid (point of averages) is $(\bar{x}, \bar{y}).$
The question asks for the distribution of the distances. When the balls have an isotropic bivariate Normal distribution around their centroid--which is a standard and physically reasonable assumption--the squared distance is proportional to a chi-squared distribution with two degrees of freedom (one for each coordinate). This is a direct consequence of one definition of the chi-squared distribution as a sum of squares of independent standard normal variables, because $$x_i - \bar{x} = \frac{n-1}{n}x_i - \sum_{j\ne i}\frac{1}{n}x_j$$ is a linear combination of independent normal variates with expectation $$\mathbb{E}[x_i - \bar{x}] = \frac{n-1}{n}\mathbb{E}[x_i] -\sum_{j\ne i}\frac{1}{n}\mathbb{E}[x_j] = 0.$$ Writing the common variance of the $x_i$ as $\sigma^2$, $$\mathbb{E}[\left(x_i -\bar{x}\right)^2]=\text{Var}(x_i - \bar{x}) = \left(\frac{n-1}{n}\right)^2\text{Var}(x_i) + \sum_{j\ne i}\left(\frac{1}{n}\right)^2\text{Var}(x_j) = \frac{n-1}{n}\sigma^2.$$ The assumption of anisotropy is that the $y_j$ have the same distribution as the $x_i$ and are independent of them, so an identical result holds for the distribution of $(y_j - \bar{y})^2$. This establishes the constant of proportionality: the squares of the distances have a chi-squared distribution with two degrees of freedom, scaled by $\frac{n-1}{n}\sigma^2$.
The most severe test of these equations is the case $n=2$, for then the fraction $\frac{n-1}{n}$ differs the most from $1$. By simulating the experiment, both for $n=2$ and $n=40$, and overplotting the histograms of squared distances with the scaled chi-squared distributions (in red), we can verify this theory.
Each row shows the same data: on the left the x-axis is logarithmic; on the right it shows the actual squared distance. The true value of $\sigma$ for these simulations was set to $1$.
These results are for 100,000 iterations with $n=2$ and 50,000 iterations with $n=40$. The agreements between the histograms and chi-squared densities are excellent.
Although $\sigma^2$ is unknown, it can be estimated in various ways. For instance, the mean squared distance should be $\frac{n-1}{n}\sigma^2$ times the mean of $\chi^2_2$, which is $2$. With $n=40$, for example, estimate $\sigma^2$ as $\frac{40}{39}/2$ times the mean squared distance. Thus an estimate of $\sigma$ would be $\sqrt{40/78}$ times the RMS distance. Using values of the $\chi^2_2$ distribution we can then say that:
Approximately 39% of the distances will be less than $\sqrt{39/40}\hat\sigma$, because 39% of a $\chi^2_2$ distribution is less than $1$.
Approximately 78% of the distances will be less than $\sqrt{3}$ times $\sqrt{39/40}\hat\sigma$, because 78% of a $\chi^2_2$ distribution is less than $3$.
And so on, for any multiple you care to use in place of $1$ or $3$. As a check, in the simulations for $n=40$ plotted previously, the actual proportions of squared distances less than $1, 2, \ldots, 10$ times $\frac{n-1}{n}\hat\sigma^2$ were
0.3932 0.6320 0.7767 0.8647 0.9178 0.9504 0.9700 0.9818 0.9890 0.9933
The theoretical proportions are
0.3935 0.6321 0.7769 0.8647 0.9179 0.9502 0.9698 0.9817 0.9889 0.9933
The agreement is excellent.
Here is R code to conduct and analyze the simulations.
f <- function(n, n.iter, x.min=0, x.max=Inf, plot=TRUE) {
#
# Generate `n.iter` experiments in which `n` locations are generated using
# standard normal variates for their coordinates.
#
xy <- array(rnorm(n*2*n.iter), c(n.iter,2,n))
#
# Compute the squared distances to the centers for each experiment.
#
xy.center <- apply(xy, c(1,2), mean)
xy.distances2 <- apply(xy-array(xy.center, c(n.iter,2,n)), c(1,3),
function(z) sum(z^2))
#
# Optionally plot histograms.
#
if(plot) {
xy.plot <- xy.distances2[xy.distances2 >= x.min & xy.distances2 <= x.max]
hist(log(xy.plot), prob=TRUE, breaks=30,
main=paste("Histogram of log squared distance, n=", n),
xlab="Log squared distance")
curve(dchisq(n/(n-1) * exp(x), df=2) * exp(x) * n/(n-1),
from=log(min(xy.plot)), to=log(max(xy.plot)),
n=513, add=TRUE, col="Red", lwd=2)
hist(xy.plot, prob=TRUE, breaks=30,
main=paste("Histogram of squared distance, n=", n),
xlab="Squared distance")
curve(n/(n-1) * dchisq(n/(n-1) * x, df=2),
from=min(xy.plot), to=max(xy.plot),
n=513, add=TRUE, col="Red", lwd=2)
}
return(xy.distances2)
}
#
# Plot the histograms and compare to scaled chi-squared distributions.
#
par(mfrow=c(2,2))
set.seed(17)
xy.distances2 <- f(2, 10^5, exp(-6), 6)
xy.distances2 <- f(n <- 40, n.iter <- 50000, exp(-6), 12)
#
# Compare the last simulation to cumulative chi-squared distributions.
#
sigma.hat <- sqrt((n / (2*(n-1)) * mean(xy.distances2)))
print(cumsum(tabulate(cut(xy.distances2,
(0:10) * (n-1)/n * sigma.hat^2))) / (n*n.iter), digits=4)
print(pchisq(1:10, df=2), digits=4) | How to calculate 2D standard deviation, with 0 mean, bounded by limits | To characterize the amount of 2D dispersion around the centroid, you just want the (root) mean squared distance,
$$\hat\sigma=\text{RMS} = \sqrt{\frac{1}{n}\sum_i\left((x_i - \bar{x})^2 + (y_i - \bar{ | How to calculate 2D standard deviation, with 0 mean, bounded by limits
To characterize the amount of 2D dispersion around the centroid, you just want the (root) mean squared distance,
$$\hat\sigma=\text{RMS} = \sqrt{\frac{1}{n}\sum_i\left((x_i - \bar{x})^2 + (y_i - \bar{y})^2\right)}.$$
In this formula, $(x_i, y_i), i=1, 2, \ldots, n$ are the point coordinates and their centroid (point of averages) is $(\bar{x}, \bar{y}).$
The question asks for the distribution of the distances. When the balls have an isotropic bivariate Normal distribution around their centroid--which is a standard and physically reasonable assumption--the squared distance is proportional to a chi-squared distribution with two degrees of freedom (one for each coordinate). This is a direct consequence of one definition of the chi-squared distribution as a sum of squares of independent standard normal variables, because $$x_i - \bar{x} = \frac{n-1}{n}x_i - \sum_{j\ne i}\frac{1}{n}x_j$$ is a linear combination of independent normal variates with expectation $$\mathbb{E}[x_i - \bar{x}] = \frac{n-1}{n}\mathbb{E}[x_i] -\sum_{j\ne i}\frac{1}{n}\mathbb{E}[x_j] = 0.$$ Writing the common variance of the $x_i$ as $\sigma^2$, $$\mathbb{E}[\left(x_i -\bar{x}\right)^2]=\text{Var}(x_i - \bar{x}) = \left(\frac{n-1}{n}\right)^2\text{Var}(x_i) + \sum_{j\ne i}\left(\frac{1}{n}\right)^2\text{Var}(x_j) = \frac{n-1}{n}\sigma^2.$$ The assumption of anisotropy is that the $y_j$ have the same distribution as the $x_i$ and are independent of them, so an identical result holds for the distribution of $(y_j - \bar{y})^2$. This establishes the constant of proportionality: the squares of the distances have a chi-squared distribution with two degrees of freedom, scaled by $\frac{n-1}{n}\sigma^2$.
The most severe test of these equations is the case $n=2$, for then the fraction $\frac{n-1}{n}$ differs the most from $1$. By simulating the experiment, both for $n=2$ and $n=40$, and overplotting the histograms of squared distances with the scaled chi-squared distributions (in red), we can verify this theory.
Each row shows the same data: on the left the x-axis is logarithmic; on the right it shows the actual squared distance. The true value of $\sigma$ for these simulations was set to $1$.
These results are for 100,000 iterations with $n=2$ and 50,000 iterations with $n=40$. The agreements between the histograms and chi-squared densities are excellent.
Although $\sigma^2$ is unknown, it can be estimated in various ways. For instance, the mean squared distance should be $\frac{n-1}{n}\sigma^2$ times the mean of $\chi^2_2$, which is $2$. With $n=40$, for example, estimate $\sigma^2$ as $\frac{40}{39}/2$ times the mean squared distance. Thus an estimate of $\sigma$ would be $\sqrt{40/78}$ times the RMS distance. Using values of the $\chi^2_2$ distribution we can then say that:
Approximately 39% of the distances will be less than $\sqrt{39/40}\hat\sigma$, because 39% of a $\chi^2_2$ distribution is less than $1$.
Approximately 78% of the distances will be less than $\sqrt{3}$ times $\sqrt{39/40}\hat\sigma$, because 78% of a $\chi^2_2$ distribution is less than $3$.
And so on, for any multiple you care to use in place of $1$ or $3$. As a check, in the simulations for $n=40$ plotted previously, the actual proportions of squared distances less than $1, 2, \ldots, 10$ times $\frac{n-1}{n}\hat\sigma^2$ were
0.3932 0.6320 0.7767 0.8647 0.9178 0.9504 0.9700 0.9818 0.9890 0.9933
The theoretical proportions are
0.3935 0.6321 0.7769 0.8647 0.9179 0.9502 0.9698 0.9817 0.9889 0.9933
The agreement is excellent.
Here is R code to conduct and analyze the simulations.
f <- function(n, n.iter, x.min=0, x.max=Inf, plot=TRUE) {
#
# Generate `n.iter` experiments in which `n` locations are generated using
# standard normal variates for their coordinates.
#
xy <- array(rnorm(n*2*n.iter), c(n.iter,2,n))
#
# Compute the squared distances to the centers for each experiment.
#
xy.center <- apply(xy, c(1,2), mean)
xy.distances2 <- apply(xy-array(xy.center, c(n.iter,2,n)), c(1,3),
function(z) sum(z^2))
#
# Optionally plot histograms.
#
if(plot) {
xy.plot <- xy.distances2[xy.distances2 >= x.min & xy.distances2 <= x.max]
hist(log(xy.plot), prob=TRUE, breaks=30,
main=paste("Histogram of log squared distance, n=", n),
xlab="Log squared distance")
curve(dchisq(n/(n-1) * exp(x), df=2) * exp(x) * n/(n-1),
from=log(min(xy.plot)), to=log(max(xy.plot)),
n=513, add=TRUE, col="Red", lwd=2)
hist(xy.plot, prob=TRUE, breaks=30,
main=paste("Histogram of squared distance, n=", n),
xlab="Squared distance")
curve(n/(n-1) * dchisq(n/(n-1) * x, df=2),
from=min(xy.plot), to=max(xy.plot),
n=513, add=TRUE, col="Red", lwd=2)
}
return(xy.distances2)
}
#
# Plot the histograms and compare to scaled chi-squared distributions.
#
par(mfrow=c(2,2))
set.seed(17)
xy.distances2 <- f(2, 10^5, exp(-6), 6)
xy.distances2 <- f(n <- 40, n.iter <- 50000, exp(-6), 12)
#
# Compare the last simulation to cumulative chi-squared distributions.
#
sigma.hat <- sqrt((n / (2*(n-1)) * mean(xy.distances2)))
print(cumsum(tabulate(cut(xy.distances2,
(0:10) * (n-1)/n * sigma.hat^2))) / (n*n.iter), digits=4)
print(pchisq(1:10, df=2), digits=4) | How to calculate 2D standard deviation, with 0 mean, bounded by limits
To characterize the amount of 2D dispersion around the centroid, you just want the (root) mean squared distance,
$$\hat\sigma=\text{RMS} = \sqrt{\frac{1}{n}\sum_i\left((x_i - \bar{x})^2 + (y_i - \bar{ |
25,061 | How to calculate 2D standard deviation, with 0 mean, bounded by limits | I think you have some things a bit confused. It's true that distance can't be negative, but that doesn't affect calculation of the standard deviation. Although it means the distribution of distances can't be exactly normal, it could still be close; but even if its is far from normal, there is still a standard deviation.
Also, there is no "one sided" standard deviation - you may be thinking of hypothesis tests (which can be one sided or two sided). In your title, you say mean is 0, but the mean distance won't be 0 (unless the balls are in a stack 40 balls high!) and you say there are limits - there could be limits, if the balls are dropped in a room then they can't be farther from the center than the distance to the nearest wall. But unless some of the balls bounce against a wall, that won't affect things.
So, once you have the 40 distances you calculate the standard deviation (and mean, median, interquartile range, etc) using standard methods. You can also make plots of the distance (e.g. quantile normal plot, box plot) to see if it is roughly normally distributed (if that's of interest). | How to calculate 2D standard deviation, with 0 mean, bounded by limits | I think you have some things a bit confused. It's true that distance can't be negative, but that doesn't affect calculation of the standard deviation. Although it means the distribution of distances c | How to calculate 2D standard deviation, with 0 mean, bounded by limits
I think you have some things a bit confused. It's true that distance can't be negative, but that doesn't affect calculation of the standard deviation. Although it means the distribution of distances can't be exactly normal, it could still be close; but even if its is far from normal, there is still a standard deviation.
Also, there is no "one sided" standard deviation - you may be thinking of hypothesis tests (which can be one sided or two sided). In your title, you say mean is 0, but the mean distance won't be 0 (unless the balls are in a stack 40 balls high!) and you say there are limits - there could be limits, if the balls are dropped in a room then they can't be farther from the center than the distance to the nearest wall. But unless some of the balls bounce against a wall, that won't affect things.
So, once you have the 40 distances you calculate the standard deviation (and mean, median, interquartile range, etc) using standard methods. You can also make plots of the distance (e.g. quantile normal plot, box plot) to see if it is roughly normally distributed (if that's of interest). | How to calculate 2D standard deviation, with 0 mean, bounded by limits
I think you have some things a bit confused. It's true that distance can't be negative, but that doesn't affect calculation of the standard deviation. Although it means the distribution of distances c |
25,062 | How to calculate 2D standard deviation, with 0 mean, bounded by limits | Its been a while since this was asked, but the answer to the question is that this is the 2D distribution named the Rayleigh distribution. Here the assumption is that the Rayleigh shape factor is equal to both the standard deviations of the X and Y coordinates. In practice the value of the shape factor would be calculated from the pooled average of the standard deviation of X and Y.
starting with
$$ X \sim \mathcal{N}(\mu_x,\sigma_x^2)$$, and $$Y \sim \mathcal{N}(\mu_y,\sigma_y^2)$$
use bivariant normal distribution.
$$ f(x,y) =
\frac{1}{2 \pi \sigma_x \sigma_y \sqrt{1-\rho^2}}
\exp\left(
-\frac{1}{2(1-\rho^2)}\left[
\frac{(x-\mu_x)^2}{\sigma_x^2} +
\frac{(y-\mu_y)^2}{\sigma_y^2} -
\frac{2\rho(x-\mu_x)(y-\mu_y)}{\sigma_x \sigma_y}
\right]
\right)$$
translate to point $$(\mu_x, \mu_y)$$ and assume $$\rho = 0$$.
Also assume that $$\sigma_x^2 = \sigma_y^2$$ so replace both with $$\sigma^2$$
then the 2-D distribution is expressed as the radius around point $$(\mu_x, \mu_y)$$ which is known as the Rayleigh distribution.
$$PDF(r; \sigma) = \frac{r}{\sigma^2 }
\exp\left(
- \frac{r^2}{2\sigma^2}
\right)
$$
where $$\sigma = \sigma_x = \sigma_y$$ and $$r_i = \sqrt{(x_i - \mu_x)^2 + (y_i - \mu_y)^2}$$
$$ CDF(r; \sigma) = 1 - \exp\left(
- \frac{r^2}{2\sigma^2}
\right)$$
Of course this is for the continuous distribution. For a sample of just 40 balls there is no exact solution. You'd need to do a Monte Carlo Analysis with a sample of 40 balls. Taylor, M. S. & Grubbs, Frank E. (1975). "Approximate Probability Distributions for the Extreme Spread" found estimates for the Chi distribution and the log-normal for that would fit the distribution of a sample.
Edit - Despite Wuber's doubt, the theoretical proportions he calculated are:
0.3935 0.6321 0.7769 0.8647 0.9179 0.9502 0.9698 0.9817 0.9889 0.9933
From the CDF function the cumulative Sigma values for r (in sigmas) equal to range from:
0-1, 0-2, 0-3, ... , 0-10
are:
0.3935, 0.6321, 0.7769, 0.8647, 0.9179, 0.9502, 0.9698, 0.9817, 0.9889, 0.9933 | How to calculate 2D standard deviation, with 0 mean, bounded by limits | Its been a while since this was asked, but the answer to the question is that this is the 2D distribution named the Rayleigh distribution. Here the assumption is that the Rayleigh shape factor is equa | How to calculate 2D standard deviation, with 0 mean, bounded by limits
Its been a while since this was asked, but the answer to the question is that this is the 2D distribution named the Rayleigh distribution. Here the assumption is that the Rayleigh shape factor is equal to both the standard deviations of the X and Y coordinates. In practice the value of the shape factor would be calculated from the pooled average of the standard deviation of X and Y.
starting with
$$ X \sim \mathcal{N}(\mu_x,\sigma_x^2)$$, and $$Y \sim \mathcal{N}(\mu_y,\sigma_y^2)$$
use bivariant normal distribution.
$$ f(x,y) =
\frac{1}{2 \pi \sigma_x \sigma_y \sqrt{1-\rho^2}}
\exp\left(
-\frac{1}{2(1-\rho^2)}\left[
\frac{(x-\mu_x)^2}{\sigma_x^2} +
\frac{(y-\mu_y)^2}{\sigma_y^2} -
\frac{2\rho(x-\mu_x)(y-\mu_y)}{\sigma_x \sigma_y}
\right]
\right)$$
translate to point $$(\mu_x, \mu_y)$$ and assume $$\rho = 0$$.
Also assume that $$\sigma_x^2 = \sigma_y^2$$ so replace both with $$\sigma^2$$
then the 2-D distribution is expressed as the radius around point $$(\mu_x, \mu_y)$$ which is known as the Rayleigh distribution.
$$PDF(r; \sigma) = \frac{r}{\sigma^2 }
\exp\left(
- \frac{r^2}{2\sigma^2}
\right)
$$
where $$\sigma = \sigma_x = \sigma_y$$ and $$r_i = \sqrt{(x_i - \mu_x)^2 + (y_i - \mu_y)^2}$$
$$ CDF(r; \sigma) = 1 - \exp\left(
- \frac{r^2}{2\sigma^2}
\right)$$
Of course this is for the continuous distribution. For a sample of just 40 balls there is no exact solution. You'd need to do a Monte Carlo Analysis with a sample of 40 balls. Taylor, M. S. & Grubbs, Frank E. (1975). "Approximate Probability Distributions for the Extreme Spread" found estimates for the Chi distribution and the log-normal for that would fit the distribution of a sample.
Edit - Despite Wuber's doubt, the theoretical proportions he calculated are:
0.3935 0.6321 0.7769 0.8647 0.9179 0.9502 0.9698 0.9817 0.9889 0.9933
From the CDF function the cumulative Sigma values for r (in sigmas) equal to range from:
0-1, 0-2, 0-3, ... , 0-10
are:
0.3935, 0.6321, 0.7769, 0.8647, 0.9179, 0.9502, 0.9698, 0.9817, 0.9889, 0.9933 | How to calculate 2D standard deviation, with 0 mean, bounded by limits
Its been a while since this was asked, but the answer to the question is that this is the 2D distribution named the Rayleigh distribution. Here the assumption is that the Rayleigh shape factor is equa |
25,063 | How to calculate 2D standard deviation, with 0 mean, bounded by limits | The normal distribution, both positive and negative values, makes sense if you recognize that this normal distribution is for radius or "distance from centroid". The other variable, angle, is random and is uniformly distributed from 0-pi | How to calculate 2D standard deviation, with 0 mean, bounded by limits | The normal distribution, both positive and negative values, makes sense if you recognize that this normal distribution is for radius or "distance from centroid". The other variable, angle, is random | How to calculate 2D standard deviation, with 0 mean, bounded by limits
The normal distribution, both positive and negative values, makes sense if you recognize that this normal distribution is for radius or "distance from centroid". The other variable, angle, is random and is uniformly distributed from 0-pi | How to calculate 2D standard deviation, with 0 mean, bounded by limits
The normal distribution, both positive and negative values, makes sense if you recognize that this normal distribution is for radius or "distance from centroid". The other variable, angle, is random |
25,064 | Proper way to combine conditional probability distributions of the same random variable conditioned on a discrete variable ? (based on assumptions) | Short answer
The conditional distribution $P\left(x|yz\right)$ can be expressed in terms of $P\left(x|y\right)$ and $P\left(x|z\right)$ as
$$
P\left(x|yz\right)\propto\frac{P\left(x|y\right)P\left(x|z\right)}{P\left(x\right)},
$$
where $P\left(x\right)$ is the prior on $x$ and $y$ and $z$ are conditionally independent given $x$ (see below for more details).
Long answer
Suppose we know the conditional distributions $P\left(x|y\right)$ and $P\left(x|z\right)$ which we would like to combine to obtain the distribution $P\left(x|yz\right)$. Using Bayes' theorem, we find
$$
P\left(x|yz\right)=\frac{P\left(yz|x\right)P\left(x\right)}{P\left(yz\right)}.
$$
We assume conditional independence of $y$ and $z$ given $x$ to obtain
$$
\begin{align}
P\left(x|yz\right)&=\frac{P\left(y|x\right)P\left(x\right)P\left(z|x\right)P\left(x\right)}{P\left(x\right)P\left(yz\right)}\\
&=\frac{P\left(y\right)P\left(z\right)}{P\left(yz\right)}\frac{P\left(x|y\right)P\left(x|z\right)}{P\left(x\right)}\\
&\propto\frac{P\left(x|y\right)P\left(x|z\right)}{P\left(x\right)},
\end{align}
$$
where we have dropped the first term because it is only an overall normalisation.
Note: The above relation only holds if $y$ and $z$ are conditionally independent given $x$. Intuitively, this is the case if $y$ and $z$ are independent sources of information (see below for an example).
Example
Let $x=1$ if a sportsman took a performance enhancing drug, let $y=1$ if a drug test was positive, and let $z=1$ if the sportsman won a competition. The conditional independence assumption holds because the outcome of the drug test will not affect the outcome of the competition given $x$. Note that $y$ and $z$ are not unconditionally independent because the events are coupled by cheating.
Our prior suspicion of doping is $P\left(x\right)=\left(\begin{array}{cc}0.99 & 0.01\end{array}\right)$, where the first element corresponds to $x=0$ and the second corresponds to $x=1$. We assume that the test is 95% reliable such that
$$
P\left(y|x\right)=\left(\begin{array}{cc}
0.95 & 0.05\\
0.05 & 0.95
\end{array}\right),
$$
where $y$ is the row index and $x$ is the column index. Furthermore, assume that a competitor gains a 5% advantage to win a competition by taking a performance enhancing drug such that
$$
P\left(z|x\right)=\left(\begin{array}{cc}
1-p & 1-1.05\times p\\
p & 1.05\times p
\end{array}\right),
$$
where $p=0.1$ is the probability to win a competition if the sportsman has not taken a drug.
Using Bayes' theorem and the relation derived above, the conditional probabilities that the sportsman cheated are
$$\begin{align}
P\left(x=1|y\right) &=\left(\begin{array}{cc}
0.161017 & 0.000531\end{array}\right),\\
P\left(x=1|z\right) &=\left(\begin{array}{cc}
0.009995 & 0.010498\end{array}\right),\\
P\left(x=1|yz\right) &=\left(\begin{array}{cc}
0.000531 & 0.000558\\
0.160949 & 0.167718
\end{array}\right),
\end{align}
$$
where $y$ is the row index and $z$ is the column index in the last equation. As expected, the drug test provides stronger evidence for cheating than winning a competition $P\left(x=1|y=1\right)>P\left(x=1|z=1\right)$ but both pieces of evidence provide an even stronger case for the sportsman cheating $P\left(x=1|y=1\cap z=1\right)>P\left(x=1|y=1\right)$. | Proper way to combine conditional probability distributions of the same random variable conditioned | Short answer
The conditional distribution $P\left(x|yz\right)$ can be expressed in terms of $P\left(x|y\right)$ and $P\left(x|z\right)$ as
$$
P\left(x|yz\right)\propto\frac{P\left(x|y\right)P\left(x|z | Proper way to combine conditional probability distributions of the same random variable conditioned on a discrete variable ? (based on assumptions)
Short answer
The conditional distribution $P\left(x|yz\right)$ can be expressed in terms of $P\left(x|y\right)$ and $P\left(x|z\right)$ as
$$
P\left(x|yz\right)\propto\frac{P\left(x|y\right)P\left(x|z\right)}{P\left(x\right)},
$$
where $P\left(x\right)$ is the prior on $x$ and $y$ and $z$ are conditionally independent given $x$ (see below for more details).
Long answer
Suppose we know the conditional distributions $P\left(x|y\right)$ and $P\left(x|z\right)$ which we would like to combine to obtain the distribution $P\left(x|yz\right)$. Using Bayes' theorem, we find
$$
P\left(x|yz\right)=\frac{P\left(yz|x\right)P\left(x\right)}{P\left(yz\right)}.
$$
We assume conditional independence of $y$ and $z$ given $x$ to obtain
$$
\begin{align}
P\left(x|yz\right)&=\frac{P\left(y|x\right)P\left(x\right)P\left(z|x\right)P\left(x\right)}{P\left(x\right)P\left(yz\right)}\\
&=\frac{P\left(y\right)P\left(z\right)}{P\left(yz\right)}\frac{P\left(x|y\right)P\left(x|z\right)}{P\left(x\right)}\\
&\propto\frac{P\left(x|y\right)P\left(x|z\right)}{P\left(x\right)},
\end{align}
$$
where we have dropped the first term because it is only an overall normalisation.
Note: The above relation only holds if $y$ and $z$ are conditionally independent given $x$. Intuitively, this is the case if $y$ and $z$ are independent sources of information (see below for an example).
Example
Let $x=1$ if a sportsman took a performance enhancing drug, let $y=1$ if a drug test was positive, and let $z=1$ if the sportsman won a competition. The conditional independence assumption holds because the outcome of the drug test will not affect the outcome of the competition given $x$. Note that $y$ and $z$ are not unconditionally independent because the events are coupled by cheating.
Our prior suspicion of doping is $P\left(x\right)=\left(\begin{array}{cc}0.99 & 0.01\end{array}\right)$, where the first element corresponds to $x=0$ and the second corresponds to $x=1$. We assume that the test is 95% reliable such that
$$
P\left(y|x\right)=\left(\begin{array}{cc}
0.95 & 0.05\\
0.05 & 0.95
\end{array}\right),
$$
where $y$ is the row index and $x$ is the column index. Furthermore, assume that a competitor gains a 5% advantage to win a competition by taking a performance enhancing drug such that
$$
P\left(z|x\right)=\left(\begin{array}{cc}
1-p & 1-1.05\times p\\
p & 1.05\times p
\end{array}\right),
$$
where $p=0.1$ is the probability to win a competition if the sportsman has not taken a drug.
Using Bayes' theorem and the relation derived above, the conditional probabilities that the sportsman cheated are
$$\begin{align}
P\left(x=1|y\right) &=\left(\begin{array}{cc}
0.161017 & 0.000531\end{array}\right),\\
P\left(x=1|z\right) &=\left(\begin{array}{cc}
0.009995 & 0.010498\end{array}\right),\\
P\left(x=1|yz\right) &=\left(\begin{array}{cc}
0.000531 & 0.000558\\
0.160949 & 0.167718
\end{array}\right),
\end{align}
$$
where $y$ is the row index and $z$ is the column index in the last equation. As expected, the drug test provides stronger evidence for cheating than winning a competition $P\left(x=1|y=1\right)>P\left(x=1|z=1\right)$ but both pieces of evidence provide an even stronger case for the sportsman cheating $P\left(x=1|y=1\cap z=1\right)>P\left(x=1|y=1\right)$. | Proper way to combine conditional probability distributions of the same random variable conditioned
Short answer
The conditional distribution $P\left(x|yz\right)$ can be expressed in terms of $P\left(x|y\right)$ and $P\left(x|z\right)$ as
$$
P\left(x|yz\right)\propto\frac{P\left(x|y\right)P\left(x|z |
25,065 | Proper way to combine conditional probability distributions of the same random variable conditioned on a discrete variable ? (based on assumptions) | The solution is indeterminant. Even using p(b and c)= p(b) p(c) all we have is that the conditional density h(x|b and c) = h(x and b and c)/p(b and c)= h(x and b and c)/[p(b) p(c)]=h(x and c|b)/p(c). But this does nothing to relate the distribution h(x and c|b) to f(x|b) and g(x|c) | Proper way to combine conditional probability distributions of the same random variable conditioned | The solution is indeterminant. Even using p(b and c)= p(b) p(c) all we have is that the conditional density h(x|b and c) = h(x and b and c)/p(b and c)= h(x and b and c)/[p(b) p(c)]=h(x and c|b)/p(c) | Proper way to combine conditional probability distributions of the same random variable conditioned on a discrete variable ? (based on assumptions)
The solution is indeterminant. Even using p(b and c)= p(b) p(c) all we have is that the conditional density h(x|b and c) = h(x and b and c)/p(b and c)= h(x and b and c)/[p(b) p(c)]=h(x and c|b)/p(c). But this does nothing to relate the distribution h(x and c|b) to f(x|b) and g(x|c) | Proper way to combine conditional probability distributions of the same random variable conditioned
The solution is indeterminant. Even using p(b and c)= p(b) p(c) all we have is that the conditional density h(x|b and c) = h(x and b and c)/p(b and c)= h(x and b and c)/[p(b) p(c)]=h(x and c|b)/p(c) |
25,066 | Proper way to combine conditional probability distributions of the same random variable conditioned on a discrete variable ? (based on assumptions) | "10 'experts' forecast some pdf of risk (or an event related to
risk) - how do you combine these to make a decision?
Assuming the experts come up with their pdfs using independent pieces of information, the unique correct way to combine the evidence is using the pointwise product of the density functions, just as we do when doing Bayesian estimation. | Proper way to combine conditional probability distributions of the same random variable conditioned | "10 'experts' forecast some pdf of risk (or an event related to
risk) - how do you combine these to make a decision?
Assuming the experts come up with their pdfs using independent pieces of informa | Proper way to combine conditional probability distributions of the same random variable conditioned on a discrete variable ? (based on assumptions)
"10 'experts' forecast some pdf of risk (or an event related to
risk) - how do you combine these to make a decision?
Assuming the experts come up with their pdfs using independent pieces of information, the unique correct way to combine the evidence is using the pointwise product of the density functions, just as we do when doing Bayesian estimation. | Proper way to combine conditional probability distributions of the same random variable conditioned
"10 'experts' forecast some pdf of risk (or an event related to
risk) - how do you combine these to make a decision?
Assuming the experts come up with their pdfs using independent pieces of informa |
25,067 | How to make waffle charts in R? | Now there is a package called waffle.
Example from the github page:
parts <- c(80, 30, 20, 10)
waffle(parts, rows=8)
Result:
Regards | How to make waffle charts in R? | Now there is a package called waffle.
Example from the github page:
parts <- c(80, 30, 20, 10)
waffle(parts, rows=8)
Result:
Regards | How to make waffle charts in R?
Now there is a package called waffle.
Example from the github page:
parts <- c(80, 30, 20, 10)
waffle(parts, rows=8)
Result:
Regards | How to make waffle charts in R?
Now there is a package called waffle.
Example from the github page:
parts <- c(80, 30, 20, 10)
waffle(parts, rows=8)
Result:
Regards |
25,068 | How to make waffle charts in R? | I suspect that geom_tile from the package ggplot2 can do what you're looking for. Shane's answer on this StackOverflow question should get you started.
Edit: Here's an example, with a few other plots for comparison.
library(ggplot2)
# Here's some data I had lying around
tb <- structure(list(region = c("Africa", "Asia", "Latin America",
"Other", "US-born"), ncases = c(36L, 34L, 56L, 2L, 44L)), .Names = c("region",
"ncases"), row.names = c(NA, -5L), class = "data.frame")
# A bar chart of counts
ggplot(tb, aes(x = region, weight = ncases, fill = region)) +
geom_bar()
# Pie chart. Forgive me, Hadley, for I must sin.
ggplot(tb, aes(x = factor(1), weight = ncases, fill = region)) +
geom_bar(width = 1) +
coord_polar(theta = "y") +
labs(x = "", y = "")
# Percentage pie.
ggplot(tb, aes(x = factor(1), weight = ncases/sum(ncases), fill = region)) +
geom_bar() +
scale_y_continuous(formatter = 'percent') +
coord_polar(theta = "y") +
labs(x = "", y = "")
# Waffles
# How many rows do you want the y axis to have?
ndeep <- 5
# I need to convert my data into a data.frame with uniquely-specified x
# and y coordinates for each case
# Note - it's actually important to specify y first for a
# horizontally-accumulating waffle
# One y for each row; then divide the total number of cases by the number of
# rows and round up to get the appropriate number of x increments
tb4waffles <- expand.grid(y = 1:ndeep,
x = seq_len(ceiling(sum(tb$ncases) / ndeep)))
# Expand the counts into a full vector of region labels - i.e., de-aggregate
regionvec <- rep(tb$region, tb$ncases)
# Depending on the value of ndeep, there might be more spots on the x-y grid
# than there are cases - so fill those with NA
tb4waffles$region <- c(regionvec, rep(NA, nrow(tb4waffles) - length(regionvec)))
# Plot it
ggplot(tb4waffles, aes(x = x, y = y, fill = region)) +
geom_tile(color = "white") + # The color of the lines between tiles
scale_fill_manual("Region of Birth",
values = RColorBrewer::brewer.pal(5, "Dark2")) +
opts(title = "TB Cases by Region of Birth")
Clearly, there's extra work to be done on getting the aesthetics right (e.g., what the hell do those axes even mean?), but that's the mechanics of it. I leave "pretty" as an exercise for the reader. | How to make waffle charts in R? | I suspect that geom_tile from the package ggplot2 can do what you're looking for. Shane's answer on this StackOverflow question should get you started.
Edit: Here's an example, with a few other plots | How to make waffle charts in R?
I suspect that geom_tile from the package ggplot2 can do what you're looking for. Shane's answer on this StackOverflow question should get you started.
Edit: Here's an example, with a few other plots for comparison.
library(ggplot2)
# Here's some data I had lying around
tb <- structure(list(region = c("Africa", "Asia", "Latin America",
"Other", "US-born"), ncases = c(36L, 34L, 56L, 2L, 44L)), .Names = c("region",
"ncases"), row.names = c(NA, -5L), class = "data.frame")
# A bar chart of counts
ggplot(tb, aes(x = region, weight = ncases, fill = region)) +
geom_bar()
# Pie chart. Forgive me, Hadley, for I must sin.
ggplot(tb, aes(x = factor(1), weight = ncases, fill = region)) +
geom_bar(width = 1) +
coord_polar(theta = "y") +
labs(x = "", y = "")
# Percentage pie.
ggplot(tb, aes(x = factor(1), weight = ncases/sum(ncases), fill = region)) +
geom_bar() +
scale_y_continuous(formatter = 'percent') +
coord_polar(theta = "y") +
labs(x = "", y = "")
# Waffles
# How many rows do you want the y axis to have?
ndeep <- 5
# I need to convert my data into a data.frame with uniquely-specified x
# and y coordinates for each case
# Note - it's actually important to specify y first for a
# horizontally-accumulating waffle
# One y for each row; then divide the total number of cases by the number of
# rows and round up to get the appropriate number of x increments
tb4waffles <- expand.grid(y = 1:ndeep,
x = seq_len(ceiling(sum(tb$ncases) / ndeep)))
# Expand the counts into a full vector of region labels - i.e., de-aggregate
regionvec <- rep(tb$region, tb$ncases)
# Depending on the value of ndeep, there might be more spots on the x-y grid
# than there are cases - so fill those with NA
tb4waffles$region <- c(regionvec, rep(NA, nrow(tb4waffles) - length(regionvec)))
# Plot it
ggplot(tb4waffles, aes(x = x, y = y, fill = region)) +
geom_tile(color = "white") + # The color of the lines between tiles
scale_fill_manual("Region of Birth",
values = RColorBrewer::brewer.pal(5, "Dark2")) +
opts(title = "TB Cases by Region of Birth")
Clearly, there's extra work to be done on getting the aesthetics right (e.g., what the hell do those axes even mean?), but that's the mechanics of it. I leave "pretty" as an exercise for the reader. | How to make waffle charts in R?
I suspect that geom_tile from the package ggplot2 can do what you're looking for. Shane's answer on this StackOverflow question should get you started.
Edit: Here's an example, with a few other plots |
25,069 | How to make waffle charts in R? | Here's one in base r using @jbkunst 's data:
waffle <- function(x, rows, cols = seq_along(x), ...) {
xx <- rep(cols, times = x)
lx <- length(xx)
m <- matrix(nrow = rows, ncol = (lx %/% rows) + (lx %% rows != 0))
m[1:length(xx)] <- xx
op <- par(no.readonly = TRUE)
on.exit(par(op))
par(list(...))
plot.new()
o <- cbind(c(row(m)), c(col(m))) + 1
plot.window(xlim = c(0, max(o[, 2]) + 1), ylim = c(0, max(o[, 1]) + 1),
asp = 1, xaxs = 'i', yaxs = 'i')
rect(o[, 2], o[, 1], o[, 2] + .85, o[, 1] + .85, col = c(m), border = NA)
invisible(list(m = m, o = o))
}
cols <- c("#F8766D", "#7CAE00", "#00BFC4", "#C77CFF")
m <- waffle(c(80, 30, 20, 10), rows = 8, cols = cols, mar = c(0,0,0,7),
bg = 'cornsilk')
legend('right', legend = LETTERS[1:4], pch = 15, col = cols, pt.cex = 2,
bty = 'n') | How to make waffle charts in R? | Here's one in base r using @jbkunst 's data:
waffle <- function(x, rows, cols = seq_along(x), ...) {
xx <- rep(cols, times = x)
lx <- length(xx)
m <- matrix(nrow = rows, ncol = (lx %/% rows) + ( | How to make waffle charts in R?
Here's one in base r using @jbkunst 's data:
waffle <- function(x, rows, cols = seq_along(x), ...) {
xx <- rep(cols, times = x)
lx <- length(xx)
m <- matrix(nrow = rows, ncol = (lx %/% rows) + (lx %% rows != 0))
m[1:length(xx)] <- xx
op <- par(no.readonly = TRUE)
on.exit(par(op))
par(list(...))
plot.new()
o <- cbind(c(row(m)), c(col(m))) + 1
plot.window(xlim = c(0, max(o[, 2]) + 1), ylim = c(0, max(o[, 1]) + 1),
asp = 1, xaxs = 'i', yaxs = 'i')
rect(o[, 2], o[, 1], o[, 2] + .85, o[, 1] + .85, col = c(m), border = NA)
invisible(list(m = m, o = o))
}
cols <- c("#F8766D", "#7CAE00", "#00BFC4", "#C77CFF")
m <- waffle(c(80, 30, 20, 10), rows = 8, cols = cols, mar = c(0,0,0,7),
bg = 'cornsilk')
legend('right', legend = LETTERS[1:4], pch = 15, col = cols, pt.cex = 2,
bty = 'n') | How to make waffle charts in R?
Here's one in base r using @jbkunst 's data:
waffle <- function(x, rows, cols = seq_along(x), ...) {
xx <- rep(cols, times = x)
lx <- length(xx)
m <- matrix(nrow = rows, ncol = (lx %/% rows) + ( |
25,070 | Why don't we use absolute values of differences instead of squared differences in the denominator of the correlation coefficient? | There are many reasons for using squared differences, including
A relationship to the Gaussian distribution where squared differences play a central role (the normal distribution's probability density function is the anti-log of a scaled squared difference)
If a distribution is not too heavy tailed, it is a good idea to give a lot of weight to values far from the mean (e.g., by squaring the difference from the mean), and other weighting schemes will result in relative inefficient estimators
$r^2$ is scaled from 0 to 1 and in the case where there are multiple predictors in a linear model, semipartial $R^2$ is tied to the partial sum of squares explained by each predictor. In other words, sums of squares can be partitioned into component effects that "add up". In the case of uncorrelated predictors, regression sums of squares and semipartial $R^2$ add up to the whole amount of explained variation due to the combination of predictors. There is no corresponding partitioning of explained variation on the absolute difference scale.
Variances and covariances have a long history and many probability models are stated in terms of them (e.g., the multivariate normal distribution).
As I discuss in Regression Modeling Strategies an absolute difference measure $g$ based on Gini's mean difference (average absolute difference over all possible pairs of values) can be used to quantify strength of association, and I believe that average absolute differences are easier to interpret. But they don't partition. The $g$-index for a subset of predictors can be larger than the $g$-index for the entire linear predictor $X\hat{\beta}$. On the other hand semipartial $R^2$ for a subset of a multivariable model has to be no greater than the overall model $R^2$. | Why don't we use absolute values of differences instead of squared differences in the denominator of | There are many reasons for using squared differences, including
A relationship to the Gaussian distribution where squared differences play a central role (the normal distribution's probability densit | Why don't we use absolute values of differences instead of squared differences in the denominator of the correlation coefficient?
There are many reasons for using squared differences, including
A relationship to the Gaussian distribution where squared differences play a central role (the normal distribution's probability density function is the anti-log of a scaled squared difference)
If a distribution is not too heavy tailed, it is a good idea to give a lot of weight to values far from the mean (e.g., by squaring the difference from the mean), and other weighting schemes will result in relative inefficient estimators
$r^2$ is scaled from 0 to 1 and in the case where there are multiple predictors in a linear model, semipartial $R^2$ is tied to the partial sum of squares explained by each predictor. In other words, sums of squares can be partitioned into component effects that "add up". In the case of uncorrelated predictors, regression sums of squares and semipartial $R^2$ add up to the whole amount of explained variation due to the combination of predictors. There is no corresponding partitioning of explained variation on the absolute difference scale.
Variances and covariances have a long history and many probability models are stated in terms of them (e.g., the multivariate normal distribution).
As I discuss in Regression Modeling Strategies an absolute difference measure $g$ based on Gini's mean difference (average absolute difference over all possible pairs of values) can be used to quantify strength of association, and I believe that average absolute differences are easier to interpret. But they don't partition. The $g$-index for a subset of predictors can be larger than the $g$-index for the entire linear predictor $X\hat{\beta}$. On the other hand semipartial $R^2$ for a subset of a multivariable model has to be no greater than the overall model $R^2$. | Why don't we use absolute values of differences instead of squared differences in the denominator of
There are many reasons for using squared differences, including
A relationship to the Gaussian distribution where squared differences play a central role (the normal distribution's probability densit |
25,071 | Is a uniformly random number over the real line a valid distribution? | Uniform distribution has a finite range $-\infty < a < b < \infty$. It's probability density function is $p(x) = \frac{1}{b - a}$ for $x \in (a, b)$. If you set the range to infinities, you'd end up with $p(x) = \frac{1}{\infty } \to 0$. It doesn't integrate to unity since it would need to be $p(x) = c$ for some $c > 0$. For a finite support, as the support grows, $c \to 0$. If you think of it differently, for every $c > 0$ there would be an uniform distribution with a finite support with probability density function equal to $\tfrac{1}{b - a} = c$, so there cannot be such distribution with an infinite support. It's not a proper distribution.
As for your idea with mapping, notice that using such transformation would not lead to having uniformly distributed values. Try the following numerical experiment.
x <- runif(1e6, -1, 3)
y <- -log(4/(x+1) - 1)
hist(y, breaks=100)
As you can see, the result looks nothing like a uniform distribution. | Is a uniformly random number over the real line a valid distribution? | Uniform distribution has a finite range $-\infty < a < b < \infty$. It's probability density function is $p(x) = \frac{1}{b - a}$ for $x \in (a, b)$. If you set the range to infinities, you'd end up w | Is a uniformly random number over the real line a valid distribution?
Uniform distribution has a finite range $-\infty < a < b < \infty$. It's probability density function is $p(x) = \frac{1}{b - a}$ for $x \in (a, b)$. If you set the range to infinities, you'd end up with $p(x) = \frac{1}{\infty } \to 0$. It doesn't integrate to unity since it would need to be $p(x) = c$ for some $c > 0$. For a finite support, as the support grows, $c \to 0$. If you think of it differently, for every $c > 0$ there would be an uniform distribution with a finite support with probability density function equal to $\tfrac{1}{b - a} = c$, so there cannot be such distribution with an infinite support. It's not a proper distribution.
As for your idea with mapping, notice that using such transformation would not lead to having uniformly distributed values. Try the following numerical experiment.
x <- runif(1e6, -1, 3)
y <- -log(4/(x+1) - 1)
hist(y, breaks=100)
As you can see, the result looks nothing like a uniform distribution. | Is a uniformly random number over the real line a valid distribution?
Uniform distribution has a finite range $-\infty < a < b < \infty$. It's probability density function is $p(x) = \frac{1}{b - a}$ for $x \in (a, b)$. If you set the range to infinities, you'd end up w |
25,072 | Is a uniformly random number over the real line a valid distribution? | The main answer by Tim tells you about the uniform distribution as conceived in the traditional framework of probability theory, and it explains this by appeal to the asymptotics of density functions. In this answer I will give a more traditional explanation that goes back to the underlying axioms of probability within the standard framework, and I will also explain how one might go about obtaining the distribution of interest within alternative probability frameworks. My own view is that there are generalised frameworks for probability that are reasonable extensions that can be used in this case, and so I would go so far as to say that the uniform distribution on the reals is a valid distribution.
Why can't we have a uniform distribution on the reals (within the standard framework)?
Firstly, let us note the mathematical rules of the standard framework of probability theory (i.e., representing probability as a probability measure satisfying
the Kolmogorov axioms). In this framework, probabilities of events are represented by real numbers, and the probability measure must obey three axioms: (1) non-negativity; (2) norming (i.e., unit probability on the sample space); and (3) countable additivity.
Within this framework, it is not possible to obtain a uniform random variable on the real numbers. Within this set of axioms, the problem comes from the fact that we can partition the set of real numbers into a countably infinite set of bounded parts that have equal width. For example, we can write the real numbers as the following union of disjoint sets:
$$\mathbb{R} = \bigcup_{a \in \mathbb{Z}} [a, a+1).$$
Consequently, if the norming axiom and the countable additivity axiom both hold, then we must have:
$$\begin{align}
1
&= \mathbb{P}(X \in \mathbb{R}) \\[6pt]
&= \mathbb{P} \Bigg( X \in \bigcup_{a \in \mathbb{Z}} [a, a+1) \Bigg) \\[6pt]
&= \sum_{a \in \mathbb{Z}} \mathbb{P} ( a \leqslant X < a+1). \\[6pt]
\end{align}$$
Now, under uniformity, we would want the probability $p \equiv \mathbb{P} ( a \leqslant X < a+1)$ to be a fixed value that does not depend on $a$. This means that we must have $\sum_{a \in \mathbb{Z}} p = 1$, and there is no real number $p \in \mathbb{R}$ that satisfies this equation. Another way to look at this is, if we set $p=0$ and apply countable additivity then we get $\mathbb{P}(X \in \mathbb{R}) = 0$ and if we set $p>0$ and apply countable additivity then we get $\mathbb{P}(X \in \mathbb{R}) = \infty$. Either way, we break the norming axiom.
Operational difficulties with the uniform distribution over the reals
Before examining alternative probability frameworks, it is also worth noting some operational difficulties that would apply to the uniform distribution over the reals even if we can define it validly. One of the requirements of the distribution is that:
$$\mathbb{P}(X \in \mathcal{A} | X \in \mathcal{B})
= \frac{|\mathcal{A} \cap \mathcal{B}|}{|\mathcal{B}|}.$$
(We use $| \ \cdot \ |$ to denote the Lebesgue measure of a set.) Consequently, for any $0<a<b$ we have:
$$\mathbb{P}(|X| \leqslant a)
\leqslant \mathbb{P}(|X| \leqslant a | |X| \leqslant b) = \frac{a}{b}.$$
We can use this inequality and make $b = a/\epsilon$ arbitrarily large, so we have:
$$\mathbb{P}(|X| \leqslant a) \leqslant \epsilon
\quad \quad \quad \text{for all } \epsilon>0.$$
If the probability is a real value then this implies that $\mathbb{P}(|X| \leqslant a)=0$ for all $a>0$, but even if we use an alternative framework allowing infinitesmals (see below), we can still say that this probability is smaller than any positive real number. Essentially this means that under the uniform distribution over the reals, for any specified real number, we will "almost surely" get a value that is higher than this. Intuitively, this means that the uniform distribution over the reals will always give values that are "infinitely large" in a certain sense.
This requirement of the distribution means that there are constructive problems when dealing with this distribution. Even if we work within a probability framework where this distribution is valid, it will be "non-constructive" in the sense that we will be unable to create a computational facility that can generate numbers from the distribution.
What alternative probability frameworks can we use to get around this?
In order to allow a uniform distribution on the real numbers, we obviously need to relax one or more of the rules of the standard probability framework. There are a number of ways we could do this which would allow a uniform distribution on the reals, but they all have some other potential drawbacks. Here are some of the possibilities for how we might generalise the standard framework.
Allow infinitesimal probabilities: One possibility is to relax the requirement that a probability must be a real value, and instead extend this to allow infinitesimals. If we allow this, we then set $dp \equiv \mathbb{P} ( a \leqslant X < a+1)$ to be an infinitesimal value that satisfies the requirements $\sum_{a \in \mathbb{Z}} dp = 1$ and $dp \geqslant 0$. With this extension we can keep all three of the probability axioms in the standard theory, with the non-negativity axiom suitably extended to recognise non-negative infinitesimal numbers.
Probability frameworks allowing infinitesimal probabilities exist and have been examined in the philosophy and statistical literature (see e.g., Barrett 2010, Hofweber 2014 and Benci, Horsten and Wenmackers 2018. There are also broader non-standard frameworks of measure theory that allow infinitesimal measures, and infinitesimal probability can be regarded as a part of that broader theory.
In my view, this is quite a reasonable extension to standard probability theory, and its only real drawback is that it is more complicated, and it requires users to learn about infinitesimals. Since I regard this as a perfectly legitimate extension of probability theory, I would go so far as to say that the uniform distribution on the real numbers does exist since the user can adopt this broader framework to use that distribution.
Allow "distributions" that are actually limits of sequences/classes of distributions: Another possibility for dealing with the uniform distribution on the real numbers is to define it via a limit of a sequence/class of distributions. Traditionally, this is done by looking at a sequence of normal distributions with zero mean and increasing variance, and taking the uniform distribution to be the limit of this sequence of distributions as the variance approaches infinity (see related answer here). (There are many other ways you could define the distribution as a limit.)
This method extends our conception of what constitutes a "distribution" and a corresponding "random variable" but it can be framed in a way that is internally consistent and constitutes a valid extension to probability theory. By broadening the conception of a "random variable" and its "distribution" this also allows us to preserve all the standard axioms. In the above treatment, we would create a sequence of standard probability distributions $F_1,F_2,F_3,...$ where the values $p_n(a) = \mathbb{P} ( a \leqslant X < a+1 | X \sim F_n)$ depend on $a$, but where the ratios of these terms all converge to unity in the limit $n \rightarrow \infty$.
The advantage of this approach is that it allows us to preserve the standard probability axioms (just like in infinitesimal probability frameworks). The main disadvantage is that it leads to some tricky issues involving limits, particularly with regard to the interchange of limits in various equations involving non-standard distributions.
Replace the countable additivity with finite additivity: Another possibility is that we could scrap the countable additivity axiom and use the (weaker) finite additivity axiom instead. In this case we can set $p = \mathbb{P} ( a \leqslant X < a+1) = 0$ for all $a \in \mathbb{Z}$ and still have $\mathbb{P}(X \in \mathbb{R}) = 1$ to satisfy the norming axiom. (In this framework, the mathematical equations in the problem above do not apply since countable additivity no longer holds.)
Various probability theorists (notably Bruno de Finetti) have worked within the framework of this broader set of probability axioms and some still argue that it is superior to the standard framework. The main disadvantage of this broader framework of probability is that a lot of limiting results in probability are no longer valid, which wipes away a lot of useful asymptotic theory that is available in the standard framework. | Is a uniformly random number over the real line a valid distribution? | The main answer by Tim tells you about the uniform distribution as conceived in the traditional framework of probability theory, and it explains this by appeal to the asymptotics of density functions. | Is a uniformly random number over the real line a valid distribution?
The main answer by Tim tells you about the uniform distribution as conceived in the traditional framework of probability theory, and it explains this by appeal to the asymptotics of density functions. In this answer I will give a more traditional explanation that goes back to the underlying axioms of probability within the standard framework, and I will also explain how one might go about obtaining the distribution of interest within alternative probability frameworks. My own view is that there are generalised frameworks for probability that are reasonable extensions that can be used in this case, and so I would go so far as to say that the uniform distribution on the reals is a valid distribution.
Why can't we have a uniform distribution on the reals (within the standard framework)?
Firstly, let us note the mathematical rules of the standard framework of probability theory (i.e., representing probability as a probability measure satisfying
the Kolmogorov axioms). In this framework, probabilities of events are represented by real numbers, and the probability measure must obey three axioms: (1) non-negativity; (2) norming (i.e., unit probability on the sample space); and (3) countable additivity.
Within this framework, it is not possible to obtain a uniform random variable on the real numbers. Within this set of axioms, the problem comes from the fact that we can partition the set of real numbers into a countably infinite set of bounded parts that have equal width. For example, we can write the real numbers as the following union of disjoint sets:
$$\mathbb{R} = \bigcup_{a \in \mathbb{Z}} [a, a+1).$$
Consequently, if the norming axiom and the countable additivity axiom both hold, then we must have:
$$\begin{align}
1
&= \mathbb{P}(X \in \mathbb{R}) \\[6pt]
&= \mathbb{P} \Bigg( X \in \bigcup_{a \in \mathbb{Z}} [a, a+1) \Bigg) \\[6pt]
&= \sum_{a \in \mathbb{Z}} \mathbb{P} ( a \leqslant X < a+1). \\[6pt]
\end{align}$$
Now, under uniformity, we would want the probability $p \equiv \mathbb{P} ( a \leqslant X < a+1)$ to be a fixed value that does not depend on $a$. This means that we must have $\sum_{a \in \mathbb{Z}} p = 1$, and there is no real number $p \in \mathbb{R}$ that satisfies this equation. Another way to look at this is, if we set $p=0$ and apply countable additivity then we get $\mathbb{P}(X \in \mathbb{R}) = 0$ and if we set $p>0$ and apply countable additivity then we get $\mathbb{P}(X \in \mathbb{R}) = \infty$. Either way, we break the norming axiom.
Operational difficulties with the uniform distribution over the reals
Before examining alternative probability frameworks, it is also worth noting some operational difficulties that would apply to the uniform distribution over the reals even if we can define it validly. One of the requirements of the distribution is that:
$$\mathbb{P}(X \in \mathcal{A} | X \in \mathcal{B})
= \frac{|\mathcal{A} \cap \mathcal{B}|}{|\mathcal{B}|}.$$
(We use $| \ \cdot \ |$ to denote the Lebesgue measure of a set.) Consequently, for any $0<a<b$ we have:
$$\mathbb{P}(|X| \leqslant a)
\leqslant \mathbb{P}(|X| \leqslant a | |X| \leqslant b) = \frac{a}{b}.$$
We can use this inequality and make $b = a/\epsilon$ arbitrarily large, so we have:
$$\mathbb{P}(|X| \leqslant a) \leqslant \epsilon
\quad \quad \quad \text{for all } \epsilon>0.$$
If the probability is a real value then this implies that $\mathbb{P}(|X| \leqslant a)=0$ for all $a>0$, but even if we use an alternative framework allowing infinitesmals (see below), we can still say that this probability is smaller than any positive real number. Essentially this means that under the uniform distribution over the reals, for any specified real number, we will "almost surely" get a value that is higher than this. Intuitively, this means that the uniform distribution over the reals will always give values that are "infinitely large" in a certain sense.
This requirement of the distribution means that there are constructive problems when dealing with this distribution. Even if we work within a probability framework where this distribution is valid, it will be "non-constructive" in the sense that we will be unable to create a computational facility that can generate numbers from the distribution.
What alternative probability frameworks can we use to get around this?
In order to allow a uniform distribution on the real numbers, we obviously need to relax one or more of the rules of the standard probability framework. There are a number of ways we could do this which would allow a uniform distribution on the reals, but they all have some other potential drawbacks. Here are some of the possibilities for how we might generalise the standard framework.
Allow infinitesimal probabilities: One possibility is to relax the requirement that a probability must be a real value, and instead extend this to allow infinitesimals. If we allow this, we then set $dp \equiv \mathbb{P} ( a \leqslant X < a+1)$ to be an infinitesimal value that satisfies the requirements $\sum_{a \in \mathbb{Z}} dp = 1$ and $dp \geqslant 0$. With this extension we can keep all three of the probability axioms in the standard theory, with the non-negativity axiom suitably extended to recognise non-negative infinitesimal numbers.
Probability frameworks allowing infinitesimal probabilities exist and have been examined in the philosophy and statistical literature (see e.g., Barrett 2010, Hofweber 2014 and Benci, Horsten and Wenmackers 2018. There are also broader non-standard frameworks of measure theory that allow infinitesimal measures, and infinitesimal probability can be regarded as a part of that broader theory.
In my view, this is quite a reasonable extension to standard probability theory, and its only real drawback is that it is more complicated, and it requires users to learn about infinitesimals. Since I regard this as a perfectly legitimate extension of probability theory, I would go so far as to say that the uniform distribution on the real numbers does exist since the user can adopt this broader framework to use that distribution.
Allow "distributions" that are actually limits of sequences/classes of distributions: Another possibility for dealing with the uniform distribution on the real numbers is to define it via a limit of a sequence/class of distributions. Traditionally, this is done by looking at a sequence of normal distributions with zero mean and increasing variance, and taking the uniform distribution to be the limit of this sequence of distributions as the variance approaches infinity (see related answer here). (There are many other ways you could define the distribution as a limit.)
This method extends our conception of what constitutes a "distribution" and a corresponding "random variable" but it can be framed in a way that is internally consistent and constitutes a valid extension to probability theory. By broadening the conception of a "random variable" and its "distribution" this also allows us to preserve all the standard axioms. In the above treatment, we would create a sequence of standard probability distributions $F_1,F_2,F_3,...$ where the values $p_n(a) = \mathbb{P} ( a \leqslant X < a+1 | X \sim F_n)$ depend on $a$, but where the ratios of these terms all converge to unity in the limit $n \rightarrow \infty$.
The advantage of this approach is that it allows us to preserve the standard probability axioms (just like in infinitesimal probability frameworks). The main disadvantage is that it leads to some tricky issues involving limits, particularly with regard to the interchange of limits in various equations involving non-standard distributions.
Replace the countable additivity with finite additivity: Another possibility is that we could scrap the countable additivity axiom and use the (weaker) finite additivity axiom instead. In this case we can set $p = \mathbb{P} ( a \leqslant X < a+1) = 0$ for all $a \in \mathbb{Z}$ and still have $\mathbb{P}(X \in \mathbb{R}) = 1$ to satisfy the norming axiom. (In this framework, the mathematical equations in the problem above do not apply since countable additivity no longer holds.)
Various probability theorists (notably Bruno de Finetti) have worked within the framework of this broader set of probability axioms and some still argue that it is superior to the standard framework. The main disadvantage of this broader framework of probability is that a lot of limiting results in probability are no longer valid, which wipes away a lot of useful asymptotic theory that is available in the standard framework. | Is a uniformly random number over the real line a valid distribution?
The main answer by Tim tells you about the uniform distribution as conceived in the traditional framework of probability theory, and it explains this by appeal to the asymptotics of density functions. |
25,073 | Is a uniformly random number over the real line a valid distribution? | Tim's answer is a fantastic answer, and I wanted to go more into depth about the results of their answer in a way that won't fit into a comment.
Let's walk through the mapping described in the question. We define the following process. Pick any random number between -1 and 3. (Sample a number from $\text{Unif}(-1, 3)$). Then, use the function $f(x) = - \log (\frac{4}{x+1} - 1)$ to convert your number between -1 and 3 to number between $-\infty$ and $\infty$ (which is the range of $f\,$).
Note that $f$ is a one-to-one function (since it passes the horizontal line test), which means that after the conversion, every single number has an equal chance of being chosen.
So then why isn't this a uniform distribution over all of the real numbers? If every number has an equal chance of being chosen, doesn't that make it a uniform distribution? No!
The reason is that distributions don't indicate the probability of a particular value being chosen; they indicate the probability that a value within a particular range will be chosen.
In our case, it is true that every number has an equal chance of being chosen. However, there are some numbers where there's a higher chance of choosing a value that's close to that number. And that is what the distribution reflects. So the distribution is not uniform.
Overall, a uniform distribution does not mean that every number has an equal chance of being chosen. Instead, it means that no matter what range you pick, the probability of a sampled value falling within that range only depends on the size of the range. (Not the specific endpoints of the range.)
EDIT:
After writing this answer, I came across a video recently published on YouTube (after this answer was written) by Numberphile (technically, Numberphile2) titled "More on Bertrand's Paradox (with 3blue1brown) - Numberphile" which gives a better intuition about this exact question. In the video, the idea that "the probability of a sampled value falling within that range only depends on the size of the range" is what is described as "translational symmetry."
Based on the video, it is likely not correct to say that a "uniform distribution" must have translational symmetry. However, it does seem to be the case that the most common way of clearly defining an unclear uniform distribution is to restrict the distribution to have translational symmetry. (For example, one might be willing to call the distribution based on $f(x) = -\log(\frac{4}{x+1} - 1)$ a "uniform distribution." However, as clearly shown by the graph in Tim's answer, that distribution is not translationally symmetric. That is, if we look through a window at the graph, and we move that window from side to side, the graph looks different based on where we have the window.) | Is a uniformly random number over the real line a valid distribution? | Tim's answer is a fantastic answer, and I wanted to go more into depth about the results of their answer in a way that won't fit into a comment.
Let's walk through the mapping described in the questio | Is a uniformly random number over the real line a valid distribution?
Tim's answer is a fantastic answer, and I wanted to go more into depth about the results of their answer in a way that won't fit into a comment.
Let's walk through the mapping described in the question. We define the following process. Pick any random number between -1 and 3. (Sample a number from $\text{Unif}(-1, 3)$). Then, use the function $f(x) = - \log (\frac{4}{x+1} - 1)$ to convert your number between -1 and 3 to number between $-\infty$ and $\infty$ (which is the range of $f\,$).
Note that $f$ is a one-to-one function (since it passes the horizontal line test), which means that after the conversion, every single number has an equal chance of being chosen.
So then why isn't this a uniform distribution over all of the real numbers? If every number has an equal chance of being chosen, doesn't that make it a uniform distribution? No!
The reason is that distributions don't indicate the probability of a particular value being chosen; they indicate the probability that a value within a particular range will be chosen.
In our case, it is true that every number has an equal chance of being chosen. However, there are some numbers where there's a higher chance of choosing a value that's close to that number. And that is what the distribution reflects. So the distribution is not uniform.
Overall, a uniform distribution does not mean that every number has an equal chance of being chosen. Instead, it means that no matter what range you pick, the probability of a sampled value falling within that range only depends on the size of the range. (Not the specific endpoints of the range.)
EDIT:
After writing this answer, I came across a video recently published on YouTube (after this answer was written) by Numberphile (technically, Numberphile2) titled "More on Bertrand's Paradox (with 3blue1brown) - Numberphile" which gives a better intuition about this exact question. In the video, the idea that "the probability of a sampled value falling within that range only depends on the size of the range" is what is described as "translational symmetry."
Based on the video, it is likely not correct to say that a "uniform distribution" must have translational symmetry. However, it does seem to be the case that the most common way of clearly defining an unclear uniform distribution is to restrict the distribution to have translational symmetry. (For example, one might be willing to call the distribution based on $f(x) = -\log(\frac{4}{x+1} - 1)$ a "uniform distribution." However, as clearly shown by the graph in Tim's answer, that distribution is not translationally symmetric. That is, if we look through a window at the graph, and we move that window from side to side, the graph looks different based on where we have the window.) | Is a uniformly random number over the real line a valid distribution?
Tim's answer is a fantastic answer, and I wanted to go more into depth about the results of their answer in a way that won't fit into a comment.
Let's walk through the mapping described in the questio |
25,074 | How many dimensions does a neural network have? | You're talking about the dimension of the loss function, and the answer is that the input dimension of the loss function is how many parameters and biases there are, and the output dimension is $1$.
Let's focus on that first one by looking at an example with linear regression.
$$y
=
\beta_0 + \beta_1x_1+\beta_2x_2+\beta_3x_3
$$
Square loss is thus
$$
L\big(\beta_0, \beta_1, \beta_2, \beta_3\big) = \sum_{i=1}^n \Bigg[\bigg(y_i - \big( \beta_0 + \beta_1x_{i1}+\beta_2x_{i2}+\beta_3x_{i3} \big)\bigg)^2 \Bigg]
$$
That is a function from $\mathbb{R}^4 \rightarrow \mathbb{R}$, agreed? I would call that five dimensions: four for the regression parameters and one for the output loss.
A neural network is surprisingly simular to this. The estimated value is some composition of functions, and then the loss depends on the values of the estimated parameters.
$$
y = b_2 + w_2\text{ReLU}\big(b_0 + w_0x\big) + w_3\text{ReLU}\big(b_1 + w_1x\big)
$$
(I'll post that network later, but I think it would be a useful exercise to draw out what's going on. People appear quite eager to think of neural networks as being webs of circles and lines, yet there is real math going on.)
Then the loss is a function of the weights $w$ and biases $b$. Let's do absolute loss here.
$$
L\big(
b_0, b_1, b_2, w_0, w_1, w_2, w_3
\big)
=$$
$$
\sum_{i=1}^n \Bigg\vert y_i - \bigg(b_2 + w_2\text{ReLU}\big(b_0 + w_0x_i\big) + w_3\text{ReLU}\big(b_1 + w_1x_i\big)\bigg)\Bigg\vert
$$
This is a function $\mathbb{R}^7 \rightarrow \mathbb{R}$. I'd call that eight dimensions. | How many dimensions does a neural network have? | You're talking about the dimension of the loss function, and the answer is that the input dimension of the loss function is how many parameters and biases there are, and the output dimension is $1$.
L | How many dimensions does a neural network have?
You're talking about the dimension of the loss function, and the answer is that the input dimension of the loss function is how many parameters and biases there are, and the output dimension is $1$.
Let's focus on that first one by looking at an example with linear regression.
$$y
=
\beta_0 + \beta_1x_1+\beta_2x_2+\beta_3x_3
$$
Square loss is thus
$$
L\big(\beta_0, \beta_1, \beta_2, \beta_3\big) = \sum_{i=1}^n \Bigg[\bigg(y_i - \big( \beta_0 + \beta_1x_{i1}+\beta_2x_{i2}+\beta_3x_{i3} \big)\bigg)^2 \Bigg]
$$
That is a function from $\mathbb{R}^4 \rightarrow \mathbb{R}$, agreed? I would call that five dimensions: four for the regression parameters and one for the output loss.
A neural network is surprisingly simular to this. The estimated value is some composition of functions, and then the loss depends on the values of the estimated parameters.
$$
y = b_2 + w_2\text{ReLU}\big(b_0 + w_0x\big) + w_3\text{ReLU}\big(b_1 + w_1x\big)
$$
(I'll post that network later, but I think it would be a useful exercise to draw out what's going on. People appear quite eager to think of neural networks as being webs of circles and lines, yet there is real math going on.)
Then the loss is a function of the weights $w$ and biases $b$. Let's do absolute loss here.
$$
L\big(
b_0, b_1, b_2, w_0, w_1, w_2, w_3
\big)
=$$
$$
\sum_{i=1}^n \Bigg\vert y_i - \bigg(b_2 + w_2\text{ReLU}\big(b_0 + w_0x_i\big) + w_3\text{ReLU}\big(b_1 + w_1x_i\big)\bigg)\Bigg\vert
$$
This is a function $\mathbb{R}^7 \rightarrow \mathbb{R}$. I'd call that eight dimensions. | How many dimensions does a neural network have?
You're talking about the dimension of the loss function, and the answer is that the input dimension of the loss function is how many parameters and biases there are, and the output dimension is $1$.
L |
25,075 | How many dimensions does a neural network have? | Your plot shows a model with 2 parameters, because the loss $h$ is expressed as a function of $q_1, q_2$. The loss surface of a neural network is a function of each one of its parameters, so the "dimension" is the number of parameters (weights, biases) in the model. | How many dimensions does a neural network have? | Your plot shows a model with 2 parameters, because the loss $h$ is expressed as a function of $q_1, q_2$. The loss surface of a neural network is a function of each one of its parameters, so the "dime | How many dimensions does a neural network have?
Your plot shows a model with 2 parameters, because the loss $h$ is expressed as a function of $q_1, q_2$. The loss surface of a neural network is a function of each one of its parameters, so the "dimension" is the number of parameters (weights, biases) in the model. | How many dimensions does a neural network have?
Your plot shows a model with 2 parameters, because the loss $h$ is expressed as a function of $q_1, q_2$. The loss surface of a neural network is a function of each one of its parameters, so the "dime |
25,076 | Can KL-Divergence ever be greater than 1? | The Kullback-Leibler divergence is unbounded. Indeed, since there is no lower bound on the $q(i)$'s, there is no upper bound on the $p(i)/q(i)$'s. For instance, the Kullback-Leibler divergence between a Normal $N(\mu_1,\sigma^2)$ and a Normal $N(\mu_2,\sigma^2)$ with equal variance is
$$\frac{1}{2\sigma^{2}}(\mu_1-\mu_2)^2$$which is clearly unbounded.
Wikipedia [which has been known to be wrong!] indeed states
"...a Kullback–Leibler divergence of 1 indicates that the two
distributions behave in such a different manner that the expectation
given the first distribution approaches zero."
which makes no sense (expectation of which function? why 1 and not 2?)
A more satisfactory explanation from the same
Wikipedia page is that the Kullback–Leibler divergence
"...can be construed as measuring the expected number of extra bits
required to code samples from P using a code optimized for Q rather
than the code optimized for P." | Can KL-Divergence ever be greater than 1? | The Kullback-Leibler divergence is unbounded. Indeed, since there is no lower bound on the $q(i)$'s, there is no upper bound on the $p(i)/q(i)$'s. For instance, the Kullback-Leibler divergence betwee | Can KL-Divergence ever be greater than 1?
The Kullback-Leibler divergence is unbounded. Indeed, since there is no lower bound on the $q(i)$'s, there is no upper bound on the $p(i)/q(i)$'s. For instance, the Kullback-Leibler divergence between a Normal $N(\mu_1,\sigma^2)$ and a Normal $N(\mu_2,\sigma^2)$ with equal variance is
$$\frac{1}{2\sigma^{2}}(\mu_1-\mu_2)^2$$which is clearly unbounded.
Wikipedia [which has been known to be wrong!] indeed states
"...a Kullback–Leibler divergence of 1 indicates that the two
distributions behave in such a different manner that the expectation
given the first distribution approaches zero."
which makes no sense (expectation of which function? why 1 and not 2?)
A more satisfactory explanation from the same
Wikipedia page is that the Kullback–Leibler divergence
"...can be construed as measuring the expected number of extra bits
required to code samples from P using a code optimized for Q rather
than the code optimized for P." | Can KL-Divergence ever be greater than 1?
The Kullback-Leibler divergence is unbounded. Indeed, since there is no lower bound on the $q(i)$'s, there is no upper bound on the $p(i)/q(i)$'s. For instance, the Kullback-Leibler divergence betwee |
25,077 | Will this introduce bias into what should be random numbers? | Let's count and see. By construction of the file, all 4-bit strings are equally likely. There are 16 such strings. Here they are:
0. 0000
1. 0001
2. 0010
3. 0011
4. 0100
5. 0101
6. 0110
7. 0111
8. 1000
9. 1001
10. 1010
11. 1011
12. 1100
13. 1101
14. 1110
15. 1111
Your procedure throws out strings 10 through 15. So in the cases that you actually use, you'll be choosing 0 through 9, each of which is equally likely, as desired. And we know the generated decimal digits are independent of each other because each uses a separate string of 4 bits and all the bits are independent. Your procedure constitutes a simple kind of rejection sampling. | Will this introduce bias into what should be random numbers? | Let's count and see. By construction of the file, all 4-bit strings are equally likely. There are 16 such strings. Here they are:
0. 0000
1. 0001
2. 0010
3. 0011
4. 0100
5. 0101
6. 0110
7. 011 | Will this introduce bias into what should be random numbers?
Let's count and see. By construction of the file, all 4-bit strings are equally likely. There are 16 such strings. Here they are:
0. 0000
1. 0001
2. 0010
3. 0011
4. 0100
5. 0101
6. 0110
7. 0111
8. 1000
9. 1001
10. 1010
11. 1011
12. 1100
13. 1101
14. 1110
15. 1111
Your procedure throws out strings 10 through 15. So in the cases that you actually use, you'll be choosing 0 through 9, each of which is equally likely, as desired. And we know the generated decimal digits are independent of each other because each uses a separate string of 4 bits and all the bits are independent. Your procedure constitutes a simple kind of rejection sampling. | Will this introduce bias into what should be random numbers?
Let's count and see. By construction of the file, all 4-bit strings are equally likely. There are 16 such strings. Here they are:
0. 0000
1. 0001
2. 0010
3. 0011
4. 0100
5. 0101
6. 0110
7. 011 |
25,078 | Will this introduce bias into what should be random numbers? | There is no bias since you just simulate some values that are discarded and all values including those that are kept are generated with the same probability:
The R code for the above graph is
generza=matrix(sample(0:1,4*1e6,rep=TRUE),ncol=4)
uniz=generza[,1]+2*generza[,2]+4*generza[,3]+8*generza[,4]
barplot(hist(uniz[uniz<10],breaks=seq(-0.5,9.5,le=11))$counts,col="steelblue") | Will this introduce bias into what should be random numbers? | There is no bias since you just simulate some values that are discarded and all values including those that are kept are generated with the same probability:
The R code for the above graph is
generza | Will this introduce bias into what should be random numbers?
There is no bias since you just simulate some values that are discarded and all values including those that are kept are generated with the same probability:
The R code for the above graph is
generza=matrix(sample(0:1,4*1e6,rep=TRUE),ncol=4)
uniz=generza[,1]+2*generza[,2]+4*generza[,3]+8*generza[,4]
barplot(hist(uniz[uniz<10],breaks=seq(-0.5,9.5,le=11))$counts,col="steelblue") | Will this introduce bias into what should be random numbers?
There is no bias since you just simulate some values that are discarded and all values including those that are kept are generated with the same probability:
The R code for the above graph is
generza |
25,079 | How to implement L2 regularization towards an arbitrary point in space? | You actually ask two different questions.
Having the norm tend to 5 implies that you want the weights to be near the surface of a hypersphere centered at the origin with radius 5. This regularization looks something like
$$J(\Theta, X, y) = L(\Theta, X, y) + \lambda (||w||_2^2-5)^2$$
But you could instead use something like $\lambda \cdot\text{abs}(||w||_2^2-5)$, I suppose.
On the other hand, if you want to tend towards an arbitrary point, you just need to use that point as the center $c$.
$$J(\Theta, X, y) = L(\Theta, X, y) + \lambda ||w-c||_2^2$$ | How to implement L2 regularization towards an arbitrary point in space? | You actually ask two different questions.
Having the norm tend to 5 implies that you want the weights to be near the surface of a hypersphere centered at the origin with radius 5. This regularization | How to implement L2 regularization towards an arbitrary point in space?
You actually ask two different questions.
Having the norm tend to 5 implies that you want the weights to be near the surface of a hypersphere centered at the origin with radius 5. This regularization looks something like
$$J(\Theta, X, y) = L(\Theta, X, y) + \lambda (||w||_2^2-5)^2$$
But you could instead use something like $\lambda \cdot\text{abs}(||w||_2^2-5)$, I suppose.
On the other hand, if you want to tend towards an arbitrary point, you just need to use that point as the center $c$.
$$J(\Theta, X, y) = L(\Theta, X, y) + \lambda ||w-c||_2^2$$ | How to implement L2 regularization towards an arbitrary point in space?
You actually ask two different questions.
Having the norm tend to 5 implies that you want the weights to be near the surface of a hypersphere centered at the origin with radius 5. This regularization |
25,080 | How to implement L2 regularization towards an arbitrary point in space? | Define $$\hat w_\lambda = \arg\min_w L(\Theta, X, y) + \lambda \|w\|_2^2.$$ We know that $\lim_{\lambda \to \infty} \hat w_\lambda = 0$, due to the penalty $w \mapsto \|w\|_2^2$ having the origin as its minimizer.
Sycorax points out that, similarly, $\lim_{\lambda \to \infty} \left\{ \arg\min_w L(\Theta, X, y) + \lambda \|w-c\|_2^2 \right\} = c.$ This successful generalization may lead us to propose the estimator $$\tilde w_\lambda = \arg\min_w L(\Theta, X, y) + \lambda \mathrm{pen}(w),$$ where $\mathrm{pen}$ is a function whose minimizer satisfies some property that we seek. Indeed, Sycorax takes $\mathrm{pen}(w) = g(\|w\|_2^2 - 5)$, where $g$ is (uniquely) minimized at the origin, and, in particular, $g \in \{|\cdot|, \, (\cdot)^2\}$. Therefore $\lim_{\lambda \to \infty} \|\tilde w_\lambda \|_2^2 = 5$, as desired. Unfortunately, though, both of the choices of $g$ lead to penalties which are nonconvex, leading the estimator to be difficult to compute.
The above analysis seems to be the best solution (maybe up to the choice of $g$, for which I have no better one to suggest) if we insist on $\lambda \to \infty$ as being the unique interpretation of "tends to" described in the question. However, assuming that $\|\arg\min_w L(\Theta, X, y) \|_2^2 \geq 5$, there exists some $\Lambda$ so that the minimizer $\hat w_\Lambda$ of OP's problem satsifes $\|\hat w_\Lambda\|_2^2 = 5$. Therefore $$\lim_{\lambda \to \Lambda} \left\| \hat w_\lambda \right\|_2^2 = 5,$$ without needing to change the objective function. If no such $\Lambda$ exists, then the problem of computing $\arg\min_{w : \|w\|_2^2 = 5} L(\Theta, X, y)$ is intrinsically difficult. Indeed, there's no need to consider any estimator besides $\hat w_\lambda$ when trying to encourage natural properties of $\|\hat w_\lambda\|_2^2$.
(To enforce that a penalized estimator attains a value of the penalty which is not achieved by the unpenalized estimator seems highly unnatural to me. If anyone is aware of any places where this is in fact desired, please do comment!) | How to implement L2 regularization towards an arbitrary point in space? | Define $$\hat w_\lambda = \arg\min_w L(\Theta, X, y) + \lambda \|w\|_2^2.$$ We know that $\lim_{\lambda \to \infty} \hat w_\lambda = 0$, due to the penalty $w \mapsto \|w\|_2^2$ having the origin as i | How to implement L2 regularization towards an arbitrary point in space?
Define $$\hat w_\lambda = \arg\min_w L(\Theta, X, y) + \lambda \|w\|_2^2.$$ We know that $\lim_{\lambda \to \infty} \hat w_\lambda = 0$, due to the penalty $w \mapsto \|w\|_2^2$ having the origin as its minimizer.
Sycorax points out that, similarly, $\lim_{\lambda \to \infty} \left\{ \arg\min_w L(\Theta, X, y) + \lambda \|w-c\|_2^2 \right\} = c.$ This successful generalization may lead us to propose the estimator $$\tilde w_\lambda = \arg\min_w L(\Theta, X, y) + \lambda \mathrm{pen}(w),$$ where $\mathrm{pen}$ is a function whose minimizer satisfies some property that we seek. Indeed, Sycorax takes $\mathrm{pen}(w) = g(\|w\|_2^2 - 5)$, where $g$ is (uniquely) minimized at the origin, and, in particular, $g \in \{|\cdot|, \, (\cdot)^2\}$. Therefore $\lim_{\lambda \to \infty} \|\tilde w_\lambda \|_2^2 = 5$, as desired. Unfortunately, though, both of the choices of $g$ lead to penalties which are nonconvex, leading the estimator to be difficult to compute.
The above analysis seems to be the best solution (maybe up to the choice of $g$, for which I have no better one to suggest) if we insist on $\lambda \to \infty$ as being the unique interpretation of "tends to" described in the question. However, assuming that $\|\arg\min_w L(\Theta, X, y) \|_2^2 \geq 5$, there exists some $\Lambda$ so that the minimizer $\hat w_\Lambda$ of OP's problem satsifes $\|\hat w_\Lambda\|_2^2 = 5$. Therefore $$\lim_{\lambda \to \Lambda} \left\| \hat w_\lambda \right\|_2^2 = 5,$$ without needing to change the objective function. If no such $\Lambda$ exists, then the problem of computing $\arg\min_{w : \|w\|_2^2 = 5} L(\Theta, X, y)$ is intrinsically difficult. Indeed, there's no need to consider any estimator besides $\hat w_\lambda$ when trying to encourage natural properties of $\|\hat w_\lambda\|_2^2$.
(To enforce that a penalized estimator attains a value of the penalty which is not achieved by the unpenalized estimator seems highly unnatural to me. If anyone is aware of any places where this is in fact desired, please do comment!) | How to implement L2 regularization towards an arbitrary point in space?
Define $$\hat w_\lambda = \arg\min_w L(\Theta, X, y) + \lambda \|w\|_2^2.$$ We know that $\lim_{\lambda \to \infty} \hat w_\lambda = 0$, due to the penalty $w \mapsto \|w\|_2^2$ having the origin as i |
25,081 | How to implement L2 regularization towards an arbitrary point in space? | For appropriate $L$ it is possible to view it as negative log-likelihood and appropriate regularization $J$ can be viewed as negative log-likelihood for prior distribution. This approach is called Maximum A Posteriori (MAP).
It should be easy to see Sycorax's examples in the light of MAP.
For details of MAP you can look at these notes. From my experience googling 'maximum a posteriori regularization' gives good results. | How to implement L2 regularization towards an arbitrary point in space? | For appropriate $L$ it is possible to view it as negative log-likelihood and appropriate regularization $J$ can be viewed as negative log-likelihood for prior distribution. This approach is called Ma | How to implement L2 regularization towards an arbitrary point in space?
For appropriate $L$ it is possible to view it as negative log-likelihood and appropriate regularization $J$ can be viewed as negative log-likelihood for prior distribution. This approach is called Maximum A Posteriori (MAP).
It should be easy to see Sycorax's examples in the light of MAP.
For details of MAP you can look at these notes. From my experience googling 'maximum a posteriori regularization' gives good results. | How to implement L2 regularization towards an arbitrary point in space?
For appropriate $L$ it is possible to view it as negative log-likelihood and appropriate regularization $J$ can be viewed as negative log-likelihood for prior distribution. This approach is called Ma |
25,082 | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function? | This reasoning is essentially that of Sycorax's answer, but no need to resort to that theorem:
Consider two distinct points $x$ and $y$. For $\theta<0$, their Gram matrix is
$$
\begin{bmatrix}
k(x, x) & k(x, y) \\
k(x, y) & k(y, y)
\end{bmatrix}
=
\begin{bmatrix}
1 & \alpha \\
\alpha & 1
\end{bmatrix}
$$
where $\alpha = k(x, y) = \exp\left( - \frac{\theta}{2} \lVert x - y \rVert^2 \right) = \exp\left( \tfrac12 \lvert{\theta}\rvert \lVert x - y \rVert^2 \right) > 1$, since the argument to $\exp$ is strictly positive.
The characteristic polynomial of this Gram matrix gives $(\lambda - 1)^2 - \alpha^2 = 0$, so that $\lvert \lambda - 1 \rvert = \alpha$, and
the eigenvalues of this matrix are $1 + \alpha$ and $1 - \alpha$. Since $\alpha > 1$, that second eigenvalue is negative, and the kernel is not psd. | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function? | This reasoning is essentially that of Sycorax's answer, but no need to resort to that theorem:
Consider two distinct points $x$ and $y$. For $\theta<0$, their Gram matrix is
$$
\begin{bmatrix}
k(x, x) | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function?
This reasoning is essentially that of Sycorax's answer, but no need to resort to that theorem:
Consider two distinct points $x$ and $y$. For $\theta<0$, their Gram matrix is
$$
\begin{bmatrix}
k(x, x) & k(x, y) \\
k(x, y) & k(y, y)
\end{bmatrix}
=
\begin{bmatrix}
1 & \alpha \\
\alpha & 1
\end{bmatrix}
$$
where $\alpha = k(x, y) = \exp\left( - \frac{\theta}{2} \lVert x - y \rVert^2 \right) = \exp\left( \tfrac12 \lvert{\theta}\rvert \lVert x - y \rVert^2 \right) > 1$, since the argument to $\exp$ is strictly positive.
The characteristic polynomial of this Gram matrix gives $(\lambda - 1)^2 - \alpha^2 = 0$, so that $\lvert \lambda - 1 \rvert = \alpha$, and
the eigenvalues of this matrix are $1 + \alpha$ and $1 - \alpha$. Since $\alpha > 1$, that second eigenvalue is negative, and the kernel is not psd. | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function?
This reasoning is essentially that of Sycorax's answer, but no need to resort to that theorem:
Consider two distinct points $x$ and $y$. For $\theta<0$, their Gram matrix is
$$
\begin{bmatrix}
k(x, x) |
25,083 | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function? | This is an extended comment, please don't judge me too harshly.
Mercer's theorem characterizes the positive semidefinite (PSD) kernel which is of interest to OP. Mercer provides two conditions for a valid kernel:
The function is symmetric: $f(x,y)=f(y,x)$.
The resulting kernel matrix $K_{n\times n}$ is PSD for all valid inputs, which implies that its eigenvalues are all nonnegative. (Kernels may be restricted to only consider specific intervals or sets, so it's feasible to define a kernel that is PSD for just some input values.)
Let's approach the problem by cases.
Note that $\theta=0$ results in a matrix of 1s. It has rank 1, and has the eigenvalue 1 once and the remaining $n-1$ of its eigenvalues are 0. Hence, it is PSD.
For $\theta>0$, the farther apart two points are, the smaller the similarity between them. Unless two points are identical, the off-diagonal elements of $K$ are less than 1, and the diagonal elements are 1.
We can use the same reasoning to show that for $\theta<0$, $K$ is not diagonally dominant; that is, non-idential elements will have larger entries on the off-diagonal than the diagonal (because $f(x,y;\theta<0)$ is convex with a minimum at 1). I think that we could get clever with the Girshgorin circle theorem to show that in this case, the matrix is indefinite, but I've tried and am stuck. I'll keep thinking about it. | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function? | This is an extended comment, please don't judge me too harshly.
Mercer's theorem characterizes the positive semidefinite (PSD) kernel which is of interest to OP. Mercer provides two conditions for a v | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function?
This is an extended comment, please don't judge me too harshly.
Mercer's theorem characterizes the positive semidefinite (PSD) kernel which is of interest to OP. Mercer provides two conditions for a valid kernel:
The function is symmetric: $f(x,y)=f(y,x)$.
The resulting kernel matrix $K_{n\times n}$ is PSD for all valid inputs, which implies that its eigenvalues are all nonnegative. (Kernels may be restricted to only consider specific intervals or sets, so it's feasible to define a kernel that is PSD for just some input values.)
Let's approach the problem by cases.
Note that $\theta=0$ results in a matrix of 1s. It has rank 1, and has the eigenvalue 1 once and the remaining $n-1$ of its eigenvalues are 0. Hence, it is PSD.
For $\theta>0$, the farther apart two points are, the smaller the similarity between them. Unless two points are identical, the off-diagonal elements of $K$ are less than 1, and the diagonal elements are 1.
We can use the same reasoning to show that for $\theta<0$, $K$ is not diagonally dominant; that is, non-idential elements will have larger entries on the off-diagonal than the diagonal (because $f(x,y;\theta<0)$ is convex with a minimum at 1). I think that we could get clever with the Girshgorin circle theorem to show that in this case, the matrix is indefinite, but I've tried and am stuck. I'll keep thinking about it. | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function?
This is an extended comment, please don't judge me too harshly.
Mercer's theorem characterizes the positive semidefinite (PSD) kernel which is of interest to OP. Mercer provides two conditions for a v |
25,084 | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function? | After some more thinking I will make an attempt to answer my own question. From Bishop's Pattern Recognition and Machine Learning, p. 296, I take rules for building new Kernels from valid Kernels. Let $k_1$ be a valid Kernel then
$$ k(x_n,x_m) = f(x) k_1(x_n,x_m) f(x^T) $$
$$ k(x_n,x_m) = \exp(k_1(x_n,x_m)) $$
are again valid Kernels. Now we have
$$\frac{\theta}{2} \lVert x_n-x_m \rVert^2 = \frac{\theta}{2} x_n^T x_n + \frac{\theta}{2} x_m^T x_m - \theta x_n^T x_m$$
So
$$\exp (-\frac{\theta}{2} \lVert x_n-x_m \rVert^2)= \exp (-\frac{\theta}{2} x_n^T x_n) \exp (\theta x_n^T x_m) \exp (-\frac{\theta}{2} x_m^T x_m)$$
Hence by the second rule from above and since we know $x_n^T x_m$ is a valid kernel, $\exp (\theta x_n^T x_m) $ is a valid kernel if $\theta>0$, but it is not if $\theta<0$. By the first rule then $\exp (-\frac{\theta}{2} \lVert x_n-x_m \rVert^2)$ is a valid kernel if $\theta>0$ but not if $\theta<0$. I am not sure about this though. Comments welcome. | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function? | After some more thinking I will make an attempt to answer my own question. From Bishop's Pattern Recognition and Machine Learning, p. 296, I take rules for building new Kernels from valid Kernels. Let | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function?
After some more thinking I will make an attempt to answer my own question. From Bishop's Pattern Recognition and Machine Learning, p. 296, I take rules for building new Kernels from valid Kernels. Let $k_1$ be a valid Kernel then
$$ k(x_n,x_m) = f(x) k_1(x_n,x_m) f(x^T) $$
$$ k(x_n,x_m) = \exp(k_1(x_n,x_m)) $$
are again valid Kernels. Now we have
$$\frac{\theta}{2} \lVert x_n-x_m \rVert^2 = \frac{\theta}{2} x_n^T x_n + \frac{\theta}{2} x_m^T x_m - \theta x_n^T x_m$$
So
$$\exp (-\frac{\theta}{2} \lVert x_n-x_m \rVert^2)= \exp (-\frac{\theta}{2} x_n^T x_n) \exp (\theta x_n^T x_m) \exp (-\frac{\theta}{2} x_m^T x_m)$$
Hence by the second rule from above and since we know $x_n^T x_m$ is a valid kernel, $\exp (\theta x_n^T x_m) $ is a valid kernel if $\theta>0$, but it is not if $\theta<0$. By the first rule then $\exp (-\frac{\theta}{2} \lVert x_n-x_m \rVert^2)$ is a valid kernel if $\theta>0$ but not if $\theta<0$. I am not sure about this though. Comments welcome. | Is the Gaussian Kernel still a valid Kernel when taking the negative of the inner function?
After some more thinking I will make an attempt to answer my own question. From Bishop's Pattern Recognition and Machine Learning, p. 296, I take rules for building new Kernels from valid Kernels. Let |
25,085 | Using MSE instead of log-loss in logistic regression | The short answer is that likelihood theory exists to guide us towards optimum solutions, and maximizing something other than the likelihood, penalized likelihood, or Bayesian posterior density results in suboptimal estimators. Secondly, minimizing sum of squared errors leads to unbiased estimates of true probabilities. Here you do not desire unbiased estimates, because to have that estimates can be negative or greater than one. To properly constrain estimates requires one to get slightly biased estimates (towards the middle) in general, on the probability (not the logit) scale.
Don't believe that machine learning methods do not make assumptions. This issue has little to do with machine learning.
Note that an individual proportion is an unbiased estimate of the true probability, hence a binary logistic model with only an intercept provides an unbiased estimate. A binary logistic model with a single predictor that has $k$ mutually exclusive categories will provide $k$ unbiased estimates of probabilities. I think that a model that capitalizes on additivity assumptions and allows the user to request estimates outside the data range (e.g., a single predictor that is continuous) will have a small bias on the probability scale so as to respect the $[0,1]$ constraint. | Using MSE instead of log-loss in logistic regression | The short answer is that likelihood theory exists to guide us towards optimum solutions, and maximizing something other than the likelihood, penalized likelihood, or Bayesian posterior density results | Using MSE instead of log-loss in logistic regression
The short answer is that likelihood theory exists to guide us towards optimum solutions, and maximizing something other than the likelihood, penalized likelihood, or Bayesian posterior density results in suboptimal estimators. Secondly, minimizing sum of squared errors leads to unbiased estimates of true probabilities. Here you do not desire unbiased estimates, because to have that estimates can be negative or greater than one. To properly constrain estimates requires one to get slightly biased estimates (towards the middle) in general, on the probability (not the logit) scale.
Don't believe that machine learning methods do not make assumptions. This issue has little to do with machine learning.
Note that an individual proportion is an unbiased estimate of the true probability, hence a binary logistic model with only an intercept provides an unbiased estimate. A binary logistic model with a single predictor that has $k$ mutually exclusive categories will provide $k$ unbiased estimates of probabilities. I think that a model that capitalizes on additivity assumptions and allows the user to request estimates outside the data range (e.g., a single predictor that is continuous) will have a small bias on the probability scale so as to respect the $[0,1]$ constraint. | Using MSE instead of log-loss in logistic regression
The short answer is that likelihood theory exists to guide us towards optimum solutions, and maximizing something other than the likelihood, penalized likelihood, or Bayesian posterior density results |
25,086 | Using MSE instead of log-loss in logistic regression | Although Frank Harrell's answer is correct, I think it misses the scope of the question. The answer to your question is yes, MSE would make sense in a ML nonparametric scenario. The ML equivalent of logistic regression is the linear perceptron, which makes no assumptions and does use MSE as a cost function. It uses online gradient descent for parameter training and, since it solves a convex optimisation problem, parameter estimates should be at the global optimum. The main difference between the two methods is that with the nonparametric approach you don't get confidence intervals and p-values and therefore you cannot use your model for inference, you can only use it for prediction.
The Linear Perceptron makes no probabilistic assumptions. There is the assumption on the data that it is linearly separable, but this is not an assumption on the model. MSE could be in theory affected by heteroscedasticity but in practice this effect is nullified by the activation function. | Using MSE instead of log-loss in logistic regression | Although Frank Harrell's answer is correct, I think it misses the scope of the question. The answer to your question is yes, MSE would make sense in a ML nonparametric scenario. The ML equivalent of l | Using MSE instead of log-loss in logistic regression
Although Frank Harrell's answer is correct, I think it misses the scope of the question. The answer to your question is yes, MSE would make sense in a ML nonparametric scenario. The ML equivalent of logistic regression is the linear perceptron, which makes no assumptions and does use MSE as a cost function. It uses online gradient descent for parameter training and, since it solves a convex optimisation problem, parameter estimates should be at the global optimum. The main difference between the two methods is that with the nonparametric approach you don't get confidence intervals and p-values and therefore you cannot use your model for inference, you can only use it for prediction.
The Linear Perceptron makes no probabilistic assumptions. There is the assumption on the data that it is linearly separable, but this is not an assumption on the model. MSE could be in theory affected by heteroscedasticity but in practice this effect is nullified by the activation function. | Using MSE instead of log-loss in logistic regression
Although Frank Harrell's answer is correct, I think it misses the scope of the question. The answer to your question is yes, MSE would make sense in a ML nonparametric scenario. The ML equivalent of l |
25,087 | What are the consequences of "copying" a data set for OLS? | Do you have a good reason to do the doubling (or duplication?) It doesn't make much statistical sense, but still it is interesting to see what happens algebraically. In matrix form your linear model is
$$ \DeclareMathOperator{\V}{\mathbb{V}}
Y = X \beta + E,
$$
the least square estimator is $\hat{\beta}_{\text{ols}} = (X^T X)^{-1} X^T Y $ and the variance matrix is $ \V \hat{\beta}_{\text{ols}}= \sigma^2 (X^t X)^{-1} $. "Doubling the data" means that $Y$ is replaced by $\begin{pmatrix} Y \\ Y \end{pmatrix}$ and $X$ is replaced by $\begin{pmatrix} X \\ X \end{pmatrix}$. The ordinary least squares estimator then becomes
$$
\left(\begin{pmatrix}X \\ X \end{pmatrix}^T \begin{pmatrix} X \\ X \end{pmatrix} \right )^{-1} \begin{pmatrix} X \\ X \end{pmatrix}^T \begin{pmatrix} Y \\ Y \end{pmatrix} = \\
(x^T X + X^T X)^{-1} (X^T Y + X^T Y ) = (2 X^T X)^{-1} 2 X^T Y = \\
\hat{\beta}_{\text{ols}}
$$
so the calculated estimator doesn't change at all. But the calculated variance matrix becomes wrong: Using the same kind of algebra as above, we get the variance matrix $\frac{\sigma^2}{2}(X^T X)^{-1}$, half of the correct value. A consequence is that confidence intervals will shrink with a factor of $\frac{1}{\sqrt{2}}$.
The reason is that we have calculated as if we still have iid data, which is untrue: the pair of doubled values obviously have a correlation equal to $1.0$. If we take this into account and use weighted least squares correctly, we will find the correct variance matrix.
From this, more consequences of the doubling will be easy to find as an exercise, for instance, the value of R-squared will not change. | What are the consequences of "copying" a data set for OLS? | Do you have a good reason to do the doubling (or duplication?) It doesn't make much statistical sense, but still it is interesting to see what happens algebraically. In matrix form your linear model | What are the consequences of "copying" a data set for OLS?
Do you have a good reason to do the doubling (or duplication?) It doesn't make much statistical sense, but still it is interesting to see what happens algebraically. In matrix form your linear model is
$$ \DeclareMathOperator{\V}{\mathbb{V}}
Y = X \beta + E,
$$
the least square estimator is $\hat{\beta}_{\text{ols}} = (X^T X)^{-1} X^T Y $ and the variance matrix is $ \V \hat{\beta}_{\text{ols}}= \sigma^2 (X^t X)^{-1} $. "Doubling the data" means that $Y$ is replaced by $\begin{pmatrix} Y \\ Y \end{pmatrix}$ and $X$ is replaced by $\begin{pmatrix} X \\ X \end{pmatrix}$. The ordinary least squares estimator then becomes
$$
\left(\begin{pmatrix}X \\ X \end{pmatrix}^T \begin{pmatrix} X \\ X \end{pmatrix} \right )^{-1} \begin{pmatrix} X \\ X \end{pmatrix}^T \begin{pmatrix} Y \\ Y \end{pmatrix} = \\
(x^T X + X^T X)^{-1} (X^T Y + X^T Y ) = (2 X^T X)^{-1} 2 X^T Y = \\
\hat{\beta}_{\text{ols}}
$$
so the calculated estimator doesn't change at all. But the calculated variance matrix becomes wrong: Using the same kind of algebra as above, we get the variance matrix $\frac{\sigma^2}{2}(X^T X)^{-1}$, half of the correct value. A consequence is that confidence intervals will shrink with a factor of $\frac{1}{\sqrt{2}}$.
The reason is that we have calculated as if we still have iid data, which is untrue: the pair of doubled values obviously have a correlation equal to $1.0$. If we take this into account and use weighted least squares correctly, we will find the correct variance matrix.
From this, more consequences of the doubling will be easy to find as an exercise, for instance, the value of R-squared will not change. | What are the consequences of "copying" a data set for OLS?
Do you have a good reason to do the doubling (or duplication?) It doesn't make much statistical sense, but still it is interesting to see what happens algebraically. In matrix form your linear model |
25,088 | What are the consequences of "copying" a data set for OLS? | I am not yet familiar enough with the theory to give you a very mathematical answer, but intuitively, OLS only cares about proportions in which different cases are present. This makes sense when you recall that OLS chooses the coefficients that minimize the mean of the squared residuals, and the mean reflects purely the proportions of its inputs (in the sense that the mean of (1, 3, 3) is the same as the mean of a dataset with a million 1s and two million 3s). So, doubling the dataset will get you the identical model.
Here's an R example, where we generate a random regression problem and notice that the coefficients are unchanged when doubling the data:
nc = sample(1:10, 1, replace = T)
n = sample(11:500, 1, replace = T)
x = as.matrix(replicate(nc, rnorm(n)))
coef = rnorm(nc)
sd.resid = runif(1, 0, 5)
y = x %*% matrix(coef) + rnorm(n, sd = sd.resid)
print(cbind(
coef(lm(y ~ x)),
coef(lm(c(y, y) ~ rbind(x, x)))))
One run gives me:
[,1] [,2]
(Intercept) -0.10002238 -0.10002238
x1 -2.14801619 -2.14801619
x2 0.23120764 0.23120764
x3 0.05360792 0.05360792
x4 1.91972198 1.91972198
x5 -1.09887264 -1.09887264
x6 0.04248358 0.04248358 | What are the consequences of "copying" a data set for OLS? | I am not yet familiar enough with the theory to give you a very mathematical answer, but intuitively, OLS only cares about proportions in which different cases are present. This makes sense when you r | What are the consequences of "copying" a data set for OLS?
I am not yet familiar enough with the theory to give you a very mathematical answer, but intuitively, OLS only cares about proportions in which different cases are present. This makes sense when you recall that OLS chooses the coefficients that minimize the mean of the squared residuals, and the mean reflects purely the proportions of its inputs (in the sense that the mean of (1, 3, 3) is the same as the mean of a dataset with a million 1s and two million 3s). So, doubling the dataset will get you the identical model.
Here's an R example, where we generate a random regression problem and notice that the coefficients are unchanged when doubling the data:
nc = sample(1:10, 1, replace = T)
n = sample(11:500, 1, replace = T)
x = as.matrix(replicate(nc, rnorm(n)))
coef = rnorm(nc)
sd.resid = runif(1, 0, 5)
y = x %*% matrix(coef) + rnorm(n, sd = sd.resid)
print(cbind(
coef(lm(y ~ x)),
coef(lm(c(y, y) ~ rbind(x, x)))))
One run gives me:
[,1] [,2]
(Intercept) -0.10002238 -0.10002238
x1 -2.14801619 -2.14801619
x2 0.23120764 0.23120764
x3 0.05360792 0.05360792
x4 1.91972198 1.91972198
x5 -1.09887264 -1.09887264
x6 0.04248358 0.04248358 | What are the consequences of "copying" a data set for OLS?
I am not yet familiar enough with the theory to give you a very mathematical answer, but intuitively, OLS only cares about proportions in which different cases are present. This makes sense when you r |
25,089 | Seasonality not taken account of in `auto.arima()` | (First off, cmort is already a ts object with frequency 52, so you don't need to coerce it.)
I'd say seasonality is visible, not that it is blatant:
library(forecast)
library(astsa)
seasonplot(cmort)
Per the help page (?auto.arima), auto.arima() decides whether or not to take seasonal differences by using a OCSB test. It's quite possible that this test simply got it wrong in this instance; it's a statistical test, after all. You can force a seasonal model by setting D=1, although auto.arima() runs for quite some time with forced seasonality. (Note that the information criteria are not comparable between the original and the differenced series.)
Auto-fitted model:
> auto.arima(cmort)
Series: cmort
ARIMA(2,1,1)
Coefficients:
ar1 ar2 ma1
0.0957 0.2515 -0.6435
s.e. 0.4302 0.2444 0.4155
sigma^2 estimated as 33.72: log likelihood=-1609.89
AIC=3227.77 AICc=3227.85 BIC=3244.68
Model with forced seasonality:
> auto.arima(cmort,D=1)
Series: cmort
ARIMA(0,0,0)(1,1,0)[52] with drift
Coefficients:
sar1 drift
-0.5737 -0.0257
s.e. 0.0378 0.0041
sigma^2 estimated as 47.7: log likelihood=-1537.6
AIC=3081.21 AICc=3081.26 BIC=3093.57 | Seasonality not taken account of in `auto.arima()` | (First off, cmort is already a ts object with frequency 52, so you don't need to coerce it.)
I'd say seasonality is visible, not that it is blatant:
library(forecast)
library(astsa)
seasonplot(cmort)
| Seasonality not taken account of in `auto.arima()`
(First off, cmort is already a ts object with frequency 52, so you don't need to coerce it.)
I'd say seasonality is visible, not that it is blatant:
library(forecast)
library(astsa)
seasonplot(cmort)
Per the help page (?auto.arima), auto.arima() decides whether or not to take seasonal differences by using a OCSB test. It's quite possible that this test simply got it wrong in this instance; it's a statistical test, after all. You can force a seasonal model by setting D=1, although auto.arima() runs for quite some time with forced seasonality. (Note that the information criteria are not comparable between the original and the differenced series.)
Auto-fitted model:
> auto.arima(cmort)
Series: cmort
ARIMA(2,1,1)
Coefficients:
ar1 ar2 ma1
0.0957 0.2515 -0.6435
s.e. 0.4302 0.2444 0.4155
sigma^2 estimated as 33.72: log likelihood=-1609.89
AIC=3227.77 AICc=3227.85 BIC=3244.68
Model with forced seasonality:
> auto.arima(cmort,D=1)
Series: cmort
ARIMA(0,0,0)(1,1,0)[52] with drift
Coefficients:
sar1 drift
-0.5737 -0.0257
s.e. 0.0378 0.0041
sigma^2 estimated as 47.7: log likelihood=-1537.6
AIC=3081.21 AICc=3081.26 BIC=3093.57 | Seasonality not taken account of in `auto.arima()`
(First off, cmort is already a ts object with frequency 52, so you don't need to coerce it.)
I'd say seasonality is visible, not that it is blatant:
library(forecast)
library(astsa)
seasonplot(cmort)
|
25,090 | Seasonality not taken account of in `auto.arima()` | A glance at the manual for auto.arima shows that an explanation of precisely why it found the solution it did in this case would be complicated: depending on the fitting algorithm (conditional least squares by default); on the details of the stepwise selection procedure, & the criteria used (approximate AICc by default); & on the particular configuration & the sequence of the stationarity tests carried out. Nevertheless, I daresay that ARIMA(2,1,1) is a perfectly good model for one-step-ahead forecasts, because the evident smoothness of the seasonality means that knowing the observed value from exactly one year ago will give you little more information about this week's likely value than just knowing the last couple of weeks' observations.
If you want to forecast over the next year or two, you will need to take seasonality into account. Rather than taking seasonal differences, or looking for seasonal autoregressive or moving average terms, or estimating 52 fixed seasonal effects; you might be better off taking advantage of the smoothness & regressing on a few Fourier terms, as explained by @Glen_b here. (This also makes it easy to allow for non-integer frequencies—as @RichardHardy ponts out might be appropriate in this case (if the extra day or two each year weren't simply dropped).) Your model will then have deterministic, but smoothed, seasonal effects, & you can still allow ARIMA errors:
$$
y_t = \alpha + \sum_{i=1}^k \beta_i \sin \left(i \cdot \frac{2 \pi}{\omega}\cdot t\right)
+ \sum_{i=1}^k \gamma_i \cos\left(i \cdot \frac{2 \pi}{\omega} \cdot t \right)
+ \frac{1+\sum_{i=1}^q \theta_i B^i}{(1-B)^d\left(1-\sum_{i=1}^p \phi_i B^i\right)}\cdot\varepsilon_t
$$
$$
\varepsilon\sim\mathrm{WN}(\sigma^2)
$$
The frequency $\omega$ is assumed known. The parameters you need to estimate are: $\alpha$, the intercept; the $\beta$s & $\gamma$s, the coefficients of the sine & cosine terms terms; the $\phi$s & $\theta$'s, the autoregressive & moving average coefficients; & $\sigma^2$, the variance of the white noise innovations. The orders for the $\mathrm{ARIMA}(p,d,q)$ errors & the number of harmonics $k$ can be chosen heuristically or by using significance tests/information criteria.
The forecast package has a function to create the Fourier terms; here's an illustration:
library(astsa)
library(forecast)
# make a training set & test set
window(cmort, start=c(1970,1), end=c(1977,40)) -> cmort.train
window(cmort, start=c(1977,41), end=c(1979,40)) -> cmort.test
# fit non-seasonal & seasonally-differenced models for comparison
Arima(cmort.train, order=c(2,1,1)) -> mod.ns
Arima(cmort.train, seasonal=c(1,1,0), include.drift=T) -> mod.sd
# make predictors
fourier(cmort, K=10) -> fourier.terms
fourier.terms.train <- fourier.terms[1:length(cmort.train),]
fourier.terms.test <- fourier.terms[(length(cmort.train)+1):length(cmort),]
# plot first 5 harmonics
plot(cmort.train, col="grey")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:2])), col="red")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:4])), col="darkorange")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:6])), col="green")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:8])), col="blue")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:10])), col="violet")
Up to the third harmonic seems to be enough, and you still need to difference.
# fit models
Arima(cmort.train, order=c(0,1,0), xreg=(fourier.terms.train[,1:6])) -> mod.ft3.df
acf(residuals(mod.ft3.df), ci.type="ma", lag.max=52)
acf(residuals(mod.ft3.df), type="partial", lag.max=52)
Arima(cmort.train, order=c(2,1,0), xreg=(fourier.terms.train[,1:6])) -> mod.ft3.df.ar2
acf(residuals(mod.ft3.df.ar2), lag.max=52)
acf(residuals(mod.ft3.df.ar2), type="partial", lag.max=52)
Examining correlograms suggests a couple of AR terms will do to leave the residuals looking like white noise. Or you can investigate the number of harmonics to use, as well as the ARMA structure, usng auto.arima:
# auto.arima
auto.arima(cmort.train, xreg=fourier.terms.train[,1:2], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto1
auto.arima(cmort.train, xreg=fourier.terms.train[,1:4], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto2
auto.arima(cmort.train, xreg=fourier.terms.train[,1:6], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto3
auto.arima(cmort.train, xreg=fourier.terms.train[,1:8], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto4
auto.arima(cmort.train, xreg=fourier.terms.train[,1:10], seasonal=F, d=1, allowdrift=T, stepwise=F, approximation=F) -> auto5
auto1
auto2
auto3
auto4
auto5
The ARMA(2,1) structure is found by auto.arima's minimizing the AICc for the model with 4 harmonics on differenced observations, & has the lowest AICc overall.
# look at accuracy on test set
plot(cmort.test, col="grey")
lines(forecast(mod.ns,h=length(cmort.test))$mean, col="red")
lines(forecast(mod.sd,h=length(cmort.test))$mean, col="darkorange")
lines(forecast(mod.ft3.df.ar2,h=length(cmort.test), xreg=fourier.terms.test[,1:6])$mean, col="green")
lines(forecast(auto4,h=length(cmort.test), xreg=fourier.terms.test[,1:8])$mean, col="blue")
accuracy(forecast(mod.ns,h=length(cmort.test)),cmort.test)
accuracy(forecast(mod.sd,h=length(cmort.test)),cmort.test)
accuracy(forecast(mod.ft3.df.ar2,h=length(cmort.test),xreg=fourier.terms.test[,1:6]),cmort.test)
accuracy(forecast(auto4,h=length(cmort.test),xreg=fourier.terms.test[,1:8]),cmort.test)
Summarizing the root mean square errors shows that both the harmonic models perform better on the test set, with little to choose between them:
$$
\begin{array}{l,l,l}
&\text{Training} & \text{Test}\\
\mathrm{ARIMA}(2,1,1) & 5.729 & 7.657\\
\mathrm{SARIMA}(1,1,0)_{52}\text{ with drift} & 6.481 & 7.390\\
\text{3 harmonics, }\mathrm{ARIMA}(2,1,0) & 5.578 & 5.151\\
\text{4 harmonics, }\mathrm{ARIMA}(2,1,1) & 5.219 & 5.188
\end{array}
$$ | Seasonality not taken account of in `auto.arima()` | A glance at the manual for auto.arima shows that an explanation of precisely why it found the solution it did in this case would be complicated: depending on the fitting algorithm (conditional least s | Seasonality not taken account of in `auto.arima()`
A glance at the manual for auto.arima shows that an explanation of precisely why it found the solution it did in this case would be complicated: depending on the fitting algorithm (conditional least squares by default); on the details of the stepwise selection procedure, & the criteria used (approximate AICc by default); & on the particular configuration & the sequence of the stationarity tests carried out. Nevertheless, I daresay that ARIMA(2,1,1) is a perfectly good model for one-step-ahead forecasts, because the evident smoothness of the seasonality means that knowing the observed value from exactly one year ago will give you little more information about this week's likely value than just knowing the last couple of weeks' observations.
If you want to forecast over the next year or two, you will need to take seasonality into account. Rather than taking seasonal differences, or looking for seasonal autoregressive or moving average terms, or estimating 52 fixed seasonal effects; you might be better off taking advantage of the smoothness & regressing on a few Fourier terms, as explained by @Glen_b here. (This also makes it easy to allow for non-integer frequencies—as @RichardHardy ponts out might be appropriate in this case (if the extra day or two each year weren't simply dropped).) Your model will then have deterministic, but smoothed, seasonal effects, & you can still allow ARIMA errors:
$$
y_t = \alpha + \sum_{i=1}^k \beta_i \sin \left(i \cdot \frac{2 \pi}{\omega}\cdot t\right)
+ \sum_{i=1}^k \gamma_i \cos\left(i \cdot \frac{2 \pi}{\omega} \cdot t \right)
+ \frac{1+\sum_{i=1}^q \theta_i B^i}{(1-B)^d\left(1-\sum_{i=1}^p \phi_i B^i\right)}\cdot\varepsilon_t
$$
$$
\varepsilon\sim\mathrm{WN}(\sigma^2)
$$
The frequency $\omega$ is assumed known. The parameters you need to estimate are: $\alpha$, the intercept; the $\beta$s & $\gamma$s, the coefficients of the sine & cosine terms terms; the $\phi$s & $\theta$'s, the autoregressive & moving average coefficients; & $\sigma^2$, the variance of the white noise innovations. The orders for the $\mathrm{ARIMA}(p,d,q)$ errors & the number of harmonics $k$ can be chosen heuristically or by using significance tests/information criteria.
The forecast package has a function to create the Fourier terms; here's an illustration:
library(astsa)
library(forecast)
# make a training set & test set
window(cmort, start=c(1970,1), end=c(1977,40)) -> cmort.train
window(cmort, start=c(1977,41), end=c(1979,40)) -> cmort.test
# fit non-seasonal & seasonally-differenced models for comparison
Arima(cmort.train, order=c(2,1,1)) -> mod.ns
Arima(cmort.train, seasonal=c(1,1,0), include.drift=T) -> mod.sd
# make predictors
fourier(cmort, K=10) -> fourier.terms
fourier.terms.train <- fourier.terms[1:length(cmort.train),]
fourier.terms.test <- fourier.terms[(length(cmort.train)+1):length(cmort),]
# plot first 5 harmonics
plot(cmort.train, col="grey")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:2])), col="red")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:4])), col="darkorange")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:6])), col="green")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:8])), col="blue")
lines(fitted(Arima(cmort.train, order=c(0,0,0), xreg=fourier.terms.train[,1:10])), col="violet")
Up to the third harmonic seems to be enough, and you still need to difference.
# fit models
Arima(cmort.train, order=c(0,1,0), xreg=(fourier.terms.train[,1:6])) -> mod.ft3.df
acf(residuals(mod.ft3.df), ci.type="ma", lag.max=52)
acf(residuals(mod.ft3.df), type="partial", lag.max=52)
Arima(cmort.train, order=c(2,1,0), xreg=(fourier.terms.train[,1:6])) -> mod.ft3.df.ar2
acf(residuals(mod.ft3.df.ar2), lag.max=52)
acf(residuals(mod.ft3.df.ar2), type="partial", lag.max=52)
Examining correlograms suggests a couple of AR terms will do to leave the residuals looking like white noise. Or you can investigate the number of harmonics to use, as well as the ARMA structure, usng auto.arima:
# auto.arima
auto.arima(cmort.train, xreg=fourier.terms.train[,1:2], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto1
auto.arima(cmort.train, xreg=fourier.terms.train[,1:4], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto2
auto.arima(cmort.train, xreg=fourier.terms.train[,1:6], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto3
auto.arima(cmort.train, xreg=fourier.terms.train[,1:8], seasonal=F, d=1, allowdrift, stepwise=F, approximation=F) -> auto4
auto.arima(cmort.train, xreg=fourier.terms.train[,1:10], seasonal=F, d=1, allowdrift=T, stepwise=F, approximation=F) -> auto5
auto1
auto2
auto3
auto4
auto5
The ARMA(2,1) structure is found by auto.arima's minimizing the AICc for the model with 4 harmonics on differenced observations, & has the lowest AICc overall.
# look at accuracy on test set
plot(cmort.test, col="grey")
lines(forecast(mod.ns,h=length(cmort.test))$mean, col="red")
lines(forecast(mod.sd,h=length(cmort.test))$mean, col="darkorange")
lines(forecast(mod.ft3.df.ar2,h=length(cmort.test), xreg=fourier.terms.test[,1:6])$mean, col="green")
lines(forecast(auto4,h=length(cmort.test), xreg=fourier.terms.test[,1:8])$mean, col="blue")
accuracy(forecast(mod.ns,h=length(cmort.test)),cmort.test)
accuracy(forecast(mod.sd,h=length(cmort.test)),cmort.test)
accuracy(forecast(mod.ft3.df.ar2,h=length(cmort.test),xreg=fourier.terms.test[,1:6]),cmort.test)
accuracy(forecast(auto4,h=length(cmort.test),xreg=fourier.terms.test[,1:8]),cmort.test)
Summarizing the root mean square errors shows that both the harmonic models perform better on the test set, with little to choose between them:
$$
\begin{array}{l,l,l}
&\text{Training} & \text{Test}\\
\mathrm{ARIMA}(2,1,1) & 5.729 & 7.657\\
\mathrm{SARIMA}(1,1,0)_{52}\text{ with drift} & 6.481 & 7.390\\
\text{3 harmonics, }\mathrm{ARIMA}(2,1,0) & 5.578 & 5.151\\
\text{4 harmonics, }\mathrm{ARIMA}(2,1,1) & 5.219 & 5.188
\end{array}
$$ | Seasonality not taken account of in `auto.arima()`
A glance at the manual for auto.arima shows that an explanation of precisely why it found the solution it did in this case would be complicated: depending on the fitting algorithm (conditional least s |
25,091 | Seasonality not taken account of in `auto.arima()` | I say that the seasonality is blatant.
I ran this through Autobox(I am affiliated) and there is also a blatant downward trend in the data and some outliers too. | Seasonality not taken account of in `auto.arima()` | I say that the seasonality is blatant.
I ran this through Autobox(I am affiliated) and there is also a blatant downward trend in the data and some outliers too. | Seasonality not taken account of in `auto.arima()`
I say that the seasonality is blatant.
I ran this through Autobox(I am affiliated) and there is also a blatant downward trend in the data and some outliers too. | Seasonality not taken account of in `auto.arima()`
I say that the seasonality is blatant.
I ran this through Autobox(I am affiliated) and there is also a blatant downward trend in the data and some outliers too. |
25,092 | Interpretation of Total Law of Covariance | The first term (i): $E[\operatorname{cov}(X,Y|Z)]$
Think of $\operatorname{cov}(X,Y)$ as a function of $Z$. As you examine different values of $Z$, you will correspondingly get a value for $\operatorname{cov}(X,Y)$. The expectation simply averages these different covariances with respect to $Z$.
The second term (ii): $\operatorname{cov}([E[X|Z],E[Y|Z])$
Think of $E[X|Z]$ and $E[Y|Z]$ as functions of $Z$. As you examine different values of $Z$, you will correspondingly get a value of $E[X|Z]$ and a value of $E[Y|Z]$ realized simultaneously. Therefore, for every value of $Z$, you will get an $(X, Y)$ coordinate. This term is simply the covariance of all these coordinate points. | Interpretation of Total Law of Covariance | The first term (i): $E[\operatorname{cov}(X,Y|Z)]$
Think of $\operatorname{cov}(X,Y)$ as a function of $Z$. As you examine different values of $Z$, you will correspondingly get a value for $\operator | Interpretation of Total Law of Covariance
The first term (i): $E[\operatorname{cov}(X,Y|Z)]$
Think of $\operatorname{cov}(X,Y)$ as a function of $Z$. As you examine different values of $Z$, you will correspondingly get a value for $\operatorname{cov}(X,Y)$. The expectation simply averages these different covariances with respect to $Z$.
The second term (ii): $\operatorname{cov}([E[X|Z],E[Y|Z])$
Think of $E[X|Z]$ and $E[Y|Z]$ as functions of $Z$. As you examine different values of $Z$, you will correspondingly get a value of $E[X|Z]$ and a value of $E[Y|Z]$ realized simultaneously. Therefore, for every value of $Z$, you will get an $(X, Y)$ coordinate. This term is simply the covariance of all these coordinate points. | Interpretation of Total Law of Covariance
The first term (i): $E[\operatorname{cov}(X,Y|Z)]$
Think of $\operatorname{cov}(X,Y)$ as a function of $Z$. As you examine different values of $Z$, you will correspondingly get a value for $\operator |
25,093 | Interpretation of Total Law of Covariance | Another possible interpretation in a hierarchal framework is simple a decomposition of the total covariance $\operatorname{cov}(X,Y)$ into two terms:
the within group ($E[\operatorname{cov}(X,Y|Z)]$) and
between group $\operatorname{cov}([E[X|Z],E[Y|Z])$
covariances. The first term represents in this example the average of the covariances of $X$ and $Y$ evaluated for each group while the second term is the covariance of the group-averages for $X$ and $Y$. | Interpretation of Total Law of Covariance | Another possible interpretation in a hierarchal framework is simple a decomposition of the total covariance $\operatorname{cov}(X,Y)$ into two terms:
the within group ($E[\operatorname{cov}(X,Y|Z)]$) | Interpretation of Total Law of Covariance
Another possible interpretation in a hierarchal framework is simple a decomposition of the total covariance $\operatorname{cov}(X,Y)$ into two terms:
the within group ($E[\operatorname{cov}(X,Y|Z)]$) and
between group $\operatorname{cov}([E[X|Z],E[Y|Z])$
covariances. The first term represents in this example the average of the covariances of $X$ and $Y$ evaluated for each group while the second term is the covariance of the group-averages for $X$ and $Y$. | Interpretation of Total Law of Covariance
Another possible interpretation in a hierarchal framework is simple a decomposition of the total covariance $\operatorname{cov}(X,Y)$ into two terms:
the within group ($E[\operatorname{cov}(X,Y|Z)]$) |
25,094 | How to interpret an ANOVA table comparing full vs reduced OLS models? | I will answer your question with an example that (I hope) you can follow in [R]. If you don't use [R] you can still follow the results on this post.
I'll use the data set mtcars. You can find documentation of what it is about here. But just remember that there are 32 models, and for each one the miles-per-gallon, horse-power, and other variables are recorded. This is the beginning of it:
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
MODELS:
We'll run two almost random OLS regressions as follows:
fit1 <- lm(mpg ~ wt, mtcars) #mpg regressed on weight of the car
fit2 <- lm(mpg ~ wt + qsec, mtcars) #mpg regressed on weight and qsec
Notice that fit1 is a constrained model in the way that we force the regression coefficient for qsec in fit2 to be zero. fit2, conversely, is unconstrained.
ANOVA:
anova(fit1, fit2)
Analysis of Variance Table
Model 1: mpg ~ wt
Model 2: mpg ~ wt + qsec
Res.Df RSS Df Sum of Sq F Pr(>F)
1 30 278.32
2 29 195.46 1 82.858 12.293 0.0015 **
I won't enter into a lengthy explanation of what these values signify, but seeing where they come from will probably help you.
DEGREES OF FREEDOM:
1. Error or Residual Degrees of Freedom: We see them in the output of the anova call as Res. Df 30 and Res. Df 29. They are calculated as:
$\text{no. observations} - \text{no. indepen't variables} - 1 = 32 - 1 - 1 = \color{red}{30}$ for fit1, and $32-2-1 = \color{red}{29}$ for fit2. Remember that we have 32 car models.
2. Model Degrees of Freedom: It is equal to $\text{no. inepen't variables}.$
3. Total Degrees of Freedom: $\text{no. observations} -1.$
4. Constraints: The unconstrained model (fit2) has two independent variable, and hence, it is a model with $2$ degrees of freedom. In contrast, the constrained model (fit1) has only $1$ degree of freedom. The difference between $\text{model unconstrained df} - \text{model constrained df} =\color{red} 1$ is the number of constraints, shown on the output of the anova table as Df 1.
RESIDUAL SUM OF SQUARES & R SQUARED:
Let's calculate the RSS (residual sum of squares), also known as sum of squared errors (SSE), and the F value. To do so these are the pertinent manual calculations:
Mean dependent variable: $\bar y$
mu_mpg <- mean(mtcars$mpg) # Mean mpg in dataset
Total Sum of Squares (TSS): $\sum_1^n(y_i - \bar y)^2$
TSS <- sum((mtcars$mpg - mu_mpg)^2) # Total sum of squares
Model Sum of Squares (MSS): $\sum_1^n (\hat y_i-\bar y)^2$
MSS_fit1 <- sum((fitted(fit1) - mu_mpg)^2) # Variation accounted for by model
MSS_fit2 <- sum((fitted(fit2) - mu_mpg)^2) # Variation accounted for by model
Residual Sum of Squares (RSS, also SSE): $\sum_1^n(y_i - \hat y)^2$
RSS_fit1 <- sum((mtcars$mpg - fitted(fit1))^2) # Error sum of squares fit1
RSS_fit1 $\color{red}{278.3219}$
RSS_fit2 <- sum((mtcars$mpg - fitted(fit2))^2) # Error sum of squares fit2
RSS_fit2 $\color{red}{195.4636}$
Notice that the RSS column in the ANOVA table correspond to RSS_fit1 = 278.3219 and RSS_fit2 = 195.4636 of the manual calculations above.
In the ANOVA table we also have the difference in RSS: sum(residuals(fit1)^2)-sum(residuals(fit2)^2) = 82.85831, or calculated as indicated above:
$\text{RSS_fit1 - RSS_fit2} = \color{red}{82.85831}$, indicated in the anova table as Sum of Sq.
Fraction RSS/TSS:
Frac_RSS_fit1 <- RSS_fit1 / TSS # % Variation secndry to residuals fit1
Frac_RSS_fit2 <- RSS_fit2 / TSS # % Variation secndry to residuals fit2
R-squared of the model: $1 - RSS/TSS$
R.sq_fit1 <- 1 - Frac_RSS_fit1 # % Variation secndry to Model fit1
R.sq_fit1 $\color{blue}{0.7528328}$ Compare to summary(fit1)$r.square 0.7528328
R.sq_fit2 <- 1 - Frac_RSS_fit2 # % Variation secndry to Model fit2
R.sq_fit2 $\color{blue}{0.8264161}$ Compare to summary(fit2)$r.square 0.8264161
F VALUE:
n <- nrow(mtcars) # Number of subjects or observations
Constraints <- 1 # Constraints imposed or difference in iv's fit2 vs. fit1
UnConstrained <- 2 # Independent variables uncontrained model (fit2)
$\Large F = \frac{(R^2_{\text{mod.2}}-R^2_{\text{mod.1}})\,\times\, (N\,-\,\text{no. unconstrained}_{\text{mod.2}}\,-\,1)}{((1 - R^2_{\text{mod.2}})\,\times\, \text{no. constraints})}$
with $N$ corresponding to the number of observations; $\text{no. unconstrained}$, the number of independent variable in the full model; and $\text{no. constraints}$, the difference in independent variables between the full and the reduced model.
F_value=(R.sq_fit2 - R.sq_fit1) * (n - UnConstrained - 1) / ((1 - R.sq_fit2) * Constraints)
F_value # $\color{red}{12.29329}$
And the p-value, which in this case is 0.0015, which is significant. [R] has a system of stars to point out the level of significance, in this case p < 0.01.
In terms of a more graphical interpretation of the ANOVA of an OLS regression, we can visualize the model squared variation (MSS) for fit1 as the green lines in the plot below (equivalent to the "between groups" variance or signal). The RSS is exactly the sum of the length of the red segments separating the individual points from the fitted regression line (and corresponds to the "within group" variance or noise):
(Code here) | How to interpret an ANOVA table comparing full vs reduced OLS models? | I will answer your question with an example that (I hope) you can follow in [R]. If you don't use [R] you can still follow the results on this post.
I'll use the data set mtcars. You can find document | How to interpret an ANOVA table comparing full vs reduced OLS models?
I will answer your question with an example that (I hope) you can follow in [R]. If you don't use [R] you can still follow the results on this post.
I'll use the data set mtcars. You can find documentation of what it is about here. But just remember that there are 32 models, and for each one the miles-per-gallon, horse-power, and other variables are recorded. This is the beginning of it:
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
MODELS:
We'll run two almost random OLS regressions as follows:
fit1 <- lm(mpg ~ wt, mtcars) #mpg regressed on weight of the car
fit2 <- lm(mpg ~ wt + qsec, mtcars) #mpg regressed on weight and qsec
Notice that fit1 is a constrained model in the way that we force the regression coefficient for qsec in fit2 to be zero. fit2, conversely, is unconstrained.
ANOVA:
anova(fit1, fit2)
Analysis of Variance Table
Model 1: mpg ~ wt
Model 2: mpg ~ wt + qsec
Res.Df RSS Df Sum of Sq F Pr(>F)
1 30 278.32
2 29 195.46 1 82.858 12.293 0.0015 **
I won't enter into a lengthy explanation of what these values signify, but seeing where they come from will probably help you.
DEGREES OF FREEDOM:
1. Error or Residual Degrees of Freedom: We see them in the output of the anova call as Res. Df 30 and Res. Df 29. They are calculated as:
$\text{no. observations} - \text{no. indepen't variables} - 1 = 32 - 1 - 1 = \color{red}{30}$ for fit1, and $32-2-1 = \color{red}{29}$ for fit2. Remember that we have 32 car models.
2. Model Degrees of Freedom: It is equal to $\text{no. inepen't variables}.$
3. Total Degrees of Freedom: $\text{no. observations} -1.$
4. Constraints: The unconstrained model (fit2) has two independent variable, and hence, it is a model with $2$ degrees of freedom. In contrast, the constrained model (fit1) has only $1$ degree of freedom. The difference between $\text{model unconstrained df} - \text{model constrained df} =\color{red} 1$ is the number of constraints, shown on the output of the anova table as Df 1.
RESIDUAL SUM OF SQUARES & R SQUARED:
Let's calculate the RSS (residual sum of squares), also known as sum of squared errors (SSE), and the F value. To do so these are the pertinent manual calculations:
Mean dependent variable: $\bar y$
mu_mpg <- mean(mtcars$mpg) # Mean mpg in dataset
Total Sum of Squares (TSS): $\sum_1^n(y_i - \bar y)^2$
TSS <- sum((mtcars$mpg - mu_mpg)^2) # Total sum of squares
Model Sum of Squares (MSS): $\sum_1^n (\hat y_i-\bar y)^2$
MSS_fit1 <- sum((fitted(fit1) - mu_mpg)^2) # Variation accounted for by model
MSS_fit2 <- sum((fitted(fit2) - mu_mpg)^2) # Variation accounted for by model
Residual Sum of Squares (RSS, also SSE): $\sum_1^n(y_i - \hat y)^2$
RSS_fit1 <- sum((mtcars$mpg - fitted(fit1))^2) # Error sum of squares fit1
RSS_fit1 $\color{red}{278.3219}$
RSS_fit2 <- sum((mtcars$mpg - fitted(fit2))^2) # Error sum of squares fit2
RSS_fit2 $\color{red}{195.4636}$
Notice that the RSS column in the ANOVA table correspond to RSS_fit1 = 278.3219 and RSS_fit2 = 195.4636 of the manual calculations above.
In the ANOVA table we also have the difference in RSS: sum(residuals(fit1)^2)-sum(residuals(fit2)^2) = 82.85831, or calculated as indicated above:
$\text{RSS_fit1 - RSS_fit2} = \color{red}{82.85831}$, indicated in the anova table as Sum of Sq.
Fraction RSS/TSS:
Frac_RSS_fit1 <- RSS_fit1 / TSS # % Variation secndry to residuals fit1
Frac_RSS_fit2 <- RSS_fit2 / TSS # % Variation secndry to residuals fit2
R-squared of the model: $1 - RSS/TSS$
R.sq_fit1 <- 1 - Frac_RSS_fit1 # % Variation secndry to Model fit1
R.sq_fit1 $\color{blue}{0.7528328}$ Compare to summary(fit1)$r.square 0.7528328
R.sq_fit2 <- 1 - Frac_RSS_fit2 # % Variation secndry to Model fit2
R.sq_fit2 $\color{blue}{0.8264161}$ Compare to summary(fit2)$r.square 0.8264161
F VALUE:
n <- nrow(mtcars) # Number of subjects or observations
Constraints <- 1 # Constraints imposed or difference in iv's fit2 vs. fit1
UnConstrained <- 2 # Independent variables uncontrained model (fit2)
$\Large F = \frac{(R^2_{\text{mod.2}}-R^2_{\text{mod.1}})\,\times\, (N\,-\,\text{no. unconstrained}_{\text{mod.2}}\,-\,1)}{((1 - R^2_{\text{mod.2}})\,\times\, \text{no. constraints})}$
with $N$ corresponding to the number of observations; $\text{no. unconstrained}$, the number of independent variable in the full model; and $\text{no. constraints}$, the difference in independent variables between the full and the reduced model.
F_value=(R.sq_fit2 - R.sq_fit1) * (n - UnConstrained - 1) / ((1 - R.sq_fit2) * Constraints)
F_value # $\color{red}{12.29329}$
And the p-value, which in this case is 0.0015, which is significant. [R] has a system of stars to point out the level of significance, in this case p < 0.01.
In terms of a more graphical interpretation of the ANOVA of an OLS regression, we can visualize the model squared variation (MSS) for fit1 as the green lines in the plot below (equivalent to the "between groups" variance or signal). The RSS is exactly the sum of the length of the red segments separating the individual points from the fitted regression line (and corresponds to the "within group" variance or noise):
(Code here) | How to interpret an ANOVA table comparing full vs reduced OLS models?
I will answer your question with an example that (I hope) you can follow in [R]. If you don't use [R] you can still follow the results on this post.
I'll use the data set mtcars. You can find document |
25,095 | How to interpret an ANOVA table comparing full vs reduced OLS models? | The first line refers to Model 1, the model that includes $x_1, x_2, x_3, x_5$. This model has a residual degrees of freedom of 15.
The second line refers to Model 2, the model that adds $x_4$. Adding this additional independent variable decreases the residual d.f. to 14. | How to interpret an ANOVA table comparing full vs reduced OLS models? | The first line refers to Model 1, the model that includes $x_1, x_2, x_3, x_5$. This model has a residual degrees of freedom of 15.
The second line refers to Model 2, the model that adds $x_4$. Adding | How to interpret an ANOVA table comparing full vs reduced OLS models?
The first line refers to Model 1, the model that includes $x_1, x_2, x_3, x_5$. This model has a residual degrees of freedom of 15.
The second line refers to Model 2, the model that adds $x_4$. Adding this additional independent variable decreases the residual d.f. to 14. | How to interpret an ANOVA table comparing full vs reduced OLS models?
The first line refers to Model 1, the model that includes $x_1, x_2, x_3, x_5$. This model has a residual degrees of freedom of 15.
The second line refers to Model 2, the model that adds $x_4$. Adding |
25,096 | Interpreting ctree {partykit} output in R | So the 0.016 that you are seeing is the average of quotation while err is just the SSE.
I'm old school and don't know how to exactly show this using the new partykit package (maybe @Achim could illustrate), but I can show you how this done using the older party package.
So let's create some reproducible example
library(partykit)
airq <- subset(airquality, !is.na(Ozone))
airct <- ctree(Ozone ~ ., data = airq)
print(airct)
# Model formula:
# Ozone ~ Solar.R + Wind + Temp + Month + Day
#
# Fitted party:
# [1] root
# | [2] Temp <= 82
# | | [3] Wind <= 6.9: 55.600 (n = 10, err = 21946.4)
# | | [4] Wind > 6.9
# | | | [5] Temp <= 77: 18.479 (n = 48, err = 3956.0)
# | | | [6] Temp > 77: 31.143 (n = 21, err = 4620.6)
# | [7] Temp > 82
# | | [8] Wind <= 10.3: 81.633 (n = 30, err = 15119.0)
# | | [9] Wind > 10.3: 48.714 (n = 7, err = 1183.4)
#
# Number of inner nodes: 4
# Number of terminal nodes: 5
Now let's dtach the partykit package and fit the same tree using party and calculate the same values
detach("package:partykit", unload=TRUE)
library(party)
airct <- party::ctree(Ozone ~ ., data = airq)
t(sapply(unique(where(airct)), function(x) {
n <- nodes(airct, x)[[1]]
Ozone <- airq[as.logical(n$weights), "Ozone"]
cbind.data.frame("Node" = as.integer(x),
"n" = length(Ozone),
"Avg."= mean(Ozone),
"Variance"= var(Ozone),
"SSE" = sum((Ozone - mean(Ozone))^2))
}))
# Node n Avg. Variance SSE
# [1,] 5 48 18.47917 84.16977 3955.979
# [2,] 3 10 55.6 2438.489 21946.4
# [3,] 6 21 31.14286 231.0286 4620.571
# [4,] 9 7 48.71429 197.2381 1183.429
# [5,] 8 30 81.63333 521.3437 15118.97
I think it is easy to see from the output which is which
What the code above does is basically extract the information of Ozone information out of the fitted tree per each inner node and calculate the relevant statistics
As per the P-values, this seems like some type of printing bug, here's an example how you can calculate the P-values in the inner nodes
terNodes <- unique(where(airct))
setdiff(1:max(terNodes), terNodes)
sapply(setdiff(1:max(terNodes), terNodes), function(x) {
n <- nodes(airct, x)[[1]]
pvalue <- 1 - nodes(airct, x)[[1]]$criterion$maxcriterion
plab <- ifelse(pvalue < 10^(-3),
paste("p <", 10^(-3)),
paste("p =", round(pvalue, digits = 3)))
c("Node" = x, "P-value" = plab)
})
# [,1] [,2] [,3] [,4]
# Node "1" "2" "4" "7"
# P-value "p < 0.001" "p = 0.002" "p = 0.003" "p = 0.003"
As a side note, if quotation is a dummy variable, you should probably fit a classification tree (i.e. convert it to a factor) rather a regression tree like you are doing | Interpreting ctree {partykit} output in R | So the 0.016 that you are seeing is the average of quotation while err is just the SSE.
I'm old school and don't know how to exactly show this using the new partykit package (maybe @Achim could illus | Interpreting ctree {partykit} output in R
So the 0.016 that you are seeing is the average of quotation while err is just the SSE.
I'm old school and don't know how to exactly show this using the new partykit package (maybe @Achim could illustrate), but I can show you how this done using the older party package.
So let's create some reproducible example
library(partykit)
airq <- subset(airquality, !is.na(Ozone))
airct <- ctree(Ozone ~ ., data = airq)
print(airct)
# Model formula:
# Ozone ~ Solar.R + Wind + Temp + Month + Day
#
# Fitted party:
# [1] root
# | [2] Temp <= 82
# | | [3] Wind <= 6.9: 55.600 (n = 10, err = 21946.4)
# | | [4] Wind > 6.9
# | | | [5] Temp <= 77: 18.479 (n = 48, err = 3956.0)
# | | | [6] Temp > 77: 31.143 (n = 21, err = 4620.6)
# | [7] Temp > 82
# | | [8] Wind <= 10.3: 81.633 (n = 30, err = 15119.0)
# | | [9] Wind > 10.3: 48.714 (n = 7, err = 1183.4)
#
# Number of inner nodes: 4
# Number of terminal nodes: 5
Now let's dtach the partykit package and fit the same tree using party and calculate the same values
detach("package:partykit", unload=TRUE)
library(party)
airct <- party::ctree(Ozone ~ ., data = airq)
t(sapply(unique(where(airct)), function(x) {
n <- nodes(airct, x)[[1]]
Ozone <- airq[as.logical(n$weights), "Ozone"]
cbind.data.frame("Node" = as.integer(x),
"n" = length(Ozone),
"Avg."= mean(Ozone),
"Variance"= var(Ozone),
"SSE" = sum((Ozone - mean(Ozone))^2))
}))
# Node n Avg. Variance SSE
# [1,] 5 48 18.47917 84.16977 3955.979
# [2,] 3 10 55.6 2438.489 21946.4
# [3,] 6 21 31.14286 231.0286 4620.571
# [4,] 9 7 48.71429 197.2381 1183.429
# [5,] 8 30 81.63333 521.3437 15118.97
I think it is easy to see from the output which is which
What the code above does is basically extract the information of Ozone information out of the fitted tree per each inner node and calculate the relevant statistics
As per the P-values, this seems like some type of printing bug, here's an example how you can calculate the P-values in the inner nodes
terNodes <- unique(where(airct))
setdiff(1:max(terNodes), terNodes)
sapply(setdiff(1:max(terNodes), terNodes), function(x) {
n <- nodes(airct, x)[[1]]
pvalue <- 1 - nodes(airct, x)[[1]]$criterion$maxcriterion
plab <- ifelse(pvalue < 10^(-3),
paste("p <", 10^(-3)),
paste("p =", round(pvalue, digits = 3)))
c("Node" = x, "P-value" = plab)
})
# [,1] [,2] [,3] [,4]
# Node "1" "2" "4" "7"
# P-value "p < 0.001" "p = 0.002" "p = 0.003" "p = 0.003"
As a side note, if quotation is a dummy variable, you should probably fit a classification tree (i.e. convert it to a factor) rather a regression tree like you are doing | Interpreting ctree {partykit} output in R
So the 0.016 that you are seeing is the average of quotation while err is just the SSE.
I'm old school and don't know how to exactly show this using the new partykit package (maybe @Achim could illus |
25,097 | Interpreting ctree {partykit} output in R | As suggested by @DavidArenburg, I'm collecting my comments here in another answer for easier references.
(1) If your response is binary, you need to turn it into a factor. Otherwise the inference employed when growing the tree is not what it should be, and also the predictions, visualizations, and error measures are not those intended for classification. See the replies by @DavidArenburg and @AntoniosK for further examples. In general: Also the explanatory variables need to have appropriate classes (numeric, factor, ordered factor) to be processed correctly when growing the tree.
(2) The plot(..., type = "simple") currently does not work as desired - in other words this is a bug. We will fix the partykit package in due course. For the moment you can easily work around it by using plot(as.simpleparty(...)). As a reproducible example:
library("partykit")
data("PimaIndiansDiabetes", package = "mlbench")
ct <- ctree(diabetes ~ ., data = PimaIndiansDiabetes)
plot(as.simpleparty(ct))
(3) The $criterion table erroneously shown currently in the type = "simple" plot contains the test statistics and corresponding log 1-p values from the conditional inference conducted in each node. The log rather than the p-value is used because it is numerically much more stable when used for comparisons, computing the minimal value, etc. Note that the p-values can become extremely small when significant. As an example consider the test results corresponding to the first node from the tree above:
nodeapply(ct, ids = 1, function(n) info_node(n)$criterion)
## $`1`
## pregnant glucose pressure triceps insulin
## statistic 3.631413e+00 5.117841e+00 1.1778530 1.455334 2.570457503
## p.value -6.380290e-09 -2.710725e-37 -0.5937987 -0.313498 -0.002398554
## mass pedigree age
## statistic 4.185236e+00 3.143294e+00 3.774507e+00
## p.value -4.181295e-15 -1.180135e-05 -3.262459e-10
(4) To extract the actual p-values (without log), there is an extractor function sctest() (for structural change test) which is used by the strucchange package and also for the parameter instability tests in the mob() trees. In the example above:
library("strucchange")
sctest(ct, node = 1)
## pregnant glucose pressure triceps insulin mass
## statistic 3.776615e+01 166.9745 3.2473947 4.2859164 13.07180346 6.570902e+01
## p.value 6.380290e-09 0.0000 0.4477744 0.2691142 0.00239568 4.218847e-15
## pedigree age
## statistic 2.318009e+01 4.357601e+01
## p.value 1.180128e-05 3.262459e-10
Note that one p-value (glucose) becomes zero while its log(1 - p) is very close to zero but not quite. To only extract the minimal p-values from the selected partitioning variable (if any), you can again use the nodeapply() function to obtain it from each node's $info:
nodeapply(ct, ids = nodeids(ct), function(n) info_node(n)$p.value)
## $`1`
## glucose
## 0
##
## $`2`
## age
## 6.048661e-07
##
## $`3`
## mass
## 0.001169778
##
## ...
(5) If you want to summarize the response in each terminal node, the easiest solution (IMHO) is to do a simple tapply() on the response variable by the node groups, supplying any summary function you want. For a simpler overview, you can also rbind() this etc. For example:
tab <- tapply(PimaIndiansDiabetes$diabetes, predict(ct, type = "node"),
function(y) c("n" = length(y), 100 * prop.table(table(y))))
do.call("rbind", tab)
## n neg pos
## 5 144 99.30556 0.6944444
## 6 7 85.71429 14.2857143
## 7 120 82.50000 17.5000000
## 8 214 66.82243 33.1775701
## 11 53 79.24528 20.7547170
## 12 108 39.81481 60.1851852
## 13 122 19.67213 80.3278689 | Interpreting ctree {partykit} output in R | As suggested by @DavidArenburg, I'm collecting my comments here in another answer for easier references.
(1) If your response is binary, you need to turn it into a factor. Otherwise the inference empl | Interpreting ctree {partykit} output in R
As suggested by @DavidArenburg, I'm collecting my comments here in another answer for easier references.
(1) If your response is binary, you need to turn it into a factor. Otherwise the inference employed when growing the tree is not what it should be, and also the predictions, visualizations, and error measures are not those intended for classification. See the replies by @DavidArenburg and @AntoniosK for further examples. In general: Also the explanatory variables need to have appropriate classes (numeric, factor, ordered factor) to be processed correctly when growing the tree.
(2) The plot(..., type = "simple") currently does not work as desired - in other words this is a bug. We will fix the partykit package in due course. For the moment you can easily work around it by using plot(as.simpleparty(...)). As a reproducible example:
library("partykit")
data("PimaIndiansDiabetes", package = "mlbench")
ct <- ctree(diabetes ~ ., data = PimaIndiansDiabetes)
plot(as.simpleparty(ct))
(3) The $criterion table erroneously shown currently in the type = "simple" plot contains the test statistics and corresponding log 1-p values from the conditional inference conducted in each node. The log rather than the p-value is used because it is numerically much more stable when used for comparisons, computing the minimal value, etc. Note that the p-values can become extremely small when significant. As an example consider the test results corresponding to the first node from the tree above:
nodeapply(ct, ids = 1, function(n) info_node(n)$criterion)
## $`1`
## pregnant glucose pressure triceps insulin
## statistic 3.631413e+00 5.117841e+00 1.1778530 1.455334 2.570457503
## p.value -6.380290e-09 -2.710725e-37 -0.5937987 -0.313498 -0.002398554
## mass pedigree age
## statistic 4.185236e+00 3.143294e+00 3.774507e+00
## p.value -4.181295e-15 -1.180135e-05 -3.262459e-10
(4) To extract the actual p-values (without log), there is an extractor function sctest() (for structural change test) which is used by the strucchange package and also for the parameter instability tests in the mob() trees. In the example above:
library("strucchange")
sctest(ct, node = 1)
## pregnant glucose pressure triceps insulin mass
## statistic 3.776615e+01 166.9745 3.2473947 4.2859164 13.07180346 6.570902e+01
## p.value 6.380290e-09 0.0000 0.4477744 0.2691142 0.00239568 4.218847e-15
## pedigree age
## statistic 2.318009e+01 4.357601e+01
## p.value 1.180128e-05 3.262459e-10
Note that one p-value (glucose) becomes zero while its log(1 - p) is very close to zero but not quite. To only extract the minimal p-values from the selected partitioning variable (if any), you can again use the nodeapply() function to obtain it from each node's $info:
nodeapply(ct, ids = nodeids(ct), function(n) info_node(n)$p.value)
## $`1`
## glucose
## 0
##
## $`2`
## age
## 6.048661e-07
##
## $`3`
## mass
## 0.001169778
##
## ...
(5) If you want to summarize the response in each terminal node, the easiest solution (IMHO) is to do a simple tapply() on the response variable by the node groups, supplying any summary function you want. For a simpler overview, you can also rbind() this etc. For example:
tab <- tapply(PimaIndiansDiabetes$diabetes, predict(ct, type = "node"),
function(y) c("n" = length(y), 100 * prop.table(table(y))))
do.call("rbind", tab)
## n neg pos
## 5 144 99.30556 0.6944444
## 6 7 85.71429 14.2857143
## 7 120 82.50000 17.5000000
## 8 214 66.82243 33.1775701
## 11 53 79.24528 20.7547170
## 12 108 39.81481 60.1851852
## 13 122 19.67213 80.3278689 | Interpreting ctree {partykit} output in R
As suggested by @DavidArenburg, I'm collecting my comments here in another answer for easier references.
(1) If your response is binary, you need to turn it into a factor. Otherwise the inference empl |
25,098 | Interpreting ctree {partykit} output in R | As an addition to @DavidArenburg 's great answer I'll show you the difference in outputs between regression and classification trees
library(partykit)
# data
airquality = data.frame(airquality)
# create a numeric binary variable as dependent variable
airquality$OzoneClass = 0
airquality$OzoneClass[airquality$Ozone>=34] =1
# regression tree with scale dependent variable
airq <- subset(airquality, !is.na(Ozone))
airct <- ctree(OzoneClass ~ Temp, data = airq)
print(airct)
# Model formula:
# OzoneClass ~ Temp
#
# Fitted party:
# [1] root
# | [2] Temp <= 82
# | | [3] Temp <= 77: 0.096 (n = 52, err = 4.5)
# | | [4] Temp > 77: 0.519 (n = 27, err = 6.7)
# | [5] Temp > 82: 0.973 (n = 37, err = 1.0)
#
# Number of inner nodes: 2
# Number of terminal nodes: 3
# create a categorical binary variable as dependent variable
airquality$OzoneClass = 0
airquality$OzoneClass[airquality$Ozone>=34] =1
airquality$OzoneClass = as.factor(airquality$OzoneClass)
# classification tree
airq <- subset(airquality, !is.na(Ozone))
airct <- ctree(OzoneClass ~ Temp, data = airq)
print(airct)
# Model formula:
# OzoneClass ~ Temp
#
# Fitted party:
# [1] root
# | [2] Temp <= 82
# | | [3] Temp <= 77: 0 (n = 52, err = 9.6%)
# | | [4] Temp > 77: 1 (n = 27, err = 48.1%)
# | [5] Temp > 82: 1 (n = 37, err = 2.7%)
#
# Number of inner nodes: 2
# Number of terminal nodes: 3
Note how (a) the values of the trees change from an average value of 0s and 1s (regression tree) to the most likely class 0/1 (classification tree) and (b) the err values from a number (error) become a percentage (missclassification). | Interpreting ctree {partykit} output in R | As an addition to @DavidArenburg 's great answer I'll show you the difference in outputs between regression and classification trees
library(partykit)
# data
airquality = data.frame(airquality)
# cr | Interpreting ctree {partykit} output in R
As an addition to @DavidArenburg 's great answer I'll show you the difference in outputs between regression and classification trees
library(partykit)
# data
airquality = data.frame(airquality)
# create a numeric binary variable as dependent variable
airquality$OzoneClass = 0
airquality$OzoneClass[airquality$Ozone>=34] =1
# regression tree with scale dependent variable
airq <- subset(airquality, !is.na(Ozone))
airct <- ctree(OzoneClass ~ Temp, data = airq)
print(airct)
# Model formula:
# OzoneClass ~ Temp
#
# Fitted party:
# [1] root
# | [2] Temp <= 82
# | | [3] Temp <= 77: 0.096 (n = 52, err = 4.5)
# | | [4] Temp > 77: 0.519 (n = 27, err = 6.7)
# | [5] Temp > 82: 0.973 (n = 37, err = 1.0)
#
# Number of inner nodes: 2
# Number of terminal nodes: 3
# create a categorical binary variable as dependent variable
airquality$OzoneClass = 0
airquality$OzoneClass[airquality$Ozone>=34] =1
airquality$OzoneClass = as.factor(airquality$OzoneClass)
# classification tree
airq <- subset(airquality, !is.na(Ozone))
airct <- ctree(OzoneClass ~ Temp, data = airq)
print(airct)
# Model formula:
# OzoneClass ~ Temp
#
# Fitted party:
# [1] root
# | [2] Temp <= 82
# | | [3] Temp <= 77: 0 (n = 52, err = 9.6%)
# | | [4] Temp > 77: 1 (n = 27, err = 48.1%)
# | [5] Temp > 82: 1 (n = 37, err = 2.7%)
#
# Number of inner nodes: 2
# Number of terminal nodes: 3
Note how (a) the values of the trees change from an average value of 0s and 1s (regression tree) to the most likely class 0/1 (classification tree) and (b) the err values from a number (error) become a percentage (missclassification). | Interpreting ctree {partykit} output in R
As an addition to @DavidArenburg 's great answer I'll show you the difference in outputs between regression and classification trees
library(partykit)
# data
airquality = data.frame(airquality)
# cr |
25,099 | Roll a 6-sided die until the total $\geq M$. Mean amount by which $M$ is exceeded? | You can certainly use code, but I wouldn't simulate.
I'm going to ignore the "minus M" part (you can do that easily enough at the end).
You can compute the probabilities recursively very easily, but the actual answer (to a very high degree of accuracy) can be calculated from simple reasoning.
Let the rolls be $X_1, X_2, ...$. Let $S_t=\sum_{i=1}^t X_i$.
Let $\tau$ be the smallest index where $S_\tau\geq M$.
$P(S_\tau=M)=P(\text{got to }M-6\text{ at }\tau-1\text{ and rolled a }6) \\\qquad\qquad\qquad+ P(\text{got to }M-5\text{ at }\tau-1\text{ and rolled a }5)\\\qquad\qquad\qquad +\:\: \vdots\\\qquad\qquad\qquad+\:P(\text{got to }M-1\text{ at }\tau-1\text{ and rolled a }1)\\
\qquad\qquad\quad=\frac{1}{6}\sum_{j=1}^6 P(S_{\tau-1}=M-j)$
similarly
$P(S_\tau=M+1)=\frac{1}{6}\sum_{j=1}^5 P(S_{\tau-1}=M-j)$
$P(S_\tau=M+2)=\frac{1}{6}\sum_{j=1}^4 P(S_{\tau-1}=M-j)$
$P(S_\tau=M+3)=\frac{1}{6}\sum_{j=1}^3 P(S_{\tau-1}=M-j)$
$P(S_\tau=M+4)=\frac{1}{6}\sum_{j=1}^2 P(S_{\tau-1}=M-j)$
$P(S_\tau=M+5)=\frac{1}{6} P(S_{\tau-1}=M-1)$
Equations similar to the first one above could then (at least in principle) be run back until you hit any of the initial conditions to get an algebraic relationship between the initial conditions and the probabilities we want (which would be tedious and not especially enlightening), or you can construct the corresponding forward equations and run them forward from the initial conditions, which is easy to do numerically (and which is how I checked my answer). However, we can avoid all that.
The points' probabilities are running weighted averages of previous probabilities; these will (geometrically quickly) smooth out any variation in probability from the initial distribution (all probability at point zero in the case of our problem). The
To an approximation (a very accurate one) we can say that $M-6$ to $M-1$ should be almost equally probable at time $\tau-1$ (really close to it), and so from the above we can write down that the probabilities will be very close to being in simple ratios, and since they must be normalized, we can just write down probabilities.
Which is to say, we can see that if the probabilities of starting from $M-6$ to $M-1$ were exactly equal, there are 6 equally likely ways of getting to $M$, 5 of getting to $M+1$, and so on down to 1 way of getting to $M+5$.
That is, the probabilities are in the ratio 6:5:4:3:2:1, and sum to 1, so they're trivial to write down.
Computing it exactly (up to accumulated numerical round off errors) by running the probability recursions forward from zero (I did it in R) gives differences on the order of .Machine$double.eps ($\approx$2.22e-16 on my machine) from the above approximation (which is to say, simple reasoning along the above lines gives effectively exact answers, since they're as close to the answers computed from recursion as we'd expect the exact answers should be).
Here's my code for that (most of it's just initializing the variables, the work is all in one line). The code starts after the first roll (to save me putting in a cell 0, which is a small nuisance to deal with in R); at each step it takes the lowest cell which could be occupied and moves forward by a die roll (spreading the probability of that cell over the next 6 cells):
p = array(data = 0, dim = 305)
d6 = rep(1/6,6)
i6 = 1:6
p[i6] = d6
for (i in 1:299) p[i+i6] = p[i+i6] + p[i]*d6
(we could use rollapply (from zoo) to do this more efficiently - or a number of other such functions - but it will be easier to translate if I keep it explicit)
Note that d6 is a discrete probability function over 1 to 6, so the code inside the loop in the last line is constructing running weighted averages of earlier values. It's this relationship that makes the probabilities smooth out (until the last few values we're interested in).
So here's the first 50-odd values (the first 25 values marked with circles). At each $t$, the value on the y-axis represents the probability that accumulated in the hindmost cell before we rolled it forward into the next 6 cells.
As you see it smooths out (to $1/\mu$, the reciprocal of the mean of the number of steps each die roll takes you) quite quickly and stays constant.
And once we hit $M$, those probabilities drop away (because we're not putting the probability for values at $M$ and beyond forward in turn)
So the idea that the values at $M-1$ to $M-6$ should be equally likely because the fluctuations from the initial conditions will get smoothed out is clearly seen to be the case.
Since the reasoning doesn't depend on anything but that $M$ is large enough that the initial conditions wash out so that $M-1$ to $M-6$ are nearly equally probable at time $\tau-1$, the distribution will be essentially the same for any large $M$, as Henry suggested in comments.
In retrospect, Henry's hint (which is also in your question) to work with the sum minus M would save a little effort, but the argument would follow very similar lines. You could proceed by letting $R_t=S_t-M$ and writing similar equations relating $R_0$ to the preceding values, and so on.
From the probability distribution, the mean and the variance of the probabilities are then simple.
Edit: I suppose I should give the asymptotic mean and standard deviation of the final position minus $M$:
The asymptotic mean excess is $\frac{5}{3}$ and the standard deviation is $\frac{2\sqrt 5}{3}$. At $M=300$ this is accurate to a much greater degree than you're likely to care about. | Roll a 6-sided die until the total $\geq M$. Mean amount by which $M$ is exceeded? | You can certainly use code, but I wouldn't simulate.
I'm going to ignore the "minus M" part (you can do that easily enough at the end).
You can compute the probabilities recursively very easily, but | Roll a 6-sided die until the total $\geq M$. Mean amount by which $M$ is exceeded?
You can certainly use code, but I wouldn't simulate.
I'm going to ignore the "minus M" part (you can do that easily enough at the end).
You can compute the probabilities recursively very easily, but the actual answer (to a very high degree of accuracy) can be calculated from simple reasoning.
Let the rolls be $X_1, X_2, ...$. Let $S_t=\sum_{i=1}^t X_i$.
Let $\tau$ be the smallest index where $S_\tau\geq M$.
$P(S_\tau=M)=P(\text{got to }M-6\text{ at }\tau-1\text{ and rolled a }6) \\\qquad\qquad\qquad+ P(\text{got to }M-5\text{ at }\tau-1\text{ and rolled a }5)\\\qquad\qquad\qquad +\:\: \vdots\\\qquad\qquad\qquad+\:P(\text{got to }M-1\text{ at }\tau-1\text{ and rolled a }1)\\
\qquad\qquad\quad=\frac{1}{6}\sum_{j=1}^6 P(S_{\tau-1}=M-j)$
similarly
$P(S_\tau=M+1)=\frac{1}{6}\sum_{j=1}^5 P(S_{\tau-1}=M-j)$
$P(S_\tau=M+2)=\frac{1}{6}\sum_{j=1}^4 P(S_{\tau-1}=M-j)$
$P(S_\tau=M+3)=\frac{1}{6}\sum_{j=1}^3 P(S_{\tau-1}=M-j)$
$P(S_\tau=M+4)=\frac{1}{6}\sum_{j=1}^2 P(S_{\tau-1}=M-j)$
$P(S_\tau=M+5)=\frac{1}{6} P(S_{\tau-1}=M-1)$
Equations similar to the first one above could then (at least in principle) be run back until you hit any of the initial conditions to get an algebraic relationship between the initial conditions and the probabilities we want (which would be tedious and not especially enlightening), or you can construct the corresponding forward equations and run them forward from the initial conditions, which is easy to do numerically (and which is how I checked my answer). However, we can avoid all that.
The points' probabilities are running weighted averages of previous probabilities; these will (geometrically quickly) smooth out any variation in probability from the initial distribution (all probability at point zero in the case of our problem). The
To an approximation (a very accurate one) we can say that $M-6$ to $M-1$ should be almost equally probable at time $\tau-1$ (really close to it), and so from the above we can write down that the probabilities will be very close to being in simple ratios, and since they must be normalized, we can just write down probabilities.
Which is to say, we can see that if the probabilities of starting from $M-6$ to $M-1$ were exactly equal, there are 6 equally likely ways of getting to $M$, 5 of getting to $M+1$, and so on down to 1 way of getting to $M+5$.
That is, the probabilities are in the ratio 6:5:4:3:2:1, and sum to 1, so they're trivial to write down.
Computing it exactly (up to accumulated numerical round off errors) by running the probability recursions forward from zero (I did it in R) gives differences on the order of .Machine$double.eps ($\approx$2.22e-16 on my machine) from the above approximation (which is to say, simple reasoning along the above lines gives effectively exact answers, since they're as close to the answers computed from recursion as we'd expect the exact answers should be).
Here's my code for that (most of it's just initializing the variables, the work is all in one line). The code starts after the first roll (to save me putting in a cell 0, which is a small nuisance to deal with in R); at each step it takes the lowest cell which could be occupied and moves forward by a die roll (spreading the probability of that cell over the next 6 cells):
p = array(data = 0, dim = 305)
d6 = rep(1/6,6)
i6 = 1:6
p[i6] = d6
for (i in 1:299) p[i+i6] = p[i+i6] + p[i]*d6
(we could use rollapply (from zoo) to do this more efficiently - or a number of other such functions - but it will be easier to translate if I keep it explicit)
Note that d6 is a discrete probability function over 1 to 6, so the code inside the loop in the last line is constructing running weighted averages of earlier values. It's this relationship that makes the probabilities smooth out (until the last few values we're interested in).
So here's the first 50-odd values (the first 25 values marked with circles). At each $t$, the value on the y-axis represents the probability that accumulated in the hindmost cell before we rolled it forward into the next 6 cells.
As you see it smooths out (to $1/\mu$, the reciprocal of the mean of the number of steps each die roll takes you) quite quickly and stays constant.
And once we hit $M$, those probabilities drop away (because we're not putting the probability for values at $M$ and beyond forward in turn)
So the idea that the values at $M-1$ to $M-6$ should be equally likely because the fluctuations from the initial conditions will get smoothed out is clearly seen to be the case.
Since the reasoning doesn't depend on anything but that $M$ is large enough that the initial conditions wash out so that $M-1$ to $M-6$ are nearly equally probable at time $\tau-1$, the distribution will be essentially the same for any large $M$, as Henry suggested in comments.
In retrospect, Henry's hint (which is also in your question) to work with the sum minus M would save a little effort, but the argument would follow very similar lines. You could proceed by letting $R_t=S_t-M$ and writing similar equations relating $R_0$ to the preceding values, and so on.
From the probability distribution, the mean and the variance of the probabilities are then simple.
Edit: I suppose I should give the asymptotic mean and standard deviation of the final position minus $M$:
The asymptotic mean excess is $\frac{5}{3}$ and the standard deviation is $\frac{2\sqrt 5}{3}$. At $M=300$ this is accurate to a much greater degree than you're likely to care about. | Roll a 6-sided die until the total $\geq M$. Mean amount by which $M$ is exceeded?
You can certainly use code, but I wouldn't simulate.
I'm going to ignore the "minus M" part (you can do that easily enough at the end).
You can compute the probabilities recursively very easily, but |
25,100 | Roll a 6-sided die until the total $\geq M$. Mean amount by which $M$ is exceeded? | Let $\Omega$ be the set of sequences of partial sums of the dice rolls (with each sequence beginning at $0$). For any integer $n$, let $E_n$ be the event that $n$ appears in a sequence; that is,
$$E_n = \{\omega\in\Omega\,|\, n \in \omega\}.$$
Define $X_M(\omega)$ to be the first value in $\omega$ that equals or exceeds $M$. The question asks for properties of $X_M-M$. We can obtain the exact distribution of $X_M$, and from that everything follows.
First, notice that $X_M(\omega) - M \in \{0, 1, 2, 3, 4, 5\}$. By partitioning the event $X_M - M = k$ according to the immediately preceding value in $\omega$, and letting $p(i) = 1/6$ be the probability of observing face $i$ on one roll of the die ($i=1, 2, 3, 4, 5, 6$), it follows that
$$\Pr(X_M - M = k) = \sum_{j=k}^6 \Pr(E_{M+k-j}) p(j) = \frac{1}{6} \sum_{j=k}^6 \Pr(E_{M+k-j}).$$
At this point we could argue heuristically that, to a very good approximation for all but the smallest $M$, $$\Pr(E_i) \approx 2/7.$$ This is because the expected value of a roll is $(1+2+3+4+5+6)/6 = 7/2$ and its reciprocal should be the limiting, stable long-run frequency of any particular value in $\omega$.
A rigorous way to demonstrate this considers how $E_i$ could occur. Either $E_{i-1}$ occurs and the subsequent roll was a $1$; or $E_{i-2}$ occurs and the subsequent roll was a $2$; or ... or $E_{i-6}$ occurs and the subsequent roll was a $6$. This is an exhaustive partition of the possibilities, whence
$$\Pr(E_i) = \sum_{j=1}^6 \Pr(E_{i-j}) p(j) = \frac{1}{6} \sum_{j=1}^6 \Pr(E_{i-j}).$$
The initial values of this sequence are
$$\Pr(E_0) = 1;\quad \Pr(E_{-i}) = 0, i = 1, 2, 3, \ldots .$$
This plot of $\Pr(E_i)$ against $i$ shows how rapidly the chances settle down to a constant $2/7$, shown by the horizontal dotted line.
There is a standard theory of such recursive sequences. It can be developed by means of generating functions, Markov chains, or even algebraic manipulation. The general result is that a closed-form formula for $\Pr(E_i)$ exists. It will be a linear combination of a constant and the $i^\text{th}$ powers of roots of the polynomial
$$x^6 - p(1) x^5 - p(2) x^4 - p(3) x^3 \cdots - p(6) = x^6 - (x^5 + x^4+x^3+x^2+x+1)/6.$$
The largest magnitude of these roots is approximately $\exp(-0.314368)$. In a double precision floating point representation, $\exp(-36.05)$ is essentially zero. Therefore, for $i \gg -36.05 / -0.314368 = 115$, we may completely ignore all but the constant. This constant is $2/7$.
Consequently, for $M = 300 \gg 115$, for all practical purposes we may take $E_{M+k-j} = 2/7$, whence
$$\Pr(X_M - M = (0,1,2,3,4,5)) = \left(\frac{2}{7}\right)\left(\frac{1}{6}\right)(6,5,4,3,2,1).$$
Computing the mean and variance of this distribution is straightforward and easy.
Here is an R simulation to confirm these conclusions. It generates almost 100,000 sequences through $M+5 = 305$, tabulates the values of $X_{300} - 300$, and applies a $\chi^2$ test to assess whether the results are consistent with the foregoing. The p-value (in this case) of $0.1367$ is large enough to indicate they are consistent.
M <- 300
n.iter <- 1e5
set.seed(17)
n <- ceiling((2/7) * (M + 3*sqrt(M)))
dice <- matrix(ceiling(6*runif(n*n.iter)), n, n.iter)
omega <- apply(dice, 2, cumsum)
omega <- omega[, apply(omega, 2, max) >= M+5]
omega[omega < M] <- NA
x <- apply(omega, 2, min, na.rm=TRUE)
count <- tabulate(x)[0:5+M]
(cbind(count, expected=round((2/7) * (6:1)/6 * length(x), 1)))
chisq.test(count, p=(2/7) * (6:1)/6) | Roll a 6-sided die until the total $\geq M$. Mean amount by which $M$ is exceeded? | Let $\Omega$ be the set of sequences of partial sums of the dice rolls (with each sequence beginning at $0$). For any integer $n$, let $E_n$ be the event that $n$ appears in a sequence; that is,
$$E_ | Roll a 6-sided die until the total $\geq M$. Mean amount by which $M$ is exceeded?
Let $\Omega$ be the set of sequences of partial sums of the dice rolls (with each sequence beginning at $0$). For any integer $n$, let $E_n$ be the event that $n$ appears in a sequence; that is,
$$E_n = \{\omega\in\Omega\,|\, n \in \omega\}.$$
Define $X_M(\omega)$ to be the first value in $\omega$ that equals or exceeds $M$. The question asks for properties of $X_M-M$. We can obtain the exact distribution of $X_M$, and from that everything follows.
First, notice that $X_M(\omega) - M \in \{0, 1, 2, 3, 4, 5\}$. By partitioning the event $X_M - M = k$ according to the immediately preceding value in $\omega$, and letting $p(i) = 1/6$ be the probability of observing face $i$ on one roll of the die ($i=1, 2, 3, 4, 5, 6$), it follows that
$$\Pr(X_M - M = k) = \sum_{j=k}^6 \Pr(E_{M+k-j}) p(j) = \frac{1}{6} \sum_{j=k}^6 \Pr(E_{M+k-j}).$$
At this point we could argue heuristically that, to a very good approximation for all but the smallest $M$, $$\Pr(E_i) \approx 2/7.$$ This is because the expected value of a roll is $(1+2+3+4+5+6)/6 = 7/2$ and its reciprocal should be the limiting, stable long-run frequency of any particular value in $\omega$.
A rigorous way to demonstrate this considers how $E_i$ could occur. Either $E_{i-1}$ occurs and the subsequent roll was a $1$; or $E_{i-2}$ occurs and the subsequent roll was a $2$; or ... or $E_{i-6}$ occurs and the subsequent roll was a $6$. This is an exhaustive partition of the possibilities, whence
$$\Pr(E_i) = \sum_{j=1}^6 \Pr(E_{i-j}) p(j) = \frac{1}{6} \sum_{j=1}^6 \Pr(E_{i-j}).$$
The initial values of this sequence are
$$\Pr(E_0) = 1;\quad \Pr(E_{-i}) = 0, i = 1, 2, 3, \ldots .$$
This plot of $\Pr(E_i)$ against $i$ shows how rapidly the chances settle down to a constant $2/7$, shown by the horizontal dotted line.
There is a standard theory of such recursive sequences. It can be developed by means of generating functions, Markov chains, or even algebraic manipulation. The general result is that a closed-form formula for $\Pr(E_i)$ exists. It will be a linear combination of a constant and the $i^\text{th}$ powers of roots of the polynomial
$$x^6 - p(1) x^5 - p(2) x^4 - p(3) x^3 \cdots - p(6) = x^6 - (x^5 + x^4+x^3+x^2+x+1)/6.$$
The largest magnitude of these roots is approximately $\exp(-0.314368)$. In a double precision floating point representation, $\exp(-36.05)$ is essentially zero. Therefore, for $i \gg -36.05 / -0.314368 = 115$, we may completely ignore all but the constant. This constant is $2/7$.
Consequently, for $M = 300 \gg 115$, for all practical purposes we may take $E_{M+k-j} = 2/7$, whence
$$\Pr(X_M - M = (0,1,2,3,4,5)) = \left(\frac{2}{7}\right)\left(\frac{1}{6}\right)(6,5,4,3,2,1).$$
Computing the mean and variance of this distribution is straightforward and easy.
Here is an R simulation to confirm these conclusions. It generates almost 100,000 sequences through $M+5 = 305$, tabulates the values of $X_{300} - 300$, and applies a $\chi^2$ test to assess whether the results are consistent with the foregoing. The p-value (in this case) of $0.1367$ is large enough to indicate they are consistent.
M <- 300
n.iter <- 1e5
set.seed(17)
n <- ceiling((2/7) * (M + 3*sqrt(M)))
dice <- matrix(ceiling(6*runif(n*n.iter)), n, n.iter)
omega <- apply(dice, 2, cumsum)
omega <- omega[, apply(omega, 2, max) >= M+5]
omega[omega < M] <- NA
x <- apply(omega, 2, min, na.rm=TRUE)
count <- tabulate(x)[0:5+M]
(cbind(count, expected=round((2/7) * (6:1)/6 * length(x), 1)))
chisq.test(count, p=(2/7) * (6:1)/6) | Roll a 6-sided die until the total $\geq M$. Mean amount by which $M$ is exceeded?
Let $\Omega$ be the set of sequences of partial sums of the dice rolls (with each sequence beginning at $0$). For any integer $n$, let $E_n$ be the event that $n$ appears in a sequence; that is,
$$E_ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.