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
|
|---|---|---|---|---|---|---|
12,401
|
The proof of equivalent formulas of ridge regression
|
It's perhaps worth reading about Lagrangian duality and a broader relation (at times equivalence) between:
optimization subject to hard (i.e. inviolable) constraints
optimization with penalties for violating constraints.
Quick intro to weak duality and strong duality
Assume we have some function $f(x,y)$ of two variables. For any $\hat{x}$ and $\hat{y}$, we have:
$$ \min_x f(x, \hat{y}) \leq f(\hat{x}, \hat{y}) \leq \max_y f(\hat{x}, y)$$
Since that holds for any $\hat{x}$ and $\hat{y}$ it also holds that:
$$ \max_y \min_x f(x, y) \leq \min_x \max_y f(x, y)$$
This is known as weak duality. In certain circumstances, you have also have strong duality (also known as the saddle point property):
$$ \max_y \min_x f(x, y) = \min_x \max_y f(x, y)$$
When strong duality holds, solving $\max_y \min_x f(x, y)$ also solves $\min_x \max_y f(x, y)$.
Lagrangian for constrained Ridge Regression
Let me define the function $\mathcal{L}$ as:
$$ \mathcal{L}(\mathbf{b}, \lambda) = \sum_{i=1}^n (y - \mathbf{x}_i \cdot \mathbf{b})^2 + \lambda \left( \sum_{j=1}^p b_j^2 - t \right) $$
The min-max interpretation of the Lagrangian
The Ridge regression problem subject to hard constraints is:
$$ \min_\mathbf{b} \max_{\lambda \geq 0} \mathcal{L}(\mathbf{b}, \lambda) $$
You pick $\mathbf{b}$ to minimize the objective, cognizant that after you pick $\mathbf{b}$, your opponent will set $\lambda$ to infinity if you chose $\mathbf{b}$ such that the constraint was violated (in this case $\sum_{j=1}^p b_j^2 > t$).
If strong duality holds (which it does here because it's a convex optimization problem where Slater's condition is satisfied for $t>0$), you then achieve the same result by reversing the order:
$$ \max_{\lambda \geq 0} \min_\mathbf{b} \mathcal{L}(\mathbf{b}, \lambda) $$
In this dual problem, your opponent chooses $\lambda$ first! You then choose $\mathbf{b}$ to minimize the objective, already knowing your opponent's choice of $\lambda$. The $\min_\mathbf{b} \mathcal{L}(\mathbf{b}, \lambda)$ part (taking $\lambda$ as given) is equivalent to the 2nd form of your Ridge Regression problem.
As you can see, this isn't a result particular to Ridge Regression. It is a broader concept.
References
I started this post following an exposition of Rockafellar.
Rockafellar, R.T., Convex Analysis
You might also examine lectures 7 and lecture 8 from Prof. Stephen Boyd's course on convex optimization.
|
The proof of equivalent formulas of ridge regression
|
It's perhaps worth reading about Lagrangian duality and a broader relation (at times equivalence) between:
optimization subject to hard (i.e. inviolable) constraints
optimization with penalties for v
|
The proof of equivalent formulas of ridge regression
It's perhaps worth reading about Lagrangian duality and a broader relation (at times equivalence) between:
optimization subject to hard (i.e. inviolable) constraints
optimization with penalties for violating constraints.
Quick intro to weak duality and strong duality
Assume we have some function $f(x,y)$ of two variables. For any $\hat{x}$ and $\hat{y}$, we have:
$$ \min_x f(x, \hat{y}) \leq f(\hat{x}, \hat{y}) \leq \max_y f(\hat{x}, y)$$
Since that holds for any $\hat{x}$ and $\hat{y}$ it also holds that:
$$ \max_y \min_x f(x, y) \leq \min_x \max_y f(x, y)$$
This is known as weak duality. In certain circumstances, you have also have strong duality (also known as the saddle point property):
$$ \max_y \min_x f(x, y) = \min_x \max_y f(x, y)$$
When strong duality holds, solving $\max_y \min_x f(x, y)$ also solves $\min_x \max_y f(x, y)$.
Lagrangian for constrained Ridge Regression
Let me define the function $\mathcal{L}$ as:
$$ \mathcal{L}(\mathbf{b}, \lambda) = \sum_{i=1}^n (y - \mathbf{x}_i \cdot \mathbf{b})^2 + \lambda \left( \sum_{j=1}^p b_j^2 - t \right) $$
The min-max interpretation of the Lagrangian
The Ridge regression problem subject to hard constraints is:
$$ \min_\mathbf{b} \max_{\lambda \geq 0} \mathcal{L}(\mathbf{b}, \lambda) $$
You pick $\mathbf{b}$ to minimize the objective, cognizant that after you pick $\mathbf{b}$, your opponent will set $\lambda$ to infinity if you chose $\mathbf{b}$ such that the constraint was violated (in this case $\sum_{j=1}^p b_j^2 > t$).
If strong duality holds (which it does here because it's a convex optimization problem where Slater's condition is satisfied for $t>0$), you then achieve the same result by reversing the order:
$$ \max_{\lambda \geq 0} \min_\mathbf{b} \mathcal{L}(\mathbf{b}, \lambda) $$
In this dual problem, your opponent chooses $\lambda$ first! You then choose $\mathbf{b}$ to minimize the objective, already knowing your opponent's choice of $\lambda$. The $\min_\mathbf{b} \mathcal{L}(\mathbf{b}, \lambda)$ part (taking $\lambda$ as given) is equivalent to the 2nd form of your Ridge Regression problem.
As you can see, this isn't a result particular to Ridge Regression. It is a broader concept.
References
I started this post following an exposition of Rockafellar.
Rockafellar, R.T., Convex Analysis
You might also examine lectures 7 and lecture 8 from Prof. Stephen Boyd's course on convex optimization.
|
The proof of equivalent formulas of ridge regression
It's perhaps worth reading about Lagrangian duality and a broader relation (at times equivalence) between:
optimization subject to hard (i.e. inviolable) constraints
optimization with penalties for v
|
12,402
|
The proof of equivalent formulas of ridge regression
|
They are not equivalent.
For a constrained minimization problem
$$\min_{\mathbf b} \sum_{i=1}^n (y - \mathbf{x}'_i \cdot \mathbf{b})^2\\
s.t. \sum_{j=1}^p b_j^2 \leq t,\;\;\; \mathbf b = (b_1,...,b_p) \tag{1}$$
we solve by minimize over $\mathbf b$ the corresponding Lagrangean
$$\Lambda = \sum_{i=1}^n (y - \mathbf{x}'_i \cdot \mathbf{b})^2 + \lambda \left( \sum_{j=1}^p b_j^2 - t \right) \tag{2}$$
Here, $t$ is a bound given exogenously, $\lambda \geq 0$ is a Karush-Kuhn-Tucker non-negative multiplier, and both the beta vector and $\lambda$ are to be determined optimally through the minimization procedure given $t$.
Comparing $(2)$ and eq $(3.41)$ in the OP's post, it appears that the Ridge estimator can be obtained as the solution to
$$\min_{\mathbf b}\{\Lambda + \lambda t\} \tag{3}$$
Since in $(3)$ the function to be minimized appears to be the Lagrangean of the constrained minimization problem plus a term that does not involve $\mathbf b$, it would appear that indeed the two approaches are equivalent...
But this is not correct because in the Ridge regression we minimize over $\mathbf b$ given $\lambda >0$. But, in the lens of the constrained minimization problem, assuming $\lambda >0$ imposes the condition that the constraint is binding, i.e that
$$\sum_{j=1}^p (b^*_{j,ridge})^2 = t$$
The general constrained minimization problem allows for $\lambda = 0$ also, and essentially it is a formulation that includes as special cases the basic least-squares estimator ($\lambda ^*=0$) and the Ridge estimator ($\lambda^* >0$).
So the two formulation are not equivalent. Nevertheless, Matthew Gunn's post shows in another and very intuitive way how the two are very closely connected. But duality is not equivalence.
|
The proof of equivalent formulas of ridge regression
|
They are not equivalent.
For a constrained minimization problem
$$\min_{\mathbf b} \sum_{i=1}^n (y - \mathbf{x}'_i \cdot \mathbf{b})^2\\
s.t. \sum_{j=1}^p b_j^2 \leq t,\;\;\; \mathbf b = (b_1,...,b
|
The proof of equivalent formulas of ridge regression
They are not equivalent.
For a constrained minimization problem
$$\min_{\mathbf b} \sum_{i=1}^n (y - \mathbf{x}'_i \cdot \mathbf{b})^2\\
s.t. \sum_{j=1}^p b_j^2 \leq t,\;\;\; \mathbf b = (b_1,...,b_p) \tag{1}$$
we solve by minimize over $\mathbf b$ the corresponding Lagrangean
$$\Lambda = \sum_{i=1}^n (y - \mathbf{x}'_i \cdot \mathbf{b})^2 + \lambda \left( \sum_{j=1}^p b_j^2 - t \right) \tag{2}$$
Here, $t$ is a bound given exogenously, $\lambda \geq 0$ is a Karush-Kuhn-Tucker non-negative multiplier, and both the beta vector and $\lambda$ are to be determined optimally through the minimization procedure given $t$.
Comparing $(2)$ and eq $(3.41)$ in the OP's post, it appears that the Ridge estimator can be obtained as the solution to
$$\min_{\mathbf b}\{\Lambda + \lambda t\} \tag{3}$$
Since in $(3)$ the function to be minimized appears to be the Lagrangean of the constrained minimization problem plus a term that does not involve $\mathbf b$, it would appear that indeed the two approaches are equivalent...
But this is not correct because in the Ridge regression we minimize over $\mathbf b$ given $\lambda >0$. But, in the lens of the constrained minimization problem, assuming $\lambda >0$ imposes the condition that the constraint is binding, i.e that
$$\sum_{j=1}^p (b^*_{j,ridge})^2 = t$$
The general constrained minimization problem allows for $\lambda = 0$ also, and essentially it is a formulation that includes as special cases the basic least-squares estimator ($\lambda ^*=0$) and the Ridge estimator ($\lambda^* >0$).
So the two formulation are not equivalent. Nevertheless, Matthew Gunn's post shows in another and very intuitive way how the two are very closely connected. But duality is not equivalence.
|
The proof of equivalent formulas of ridge regression
They are not equivalent.
For a constrained minimization problem
$$\min_{\mathbf b} \sum_{i=1}^n (y - \mathbf{x}'_i \cdot \mathbf{b})^2\\
s.t. \sum_{j=1}^p b_j^2 \leq t,\;\;\; \mathbf b = (b_1,...,b
|
12,403
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Weibull is sometimes used for modelling ping time. try a weibull distribution. To fit one in R:
x<-rweibull(n=1000,shape=2,scale=100)
#generate a weibull (this should be your data).
hist(x)
#this is an histogram of your data.
library(survival)
a1<-survreg(Surv(x,rep(1,1000))~1,dist='weibull')
exp(a1$coef) #this is the ML estimate of the scale parameter
1/a1$scale #this is the ML estimate of the shape parameter
If you're wondering for the goofy names (i.e. $scale to get the inverse of the shape)
it's because "survreg" uses another parametrization (i.e. it is parametrized in terms of the "inverse weibull" which is more comon in actuarial sciences).
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Weibull is sometimes used for modelling ping time. try a weibull distribution. To fit one in R:
x<-rweibull(n=1000,shape=2,scale=100)
#generate a weibull (this should be your data).
hist(x)
#this is a
|
How do I figure out what kind of distribution represents this data on ping response times?
Weibull is sometimes used for modelling ping time. try a weibull distribution. To fit one in R:
x<-rweibull(n=1000,shape=2,scale=100)
#generate a weibull (this should be your data).
hist(x)
#this is an histogram of your data.
library(survival)
a1<-survreg(Surv(x,rep(1,1000))~1,dist='weibull')
exp(a1$coef) #this is the ML estimate of the scale parameter
1/a1$scale #this is the ML estimate of the shape parameter
If you're wondering for the goofy names (i.e. $scale to get the inverse of the shape)
it's because "survreg" uses another parametrization (i.e. it is parametrized in terms of the "inverse weibull" which is more comon in actuarial sciences).
|
How do I figure out what kind of distribution represents this data on ping response times?
Weibull is sometimes used for modelling ping time. try a weibull distribution. To fit one in R:
x<-rweibull(n=1000,shape=2,scale=100)
#generate a weibull (this should be your data).
hist(x)
#this is a
|
12,404
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Let me ask a more basic question: what do you want to do with this distributional information?
The reason I ask is because it may well make more sense to approximate the distribution with some sort of kernel density estimator, rather than insist that it fit into one of the (possibly shifted) exponential family distributions. You can answer almost all of the same sorts of questions that a standard distribution will let you answer, and you don't have to worry (as much) about whether you've selected the correct model.
But if there's a fixed minimum time, and you must have some sort of compactly parameterized distribution to go with it, then just eyeballing it I'd subtract off the minimum and fit a gamma, like others have suggested.
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Let me ask a more basic question: what do you want to do with this distributional information?
The reason I ask is because it may well make more sense to approximate the distribution with some sort o
|
How do I figure out what kind of distribution represents this data on ping response times?
Let me ask a more basic question: what do you want to do with this distributional information?
The reason I ask is because it may well make more sense to approximate the distribution with some sort of kernel density estimator, rather than insist that it fit into one of the (possibly shifted) exponential family distributions. You can answer almost all of the same sorts of questions that a standard distribution will let you answer, and you don't have to worry (as much) about whether you've selected the correct model.
But if there's a fixed minimum time, and you must have some sort of compactly parameterized distribution to go with it, then just eyeballing it I'd subtract off the minimum and fit a gamma, like others have suggested.
|
How do I figure out what kind of distribution represents this data on ping response times?
Let me ask a more basic question: what do you want to do with this distributional information?
The reason I ask is because it may well make more sense to approximate the distribution with some sort o
|
12,405
|
How do I figure out what kind of distribution represents this data on ping response times?
|
There is no reason to expect that any real world data set will fit a known distributional form...especially from such a known messy data source.
What you want to do with the answers will largely indicate an approach. For example, if you want to know when the ping times have changed significantly, then trending the empirical distribution may be a way to go. If you want to identify outliers, other techniques may be more appropriate.
|
How do I figure out what kind of distribution represents this data on ping response times?
|
There is no reason to expect that any real world data set will fit a known distributional form...especially from such a known messy data source.
What you want to do with the answers will largely indic
|
How do I figure out what kind of distribution represents this data on ping response times?
There is no reason to expect that any real world data set will fit a known distributional form...especially from such a known messy data source.
What you want to do with the answers will largely indicate an approach. For example, if you want to know when the ping times have changed significantly, then trending the empirical distribution may be a way to go. If you want to identify outliers, other techniques may be more appropriate.
|
How do I figure out what kind of distribution represents this data on ping response times?
There is no reason to expect that any real world data set will fit a known distributional form...especially from such a known messy data source.
What you want to do with the answers will largely indic
|
12,406
|
How do I figure out what kind of distribution represents this data on ping response times?
|
A simpler approach might be to transform the data. After transforming, it might be close to Gaussian.
One common way to do so is by taking the logarithm of all values.
My guess is that in this case the distribution of the reciprocal of the round-trip times will be more symmetrical and perhaps close to Gaussian. By taking the reciprocal, you are essentially tabulating velocities instead of times, so it still is easy to interpret the results (unlike logarithms or many transforms).
|
How do I figure out what kind of distribution represents this data on ping response times?
|
A simpler approach might be to transform the data. After transforming, it might be close to Gaussian.
One common way to do so is by taking the logarithm of all values.
My guess is that in this case
|
How do I figure out what kind of distribution represents this data on ping response times?
A simpler approach might be to transform the data. After transforming, it might be close to Gaussian.
One common way to do so is by taking the logarithm of all values.
My guess is that in this case the distribution of the reciprocal of the round-trip times will be more symmetrical and perhaps close to Gaussian. By taking the reciprocal, you are essentially tabulating velocities instead of times, so it still is easy to interpret the results (unlike logarithms or many transforms).
|
How do I figure out what kind of distribution represents this data on ping response times?
A simpler approach might be to transform the data. After transforming, it might be close to Gaussian.
One common way to do so is by taking the logarithm of all values.
My guess is that in this case
|
12,407
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Try the gamma distribution which is parametrized as $x \sim Gamma(k,\theta)$. If you see these pdf plots of the gamma from the wiki you will see that there are some plots that look similar to what you have.
Update- Estimation Process
The estimation via maximum likelihood is tricky but possible. I imagine you can start with the approximate solution given by the wiki for $\hat{\theta}$ and $\hat{k}$ and if the plots look ok and if needed you can estimate $\hat{k}$ more accurately using the details in the wiki.
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Try the gamma distribution which is parametrized as $x \sim Gamma(k,\theta)$. If you see these pdf plots of the gamma from the wiki you will see that there are some plots that look similar to what you
|
How do I figure out what kind of distribution represents this data on ping response times?
Try the gamma distribution which is parametrized as $x \sim Gamma(k,\theta)$. If you see these pdf plots of the gamma from the wiki you will see that there are some plots that look similar to what you have.
Update- Estimation Process
The estimation via maximum likelihood is tricky but possible. I imagine you can start with the approximate solution given by the wiki for $\hat{\theta}$ and $\hat{k}$ and if the plots look ok and if needed you can estimate $\hat{k}$ more accurately using the details in the wiki.
|
How do I figure out what kind of distribution represents this data on ping response times?
Try the gamma distribution which is parametrized as $x \sim Gamma(k,\theta)$. If you see these pdf plots of the gamma from the wiki you will see that there are some plots that look similar to what you
|
12,408
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Another approach, that is more justified by network considerations, is to try to fit a sum of independent exponentials with different parameters. A reasonable assumption would be that each node in the path of the ping the delay would be an independent exponential, with different parameters. A reference to the distributional form of the sum of independent exponentials with differing parameters is http://www.math.bme.hu/~balazs/sumexp.pdf.
You should probably also look at the ping times vs the number of hops.
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Another approach, that is more justified by network considerations, is to try to fit a sum of independent exponentials with different parameters. A reasonable assumption would be that each node in the
|
How do I figure out what kind of distribution represents this data on ping response times?
Another approach, that is more justified by network considerations, is to try to fit a sum of independent exponentials with different parameters. A reasonable assumption would be that each node in the path of the ping the delay would be an independent exponential, with different parameters. A reference to the distributional form of the sum of independent exponentials with differing parameters is http://www.math.bme.hu/~balazs/sumexp.pdf.
You should probably also look at the ping times vs the number of hops.
|
How do I figure out what kind of distribution represents this data on ping response times?
Another approach, that is more justified by network considerations, is to try to fit a sum of independent exponentials with different parameters. A reasonable assumption would be that each node in the
|
12,409
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Looking at it I would say a skew-normal or possibly a binormal distribution may fit it well.
In R you could use the sn library to deal with skew-normal distribution and use nls or mle to do a non-linear least square or a maximum likelihood extimation fit of your data.
===
EDIT: rereading your question/comments I would add something more
If what you're interested into is just drawing a pretty graph over the bars forget about distributions, who cares in the end if you're not doing anything with it. Just draw a B-spline over your data point and you're good.
Also, with this approach you avoid having to implement a MLE fit algorithm (or similar), and you're covered in the case of a distribution that is not skew-normal (or whatever you choose to draw)
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Looking at it I would say a skew-normal or possibly a binormal distribution may fit it well.
In R you could use the sn library to deal with skew-normal distribution and use nls or mle to do a non-line
|
How do I figure out what kind of distribution represents this data on ping response times?
Looking at it I would say a skew-normal or possibly a binormal distribution may fit it well.
In R you could use the sn library to deal with skew-normal distribution and use nls or mle to do a non-linear least square or a maximum likelihood extimation fit of your data.
===
EDIT: rereading your question/comments I would add something more
If what you're interested into is just drawing a pretty graph over the bars forget about distributions, who cares in the end if you're not doing anything with it. Just draw a B-spline over your data point and you're good.
Also, with this approach you avoid having to implement a MLE fit algorithm (or similar), and you're covered in the case of a distribution that is not skew-normal (or whatever you choose to draw)
|
How do I figure out what kind of distribution represents this data on ping response times?
Looking at it I would say a skew-normal or possibly a binormal distribution may fit it well.
In R you could use the sn library to deal with skew-normal distribution and use nls or mle to do a non-line
|
12,410
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Based on your comment "Really i want to draw the mathematical curve that follows the distribution. Granted it might not be a known distribution; but i can't imagine that this hasn't been investigated before." I am providing a function that sort of fits.
Take a look at ExtremeValueDistribution
I added an amplitude and made the two betas different. I figure your function's center is closer to 9.5 then 10.
New function:
a E^(-E^(((-x + alpha)/b1)) + (-x + alpha)/b2)/((b1 + b2)/2)
{alpha->9.5, b2 -> 0.899093, a -> 5822.2, b1 -> 0.381825}
Wolfram alpha:
plot 11193.8 E^(-E^(1.66667 (10 - x)) + 1.66667 (10 - x)) ,x 0..16, y from 0 to 4500
Some points around 10ms:
{{9, 390.254}, {10, 3979.59}, {11, 1680.73}, {12, 562.838}}
Tail does not fit perfectly though. The tail can be fit better if b2 is lower and the peak is chosen to be closer to 9.
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Based on your comment "Really i want to draw the mathematical curve that follows the distribution. Granted it might not be a known distribution; but i can't imagine that this hasn't been investigated
|
How do I figure out what kind of distribution represents this data on ping response times?
Based on your comment "Really i want to draw the mathematical curve that follows the distribution. Granted it might not be a known distribution; but i can't imagine that this hasn't been investigated before." I am providing a function that sort of fits.
Take a look at ExtremeValueDistribution
I added an amplitude and made the two betas different. I figure your function's center is closer to 9.5 then 10.
New function:
a E^(-E^(((-x + alpha)/b1)) + (-x + alpha)/b2)/((b1 + b2)/2)
{alpha->9.5, b2 -> 0.899093, a -> 5822.2, b1 -> 0.381825}
Wolfram alpha:
plot 11193.8 E^(-E^(1.66667 (10 - x)) + 1.66667 (10 - x)) ,x 0..16, y from 0 to 4500
Some points around 10ms:
{{9, 390.254}, {10, 3979.59}, {11, 1680.73}, {12, 562.838}}
Tail does not fit perfectly though. The tail can be fit better if b2 is lower and the peak is chosen to be closer to 9.
|
How do I figure out what kind of distribution represents this data on ping response times?
Based on your comment "Really i want to draw the mathematical curve that follows the distribution. Granted it might not be a known distribution; but i can't imagine that this hasn't been investigated
|
12,411
|
How do I figure out what kind of distribution represents this data on ping response times?
|
The distribution looks log-normal to me.
You can fit your data using two parameters: scale and location. These can be fitted in much the same way as a normal distribution using expectation maximisation.
http://en.wikipedia.org/wiki/Log-normal_distribution
|
How do I figure out what kind of distribution represents this data on ping response times?
|
The distribution looks log-normal to me.
You can fit your data using two parameters: scale and location. These can be fitted in much the same way as a normal distribution using expectation maximisatio
|
How do I figure out what kind of distribution represents this data on ping response times?
The distribution looks log-normal to me.
You can fit your data using two parameters: scale and location. These can be fitted in much the same way as a normal distribution using expectation maximisation.
http://en.wikipedia.org/wiki/Log-normal_distribution
|
How do I figure out what kind of distribution represents this data on ping response times?
The distribution looks log-normal to me.
You can fit your data using two parameters: scale and location. These can be fitted in much the same way as a normal distribution using expectation maximisatio
|
12,412
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Perhaps the distribution is multimodal, i.e. the distributions could be a sum of different conditions and hence multiple distributions, e.g. such as a system that is idle vs. a system that is doing heavy single file downloading vs. a system that is streaming requiring regular intervals of high data throughput. The time spaces between pings may also be important, and some Nyquist-limited information may be lost in inadequate sampling.
There is an additional post here about summing multiple exponent distributions. I could not comment on nor upvote that one, so I made this separate response. The point on multiple hops is very valid, and I would first try analyzing pings to the next immediate node.
|
How do I figure out what kind of distribution represents this data on ping response times?
|
Perhaps the distribution is multimodal, i.e. the distributions could be a sum of different conditions and hence multiple distributions, e.g. such as a system that is idle vs. a system that is doing he
|
How do I figure out what kind of distribution represents this data on ping response times?
Perhaps the distribution is multimodal, i.e. the distributions could be a sum of different conditions and hence multiple distributions, e.g. such as a system that is idle vs. a system that is doing heavy single file downloading vs. a system that is streaming requiring regular intervals of high data throughput. The time spaces between pings may also be important, and some Nyquist-limited information may be lost in inadequate sampling.
There is an additional post here about summing multiple exponent distributions. I could not comment on nor upvote that one, so I made this separate response. The point on multiple hops is very valid, and I would first try analyzing pings to the next immediate node.
|
How do I figure out what kind of distribution represents this data on ping response times?
Perhaps the distribution is multimodal, i.e. the distributions could be a sum of different conditions and hence multiple distributions, e.g. such as a system that is idle vs. a system that is doing he
|
12,413
|
Why doesn't the exponential family include all distributions?
|
First, note there is a terminology problem in your title: the exponential family seems to imply one exponential family. You should say a exponential family, there are many exponential families.
Well, one consequence of your definition: $$p(\mathbf x|\boldsymbol \eta) = h(\mathbf x) g(\boldsymbol \eta) \exp \{\boldsymbol \eta^\mathrm T \mathbf u(\mathbf x)\}$$ is that the support of the distribution family indexed by parameter $\eta$ do not depend on $\eta$. (The support of a probability distribution is the (closure of) the smallest set with probability one, or in other words, where the distribution lives.) So it is enough to give a counterexample of a distribution family with support depending on the parameter, the most easy example is the following family of uniform distributions: $ \text{U}(0, \eta), \quad \eta > 0$. The following is an interesting example: Exponential family definition appears vacuous
Another, unrelated reason that not all distributions are exponential family, is that an exponential family distribution always have an existing moment generating function. Not all distributions have a mgf.
|
Why doesn't the exponential family include all distributions?
|
First, note there is a terminology problem in your title: the exponential family seems to imply one exponential family. You should say a exponential family, there are many exponential families.
Well,
|
Why doesn't the exponential family include all distributions?
First, note there is a terminology problem in your title: the exponential family seems to imply one exponential family. You should say a exponential family, there are many exponential families.
Well, one consequence of your definition: $$p(\mathbf x|\boldsymbol \eta) = h(\mathbf x) g(\boldsymbol \eta) \exp \{\boldsymbol \eta^\mathrm T \mathbf u(\mathbf x)\}$$ is that the support of the distribution family indexed by parameter $\eta$ do not depend on $\eta$. (The support of a probability distribution is the (closure of) the smallest set with probability one, or in other words, where the distribution lives.) So it is enough to give a counterexample of a distribution family with support depending on the parameter, the most easy example is the following family of uniform distributions: $ \text{U}(0, \eta), \quad \eta > 0$. The following is an interesting example: Exponential family definition appears vacuous
Another, unrelated reason that not all distributions are exponential family, is that an exponential family distribution always have an existing moment generating function. Not all distributions have a mgf.
|
Why doesn't the exponential family include all distributions?
First, note there is a terminology problem in your title: the exponential family seems to imply one exponential family. You should say a exponential family, there are many exponential families.
Well,
|
12,414
|
Why doesn't the exponential family include all distributions?
|
Consider the non-central Laplace distribution
$$
f(x; \mu, \sigma) \propto \exp \left(-| x - \mu | / \sigma \right).
$$
Unless $\mu = 0$ you won't be able to write $|x - \mu|$ as an inner product between $\mu$ and some function of $x$.
The exponential family does include the vast majority of the nice named distributions that we commonly encounter, so at first it may seem like it has everything of interest, but it by no means is exhaustive.
|
Why doesn't the exponential family include all distributions?
|
Consider the non-central Laplace distribution
$$
f(x; \mu, \sigma) \propto \exp \left(-| x - \mu | / \sigma \right).
$$
Unless $\mu = 0$ you won't be able to write $|x - \mu|$ as an inner product bet
|
Why doesn't the exponential family include all distributions?
Consider the non-central Laplace distribution
$$
f(x; \mu, \sigma) \propto \exp \left(-| x - \mu | / \sigma \right).
$$
Unless $\mu = 0$ you won't be able to write $|x - \mu|$ as an inner product between $\mu$ and some function of $x$.
The exponential family does include the vast majority of the nice named distributions that we commonly encounter, so at first it may seem like it has everything of interest, but it by no means is exhaustive.
|
Why doesn't the exponential family include all distributions?
Consider the non-central Laplace distribution
$$
f(x; \mu, \sigma) \propto \exp \left(-| x - \mu | / \sigma \right).
$$
Unless $\mu = 0$ you won't be able to write $|x - \mu|$ as an inner product bet
|
12,415
|
Why doesn't the exponential family include all distributions?
|
Both the existing answers are good, but just to try add a bit of intuition about what is going on here.
The equation you have written defines how to make an exponential family of distributions. Fixing $h$, $g$ and $u$ will give you a set of distributions that have parameter $\eta$. The correct choice of $h$, $g$ and $u$ will give you the Normal family with $\eta = (\mu, \sigma^2)$. There are thus an infinite number of exponential families, a finite number of which have names (Normal, Dirichlet, Poisson, ...)
You are sort of correct in that any specific distribution will be in an exponential family. The issue is finding $h$, $g$ and $u$ such that you completely cover another "traditional" family. So for example, the t-Distribution family is not an exponential family, but any specific realisation of the t-distribution will be in an exponential family. For example a t on 5 degrees of freedom centred on zero with scale 1 can be put into the exponential family form in an infinite number of ways. However, no other t-distributions will now be in that exponential family that you have made. It's kind of like a stopped watch is right twice a day.
The bit that typically goes wrong algebraically if you try to write these distributions as exponential family is that to be useful you need to be able scale and shift $x$ by your parameters. $h$ is no use because it doesn't have the parameter in it, and $g$ is useless because it just multiplies the whole pdf up and down - it's just normalising. That just leaves the product in the exponential - and you aren't allowed to apply any function after it. In my t(5) example the pdf is something like
$$f(x) \propto \left( 1 + \frac{x^2}{5}\right)^{-3} = \exp\left(-3 \ln\left(1+\frac{x^2}{5}\right)\right)$$
You can't get "inside" that $\ln$ so the only thing you can really do is say make a family where the 3 changes, but that isn't even changing the d.o.f. because the 5 inside the $\ln$ isn't changing. So I've made a new (pretty silly) exponential family that contains one t-Distribution, but I can't ever get all of them in the same family, plus I also pick up a load of weird distributions that are not t.
|
Why doesn't the exponential family include all distributions?
|
Both the existing answers are good, but just to try add a bit of intuition about what is going on here.
The equation you have written defines how to make an exponential family of distributions. Fixin
|
Why doesn't the exponential family include all distributions?
Both the existing answers are good, but just to try add a bit of intuition about what is going on here.
The equation you have written defines how to make an exponential family of distributions. Fixing $h$, $g$ and $u$ will give you a set of distributions that have parameter $\eta$. The correct choice of $h$, $g$ and $u$ will give you the Normal family with $\eta = (\mu, \sigma^2)$. There are thus an infinite number of exponential families, a finite number of which have names (Normal, Dirichlet, Poisson, ...)
You are sort of correct in that any specific distribution will be in an exponential family. The issue is finding $h$, $g$ and $u$ such that you completely cover another "traditional" family. So for example, the t-Distribution family is not an exponential family, but any specific realisation of the t-distribution will be in an exponential family. For example a t on 5 degrees of freedom centred on zero with scale 1 can be put into the exponential family form in an infinite number of ways. However, no other t-distributions will now be in that exponential family that you have made. It's kind of like a stopped watch is right twice a day.
The bit that typically goes wrong algebraically if you try to write these distributions as exponential family is that to be useful you need to be able scale and shift $x$ by your parameters. $h$ is no use because it doesn't have the parameter in it, and $g$ is useless because it just multiplies the whole pdf up and down - it's just normalising. That just leaves the product in the exponential - and you aren't allowed to apply any function after it. In my t(5) example the pdf is something like
$$f(x) \propto \left( 1 + \frac{x^2}{5}\right)^{-3} = \exp\left(-3 \ln\left(1+\frac{x^2}{5}\right)\right)$$
You can't get "inside" that $\ln$ so the only thing you can really do is say make a family where the 3 changes, but that isn't even changing the d.o.f. because the 5 inside the $\ln$ isn't changing. So I've made a new (pretty silly) exponential family that contains one t-Distribution, but I can't ever get all of them in the same family, plus I also pick up a load of weird distributions that are not t.
|
Why doesn't the exponential family include all distributions?
Both the existing answers are good, but just to try add a bit of intuition about what is going on here.
The equation you have written defines how to make an exponential family of distributions. Fixin
|
12,416
|
What is the difference between decision_function, predict_proba, and predict function for logistic regression problem?
|
Recall that the functional form of logistic regression is
$$ f(x) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x_1 + \cdots + \beta_k x_k)}} $$
This is what is returned by predict_proba.
The term inside the exponential
$$ d(x) = \beta_0 + \beta_1 x_1 + \cdots + \beta_k x_k $$
is what is returned by decision_function. The "hyperplane" referred to in the documentation is
$$ \beta_0 + \beta_1 x_1 + \cdots + \beta_k x_k = 0 $$
This terminology is a holdover from support vector machines, which literally estimate a separating hyperplane. For logistic regression this hyperplane is a bit of an artificial construct, it is the plane of equal probability, where the model has determined both target classes are equally likely.
The predict function returns a class decision using the rule
$$ f(x) > 0.5 $$
At the risk of soapboxing, the predict function has very few legitimate uses, and I view using it as a sign of error when reviewing others work. I would go far enough to call it a design error in sklearn itself (the predict_proba function should have been called predict, and predict should have been called predict_class, if anything at all).
|
What is the difference between decision_function, predict_proba, and predict function for logistic r
|
Recall that the functional form of logistic regression is
$$ f(x) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x_1 + \cdots + \beta_k x_k)}} $$
This is what is returned by predict_proba.
The term inside the
|
What is the difference between decision_function, predict_proba, and predict function for logistic regression problem?
Recall that the functional form of logistic regression is
$$ f(x) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x_1 + \cdots + \beta_k x_k)}} $$
This is what is returned by predict_proba.
The term inside the exponential
$$ d(x) = \beta_0 + \beta_1 x_1 + \cdots + \beta_k x_k $$
is what is returned by decision_function. The "hyperplane" referred to in the documentation is
$$ \beta_0 + \beta_1 x_1 + \cdots + \beta_k x_k = 0 $$
This terminology is a holdover from support vector machines, which literally estimate a separating hyperplane. For logistic regression this hyperplane is a bit of an artificial construct, it is the plane of equal probability, where the model has determined both target classes are equally likely.
The predict function returns a class decision using the rule
$$ f(x) > 0.5 $$
At the risk of soapboxing, the predict function has very few legitimate uses, and I view using it as a sign of error when reviewing others work. I would go far enough to call it a design error in sklearn itself (the predict_proba function should have been called predict, and predict should have been called predict_class, if anything at all).
|
What is the difference between decision_function, predict_proba, and predict function for logistic r
Recall that the functional form of logistic regression is
$$ f(x) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x_1 + \cdots + \beta_k x_k)}} $$
This is what is returned by predict_proba.
The term inside the
|
12,417
|
Does simple linear regression imply causation?
|
The quick answer is, no. You can easily come up with non-related data that when regressed, will pass all sorts of statistical tests. Below is an old picture from Wikipedia (which, for some reason has recently been removed) that has been used to illustrate data-driven "causality".
We need more pirates to cool the planet?
For time series, there is a term called "Granger Causality" that has a very specific meaning.
http://en.wikipedia.org/wiki/Granger_causality
Other than that, "causality" is in the eye of the beholder.
|
Does simple linear regression imply causation?
|
The quick answer is, no. You can easily come up with non-related data that when regressed, will pass all sorts of statistical tests. Below is an old picture from Wikipedia (which, for some reason
|
Does simple linear regression imply causation?
The quick answer is, no. You can easily come up with non-related data that when regressed, will pass all sorts of statistical tests. Below is an old picture from Wikipedia (which, for some reason has recently been removed) that has been used to illustrate data-driven "causality".
We need more pirates to cool the planet?
For time series, there is a term called "Granger Causality" that has a very specific meaning.
http://en.wikipedia.org/wiki/Granger_causality
Other than that, "causality" is in the eye of the beholder.
|
Does simple linear regression imply causation?
The quick answer is, no. You can easily come up with non-related data that when regressed, will pass all sorts of statistical tests. Below is an old picture from Wikipedia (which, for some reason
|
12,418
|
Does simple linear regression imply causation?
|
There is nothing explicit in the mathematics of regression that state causal relationships, and hence one need not explicitly interpret the slope (strength and direction) nor the p-values (i.e. the probability a relation as strong as or stronger would have been observed if the relationship were zero in the population) in a causal manner.
That being said, I would say regression does have a much stronger connotation that one is estimating an explicit directional relationship than does estimating the correlation between two variables. Assuming by correlation you mean Pearson's r, it typically does not have an explicit causal interpretation as the metric is symmetrical (i.e. you can switch which variable is X and which is Y and you will still have the same measure). Also the colloquialism "Correlation does not imply causation" I would suspect is so well known that stating two variables are correlated the assumption is one is not making a causal statement.
Estimated effects in regression analysis are not symetrical though, and so by choosing what variable is on the right hand side versus the left hand side one is making an implicit statement unlike that of the correlation. I suspect one intends to make some causal statement in the vast majority of circumstances in which regression is used (inference vs prediction aside). Even in cases of simply stating correlations I suspect people frequently have some implied goals of causal inference in mind. Given some constraints are met correlation can imply causation!
|
Does simple linear regression imply causation?
|
There is nothing explicit in the mathematics of regression that state causal relationships, and hence one need not explicitly interpret the slope (strength and direction) nor the p-values (i.e. the pr
|
Does simple linear regression imply causation?
There is nothing explicit in the mathematics of regression that state causal relationships, and hence one need not explicitly interpret the slope (strength and direction) nor the p-values (i.e. the probability a relation as strong as or stronger would have been observed if the relationship were zero in the population) in a causal manner.
That being said, I would say regression does have a much stronger connotation that one is estimating an explicit directional relationship than does estimating the correlation between two variables. Assuming by correlation you mean Pearson's r, it typically does not have an explicit causal interpretation as the metric is symmetrical (i.e. you can switch which variable is X and which is Y and you will still have the same measure). Also the colloquialism "Correlation does not imply causation" I would suspect is so well known that stating two variables are correlated the assumption is one is not making a causal statement.
Estimated effects in regression analysis are not symetrical though, and so by choosing what variable is on the right hand side versus the left hand side one is making an implicit statement unlike that of the correlation. I suspect one intends to make some causal statement in the vast majority of circumstances in which regression is used (inference vs prediction aside). Even in cases of simply stating correlations I suspect people frequently have some implied goals of causal inference in mind. Given some constraints are met correlation can imply causation!
|
Does simple linear regression imply causation?
There is nothing explicit in the mathematics of regression that state causal relationships, and hence one need not explicitly interpret the slope (strength and direction) nor the p-values (i.e. the pr
|
12,419
|
Does simple linear regression imply causation?
|
Neither correlation nor regression can indicate causation (as is illustrated by @bill_080's answer) but as @Andy W indicates regression is often based on an explicitly fixed (i.e., independent) variable and an explicit (i.e., random) dependent variable. These designations are not appropriate in correlation analysis.
To quote Sokal and Rohlf, 1969, p. 496
"In regression we intend to describe the dependence of a variable Y on an independent variable X... to lend support to hypotheses regarding the possible causation of changes in Y by changes in X..."
"In correlation, by contrast, we are concerned largely whether two variables are interdependent or covary - that is, vary together. We do not express one as a function of the other."
Sokal, R. R. and F. J. Rohlf, 1969. Biometry. Freeman and Co.
|
Does simple linear regression imply causation?
|
Neither correlation nor regression can indicate causation (as is illustrated by @bill_080's answer) but as @Andy W indicates regression is often based on an explicitly fixed (i.e., independent) variab
|
Does simple linear regression imply causation?
Neither correlation nor regression can indicate causation (as is illustrated by @bill_080's answer) but as @Andy W indicates regression is often based on an explicitly fixed (i.e., independent) variable and an explicit (i.e., random) dependent variable. These designations are not appropriate in correlation analysis.
To quote Sokal and Rohlf, 1969, p. 496
"In regression we intend to describe the dependence of a variable Y on an independent variable X... to lend support to hypotheses regarding the possible causation of changes in Y by changes in X..."
"In correlation, by contrast, we are concerned largely whether two variables are interdependent or covary - that is, vary together. We do not express one as a function of the other."
Sokal, R. R. and F. J. Rohlf, 1969. Biometry. Freeman and Co.
|
Does simple linear regression imply causation?
Neither correlation nor regression can indicate causation (as is illustrated by @bill_080's answer) but as @Andy W indicates regression is often based on an explicitly fixed (i.e., independent) variab
|
12,420
|
Does simple linear regression imply causation?
|
From a semantic perspective, an alternative goal is to build evidence for a good predictive model instead of proving causation. A simple procedure for building evidence for the predictive value of a regression model is to divide your data in 2 parts and fit your regression with one part of the data and with the other part of the data test how well it predicts.
The notion of Granger causality is interesting.
|
Does simple linear regression imply causation?
|
From a semantic perspective, an alternative goal is to build evidence for a good predictive model instead of proving causation. A simple procedure for building evidence for the predictive value of a r
|
Does simple linear regression imply causation?
From a semantic perspective, an alternative goal is to build evidence for a good predictive model instead of proving causation. A simple procedure for building evidence for the predictive value of a regression model is to divide your data in 2 parts and fit your regression with one part of the data and with the other part of the data test how well it predicts.
The notion of Granger causality is interesting.
|
Does simple linear regression imply causation?
From a semantic perspective, an alternative goal is to build evidence for a good predictive model instead of proving causation. A simple procedure for building evidence for the predictive value of a r
|
12,421
|
Does simple linear regression imply causation?
|
If you think of regression coefficients:
$$ \hat{\beta} = \frac{Cov(x,y)}{Var(x)} $$
$$\hat{\alpha}= \bar{y}-\hat{\beta}\bar{x} ,$$
where Var(.) and Cov(.) are estimates from sample (data).
Consequently, these parameters themselves are nothing else than some functions of correlation between x and y. Especially, beta is just a "normalised" correlation coefficient. So, theres is no more implied causality in regression than in correlation. Causal regression is a special technique in econometrics where one would have to rely on e.g. instrumental variables to get around phenomenons like confounding that obscure the causal interpretation of any particular regression model.
My point is: regression can be made causal but it is not causal y default.
For more see these videos:
https://www.youtube.com/watch?v=Sqy_b5OSiXw&list=PLwJRxp3blEvaxmHgI2iOzNP6KGLSyd4dz&index=55&t=0s
The "Rubin model" by Rubin himself: http://www.stat.columbia.edu/~cook/qr33.pdf
Great introductory course on causality (though, no regression yet):
https://www.coursera.org/learn/crash-course-in-causality
|
Does simple linear regression imply causation?
|
If you think of regression coefficients:
$$ \hat{\beta} = \frac{Cov(x,y)}{Var(x)} $$
$$\hat{\alpha}= \bar{y}-\hat{\beta}\bar{x} ,$$
where Var(.) and Cov(.) are estimates from sample (data).
Consequen
|
Does simple linear regression imply causation?
If you think of regression coefficients:
$$ \hat{\beta} = \frac{Cov(x,y)}{Var(x)} $$
$$\hat{\alpha}= \bar{y}-\hat{\beta}\bar{x} ,$$
where Var(.) and Cov(.) are estimates from sample (data).
Consequently, these parameters themselves are nothing else than some functions of correlation between x and y. Especially, beta is just a "normalised" correlation coefficient. So, theres is no more implied causality in regression than in correlation. Causal regression is a special technique in econometrics where one would have to rely on e.g. instrumental variables to get around phenomenons like confounding that obscure the causal interpretation of any particular regression model.
My point is: regression can be made causal but it is not causal y default.
For more see these videos:
https://www.youtube.com/watch?v=Sqy_b5OSiXw&list=PLwJRxp3blEvaxmHgI2iOzNP6KGLSyd4dz&index=55&t=0s
The "Rubin model" by Rubin himself: http://www.stat.columbia.edu/~cook/qr33.pdf
Great introductory course on causality (though, no regression yet):
https://www.coursera.org/learn/crash-course-in-causality
|
Does simple linear regression imply causation?
If you think of regression coefficients:
$$ \hat{\beta} = \frac{Cov(x,y)}{Var(x)} $$
$$\hat{\alpha}= \bar{y}-\hat{\beta}\bar{x} ,$$
where Var(.) and Cov(.) are estimates from sample (data).
Consequen
|
12,422
|
Does simple linear regression imply causation?
|
My understanding (I'm a causality beginner) is the following:
Linear regression implies causality if your covariates are from a controlled experiment, and your experiment isolates the hypothesized causal factor well (see Linear regression and causality in a randomized controlled experiment).
Alternatively, (updated thanks to comments), many violations of causality lead to $E(\epsilon|X)\neq 0$. Note that $E(\epsilon|X)\neq 0$ means that we can't draw causal conclusions, but $E(\epsilon|X)=0$ doesn't mean that we can.
Note that we can't test whether $E(\epsilon|X)=0$, and there is some circularity in the arguments here.
|
Does simple linear regression imply causation?
|
My understanding (I'm a causality beginner) is the following:
Linear regression implies causality if your covariates are from a controlled experiment, and your experiment isolates the hypothesized ca
|
Does simple linear regression imply causation?
My understanding (I'm a causality beginner) is the following:
Linear regression implies causality if your covariates are from a controlled experiment, and your experiment isolates the hypothesized causal factor well (see Linear regression and causality in a randomized controlled experiment).
Alternatively, (updated thanks to comments), many violations of causality lead to $E(\epsilon|X)\neq 0$. Note that $E(\epsilon|X)\neq 0$ means that we can't draw causal conclusions, but $E(\epsilon|X)=0$ doesn't mean that we can.
Note that we can't test whether $E(\epsilon|X)=0$, and there is some circularity in the arguments here.
|
Does simple linear regression imply causation?
My understanding (I'm a causality beginner) is the following:
Linear regression implies causality if your covariates are from a controlled experiment, and your experiment isolates the hypothesized ca
|
12,423
|
Graph theory -- analysis and visualization
|
iGraph is a very interesting cross-language (R, Python, Ruby, C) library.
It allows you to work with unidirected and directed graphs and has quite a few analysis algorithms already implemented.
|
Graph theory -- analysis and visualization
|
iGraph is a very interesting cross-language (R, Python, Ruby, C) library.
It allows you to work with unidirected and directed graphs and has quite a few analysis algorithms already implemented.
|
Graph theory -- analysis and visualization
iGraph is a very interesting cross-language (R, Python, Ruby, C) library.
It allows you to work with unidirected and directed graphs and has quite a few analysis algorithms already implemented.
|
Graph theory -- analysis and visualization
iGraph is a very interesting cross-language (R, Python, Ruby, C) library.
It allows you to work with unidirected and directed graphs and has quite a few analysis algorithms already implemented.
|
12,424
|
Graph theory -- analysis and visualization
|
There are various packages for representing directed and undirected graphs, incidence/adjacency matrix, etc. in addition to graph$^\dagger$; look for example at the gR Task view.
For visualization and basic computation, I think the igraph package is the reliable one, in addition to Rgraphviz (on BioC as pointed out by @Rob). Be aware that for the latter to be working properly, graphviz must be installed too. The igraph package has nice algorithms for creating good layouts, much like graphviz.
Here is an example of use, starting from a fake adjacency matrix:
adj.mat <- matrix(sample(c(0,1), 9, replace=TRUE), nr=3)
g <- graph.adjacency(adj.mat)
plot(g)
$^\dagger$ Package ‘graph’ was removed from the CRAN repository.
|
Graph theory -- analysis and visualization
|
There are various packages for representing directed and undirected graphs, incidence/adjacency matrix, etc. in addition to graph$^\dagger$; look for example at the gR Task view.
For visualization and
|
Graph theory -- analysis and visualization
There are various packages for representing directed and undirected graphs, incidence/adjacency matrix, etc. in addition to graph$^\dagger$; look for example at the gR Task view.
For visualization and basic computation, I think the igraph package is the reliable one, in addition to Rgraphviz (on BioC as pointed out by @Rob). Be aware that for the latter to be working properly, graphviz must be installed too. The igraph package has nice algorithms for creating good layouts, much like graphviz.
Here is an example of use, starting from a fake adjacency matrix:
adj.mat <- matrix(sample(c(0,1), 9, replace=TRUE), nr=3)
g <- graph.adjacency(adj.mat)
plot(g)
$^\dagger$ Package ‘graph’ was removed from the CRAN repository.
|
Graph theory -- analysis and visualization
There are various packages for representing directed and undirected graphs, incidence/adjacency matrix, etc. in addition to graph$^\dagger$; look for example at the gR Task view.
For visualization and
|
12,425
|
Graph theory -- analysis and visualization
|
Aside from what has been said, for the vusualization task alone (and outside from R), you might be interested in checking Gephi.
|
Graph theory -- analysis and visualization
|
Aside from what has been said, for the vusualization task alone (and outside from R), you might be interested in checking Gephi.
|
Graph theory -- analysis and visualization
Aside from what has been said, for the vusualization task alone (and outside from R), you might be interested in checking Gephi.
|
Graph theory -- analysis and visualization
Aside from what has been said, for the vusualization task alone (and outside from R), you might be interested in checking Gephi.
|
12,426
|
Graph theory -- analysis and visualization
|
Another option is the statnet package. Statnet has functions for all the commonly used measures in SNA, and can also estimate ERG models. If you have your data in an edge list, read in the data as follows (assuming your data frame is labelled "edgelist"):
net <- as.network(edgelist, matrix.type = "edgelist", directed = TRUE) #if the network is directed, otherwise: directed = FALSE
If your data is in an adjacency matrix you replace the matrix.type argument with "adjacency":
net <- as.network(edgelist, matrix.type = "adjacency", directed = TRUE)
The statnet package has some very nice plotting capabilities. To do a simple plot simply type:
gplot(net)
To scale the nodes according to their betweenness centrality, simply do:
bet <- betweenness(net)
gplot(net, vertex.cex = bet)
By default the gplot function uses Fruchterman-Reingold algorithm for placing the nodes, however this can be controlled from the mode option, for instance to use MDS for the placement of nodes type:
gplot(net, vertex.cex, mode = "mds")
or to use a circle layout:
gplot(net, vertex.cex, mode = "circle")
There are many more possibilities, and this guide covers most of the basic options.
For a self contained example:
net <- rgraph(20) #generate a random network with 20 nodes
bet <- betweenness(net) #calculate betweenness scores
gplot(net) #a simple plot
gplot(net, vertex.cex = bet/3) #nodes scaled according to their betweenness centrality, the measure is divided by 3 so the nodes don't become to big.
gplot(net, vertex.cex = bet/3, mode = "circle") #with a circle layout
gplot(net, vertex.cex = bet/3, mode = "circle", label = 1:20) #with node labels
|
Graph theory -- analysis and visualization
|
Another option is the statnet package. Statnet has functions for all the commonly used measures in SNA, and can also estimate ERG models. If you have your data in an edge list, read in the data as fol
|
Graph theory -- analysis and visualization
Another option is the statnet package. Statnet has functions for all the commonly used measures in SNA, and can also estimate ERG models. If you have your data in an edge list, read in the data as follows (assuming your data frame is labelled "edgelist"):
net <- as.network(edgelist, matrix.type = "edgelist", directed = TRUE) #if the network is directed, otherwise: directed = FALSE
If your data is in an adjacency matrix you replace the matrix.type argument with "adjacency":
net <- as.network(edgelist, matrix.type = "adjacency", directed = TRUE)
The statnet package has some very nice plotting capabilities. To do a simple plot simply type:
gplot(net)
To scale the nodes according to their betweenness centrality, simply do:
bet <- betweenness(net)
gplot(net, vertex.cex = bet)
By default the gplot function uses Fruchterman-Reingold algorithm for placing the nodes, however this can be controlled from the mode option, for instance to use MDS for the placement of nodes type:
gplot(net, vertex.cex, mode = "mds")
or to use a circle layout:
gplot(net, vertex.cex, mode = "circle")
There are many more possibilities, and this guide covers most of the basic options.
For a self contained example:
net <- rgraph(20) #generate a random network with 20 nodes
bet <- betweenness(net) #calculate betweenness scores
gplot(net) #a simple plot
gplot(net, vertex.cex = bet/3) #nodes scaled according to their betweenness centrality, the measure is divided by 3 so the nodes don't become to big.
gplot(net, vertex.cex = bet/3, mode = "circle") #with a circle layout
gplot(net, vertex.cex = bet/3, mode = "circle", label = 1:20) #with node labels
|
Graph theory -- analysis and visualization
Another option is the statnet package. Statnet has functions for all the commonly used measures in SNA, and can also estimate ERG models. If you have your data in an edge list, read in the data as fol
|
12,427
|
Graph theory -- analysis and visualization
|
A similar question was asked on cstheory, also if you are specifically interested in planar graphs, or bibliographic visualization.
Gephi was already mentioned here, but it was also recommended by a few on cstheory, so I think that is a good choice.
Other cool options include:
Flare provides some really cool visualization tools and create very pretty graphics for reports and papers.
Cyptoscape has some very powerful analysis and visualization tools. It is particularly good for chemistry and molecular biology.
This website provides links to many other nice visualization tools and libraries (although not for R).
|
Graph theory -- analysis and visualization
|
A similar question was asked on cstheory, also if you are specifically interested in planar graphs, or bibliographic visualization.
Gephi was already mentioned here, but it was also recommended by a f
|
Graph theory -- analysis and visualization
A similar question was asked on cstheory, also if you are specifically interested in planar graphs, or bibliographic visualization.
Gephi was already mentioned here, but it was also recommended by a few on cstheory, so I think that is a good choice.
Other cool options include:
Flare provides some really cool visualization tools and create very pretty graphics for reports and papers.
Cyptoscape has some very powerful analysis and visualization tools. It is particularly good for chemistry and molecular biology.
This website provides links to many other nice visualization tools and libraries (although not for R).
|
Graph theory -- analysis and visualization
A similar question was asked on cstheory, also if you are specifically interested in planar graphs, or bibliographic visualization.
Gephi was already mentioned here, but it was also recommended by a f
|
12,428
|
Graph theory -- analysis and visualization
|
I found NodeXL very helpful and easy to use. It is an MS Excel template that provides easy import / export of a graph, formatting of edges / vertices, calculates some metrics, has some clustering algorithms. You can easily use custom images as vertices.
Another helpful tool for me was Microsoft Automatic Graph layout which provides good layout can be tried online (with a browser that supports SVG).
|
Graph theory -- analysis and visualization
|
I found NodeXL very helpful and easy to use. It is an MS Excel template that provides easy import / export of a graph, formatting of edges / vertices, calculates some metrics, has some clustering algo
|
Graph theory -- analysis and visualization
I found NodeXL very helpful and easy to use. It is an MS Excel template that provides easy import / export of a graph, formatting of edges / vertices, calculates some metrics, has some clustering algorithms. You can easily use custom images as vertices.
Another helpful tool for me was Microsoft Automatic Graph layout which provides good layout can be tried online (with a browser that supports SVG).
|
Graph theory -- analysis and visualization
I found NodeXL very helpful and easy to use. It is an MS Excel template that provides easy import / export of a graph, formatting of edges / vertices, calculates some metrics, has some clustering algo
|
12,429
|
Why does the US death rate not "match" life expectancy
|
In short
The discrepancy between death rate and the reciprocal of the life expectancy generally occurs when the age distribution of the population is not the same as the survival curve, which relates to a hypothetical population on which the life expectancy is based (and more specifically the population is younger than what the survival curve suggests). There can be several reasons that create differences between the actual population and this hypothetical population
The death rate per age group has dropped suddenly/fast and the population is not yet stabilized (not equal to the survival curve based on the new death rates per age group)
The population is growing. If every year more babies are born than the previous year, then the population will be relatively younger than the hypothetical population based on what a survival curve suggests.
Migration. Migration is often occurring with relatively younger people. So the countries with positive net immigration will be relatively younger and the countries with negative immigration will be relatively older.
Life expectancy
The life expectancy is a virtual number based on a hypothetical person/population for which the mortality rates in the future are the same as the current mortality rates.
Some example using data (2014) from the Dutch bureau of statistics
https://opendata.cbs.nl/statline/#/CBS/nl/dataset/7052_95/table?dl=98D9
graph 1 shows (current) death rate for age $i$
$$f_i$$
graph 2 shows survival rate for age $i$ (for a hypothetical population that will experience the death rate for age $i$ as it is for the people that are currently of age $i$)
$$s_i = \prod_{j=0}^{j=i-1} (1-f_j)$$
graph 3 shows probability for dying at age $i$
$$p_i = s_i f_i$$
Note that $p_i$ is a hypothetical situation.
Death rates
In the above example, the hypothetical population will follow the middle graph. However the actual population is not this hypothetical population.
In particular, we have much less elderly people than what would be expected based on the survival rates. These survival rates are based on the death rates in the present time. But when the elderly grew up these death rates were much larger. Therefore, the population contains less elderly than the current survival rate curve suggest.
The population looks more like this (sorry for it being in Dutch and not well documented, I am getting these images from some old doodles, I will see if I can make the graphs again):
So around 2040 the distribution of the population will be more similar to the curve of the survival rate. Currently, the population distribution is more pointy, and that is because the people that are currently old did not experience the probabilities of dying at age $i$ on which the hypothetical life expectancy is based.
How death rates are changing
In addition, there is a slightly lower birth rate (less than 2 per woman), and so the younger population is shrinking. This means that the death rate will not just rise to 1/life_expectancy, but even surpass it.
This is an interesting paradox. (As Neil G commented it's Simpson's paradox)
On the one hand the death rate is decreasing in each separate age group.
On the other hand the death rate is increasing for the total population.
Note this graph interactive version on gapminder
We see that in the past decades the death rates have dropped quickly (due to decrease in death rate) and now are rising again (due to stabilization of the population, and due to decrease in birth rate). Most countries follow this pattern (some started earlier some started later).
Simulation
In this question the answer contains a piece of R-code that simulates the survival rate curve for a change of the risk-ratio of death for all ages.
Below we use the same function life_expect and simulate the death rate in a population when we let this risk ratio change from 1.5 to 1.0 in the course of 50 years (thus life expectancy will increase and the inverse, the death rate based on life-expectancy, will decrease).
What we see is that the drop in the death rate in the population is larger than what we would expect based on the life expectancy, and is only stabilizing at this expected number after some time when we stop the change in risk ratios.
Note, in this population we kept the births constant. Another way how the discrepancy between the reciprocal of the life expectancy and the death rate arrises is when the number of births is increasing (population growth) which causes the population to be relatively young in comparison to the hypothetical population based on the survival curve.
### initial population
ts <- life_expect(base, 0, rr = 1.5, rrstart = 0)
pop <- ts$survival
Mpop <- pop
### death rates
dr <- sum(ts$death_rate*pop)/sum(pop)
de <- 1/(ts$Elife+1)
for (i in -100:200) {
### rr changing from 1.5 to 1 for i between 0 and 50
t <- life_expect(base, 0, rr = 1.5-max(0,0.5*min(i/50,1)), rrstart = 0)
### death rate in population
dr <- c(dr,sum(t$death_rate*pop)/sum(pop))
### death rate based on life expectancy
de <- c(de,1/(t$Elife+1))
### update population
pop <- c(1,((1-t$death_rate)*pop)[-101])
Mpop <- cbind(Mpop,pop)
}
### plotting
plot(de * 100, type = "l", lty = 2, lwd = 2, ylim = c(1.10,1.4),
xlab = "time", xaxt = "n", ylab = "rate %")
lines(dr * 100, col = 2)
legend(0,1.10, c("death rate in population", "death rate based on life expectancy"),
lty = c(1,2), lwd = c(1,2), col = c(2,1),
cex = 0.7, xjust = 0, yjust = 0)
|
Why does the US death rate not "match" life expectancy
|
In short
The discrepancy between death rate and the reciprocal of the life expectancy generally occurs when the age distribution of the population is not the same as the survival curve, which relates
|
Why does the US death rate not "match" life expectancy
In short
The discrepancy between death rate and the reciprocal of the life expectancy generally occurs when the age distribution of the population is not the same as the survival curve, which relates to a hypothetical population on which the life expectancy is based (and more specifically the population is younger than what the survival curve suggests). There can be several reasons that create differences between the actual population and this hypothetical population
The death rate per age group has dropped suddenly/fast and the population is not yet stabilized (not equal to the survival curve based on the new death rates per age group)
The population is growing. If every year more babies are born than the previous year, then the population will be relatively younger than the hypothetical population based on what a survival curve suggests.
Migration. Migration is often occurring with relatively younger people. So the countries with positive net immigration will be relatively younger and the countries with negative immigration will be relatively older.
Life expectancy
The life expectancy is a virtual number based on a hypothetical person/population for which the mortality rates in the future are the same as the current mortality rates.
Some example using data (2014) from the Dutch bureau of statistics
https://opendata.cbs.nl/statline/#/CBS/nl/dataset/7052_95/table?dl=98D9
graph 1 shows (current) death rate for age $i$
$$f_i$$
graph 2 shows survival rate for age $i$ (for a hypothetical population that will experience the death rate for age $i$ as it is for the people that are currently of age $i$)
$$s_i = \prod_{j=0}^{j=i-1} (1-f_j)$$
graph 3 shows probability for dying at age $i$
$$p_i = s_i f_i$$
Note that $p_i$ is a hypothetical situation.
Death rates
In the above example, the hypothetical population will follow the middle graph. However the actual population is not this hypothetical population.
In particular, we have much less elderly people than what would be expected based on the survival rates. These survival rates are based on the death rates in the present time. But when the elderly grew up these death rates were much larger. Therefore, the population contains less elderly than the current survival rate curve suggest.
The population looks more like this (sorry for it being in Dutch and not well documented, I am getting these images from some old doodles, I will see if I can make the graphs again):
So around 2040 the distribution of the population will be more similar to the curve of the survival rate. Currently, the population distribution is more pointy, and that is because the people that are currently old did not experience the probabilities of dying at age $i$ on which the hypothetical life expectancy is based.
How death rates are changing
In addition, there is a slightly lower birth rate (less than 2 per woman), and so the younger population is shrinking. This means that the death rate will not just rise to 1/life_expectancy, but even surpass it.
This is an interesting paradox. (As Neil G commented it's Simpson's paradox)
On the one hand the death rate is decreasing in each separate age group.
On the other hand the death rate is increasing for the total population.
Note this graph interactive version on gapminder
We see that in the past decades the death rates have dropped quickly (due to decrease in death rate) and now are rising again (due to stabilization of the population, and due to decrease in birth rate). Most countries follow this pattern (some started earlier some started later).
Simulation
In this question the answer contains a piece of R-code that simulates the survival rate curve for a change of the risk-ratio of death for all ages.
Below we use the same function life_expect and simulate the death rate in a population when we let this risk ratio change from 1.5 to 1.0 in the course of 50 years (thus life expectancy will increase and the inverse, the death rate based on life-expectancy, will decrease).
What we see is that the drop in the death rate in the population is larger than what we would expect based on the life expectancy, and is only stabilizing at this expected number after some time when we stop the change in risk ratios.
Note, in this population we kept the births constant. Another way how the discrepancy between the reciprocal of the life expectancy and the death rate arrises is when the number of births is increasing (population growth) which causes the population to be relatively young in comparison to the hypothetical population based on the survival curve.
### initial population
ts <- life_expect(base, 0, rr = 1.5, rrstart = 0)
pop <- ts$survival
Mpop <- pop
### death rates
dr <- sum(ts$death_rate*pop)/sum(pop)
de <- 1/(ts$Elife+1)
for (i in -100:200) {
### rr changing from 1.5 to 1 for i between 0 and 50
t <- life_expect(base, 0, rr = 1.5-max(0,0.5*min(i/50,1)), rrstart = 0)
### death rate in population
dr <- c(dr,sum(t$death_rate*pop)/sum(pop))
### death rate based on life expectancy
de <- c(de,1/(t$Elife+1))
### update population
pop <- c(1,((1-t$death_rate)*pop)[-101])
Mpop <- cbind(Mpop,pop)
}
### plotting
plot(de * 100, type = "l", lty = 2, lwd = 2, ylim = c(1.10,1.4),
xlab = "time", xaxt = "n", ylab = "rate %")
lines(dr * 100, col = 2)
legend(0,1.10, c("death rate in population", "death rate based on life expectancy"),
lty = c(1,2), lwd = c(1,2), col = c(2,1),
cex = 0.7, xjust = 0, yjust = 0)
|
Why does the US death rate not "match" life expectancy
In short
The discrepancy between death rate and the reciprocal of the life expectancy generally occurs when the age distribution of the population is not the same as the survival curve, which relates
|
12,430
|
Why does the US death rate not "match" life expectancy
|
There is a simpler way to understand this than the (detailed and correct) explanation in another answer.
The life expectancy now depends on the death rate in the past.
As an extreme example, suppose that some disaster infected every person in a country with a medical condition which was incurable and had a 50% fatality rate.
The annual death rate would therefore be 50,000 per 100,000 population (ignoring deaths from other causes, for simplicity).
But the life expectancy would not be 2 years, because almost everyone in the country has already lived for more than 2 years.
The only situation where the numbers are reciprocals of each other is the unlikely situation that all the factors affecting birth rate, death rate, and age-related mortality have remained constant for the lifespan of the current population.
|
Why does the US death rate not "match" life expectancy
|
There is a simpler way to understand this than the (detailed and correct) explanation in another answer.
The life expectancy now depends on the death rate in the past.
As an extreme example, suppose t
|
Why does the US death rate not "match" life expectancy
There is a simpler way to understand this than the (detailed and correct) explanation in another answer.
The life expectancy now depends on the death rate in the past.
As an extreme example, suppose that some disaster infected every person in a country with a medical condition which was incurable and had a 50% fatality rate.
The annual death rate would therefore be 50,000 per 100,000 population (ignoring deaths from other causes, for simplicity).
But the life expectancy would not be 2 years, because almost everyone in the country has already lived for more than 2 years.
The only situation where the numbers are reciprocals of each other is the unlikely situation that all the factors affecting birth rate, death rate, and age-related mortality have remained constant for the lifespan of the current population.
|
Why does the US death rate not "match" life expectancy
There is a simpler way to understand this than the (detailed and correct) explanation in another answer.
The life expectancy now depends on the death rate in the past.
As an extreme example, suppose t
|
12,431
|
Overfitting and Underfitting
|
I'll try to answer in the simplest way. Each of those problems has its own main origin:
Overfitting: Data is noisy, meaning that there are some deviations from reality (because of measurement errors, influentially random factors, unobserved variables and rubbish correlations) that makes it harder for us to see their true relationship with our explaining factors. Also, it is usually not complete (we don't have examples of everything).
As an example, let's say I am trying to classify boys and girls based on their height, just because that's the only information I have about them. We all know that even though boys are taller on average than girls, there is a huge overlap region, making it impossible to perfectly separate them just with that bit of information. Depending on the density of the data, a sufficiently complex model might be able to achieve a better success rate on this task than is theoretically possible on the training dataset because it could draw boundaries that allow some points to stand alone by themselves. So, if we only have a person who is 2.04 meters tall and she's a woman, then the model could draw a little circle around that area meaning that a random person who is 2.04 meters tall is most likely to be a woman.
The underlying reason for it all is trusting too much in training data (and in the example, the model says that as there is no man with 2.04 height, then it is only possible for women).
Underfitting is the opposite problem, in which the model fails to recognize the real complexities in our data (i.e. the non-random changes in our data). The model assumes that noise is greater than it really is and thus uses a too simplistic shape. So, if the dataset has much more girls than boys for whatever reason, then the model could just classify them all like girls.
In this case, the model didn't trust enough in data and it just assumed that deviations are all noise (and in the example, the model assumes that boys simply do not exist).
Bottom line is that we face these problems because:
We don't have complete information.
We don't know how noisy the data is (we don't know how much we should trust it).
We don't know in advance the underlying function that generated our data, and thus the optimal model complexity.
|
Overfitting and Underfitting
|
I'll try to answer in the simplest way. Each of those problems has its own main origin:
Overfitting: Data is noisy, meaning that there are some deviations from reality (because of measurement errors,
|
Overfitting and Underfitting
I'll try to answer in the simplest way. Each of those problems has its own main origin:
Overfitting: Data is noisy, meaning that there are some deviations from reality (because of measurement errors, influentially random factors, unobserved variables and rubbish correlations) that makes it harder for us to see their true relationship with our explaining factors. Also, it is usually not complete (we don't have examples of everything).
As an example, let's say I am trying to classify boys and girls based on their height, just because that's the only information I have about them. We all know that even though boys are taller on average than girls, there is a huge overlap region, making it impossible to perfectly separate them just with that bit of information. Depending on the density of the data, a sufficiently complex model might be able to achieve a better success rate on this task than is theoretically possible on the training dataset because it could draw boundaries that allow some points to stand alone by themselves. So, if we only have a person who is 2.04 meters tall and she's a woman, then the model could draw a little circle around that area meaning that a random person who is 2.04 meters tall is most likely to be a woman.
The underlying reason for it all is trusting too much in training data (and in the example, the model says that as there is no man with 2.04 height, then it is only possible for women).
Underfitting is the opposite problem, in which the model fails to recognize the real complexities in our data (i.e. the non-random changes in our data). The model assumes that noise is greater than it really is and thus uses a too simplistic shape. So, if the dataset has much more girls than boys for whatever reason, then the model could just classify them all like girls.
In this case, the model didn't trust enough in data and it just assumed that deviations are all noise (and in the example, the model assumes that boys simply do not exist).
Bottom line is that we face these problems because:
We don't have complete information.
We don't know how noisy the data is (we don't know how much we should trust it).
We don't know in advance the underlying function that generated our data, and thus the optimal model complexity.
|
Overfitting and Underfitting
I'll try to answer in the simplest way. Each of those problems has its own main origin:
Overfitting: Data is noisy, meaning that there are some deviations from reality (because of measurement errors,
|
12,432
|
Overfitting and Underfitting
|
Overfitting is when a model estimates the variable you are modeling really well on the original data, but it does not estimate well on new data set (hold out, cross validation, forecasting, etc.). You have too many variables or estimators in your model (dummy variables, etc.) and these cause your model to become too sensitive to the noise in your original data. As a result of overfitting on the noise in your original data, the model predicts poorly.
Underfitting is when a model does not estimate the variable well in either the original data or new data. Your model is missing some variables that are necessary to better estimate and predict the behavior of your dependent variable.
The balancing act between over and underfitting is challenging and sometimes without a clear finish line. In modeling econometrics time series, this issue is resolved pretty well with regularization models (LASSO, Ridge Regression, Elastic-Net) that are catered specifically to reducing overfitting by respectively reducing the number of variables in your model, reducing the sensitivity of the coefficients to your data, or a combination of both.
|
Overfitting and Underfitting
|
Overfitting is when a model estimates the variable you are modeling really well on the original data, but it does not estimate well on new data set (hold out, cross validation, forecasting, etc.). Yo
|
Overfitting and Underfitting
Overfitting is when a model estimates the variable you are modeling really well on the original data, but it does not estimate well on new data set (hold out, cross validation, forecasting, etc.). You have too many variables or estimators in your model (dummy variables, etc.) and these cause your model to become too sensitive to the noise in your original data. As a result of overfitting on the noise in your original data, the model predicts poorly.
Underfitting is when a model does not estimate the variable well in either the original data or new data. Your model is missing some variables that are necessary to better estimate and predict the behavior of your dependent variable.
The balancing act between over and underfitting is challenging and sometimes without a clear finish line. In modeling econometrics time series, this issue is resolved pretty well with regularization models (LASSO, Ridge Regression, Elastic-Net) that are catered specifically to reducing overfitting by respectively reducing the number of variables in your model, reducing the sensitivity of the coefficients to your data, or a combination of both.
|
Overfitting and Underfitting
Overfitting is when a model estimates the variable you are modeling really well on the original data, but it does not estimate well on new data set (hold out, cross validation, forecasting, etc.). Yo
|
12,433
|
Overfitting and Underfitting
|
Perhaps during your research you came across the following equation:
Error = IrreducibleError + Bias² + Variance.
Why do we face these two problems in training a model ?
The learning problem itself is basically a trade-off between bias and variance.
What are the main reasons for overfitting and underfitting ?
Short: Noise.
Long: The irreducible error: Measurement errors/fluctuations in the data as well as the part of the target function that cannot be represented by the model. Remeasuring the target variable or changing the hypothesis space (i.e. selecting a different model) changes this component.
Edit (to link to the other answers): Model performance as complexity is varied:
where errorD is the error over the entire distribution D (in practice estimated with test sets).
|
Overfitting and Underfitting
|
Perhaps during your research you came across the following equation:
Error = IrreducibleError + Bias² + Variance.
Why do we face these two problems in training a model ?
The learning problem itself
|
Overfitting and Underfitting
Perhaps during your research you came across the following equation:
Error = IrreducibleError + Bias² + Variance.
Why do we face these two problems in training a model ?
The learning problem itself is basically a trade-off between bias and variance.
What are the main reasons for overfitting and underfitting ?
Short: Noise.
Long: The irreducible error: Measurement errors/fluctuations in the data as well as the part of the target function that cannot be represented by the model. Remeasuring the target variable or changing the hypothesis space (i.e. selecting a different model) changes this component.
Edit (to link to the other answers): Model performance as complexity is varied:
where errorD is the error over the entire distribution D (in practice estimated with test sets).
|
Overfitting and Underfitting
Perhaps during your research you came across the following equation:
Error = IrreducibleError + Bias² + Variance.
Why do we face these two problems in training a model ?
The learning problem itself
|
12,434
|
Overfitting and Underfitting
|
Almost all statistical problems can be stated in the following form:
Given the data $(y, x)$ find $\hat{f}$ which produces $\hat{y}=\hat{f}(x)$.
Make this $\hat{f}$ as close as possible to "true" $f$, where $f$ is defined as
$$y = f(x) + \varepsilon$$
The temptation is always to make $\hat{f}$ produce $\hat{y}$ which are very close to the data $y$. But when new data point arrives, or we use data which was not used to construct $\hat{f}$ the prediction may be way off. This happens because we are trying to explain $\varepsilon$ instead of $f$. When we do this we stray from "true" $f$ and hence when new observation comes in we get a bad prediction. This when overfitting happens.
On the other hand when we find $\hat{f}$ the question is always maybe we can get a better $\tilde{f}$ which produces better fit and is close to "true" $f$? If we can then we underfitted in the first case.
If you look at the statistical problem this way, fitting the model is always a balance between underfitting and overfitting and any solution is always a compromise. We face this problem because our data is random and noisy.
|
Overfitting and Underfitting
|
Almost all statistical problems can be stated in the following form:
Given the data $(y, x)$ find $\hat{f}$ which produces $\hat{y}=\hat{f}(x)$.
Make this $\hat{f}$ as close as possible to "true" $f
|
Overfitting and Underfitting
Almost all statistical problems can be stated in the following form:
Given the data $(y, x)$ find $\hat{f}$ which produces $\hat{y}=\hat{f}(x)$.
Make this $\hat{f}$ as close as possible to "true" $f$, where $f$ is defined as
$$y = f(x) + \varepsilon$$
The temptation is always to make $\hat{f}$ produce $\hat{y}$ which are very close to the data $y$. But when new data point arrives, or we use data which was not used to construct $\hat{f}$ the prediction may be way off. This happens because we are trying to explain $\varepsilon$ instead of $f$. When we do this we stray from "true" $f$ and hence when new observation comes in we get a bad prediction. This when overfitting happens.
On the other hand when we find $\hat{f}$ the question is always maybe we can get a better $\tilde{f}$ which produces better fit and is close to "true" $f$? If we can then we underfitted in the first case.
If you look at the statistical problem this way, fitting the model is always a balance between underfitting and overfitting and any solution is always a compromise. We face this problem because our data is random and noisy.
|
Overfitting and Underfitting
Almost all statistical problems can be stated in the following form:
Given the data $(y, x)$ find $\hat{f}$ which produces $\hat{y}=\hat{f}(x)$.
Make this $\hat{f}$ as close as possible to "true" $f
|
12,435
|
Overfitting and Underfitting
|
What are the main reasons for overfitting and underfitting ?
For overfitting, the model is too complex to fit the training data well. For underfitting, the model is too simple.
Why do we face these two problems in training a model ?
It is hard to pick the "just right" model and parameters for the data.
|
Overfitting and Underfitting
|
What are the main reasons for overfitting and underfitting ?
For overfitting, the model is too complex to fit the training data well. For underfitting, the model is too simple.
Why do we face these
|
Overfitting and Underfitting
What are the main reasons for overfitting and underfitting ?
For overfitting, the model is too complex to fit the training data well. For underfitting, the model is too simple.
Why do we face these two problems in training a model ?
It is hard to pick the "just right" model and parameters for the data.
|
Overfitting and Underfitting
What are the main reasons for overfitting and underfitting ?
For overfitting, the model is too complex to fit the training data well. For underfitting, the model is too simple.
Why do we face these
|
12,436
|
Overfitting and Underfitting
|
Overfitting and underfitting are basically inadequate explanations of the data by an hypothesized model and can be seen as the model overexplaining or underexplaining the data. This is created by the relationship between the model used to explain the data and the model generating the data. In our attempt to explain we cannot access the underlying model so our judgement is guided by another factor: the uncertainties or error bars.
When, in an attempt to fit all the variance, we use a model that is too complex, we are overfitting. This is created by us having free reign in the model choice and according too much importance to the error bars (or trying to explain all the variability, which is the same). When restricting ourselves to a model that is too simple to describe the data, and not assigning enough importance to the error bars (or not explaining the variability), we are underfitting.
How can one avoid these two? Information backed models (not derived from the data but from prior knowledge of the problem) and meaningful uncertainties.
|
Overfitting and Underfitting
|
Overfitting and underfitting are basically inadequate explanations of the data by an hypothesized model and can be seen as the model overexplaining or underexplaining the data. This is created by the
|
Overfitting and Underfitting
Overfitting and underfitting are basically inadequate explanations of the data by an hypothesized model and can be seen as the model overexplaining or underexplaining the data. This is created by the relationship between the model used to explain the data and the model generating the data. In our attempt to explain we cannot access the underlying model so our judgement is guided by another factor: the uncertainties or error bars.
When, in an attempt to fit all the variance, we use a model that is too complex, we are overfitting. This is created by us having free reign in the model choice and according too much importance to the error bars (or trying to explain all the variability, which is the same). When restricting ourselves to a model that is too simple to describe the data, and not assigning enough importance to the error bars (or not explaining the variability), we are underfitting.
How can one avoid these two? Information backed models (not derived from the data but from prior knowledge of the problem) and meaningful uncertainties.
|
Overfitting and Underfitting
Overfitting and underfitting are basically inadequate explanations of the data by an hypothesized model and can be seen as the model overexplaining or underexplaining the data. This is created by the
|
12,437
|
Overfitting and Underfitting
|
In a nutshell, overfiitting appears as a consequence of patterns that appear in your training dataset but are not present on the entire population (they appeared out of luck) If your use a simple model (think for linear regression for instance), risk of overfitting is low, as the number of possible patterns it can detect is small and therefore the chance of one of those randomly showing in the sample is not that big either. An example of this may occur if you try to study correlations 1,000,000 variables on a population taking a 100-individual sample. Some of the features may randomly present a huge sample correlation despite being completely independent from one another
Another reason for overfitting is biased sampling (the "sample fake patterns" are there because the sample is not really random) For example, if you want to study the average size of a certain kind of mushroom by going out there and finding them in nature, you are likely to overestimate it (bigger mushrooms are easier to find)
Underfitting is, on the other hand, a quite simpler phenomenon. It can mean two very basic things: A) We do not have enough data for the model to learn the population pattern or B) Our model is not powerful enough to reflect it.
You can find a case of A if you have a phenomenon like $y = a*x + \epsilon$ where $\epsilon$ is a random variable with mean 0 and standard deviation 1000, and the actual value of a (the parameter you want to estimate) ia 1. If you don't take enough data, you may not even be able to distinguish a from 0 thus claiming y and x are uncorrelated/independent from one another.
B could occur if your model is way to simple, for example, if $y = x^2 + \epsilon$ and you try linear regression, well.... Good luck!
|
Overfitting and Underfitting
|
In a nutshell, overfiitting appears as a consequence of patterns that appear in your training dataset but are not present on the entire population (they appeared out of luck) If your use a simple mode
|
Overfitting and Underfitting
In a nutshell, overfiitting appears as a consequence of patterns that appear in your training dataset but are not present on the entire population (they appeared out of luck) If your use a simple model (think for linear regression for instance), risk of overfitting is low, as the number of possible patterns it can detect is small and therefore the chance of one of those randomly showing in the sample is not that big either. An example of this may occur if you try to study correlations 1,000,000 variables on a population taking a 100-individual sample. Some of the features may randomly present a huge sample correlation despite being completely independent from one another
Another reason for overfitting is biased sampling (the "sample fake patterns" are there because the sample is not really random) For example, if you want to study the average size of a certain kind of mushroom by going out there and finding them in nature, you are likely to overestimate it (bigger mushrooms are easier to find)
Underfitting is, on the other hand, a quite simpler phenomenon. It can mean two very basic things: A) We do not have enough data for the model to learn the population pattern or B) Our model is not powerful enough to reflect it.
You can find a case of A if you have a phenomenon like $y = a*x + \epsilon$ where $\epsilon$ is a random variable with mean 0 and standard deviation 1000, and the actual value of a (the parameter you want to estimate) ia 1. If you don't take enough data, you may not even be able to distinguish a from 0 thus claiming y and x are uncorrelated/independent from one another.
B could occur if your model is way to simple, for example, if $y = x^2 + \epsilon$ and you try linear regression, well.... Good luck!
|
Overfitting and Underfitting
In a nutshell, overfiitting appears as a consequence of patterns that appear in your training dataset but are not present on the entire population (they appeared out of luck) If your use a simple mode
|
12,438
|
Overfitting and Underfitting
|
Short answer:
The main reason for overfitting is using a complex model when you have a small training set.
The main reason for underfitting is using a model that is too simple and can not perform well on the training set.
Main reason for overfitting?
Models with high capacity can overfit by memorizing properties of the training set that do not serve them well on the test set.
-Deep Learning book, Goodfellow et al.
The goal of machine learning is to train a model on the training set in hopes that it will perform just as well on the testing data. But does getting good performance on the training set always translate to a good performance on the testing set? It will not, because your training data is limited. If you have limited data, your model might find some patterns that work for that limited training set, but those patterns do not generalize to other cases (i.e. test set). This can be solved by either:
A- Providing a larger training set to the model to reduce the chance of having arbitrary patterns in the training set.
B- Using a simpler model so that the model will not be able to find those arbitrary patterns in the training set. A more complex model will be able to find more complicated patterns, so you need more data to make sure your training set is large enough to not contain arbitrary patterns.
(e.g. Imagine you want to teach a model to detect ships from trucks and you have 10 images of each. If most of the ships in your images are in the water, your model might learn to classify any picture with a blue background as a ship instead of learning how a ship looks. Now, if you had 10,000 images of ships and trucks, your training set is more likely to contain ships and trucks in a variety of backgrounds and your model can no longer just rely on the blue background.)
Main reason for underfitting?
Underfitting occurs when the model is not able to obtain a sufficiently low error value on the training set.
Models with low capacity may struggle to fit the training set.
-Deep Learning book, Goodfellow et al.
Underfitting occurs when your model is just not good enough to learn the training set, meaning your model is too simple. Whenever we start solving a problem, we want a model which is at least able to get a good performance on the training set, and then we start to think of reducing overfitting. Generally, the solution to underfitting is pretty straight forward: Use a more complex model.
|
Overfitting and Underfitting
|
Short answer:
The main reason for overfitting is using a complex model when you have a small training set.
The main reason for underfitting is using a model that is too simple and can not perform well
|
Overfitting and Underfitting
Short answer:
The main reason for overfitting is using a complex model when you have a small training set.
The main reason for underfitting is using a model that is too simple and can not perform well on the training set.
Main reason for overfitting?
Models with high capacity can overfit by memorizing properties of the training set that do not serve them well on the test set.
-Deep Learning book, Goodfellow et al.
The goal of machine learning is to train a model on the training set in hopes that it will perform just as well on the testing data. But does getting good performance on the training set always translate to a good performance on the testing set? It will not, because your training data is limited. If you have limited data, your model might find some patterns that work for that limited training set, but those patterns do not generalize to other cases (i.e. test set). This can be solved by either:
A- Providing a larger training set to the model to reduce the chance of having arbitrary patterns in the training set.
B- Using a simpler model so that the model will not be able to find those arbitrary patterns in the training set. A more complex model will be able to find more complicated patterns, so you need more data to make sure your training set is large enough to not contain arbitrary patterns.
(e.g. Imagine you want to teach a model to detect ships from trucks and you have 10 images of each. If most of the ships in your images are in the water, your model might learn to classify any picture with a blue background as a ship instead of learning how a ship looks. Now, if you had 10,000 images of ships and trucks, your training set is more likely to contain ships and trucks in a variety of backgrounds and your model can no longer just rely on the blue background.)
Main reason for underfitting?
Underfitting occurs when the model is not able to obtain a sufficiently low error value on the training set.
Models with low capacity may struggle to fit the training set.
-Deep Learning book, Goodfellow et al.
Underfitting occurs when your model is just not good enough to learn the training set, meaning your model is too simple. Whenever we start solving a problem, we want a model which is at least able to get a good performance on the training set, and then we start to think of reducing overfitting. Generally, the solution to underfitting is pretty straight forward: Use a more complex model.
|
Overfitting and Underfitting
Short answer:
The main reason for overfitting is using a complex model when you have a small training set.
The main reason for underfitting is using a model that is too simple and can not perform well
|
12,439
|
Overfitting and Underfitting
|
Consider an example where we have a hypothesis/model equation,
y=q*X+c,
where X=feature list, y=label and q and c are the coefficients that we have to trained.
If we come up with the coefficient values such that its large enough and start suppressing the features value(i.e. X) in such a case we always get the constant value of y, irrespective of any X value. This is called highly biased or underfit model.
Consider another complex hypothesis example,
y=q*X+r*sqr(X)+s*cube(X)+c, where q,r,s and c are the coefficients.
After identifying the best coefficients value it's possible that for the training data, we can get the minimum loss. It's only because we made our model so complex and tightly coupled that it behave very well with the training data. Whereas with the unseen data wwe can get pretty opposite results. This is called highly varianced or overfit model.
Biased model needs more complexity in Model selection whereas highly varianced model needs drop in complexity in model selection. Regularization technique can help us in identifying the proper level of model complexity and through this technique we can overcome with both the issues.
|
Overfitting and Underfitting
|
Consider an example where we have a hypothesis/model equation,
y=q*X+c,
where X=feature list, y=label and q and c are the coefficients that we have to trained.
If we come up with the coefficient va
|
Overfitting and Underfitting
Consider an example where we have a hypothesis/model equation,
y=q*X+c,
where X=feature list, y=label and q and c are the coefficients that we have to trained.
If we come up with the coefficient values such that its large enough and start suppressing the features value(i.e. X) in such a case we always get the constant value of y, irrespective of any X value. This is called highly biased or underfit model.
Consider another complex hypothesis example,
y=q*X+r*sqr(X)+s*cube(X)+c, where q,r,s and c are the coefficients.
After identifying the best coefficients value it's possible that for the training data, we can get the minimum loss. It's only because we made our model so complex and tightly coupled that it behave very well with the training data. Whereas with the unseen data wwe can get pretty opposite results. This is called highly varianced or overfit model.
Biased model needs more complexity in Model selection whereas highly varianced model needs drop in complexity in model selection. Regularization technique can help us in identifying the proper level of model complexity and through this technique we can overcome with both the issues.
|
Overfitting and Underfitting
Consider an example where we have a hypothesis/model equation,
y=q*X+c,
where X=feature list, y=label and q and c are the coefficients that we have to trained.
If we come up with the coefficient va
|
12,440
|
Lasso vs. adaptive Lasso
|
Brief answers to your questions:
Lasso and adaptive lasso are different. (Check Zou (2006) to see how adaptive lasso differs from standard lasso.)
Lasso is a special case of elastic net. (See Zou & Hastie (2005).)
Adaptive lasso is not a special case of elastic net.
Elastic net is not a special case of lasso or adaptive lasso.
Function glmnet in "glmnet" package in R performs lasso (not adaptive lasso) for alpha=1.
Does lasso work under milder conditions than adaptive lasso? I cannot answer this one (should check Zou (2006) for insights).
Only the adaptive lasso (but not lasso or elastic net) has the oracle property. (See Zou (2006).)
References:
Zou, Hui. "The adaptive lasso and its oracle properties." Journal of the American Statistical Association 101.476 (2006): 1418-1429.
Zou, Hui, and Trevor Hastie. "Regularization and variable selection via the elastic net." Journal of the Royal Statistical Society: Series B (Statistical Methodology) 67.2 (2005): 301-320.
|
Lasso vs. adaptive Lasso
|
Brief answers to your questions:
Lasso and adaptive lasso are different. (Check Zou (2006) to see how adaptive lasso differs from standard lasso.)
Lasso is a special case of elastic net. (See Zou & H
|
Lasso vs. adaptive Lasso
Brief answers to your questions:
Lasso and adaptive lasso are different. (Check Zou (2006) to see how adaptive lasso differs from standard lasso.)
Lasso is a special case of elastic net. (See Zou & Hastie (2005).)
Adaptive lasso is not a special case of elastic net.
Elastic net is not a special case of lasso or adaptive lasso.
Function glmnet in "glmnet" package in R performs lasso (not adaptive lasso) for alpha=1.
Does lasso work under milder conditions than adaptive lasso? I cannot answer this one (should check Zou (2006) for insights).
Only the adaptive lasso (but not lasso or elastic net) has the oracle property. (See Zou (2006).)
References:
Zou, Hui. "The adaptive lasso and its oracle properties." Journal of the American Statistical Association 101.476 (2006): 1418-1429.
Zou, Hui, and Trevor Hastie. "Regularization and variable selection via the elastic net." Journal of the Royal Statistical Society: Series B (Statistical Methodology) 67.2 (2005): 301-320.
|
Lasso vs. adaptive Lasso
Brief answers to your questions:
Lasso and adaptive lasso are different. (Check Zou (2006) to see how adaptive lasso differs from standard lasso.)
Lasso is a special case of elastic net. (See Zou & H
|
12,441
|
Lasso vs. adaptive Lasso
|
LASSO solutions are solutions that minimize
$$Q(\beta|X,y) = \dfrac{1}{2n}||y-X\beta||^2 + \lambda\sum_{j}|\beta_j|$$
the adaptive lasso simply adds weights to this to try to counteract the known issue of LASSO estimates being biased.
$$Q_a(\beta|X,y,w) = \dfrac{1}{2n}||y-X\beta||^2 + \lambda\sum_{j}w_j|\beta_j|$$
Often you will see $w_j = 1/\tilde{\beta}_j$, where $\tilde{\beta}_j$ are some initial estimates of the $\beta$ (maybe from just using LASSO, or using least squares, etc). Sometimes adaptive lasso is fit using a "pathwise approach" where the weight is allowed to change with $\lambda$
$$w_j(\lambda) = w(\tilde{\beta}_j(\lambda))$$. In the $\texttt{glmnet}$ package the weights can be specified with the $\texttt{penalty.factor}$ argument. I'm not sure if you can specify the "pathwise approach" in $\texttt{glmnet}$.
|
Lasso vs. adaptive Lasso
|
LASSO solutions are solutions that minimize
$$Q(\beta|X,y) = \dfrac{1}{2n}||y-X\beta||^2 + \lambda\sum_{j}|\beta_j|$$
the adaptive lasso simply adds weights to this to try to counteract the known issu
|
Lasso vs. adaptive Lasso
LASSO solutions are solutions that minimize
$$Q(\beta|X,y) = \dfrac{1}{2n}||y-X\beta||^2 + \lambda\sum_{j}|\beta_j|$$
the adaptive lasso simply adds weights to this to try to counteract the known issue of LASSO estimates being biased.
$$Q_a(\beta|X,y,w) = \dfrac{1}{2n}||y-X\beta||^2 + \lambda\sum_{j}w_j|\beta_j|$$
Often you will see $w_j = 1/\tilde{\beta}_j$, where $\tilde{\beta}_j$ are some initial estimates of the $\beta$ (maybe from just using LASSO, or using least squares, etc). Sometimes adaptive lasso is fit using a "pathwise approach" where the weight is allowed to change with $\lambda$
$$w_j(\lambda) = w(\tilde{\beta}_j(\lambda))$$. In the $\texttt{glmnet}$ package the weights can be specified with the $\texttt{penalty.factor}$ argument. I'm not sure if you can specify the "pathwise approach" in $\texttt{glmnet}$.
|
Lasso vs. adaptive Lasso
LASSO solutions are solutions that minimize
$$Q(\beta|X,y) = \dfrac{1}{2n}||y-X\beta||^2 + \lambda\sum_{j}|\beta_j|$$
the adaptive lasso simply adds weights to this to try to counteract the known issu
|
12,442
|
Lasso vs. adaptive Lasso
|
Adaptive LASSO is used for consistent variable selection. The problems we encounter when using the LASSO for variable selection are:
The shrinkage parameter must be larger for selection than prediction
Large nonzero parameters will be too small so that the bias is too large
Small nonzero parameters cannot be detected consistently
High correlations between predictors leads to poor selection performance
Thus the LASSO is only consistent for variable selection under some conditions on the shrinkage parameter, parameters (beta-min condition) and correlations (irrepresentable condition). See pages 101-106 of my masters dissertation for a detailed explanation.
The LASSO often includes too many variables when selecting the tuning parameter for prediction but the true model is very likely a subset of these variables. This suggests using a secondary stage of estimation like the adaptive LASSO which controls the bias of the LASSO estimate using the prediction-optimal tuning parameter. This leads to consistent selection (or oracle property) without the conditions mentioned above.
You can use glmnet for adaptive LASSO. First you need an initial estimate, either least squares, ridge or even LASSO estimates, to calculate weights. Then you can implement adaptive LASSO by scaling the X matrix. Here's an example using least squares initial estimates on training data:
# get data
y <- train[, 11]
x <- train[, -11]
x <- as.matrix(x)
n <- nrow(x)
# standardize data
ymean <- mean(y)
y <- y-mean(y)
xmean <- colMeans(x)
xnorm <- sqrt(n-1)*apply(x,2,sd)
x <- scale(x, center = xmean, scale = xnorm)
# fit ols
lm.fit <- lm(y ~ x)
beta.init <- coef(lm.fit)[-1] # exclude 0 intercept
# calculate weights
w <- abs(beta.init)
x2 <- scale(x, center=FALSE, scale=1/w)
# fit adaptive lasso
require(glmnet)
lasso.fit <- cv.glmnet(x2, y, family = "gaussian", alpha = 1, standardize = FALSE, nfolds = 10)
beta <- predict(lasso.fit, x2, type="coefficients", s="lambda.min")[-1]
# calculate estimates
beta <- beta * w / xnorm # back to original scale
beta <- matrix(beta, nrow=1)
xmean <- matrix(xmean, nrow=10)
b0 <- apply(beta, 1, function(a) ymean - a %*% xmean) # intercept
coef <- cbind(b0, beta)
|
Lasso vs. adaptive Lasso
|
Adaptive LASSO is used for consistent variable selection. The problems we encounter when using the LASSO for variable selection are:
The shrinkage parameter must be larger for selection than predicti
|
Lasso vs. adaptive Lasso
Adaptive LASSO is used for consistent variable selection. The problems we encounter when using the LASSO for variable selection are:
The shrinkage parameter must be larger for selection than prediction
Large nonzero parameters will be too small so that the bias is too large
Small nonzero parameters cannot be detected consistently
High correlations between predictors leads to poor selection performance
Thus the LASSO is only consistent for variable selection under some conditions on the shrinkage parameter, parameters (beta-min condition) and correlations (irrepresentable condition). See pages 101-106 of my masters dissertation for a detailed explanation.
The LASSO often includes too many variables when selecting the tuning parameter for prediction but the true model is very likely a subset of these variables. This suggests using a secondary stage of estimation like the adaptive LASSO which controls the bias of the LASSO estimate using the prediction-optimal tuning parameter. This leads to consistent selection (or oracle property) without the conditions mentioned above.
You can use glmnet for adaptive LASSO. First you need an initial estimate, either least squares, ridge or even LASSO estimates, to calculate weights. Then you can implement adaptive LASSO by scaling the X matrix. Here's an example using least squares initial estimates on training data:
# get data
y <- train[, 11]
x <- train[, -11]
x <- as.matrix(x)
n <- nrow(x)
# standardize data
ymean <- mean(y)
y <- y-mean(y)
xmean <- colMeans(x)
xnorm <- sqrt(n-1)*apply(x,2,sd)
x <- scale(x, center = xmean, scale = xnorm)
# fit ols
lm.fit <- lm(y ~ x)
beta.init <- coef(lm.fit)[-1] # exclude 0 intercept
# calculate weights
w <- abs(beta.init)
x2 <- scale(x, center=FALSE, scale=1/w)
# fit adaptive lasso
require(glmnet)
lasso.fit <- cv.glmnet(x2, y, family = "gaussian", alpha = 1, standardize = FALSE, nfolds = 10)
beta <- predict(lasso.fit, x2, type="coefficients", s="lambda.min")[-1]
# calculate estimates
beta <- beta * w / xnorm # back to original scale
beta <- matrix(beta, nrow=1)
xmean <- matrix(xmean, nrow=10)
b0 <- apply(beta, 1, function(a) ymean - a %*% xmean) # intercept
coef <- cbind(b0, beta)
|
Lasso vs. adaptive Lasso
Adaptive LASSO is used for consistent variable selection. The problems we encounter when using the LASSO for variable selection are:
The shrinkage parameter must be larger for selection than predicti
|
12,443
|
Should the mean be used when data are skewed?
|
I disagree with the advice as a flat out rule. (It's not common to all books.)
The issues are more subtle.
If you're actually interested in making inference about the population mean, the sample mean is at least an unbiased estimator of it, and has a number of other advantages. In fact, see the Gauss-Markov theorem - it's best linear unbiased.
Sometimes - even with fairly skewed distributions - the sample mean actually is just the right thing to be using to estimate the population mean, which may be a perfectly reasonable quantity to be interested in.
If your variables are heavily skew, a problem can often come with 'linear' - in some situations, all linear estimators may be bad, so the best of them may still be unattractive, so an estimator of the mean which is not-linear may be better, but it would require knowing something (or even quite a lot) about the distribution. We don't always have that luxury.
If you're not necessarily interested in inference relating to a population mean ("what's a typical age?", say or whether there's a more general location shift from one population to another, which might be phrased in terms of any location, or even of a test of one variable being stochastically larger than another), then casting that in terms of the population mean is either not necessary or likely counterproductive (in the last case).
So I think it comes down to thinking about:
what are your actual questions? Is population mean even a good thing to be asking about in this situation?
what is the best way to answer the question given the situation (skewness in this case)? Is using sample means the best approach to answering our questions of interest?
It may be that you have questions not directly about population means, but nevertheless sample means are a good way to look at those questions (estimating the population median of a waiting time that you assume to be distributed as ab exponential random variable, for example is better estimated as a particular fraction of the sample mean) ... or vice versa - the question might be about population means but sample means might not be the best way to answer that question.
|
Should the mean be used when data are skewed?
|
I disagree with the advice as a flat out rule. (It's not common to all books.)
The issues are more subtle.
If you're actually interested in making inference about the population mean, the sample mean
|
Should the mean be used when data are skewed?
I disagree with the advice as a flat out rule. (It's not common to all books.)
The issues are more subtle.
If you're actually interested in making inference about the population mean, the sample mean is at least an unbiased estimator of it, and has a number of other advantages. In fact, see the Gauss-Markov theorem - it's best linear unbiased.
Sometimes - even with fairly skewed distributions - the sample mean actually is just the right thing to be using to estimate the population mean, which may be a perfectly reasonable quantity to be interested in.
If your variables are heavily skew, a problem can often come with 'linear' - in some situations, all linear estimators may be bad, so the best of them may still be unattractive, so an estimator of the mean which is not-linear may be better, but it would require knowing something (or even quite a lot) about the distribution. We don't always have that luxury.
If you're not necessarily interested in inference relating to a population mean ("what's a typical age?", say or whether there's a more general location shift from one population to another, which might be phrased in terms of any location, or even of a test of one variable being stochastically larger than another), then casting that in terms of the population mean is either not necessary or likely counterproductive (in the last case).
So I think it comes down to thinking about:
what are your actual questions? Is population mean even a good thing to be asking about in this situation?
what is the best way to answer the question given the situation (skewness in this case)? Is using sample means the best approach to answering our questions of interest?
It may be that you have questions not directly about population means, but nevertheless sample means are a good way to look at those questions (estimating the population median of a waiting time that you assume to be distributed as ab exponential random variable, for example is better estimated as a particular fraction of the sample mean) ... or vice versa - the question might be about population means but sample means might not be the best way to answer that question.
|
Should the mean be used when data are skewed?
I disagree with the advice as a flat out rule. (It's not common to all books.)
The issues are more subtle.
If you're actually interested in making inference about the population mean, the sample mean
|
12,444
|
Should the mean be used when data are skewed?
|
In real life, we should choose a measure of central tendency based on what we are trying to find out; and yes, sometimes the mode is the right thing to use. Sometimes it's the Winsorized or trimmed mean. Sometimes the geometric or harmonic mean. Sometimes there is no good measure of central tendency.
Intro books are written badly, they teach that there are cookbook rules to apply.
Take income. This is often very skewed and sometimes has outliers; sure enough, we usually see "median income" reported. But sometimes the outliers and skewness are important. It depends on context and requires thought.
I wrote more on this
|
Should the mean be used when data are skewed?
|
In real life, we should choose a measure of central tendency based on what we are trying to find out; and yes, sometimes the mode is the right thing to use. Sometimes it's the Winsorized or trimmed me
|
Should the mean be used when data are skewed?
In real life, we should choose a measure of central tendency based on what we are trying to find out; and yes, sometimes the mode is the right thing to use. Sometimes it's the Winsorized or trimmed mean. Sometimes the geometric or harmonic mean. Sometimes there is no good measure of central tendency.
Intro books are written badly, they teach that there are cookbook rules to apply.
Take income. This is often very skewed and sometimes has outliers; sure enough, we usually see "median income" reported. But sometimes the outliers and skewness are important. It depends on context and requires thought.
I wrote more on this
|
Should the mean be used when data are skewed?
In real life, we should choose a measure of central tendency based on what we are trying to find out; and yes, sometimes the mode is the right thing to use. Sometimes it's the Winsorized or trimmed me
|
12,445
|
Should the mean be used when data are skewed?
|
Even when data are skewed (e.g., health care costs calculated alongside a clinical trial, where few patients totalled zero cost because they die just after the enrollment, and few patients accrued tons of cost due to side effects of a given health care programme under investigation), mean may be preferred to median for at least one pratical reason: multiplying the mean cost for the number of patients gives health care decision-makers the budget impact of the health care technology under study.
|
Should the mean be used when data are skewed?
|
Even when data are skewed (e.g., health care costs calculated alongside a clinical trial, where few patients totalled zero cost because they die just after the enrollment, and few patients accrued ton
|
Should the mean be used when data are skewed?
Even when data are skewed (e.g., health care costs calculated alongside a clinical trial, where few patients totalled zero cost because they die just after the enrollment, and few patients accrued tons of cost due to side effects of a given health care programme under investigation), mean may be preferred to median for at least one pratical reason: multiplying the mean cost for the number of patients gives health care decision-makers the budget impact of the health care technology under study.
|
Should the mean be used when data are skewed?
Even when data are skewed (e.g., health care costs calculated alongside a clinical trial, where few patients totalled zero cost because they die just after the enrollment, and few patients accrued ton
|
12,446
|
Should the mean be used when data are skewed?
|
I think that what's missing from the question as well as both the answers so far is that the discussion of mean vs median in introductory statistics books generally occurs early on in a chapter about how to numerically summarize a distribution. As opposed to inferential statistics, this is generally about producing descriptive statistics that would be a useful way to convey information about the distribution of the data numerically as opposed to graphically. Contexts in which this arises is the descriptive statistics section of a report or journal article in which there generally is not room for graphical summaries of all the variables in your dataset. If the distribution is skewed, it seems sensible in this context to choose the median over the mean. If the distribution is symmetric without outliers, then the mean is generally preferred over the median as it will be a more efficient estimator.
|
Should the mean be used when data are skewed?
|
I think that what's missing from the question as well as both the answers so far is that the discussion of mean vs median in introductory statistics books generally occurs early on in a chapter about
|
Should the mean be used when data are skewed?
I think that what's missing from the question as well as both the answers so far is that the discussion of mean vs median in introductory statistics books generally occurs early on in a chapter about how to numerically summarize a distribution. As opposed to inferential statistics, this is generally about producing descriptive statistics that would be a useful way to convey information about the distribution of the data numerically as opposed to graphically. Contexts in which this arises is the descriptive statistics section of a report or journal article in which there generally is not room for graphical summaries of all the variables in your dataset. If the distribution is skewed, it seems sensible in this context to choose the median over the mean. If the distribution is symmetric without outliers, then the mean is generally preferred over the median as it will be a more efficient estimator.
|
Should the mean be used when data are skewed?
I think that what's missing from the question as well as both the answers so far is that the discussion of mean vs median in introductory statistics books generally occurs early on in a chapter about
|
12,447
|
Gentler approach to Bayesian statistics
|
The use of probability density functions in calculations. In other words how to evaluate such equations.
I think you're still thinking of this from a frequentist perspective: if you're looking for a point estimate, the posterior won't give it to you. You put PDFs in, you get PDFs out. You can derive point estimates by calculating statistics from your posterior distribution, but I'll get to that in a bit.
I do get the concept of priors vs posteriors and understand how to apply them using a table manually. I get (I think!) that pi represents the supposed population proportion or probability.
$\pi(x)$ is the same thing as $p(x)$: they're both PDFs. $\pi$ is just conventionally used to denote that the particular PDF is a prior density.
I suspect that you don't get priors and posteriors as well as you think you do, so let's back it up to the fundamental underpinning of Bayesian statistics: Subjective Probability.
A Thought Experiment in Subjective Probability
Let's say I present you with a coin and ask you whether or not you think this coin is a fair coin. You've heard a lot of people talk about unfair coins in probability class, but you've never actually seen one in real life, so you respond, "Yeah, sure, I think it's a fair coin." But, the fact that I'm even asking you this question puts you off a little, so although your estimation is that it's fair, you wouldn't really be surprised if it wasn't. Much less surprised than if you found this coin in your pocket change (because you assume that's all real currency, and you don't really trust me right now becaue I'm acting suspicious).
Now, we run a few experiments. After 100 flips, the coin gives back 53 Heads. You're a lot more confident that it's a fair coin, but you're still open to the possibility that it's not. The difference is that now you would be pretty surprised if this coin turned out to have some sort of bias.
How can we represent your prior and posterior beliefs here, specifically, regarding the probability that the coin will show heads (which we will denote $\theta$)? In a frequentist setting, your prior belief--your null hypothesis--is that $\theta = 0.5$. After running the experiment, you're not able to reject the null, and so you continue on with the assumption that yes, the coin is probably fair. But how do we encapsulate the change in your confidence that the coin is fair? After the experiment you are in a position that you would bet that the coin is fair, but before the experiment you would have been trepidatious.
In the Bayesian setting, you encapsulate your confidence in propositions by not treating probabilities as scalar values but as random variables, i.e. functions. Instead of saying $\theta = 0.5$ we say $\theta \sim N(0.5, \sigma^2)$, and thereby encapsulate our confidence in the variance of the PDF. If we set a high variance, we're saying, "I think that the probability is 0.5, but I wouldn't be surprised if the probability I actually observe in the world is far away from this value. I think $\theta= 0.5$, but frankly I'm not really that sure." By setting a low variance, we're saying, "Not only do I believe the probability is 0.5, but I would be very surprised if experimentation provides a value that's not very close to $\theta=0.5$." So, in this example when you start the experiment you have a prior with high variance. After receiving data that corroborates your prior, the mean of the prior stayed the same, but the variance became much narrower. Our confidence that $\theta=0.5$ is much higher after running the experiment than before.
So how do we perform calculations?
We start with PDFs, and we end with PDFs. When you need to report a point estimate, you can calculate statistics like the mean, median or mode of your posterior distribution (depending on your loss function, which I won't get into now. Let's just stick with the mean). If you have a closed form solution for your PDF, it will probably be trivial to determine these values. If the posterior is complicated, you can use procedures like MCMC to sample from your posterior and derive statistics from the sample you drew.
In the example where you have a Beta prior and a Binomial likelihood, the calculation of the posterior reduces to a very clean calculation. Given:
Prior: $\theta \sim Beta(\alpha, \beta)$
Likelihood: $X|\theta \sim Binomial(\theta)$
Then the posterior reduces to:
Posterior: $\theta|X \sim Beta(\alpha + \sum_{i=1}^n x_i,\, \beta + n - \sum_{i=1}^n x_i)$
This will happen any time you have a beta prior and a binomial likelihood, and the reason why should be evident in the calculations provided by DJE. When a particular prior-likelihood model always gives a posterior that has the same kind of distribution as the prior, the relationship between the types of distributions used for the prior and likelihood is called Conjugate. There are many pairs of distributions that have conjugate relationships, and conjugacy is very frequently leveraged by Bayesians to simplify calculations. Given a particular likelihood, you can make your life a lot easier by selecting a conjugate prior (if one exists and you can justify your choice of prior).
I believe beta(1,1) refers to a PDF where the mean is 1 and the stdev is 1?
In the common parameterization of the normal distribution, the two parameters signify the mean and standard deviation of the distribution. But that's just how we parameterize the normal distribution. Other probability distributions are parameterized very differently.
The Beta distribution is usually parameterized as $Beta(\alpha, \beta)$ where $\alpha$ and $\beta$ are called "shape" parameters. The Beta distribution is extremely flexible and takes lots of different forms depending on how these parameters are set. To illustrate how different this parameterization is from your original assumption, here's how you calculate the mean and variance for Beta random variables:
\begin{equation}
\begin{split}
X &\sim Beta(\alpha, \beta) \\
\operatorname{E}[X] &= \frac{\alpha}{\alpha + \beta} \\
\operatorname{var}[X] &= \frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}
\end{split}
\end{equation}
As you can clearly see, the mean and variance are not a part of the parameterization of this distribution, but they have closed form solutions that are simple functions of the input parameters.
I won't go into detail describing the differences in parameterizations of other well known distributions, but I recommend you look up a few. Any basic text, even Wikipedia, should somewhat describe how changing the parameters modifies the distribution. You should also read up on the relationships between the different distributions (for instance, $Beta(1,1)$ is the same thing as $Uniform(0,1)$).
|
Gentler approach to Bayesian statistics
|
The use of probability density functions in calculations. In other words how to evaluate such equations.
I think you're still thinking of this from a frequentist perspective: if you're looking for a
|
Gentler approach to Bayesian statistics
The use of probability density functions in calculations. In other words how to evaluate such equations.
I think you're still thinking of this from a frequentist perspective: if you're looking for a point estimate, the posterior won't give it to you. You put PDFs in, you get PDFs out. You can derive point estimates by calculating statistics from your posterior distribution, but I'll get to that in a bit.
I do get the concept of priors vs posteriors and understand how to apply them using a table manually. I get (I think!) that pi represents the supposed population proportion or probability.
$\pi(x)$ is the same thing as $p(x)$: they're both PDFs. $\pi$ is just conventionally used to denote that the particular PDF is a prior density.
I suspect that you don't get priors and posteriors as well as you think you do, so let's back it up to the fundamental underpinning of Bayesian statistics: Subjective Probability.
A Thought Experiment in Subjective Probability
Let's say I present you with a coin and ask you whether or not you think this coin is a fair coin. You've heard a lot of people talk about unfair coins in probability class, but you've never actually seen one in real life, so you respond, "Yeah, sure, I think it's a fair coin." But, the fact that I'm even asking you this question puts you off a little, so although your estimation is that it's fair, you wouldn't really be surprised if it wasn't. Much less surprised than if you found this coin in your pocket change (because you assume that's all real currency, and you don't really trust me right now becaue I'm acting suspicious).
Now, we run a few experiments. After 100 flips, the coin gives back 53 Heads. You're a lot more confident that it's a fair coin, but you're still open to the possibility that it's not. The difference is that now you would be pretty surprised if this coin turned out to have some sort of bias.
How can we represent your prior and posterior beliefs here, specifically, regarding the probability that the coin will show heads (which we will denote $\theta$)? In a frequentist setting, your prior belief--your null hypothesis--is that $\theta = 0.5$. After running the experiment, you're not able to reject the null, and so you continue on with the assumption that yes, the coin is probably fair. But how do we encapsulate the change in your confidence that the coin is fair? After the experiment you are in a position that you would bet that the coin is fair, but before the experiment you would have been trepidatious.
In the Bayesian setting, you encapsulate your confidence in propositions by not treating probabilities as scalar values but as random variables, i.e. functions. Instead of saying $\theta = 0.5$ we say $\theta \sim N(0.5, \sigma^2)$, and thereby encapsulate our confidence in the variance of the PDF. If we set a high variance, we're saying, "I think that the probability is 0.5, but I wouldn't be surprised if the probability I actually observe in the world is far away from this value. I think $\theta= 0.5$, but frankly I'm not really that sure." By setting a low variance, we're saying, "Not only do I believe the probability is 0.5, but I would be very surprised if experimentation provides a value that's not very close to $\theta=0.5$." So, in this example when you start the experiment you have a prior with high variance. After receiving data that corroborates your prior, the mean of the prior stayed the same, but the variance became much narrower. Our confidence that $\theta=0.5$ is much higher after running the experiment than before.
So how do we perform calculations?
We start with PDFs, and we end with PDFs. When you need to report a point estimate, you can calculate statistics like the mean, median or mode of your posterior distribution (depending on your loss function, which I won't get into now. Let's just stick with the mean). If you have a closed form solution for your PDF, it will probably be trivial to determine these values. If the posterior is complicated, you can use procedures like MCMC to sample from your posterior and derive statistics from the sample you drew.
In the example where you have a Beta prior and a Binomial likelihood, the calculation of the posterior reduces to a very clean calculation. Given:
Prior: $\theta \sim Beta(\alpha, \beta)$
Likelihood: $X|\theta \sim Binomial(\theta)$
Then the posterior reduces to:
Posterior: $\theta|X \sim Beta(\alpha + \sum_{i=1}^n x_i,\, \beta + n - \sum_{i=1}^n x_i)$
This will happen any time you have a beta prior and a binomial likelihood, and the reason why should be evident in the calculations provided by DJE. When a particular prior-likelihood model always gives a posterior that has the same kind of distribution as the prior, the relationship between the types of distributions used for the prior and likelihood is called Conjugate. There are many pairs of distributions that have conjugate relationships, and conjugacy is very frequently leveraged by Bayesians to simplify calculations. Given a particular likelihood, you can make your life a lot easier by selecting a conjugate prior (if one exists and you can justify your choice of prior).
I believe beta(1,1) refers to a PDF where the mean is 1 and the stdev is 1?
In the common parameterization of the normal distribution, the two parameters signify the mean and standard deviation of the distribution. But that's just how we parameterize the normal distribution. Other probability distributions are parameterized very differently.
The Beta distribution is usually parameterized as $Beta(\alpha, \beta)$ where $\alpha$ and $\beta$ are called "shape" parameters. The Beta distribution is extremely flexible and takes lots of different forms depending on how these parameters are set. To illustrate how different this parameterization is from your original assumption, here's how you calculate the mean and variance for Beta random variables:
\begin{equation}
\begin{split}
X &\sim Beta(\alpha, \beta) \\
\operatorname{E}[X] &= \frac{\alpha}{\alpha + \beta} \\
\operatorname{var}[X] &= \frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}
\end{split}
\end{equation}
As you can clearly see, the mean and variance are not a part of the parameterization of this distribution, but they have closed form solutions that are simple functions of the input parameters.
I won't go into detail describing the differences in parameterizations of other well known distributions, but I recommend you look up a few. Any basic text, even Wikipedia, should somewhat describe how changing the parameters modifies the distribution. You should also read up on the relationships between the different distributions (for instance, $Beta(1,1)$ is the same thing as $Uniform(0,1)$).
|
Gentler approach to Bayesian statistics
The use of probability density functions in calculations. In other words how to evaluate such equations.
I think you're still thinking of this from a frequentist perspective: if you're looking for a
|
12,448
|
Gentler approach to Bayesian statistics
|
A beta distribution has the form $p(\theta)=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}$. A beta(1,1) distribution has parameters $(\alpha, \beta)=(1,1)$. (Unfortunately, this kind of statistical short-hand places a burden on the reader to know how the particular model is parameterized!)
The beta prior with a binomial likelihood (fixed number of trials with binary outcomes and fixed probabilities of success/failure) has the property of conjugacy, which allows the posterior (the product of the prior and the likelihood) to be written as:
\begin{equation}
\begin{split}
p(\theta|y) &= \frac{p(y|\theta)p(\theta)}{p(y)} \\
~\\
~\\
&\propto\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}\binom{n}{y}\theta^y(1-\theta)^{n-y} \\
~\\
~\\
&\propto\theta^{\alpha-1}(1-\theta)^{\beta-1}*\theta^y(1-\theta)^{n-y} \\
~\\
&\propto\theta^{\alpha+y-1}(1-\theta)^{\beta+n-y-1} \\
~\\
&=\frac{\Gamma(\alpha+y-1)\Gamma(\beta+n-y-1)}{\Gamma(\alpha+\beta+n-1)}\theta^{\alpha+y-1}(1-\theta)^{\beta+n-y-1}
\end{split}
\end{equation}
For the particular example in the text, the author is indicating that a beta(1,1) prior with data n=10 and y=8 produces a beta(1+8,1+2)=beta(9,3) posterior distribution on $\theta$.
This expression is convenient, but by no means necessary. Multiplying probability densities can be done the same way as multiplying other mathematical expressions; the difficulties arrive since many products of densities are not as easily rewritten as the beta prior/binomial likelihood. Fortunately, this is where computers pick up the slack.
|
Gentler approach to Bayesian statistics
|
A beta distribution has the form $p(\theta)=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}$. A beta(1,1) distribution has parameters $(\alpha, \beta)=(1,
|
Gentler approach to Bayesian statistics
A beta distribution has the form $p(\theta)=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}$. A beta(1,1) distribution has parameters $(\alpha, \beta)=(1,1)$. (Unfortunately, this kind of statistical short-hand places a burden on the reader to know how the particular model is parameterized!)
The beta prior with a binomial likelihood (fixed number of trials with binary outcomes and fixed probabilities of success/failure) has the property of conjugacy, which allows the posterior (the product of the prior and the likelihood) to be written as:
\begin{equation}
\begin{split}
p(\theta|y) &= \frac{p(y|\theta)p(\theta)}{p(y)} \\
~\\
~\\
&\propto\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}\binom{n}{y}\theta^y(1-\theta)^{n-y} \\
~\\
~\\
&\propto\theta^{\alpha-1}(1-\theta)^{\beta-1}*\theta^y(1-\theta)^{n-y} \\
~\\
&\propto\theta^{\alpha+y-1}(1-\theta)^{\beta+n-y-1} \\
~\\
&=\frac{\Gamma(\alpha+y-1)\Gamma(\beta+n-y-1)}{\Gamma(\alpha+\beta+n-1)}\theta^{\alpha+y-1}(1-\theta)^{\beta+n-y-1}
\end{split}
\end{equation}
For the particular example in the text, the author is indicating that a beta(1,1) prior with data n=10 and y=8 produces a beta(1+8,1+2)=beta(9,3) posterior distribution on $\theta$.
This expression is convenient, but by no means necessary. Multiplying probability densities can be done the same way as multiplying other mathematical expressions; the difficulties arrive since many products of densities are not as easily rewritten as the beta prior/binomial likelihood. Fortunately, this is where computers pick up the slack.
|
Gentler approach to Bayesian statistics
A beta distribution has the form $p(\theta)=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}$. A beta(1,1) distribution has parameters $(\alpha, \beta)=(1,
|
12,449
|
Gentler approach to Bayesian statistics
|
If you are looking for a gentler approach I can highly recommend the book by Kruschke which uses R to explain the core concepts. It is a very practical and hands-on approach into learning Bayesian statistics and on his website you can find all of the codes used.
Someone also recommended the text by Cam.Davidson.Pilon to me, haven't look at it yet but it can be found here.
|
Gentler approach to Bayesian statistics
|
If you are looking for a gentler approach I can highly recommend the book by Kruschke which uses R to explain the core concepts. It is a very practical and hands-on approach into learning Bayesian sta
|
Gentler approach to Bayesian statistics
If you are looking for a gentler approach I can highly recommend the book by Kruschke which uses R to explain the core concepts. It is a very practical and hands-on approach into learning Bayesian statistics and on his website you can find all of the codes used.
Someone also recommended the text by Cam.Davidson.Pilon to me, haven't look at it yet but it can be found here.
|
Gentler approach to Bayesian statistics
If you are looking for a gentler approach I can highly recommend the book by Kruschke which uses R to explain the core concepts. It is a very practical and hands-on approach into learning Bayesian sta
|
12,450
|
Why are there extra terms $-p_i+q_i$ in SciPy's implementation of Kullback-Leibler divergence?
|
The other answer tells us why we don't usually see the $-p_i+q_i$ term: $p$ and $q$ are usually residents of the simplex and so sum to one, so this leads to $\sum - [p_i - q_i] = \sum - p_i + \sum q_i = -1 + 1 = 0$.
In this answer, I want to show why those terms are there in the first place, by viewing KL divergence as the Bregman divergence induced by the (negative) Entropy function.
Given some differentiable function $\psi$, the Bregman divergence induced by it is a binary function on the domain of $\psi$:
$$
B_\psi(p,q) = \psi(p)-\psi(q)-\langle\nabla\psi(q),p-q\rangle
$$
Intuitively, the Bregman divergence measures the difference between $\psi$ evaluated at $p$ and the linear approximation to $\psi$ (about $q$) evaluated at $p$. When $\psi$ is convex, this is guaranteed to be nonnegative, and thus so is the Bregman divergence.
Noting that if $\psi(p) = \sum_i p_i \log p_i$, $\nabla\psi(p) = [\log p_i + 1]$, the entropic Bregman divergence is thus:
$$
B_e(p,q) = \sum_i p_i \log p_i - \sum_i q_i \log q_i - \sum_i [\log q_i + 1][p_i-q_i]\\
= \sum_i p_i \log p_i - \sum_i q_i \log q_i - \sum_i [\log q_i (p_i-q_i) + p_i-q_i]\\
= \sum_i p_i \log p_i - \sum_i q_i \log q_i - \sum_i p_i \log q_i + \sum_i q_i\log q_i - \sum_i[p_i-q_i]\\
= \sum_i p_i \log p_i - \sum_i p_i \log q_i - \sum_i[p_i-q_i]\\
= \sum_i p_i \log \frac{p_i}{q_i} + \sum_i[-p_i+q_i]
$$
which we recognize as the KL divergence you mentioned.
|
Why are there extra terms $-p_i+q_i$ in SciPy's implementation of Kullback-Leibler divergence?
|
The other answer tells us why we don't usually see the $-p_i+q_i$ term: $p$ and $q$ are usually residents of the simplex and so sum to one, so this leads to $\sum - [p_i - q_i] = \sum - p_i + \sum q_i
|
Why are there extra terms $-p_i+q_i$ in SciPy's implementation of Kullback-Leibler divergence?
The other answer tells us why we don't usually see the $-p_i+q_i$ term: $p$ and $q$ are usually residents of the simplex and so sum to one, so this leads to $\sum - [p_i - q_i] = \sum - p_i + \sum q_i = -1 + 1 = 0$.
In this answer, I want to show why those terms are there in the first place, by viewing KL divergence as the Bregman divergence induced by the (negative) Entropy function.
Given some differentiable function $\psi$, the Bregman divergence induced by it is a binary function on the domain of $\psi$:
$$
B_\psi(p,q) = \psi(p)-\psi(q)-\langle\nabla\psi(q),p-q\rangle
$$
Intuitively, the Bregman divergence measures the difference between $\psi$ evaluated at $p$ and the linear approximation to $\psi$ (about $q$) evaluated at $p$. When $\psi$ is convex, this is guaranteed to be nonnegative, and thus so is the Bregman divergence.
Noting that if $\psi(p) = \sum_i p_i \log p_i$, $\nabla\psi(p) = [\log p_i + 1]$, the entropic Bregman divergence is thus:
$$
B_e(p,q) = \sum_i p_i \log p_i - \sum_i q_i \log q_i - \sum_i [\log q_i + 1][p_i-q_i]\\
= \sum_i p_i \log p_i - \sum_i q_i \log q_i - \sum_i [\log q_i (p_i-q_i) + p_i-q_i]\\
= \sum_i p_i \log p_i - \sum_i q_i \log q_i - \sum_i p_i \log q_i + \sum_i q_i\log q_i - \sum_i[p_i-q_i]\\
= \sum_i p_i \log p_i - \sum_i p_i \log q_i - \sum_i[p_i-q_i]\\
= \sum_i p_i \log \frac{p_i}{q_i} + \sum_i[-p_i+q_i]
$$
which we recognize as the KL divergence you mentioned.
|
Why are there extra terms $-p_i+q_i$ in SciPy's implementation of Kullback-Leibler divergence?
The other answer tells us why we don't usually see the $-p_i+q_i$ term: $p$ and $q$ are usually residents of the simplex and so sum to one, so this leads to $\sum - [p_i - q_i] = \sum - p_i + \sum q_i
|
12,451
|
Why are there extra terms $-p_i+q_i$ in SciPy's implementation of Kullback-Leibler divergence?
|
The referenced book has a free pdf on Boyd's site: https://web.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf
On page 90, formula 3.17 gives this definition. I suspect the reason for the added terms is that in convex optimization, the two vectors needn't be probability distributions; the authors say
Note that the relative entropy and the Kullback-Leibler divergence
are the same when $u$ and $v$ are probability vectors
When they are, in the sum the extra terms cancel. But when they aren't, the added terms ensure that the total is nonnegative.
|
Why are there extra terms $-p_i+q_i$ in SciPy's implementation of Kullback-Leibler divergence?
|
The referenced book has a free pdf on Boyd's site: https://web.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf
On page 90, formula 3.17 gives this definition. I suspect the reason for the added terms is tha
|
Why are there extra terms $-p_i+q_i$ in SciPy's implementation of Kullback-Leibler divergence?
The referenced book has a free pdf on Boyd's site: https://web.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf
On page 90, formula 3.17 gives this definition. I suspect the reason for the added terms is that in convex optimization, the two vectors needn't be probability distributions; the authors say
Note that the relative entropy and the Kullback-Leibler divergence
are the same when $u$ and $v$ are probability vectors
When they are, in the sum the extra terms cancel. But when they aren't, the added terms ensure that the total is nonnegative.
|
Why are there extra terms $-p_i+q_i$ in SciPy's implementation of Kullback-Leibler divergence?
The referenced book has a free pdf on Boyd's site: https://web.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf
On page 90, formula 3.17 gives this definition. I suspect the reason for the added terms is tha
|
12,452
|
How do I analytically calculate variance of a recursive random variable?
|
Call the next chests as $X_1,X_2$. With $0.4$ probability, our new variable is $X_1+X_2$ and with $0.6$ probability, it is $1$. So,
$$\begin{align}E[X^2]&=0.4\times E[(X_1+X_2)^2]+0.6\times1^2\\&=0.4\times E[X_1^2+X_2^2+2X_1X_2]+0.6\\&=0.4\times(2E[X^2]+2E[X]^2)+0.6\\&=0.8\times E[X^2]+7.8\rightarrow E[X^2]=39\rightarrow\operatorname{var}(X)=30\end{align}$$
|
How do I analytically calculate variance of a recursive random variable?
|
Call the next chests as $X_1,X_2$. With $0.4$ probability, our new variable is $X_1+X_2$ and with $0.6$ probability, it is $1$. So,
$$\begin{align}E[X^2]&=0.4\times E[(X_1+X_2)^2]+0.6\times1^2\\&=0.4\
|
How do I analytically calculate variance of a recursive random variable?
Call the next chests as $X_1,X_2$. With $0.4$ probability, our new variable is $X_1+X_2$ and with $0.6$ probability, it is $1$. So,
$$\begin{align}E[X^2]&=0.4\times E[(X_1+X_2)^2]+0.6\times1^2\\&=0.4\times E[X_1^2+X_2^2+2X_1X_2]+0.6\\&=0.4\times(2E[X^2]+2E[X]^2)+0.6\\&=0.8\times E[X^2]+7.8\rightarrow E[X^2]=39\rightarrow\operatorname{var}(X)=30\end{align}$$
|
How do I analytically calculate variance of a recursive random variable?
Call the next chests as $X_1,X_2$. With $0.4$ probability, our new variable is $X_1+X_2$ and with $0.6$ probability, it is $1$. So,
$$\begin{align}E[X^2]&=0.4\times E[(X_1+X_2)^2]+0.6\times1^2\\&=0.4\
|
12,453
|
How do I analytically calculate variance of a recursive random variable?
|
Actually, it's relatively simple to obtain formulas for the entire distribution as well as an easy procedure to compute any moment of it.
For $n=1,2,3,\ldots,$ let $f_n(p) = \Pr(X=n)$ with $p=0.6.$ Define
$$F_p(t) = f_1(p)t + f_2(p)t^2 + \cdots + f_n(p)t^n + \cdots$$
(the probability generating function). The problem asserts
$$F_p(t) = p\,t + (1-p)F_p^2(t),$$
a quadratic equation with solutions
$$F_p(t) = \frac{1}{2(1-p)}\left(1 \pm \sqrt{1 - 4p(1-p)t}\right).$$
Only the solution with a minus sign makes sense (because the other yields a negative value for $f_2(p)$). Expanding it as a formal power series in $t$ (using, for instance, the Binomial Theorem) gives
$$F_p(t) = \frac{1}{2(1-p)} \sum_{n=1}^\infty (-1)^{n-1} \binom{1/2}{n} \left(4p(1-p)\right)^n\,t^n = \sum_{n=1}^\infty f_n(p)\,t^n,$$
from which we can read off the entire distribution of $X$ term by term. Here's a plot of the log probabilities up to $n=80$ created using this formula:
(In R:
f <- function(p=0.6, n=1:80) (-1)^(n-1) * choose(1/2, n) * (4*p*(1-p))^n / (2*(1-p))
plot(f(), type="h", log="y")
)
Moreover,
$$E[X] = \frac{\mathrm{d}}{\mathrm{d}t}F_p(t)\bigg|_{t=1} = \frac{p}{\sqrt{1-4p(1-p)}} = 3$$
and
$$E[X(X-1)] = \frac{\mathrm{d}^2}{\mathrm{d}t^2}F_p(t)\bigg|_{t=1} = \frac{2p^2(1-p)}{\sqrt{\left(1 - 4p(1-p)\right)^3}} = 36,$$
whence
$$\operatorname{Var}(X) = E[X(X-1)] + E[X] - E[X]^2 = 36 + 3 - 3^2 = 30.$$
|
How do I analytically calculate variance of a recursive random variable?
|
Actually, it's relatively simple to obtain formulas for the entire distribution as well as an easy procedure to compute any moment of it.
For $n=1,2,3,\ldots,$ let $f_n(p) = \Pr(X=n)$ with $p=0.6.$ D
|
How do I analytically calculate variance of a recursive random variable?
Actually, it's relatively simple to obtain formulas for the entire distribution as well as an easy procedure to compute any moment of it.
For $n=1,2,3,\ldots,$ let $f_n(p) = \Pr(X=n)$ with $p=0.6.$ Define
$$F_p(t) = f_1(p)t + f_2(p)t^2 + \cdots + f_n(p)t^n + \cdots$$
(the probability generating function). The problem asserts
$$F_p(t) = p\,t + (1-p)F_p^2(t),$$
a quadratic equation with solutions
$$F_p(t) = \frac{1}{2(1-p)}\left(1 \pm \sqrt{1 - 4p(1-p)t}\right).$$
Only the solution with a minus sign makes sense (because the other yields a negative value for $f_2(p)$). Expanding it as a formal power series in $t$ (using, for instance, the Binomial Theorem) gives
$$F_p(t) = \frac{1}{2(1-p)} \sum_{n=1}^\infty (-1)^{n-1} \binom{1/2}{n} \left(4p(1-p)\right)^n\,t^n = \sum_{n=1}^\infty f_n(p)\,t^n,$$
from which we can read off the entire distribution of $X$ term by term. Here's a plot of the log probabilities up to $n=80$ created using this formula:
(In R:
f <- function(p=0.6, n=1:80) (-1)^(n-1) * choose(1/2, n) * (4*p*(1-p))^n / (2*(1-p))
plot(f(), type="h", log="y")
)
Moreover,
$$E[X] = \frac{\mathrm{d}}{\mathrm{d}t}F_p(t)\bigg|_{t=1} = \frac{p}{\sqrt{1-4p(1-p)}} = 3$$
and
$$E[X(X-1)] = \frac{\mathrm{d}^2}{\mathrm{d}t^2}F_p(t)\bigg|_{t=1} = \frac{2p^2(1-p)}{\sqrt{\left(1 - 4p(1-p)\right)^3}} = 36,$$
whence
$$\operatorname{Var}(X) = E[X(X-1)] + E[X] - E[X]^2 = 36 + 3 - 3^2 = 30.$$
|
How do I analytically calculate variance of a recursive random variable?
Actually, it's relatively simple to obtain formulas for the entire distribution as well as an easy procedure to compute any moment of it.
For $n=1,2,3,\ldots,$ let $f_n(p) = \Pr(X=n)$ with $p=0.6.$ D
|
12,454
|
When we calculate mean and variance, do we assume data are normally distributed?
|
No, those equations come directly from the mean and variance formulae in terms of expected value, considering the collected data as a population.
$$\mu = \mathbb{E}\big[X\big]$$
$$\sigma^2 = \mathbb{E}\big[\big(X-\mu\big)^2\big]$$
Since you have a finite number of observations, the distribution is discrete,$^{\dagger}$ and the expected value is a sum.
$$\mu = \mathbb{E}\big[X\big] = \sum_{i=1}^N p(x_i)x_i = \sum_{i=1}^N \dfrac{1}{N}x_i = \dfrac{1}{N}\sum_{i=1}^Nx_i$$
$$\sigma^2 = \mathbb{E}\big[\big(X-\mu\big)^2\big] = \sum_{i=1}^N p(x_i)(x_i - \mu)^2 = \sum_{i=1}^N \dfrac{1}{N}(x_i - \mu)^2 = \dfrac{1}{N}\sum_{i=1}^N (x_i - \mu)^2$$
(To get from $p(x_i)$ to $\dfrac{1}{N}$, note that each individual $x_i$ has probability $1/N$.)
This is why the $\dfrac{1}{N}\sum_{i=1}^N (x_i - \mu)^2$ gets called the "population" variance. It literally is the population variance if you consider the observed data to be the population.
$^{\dagger}$ This is a sufficient, but not necessary, condition for a discrete distribution. A Poisson distribution is an example of a discrete distribution with infinitely many values.
|
When we calculate mean and variance, do we assume data are normally distributed?
|
No, those equations come directly from the mean and variance formulae in terms of expected value, considering the collected data as a population.
$$\mu = \mathbb{E}\big[X\big]$$
$$\sigma^2 = \mathbb{E
|
When we calculate mean and variance, do we assume data are normally distributed?
No, those equations come directly from the mean and variance formulae in terms of expected value, considering the collected data as a population.
$$\mu = \mathbb{E}\big[X\big]$$
$$\sigma^2 = \mathbb{E}\big[\big(X-\mu\big)^2\big]$$
Since you have a finite number of observations, the distribution is discrete,$^{\dagger}$ and the expected value is a sum.
$$\mu = \mathbb{E}\big[X\big] = \sum_{i=1}^N p(x_i)x_i = \sum_{i=1}^N \dfrac{1}{N}x_i = \dfrac{1}{N}\sum_{i=1}^Nx_i$$
$$\sigma^2 = \mathbb{E}\big[\big(X-\mu\big)^2\big] = \sum_{i=1}^N p(x_i)(x_i - \mu)^2 = \sum_{i=1}^N \dfrac{1}{N}(x_i - \mu)^2 = \dfrac{1}{N}\sum_{i=1}^N (x_i - \mu)^2$$
(To get from $p(x_i)$ to $\dfrac{1}{N}$, note that each individual $x_i$ has probability $1/N$.)
This is why the $\dfrac{1}{N}\sum_{i=1}^N (x_i - \mu)^2$ gets called the "population" variance. It literally is the population variance if you consider the observed data to be the population.
$^{\dagger}$ This is a sufficient, but not necessary, condition for a discrete distribution. A Poisson distribution is an example of a discrete distribution with infinitely many values.
|
When we calculate mean and variance, do we assume data are normally distributed?
No, those equations come directly from the mean and variance formulae in terms of expected value, considering the collected data as a population.
$$\mu = \mathbb{E}\big[X\big]$$
$$\sigma^2 = \mathbb{E
|
12,455
|
When we calculate mean and variance, do we assume data are normally distributed?
|
You are mixing descriptive statistics of a sample (such as $\bar X, S)$ with parameters of a population (such as $\mu, \sigma),$
and description of a sample with estimation of parameters.
Describing sample center or location.
The correct version of the sample mean of a sample $X_i, X_2, \dots X_n$ of size $n$ is $\bar X = \frac 1 n \sum_{i=1}^n X_i.$ Many authors reserve $N$ for the size of the population. The sample mean $\bar X$ is a descriptive statistic. It is one way to
describe the "center" of a sample.
Some alternative ways to describe the center or location of a sample are (a) the sample median, which is the middle value when data are sorted from smallest to largest (or halfway between the middle two values if the sample size is even), (b) the midrange, which is halfway between the largest and smallest sample values, and (c) the mode which is the value that occurs most often in the sample (if there is one such value).
If you have a sample of seven test scores (78, 96, 84, 92, 88, 75, 51), then R statistical
software gives the following summary of the data:
x = c(78, 96, 84, 92, 88, 75, 51)
summary(x)
Min. 1st Qu. Median Mean 3rd Qu. Max.
51.00 76.50 84.00 80.57 90.00 96.00
length(x); sum(x); sum(x)/length(x)
[1] 7 # sample size
[1] 564 # total of seven observations
[1] 80.57143 # mean (to more places than above)
sort(x)
[1] 51 75 78 84 88 92 96
min(x); max(x); median(x)
[1] 51 # smallest
[1] 96 # largest
[1] 84 # middle value of 7 sorted values.
The midrange (96 + 51)/2 = 73.5 is not given by summary; this sample has no mode.
For small samples an effective graphical description may be the stripchart (or dotplot):
stripchart(x, pch=19)
For larger samples a boxplot or histogram (not shown here) may be used.
The choice whether to
use sample mean, sample median, sample midrange (or some other descriptive statistic) depends on the nature of the data
and on one's purpose in finding the center or location of the sample.
By contrast, $\mu$ denotes the population mean $\mu.$ So if you have a finite population of size $N$ with elements $X_i,$ then your equation (1) would be the definition of the population mean $\mu.$ [For a theoretical infinite infinite population specified in terms of
its density function $f(x),$ the population mean is defined as $\mu = \int xf(x)\,dx,$
where the integral is taken over the interval of all possible population values, provided that the integral exists. (For many of the distributions used in statistical work the population mean $\mu$ exists; Student's t distribution with one degree of freedom is a well-known exception.)]
Describing sample variation and spread.
The usual definition of the sample variance is $S^2=\frac{1}{n-1}\sum_{i-1}^n (X_i - \bar X)^2.$ [In a few textbooks the denominator $n$ is used.] The units of the sample variance are the square of the units of the sample. [So if the sample is heights
of students in inches, then the units of the sample variance are square inches.]
The sample variance describes the variation of a sample, A related descriptive
statistic for sample variation is the sample standard deviation
$S = \sqrt{\frac{1}{n-1}\sum_{i-1}^n (X_i - \bar X)^2}.$ its units are the same as the units of the sample.
Some alternative ways to describe the variation of a sample are the sample range (largest sample value minus smallest) and the midrange, which is the range of the
middle half of the data (upper quartile minus lower quartile). [There are still other
descriptions of sample variation; some are based on medians.]
For the sample of seven test scores above, the variance and standard deviation are
as follows:
var(x); sd(x)
[1] 224.619
[1] 14.9873
From the summary above, the range is (96 - 51) = 45, and the interquartile range (IQR) is
$(90 - 76.4) = 13.6.$
diff(range(x)); IQR(x)
[1] 45
[1] 13.5
(A peculiarity of R is that range returns min and max, so we get the usual sample range by subtraction.)
Estimation of parameters.
Depending on the shape of a population distribution, it may be appropriate to
estimate the population mean $\mu$ by the sample mean $\bar X,$ or to estimate
the population median $\eta$ (half of the probability on either side) by the
sample median. Also, it may be appropriate to estimate the population variance $\sigma^2$ by the sample variance $S^2,$ or to estimate the population standard
deviation by $\sigma$ by $S.$
Among many, a couple of criteria for a desirable estimator is that it unbiased
and that it have the smallest possible variance. Roughly speaking, this
amounts to ensuring that on average the estimator is aimed at the right target (unbiasedness) and that the aim is optimally precise (small variance).
This is not the place for a detailed discussion of estimation. However, it is
worth mentioning that, for normal data, $S^2$ as defined above is an unbiased
estimator for $\sigma^2,$ while the maximum likelihood estimator $\widehat{\sigma^2} = \frac 1 n\sum_{i=1}^n(X_i-\bar X)^2$, with denominator $n,$ has a downward bias, systematically underestimating $\sigma^2.$ Therefore many (but not all) statistics tests use $S^2$ (denominator $n-1)$
as the estimator of $\sigma^2.$ (Perhaps see this related Q&A.)
[As @Dave (+1) makes clear in his Answer, your equation (2), with $N$ in the denominator is the the formula for
$\sigma^2$ of a finite population consisting of $N$ possible values, for which the population mean $\mu$ is known.]
|
When we calculate mean and variance, do we assume data are normally distributed?
|
You are mixing descriptive statistics of a sample (such as $\bar X, S)$ with parameters of a population (such as $\mu, \sigma),$
and description of a sample with estimation of parameters.
Describing s
|
When we calculate mean and variance, do we assume data are normally distributed?
You are mixing descriptive statistics of a sample (such as $\bar X, S)$ with parameters of a population (such as $\mu, \sigma),$
and description of a sample with estimation of parameters.
Describing sample center or location.
The correct version of the sample mean of a sample $X_i, X_2, \dots X_n$ of size $n$ is $\bar X = \frac 1 n \sum_{i=1}^n X_i.$ Many authors reserve $N$ for the size of the population. The sample mean $\bar X$ is a descriptive statistic. It is one way to
describe the "center" of a sample.
Some alternative ways to describe the center or location of a sample are (a) the sample median, which is the middle value when data are sorted from smallest to largest (or halfway between the middle two values if the sample size is even), (b) the midrange, which is halfway between the largest and smallest sample values, and (c) the mode which is the value that occurs most often in the sample (if there is one such value).
If you have a sample of seven test scores (78, 96, 84, 92, 88, 75, 51), then R statistical
software gives the following summary of the data:
x = c(78, 96, 84, 92, 88, 75, 51)
summary(x)
Min. 1st Qu. Median Mean 3rd Qu. Max.
51.00 76.50 84.00 80.57 90.00 96.00
length(x); sum(x); sum(x)/length(x)
[1] 7 # sample size
[1] 564 # total of seven observations
[1] 80.57143 # mean (to more places than above)
sort(x)
[1] 51 75 78 84 88 92 96
min(x); max(x); median(x)
[1] 51 # smallest
[1] 96 # largest
[1] 84 # middle value of 7 sorted values.
The midrange (96 + 51)/2 = 73.5 is not given by summary; this sample has no mode.
For small samples an effective graphical description may be the stripchart (or dotplot):
stripchart(x, pch=19)
For larger samples a boxplot or histogram (not shown here) may be used.
The choice whether to
use sample mean, sample median, sample midrange (or some other descriptive statistic) depends on the nature of the data
and on one's purpose in finding the center or location of the sample.
By contrast, $\mu$ denotes the population mean $\mu.$ So if you have a finite population of size $N$ with elements $X_i,$ then your equation (1) would be the definition of the population mean $\mu.$ [For a theoretical infinite infinite population specified in terms of
its density function $f(x),$ the population mean is defined as $\mu = \int xf(x)\,dx,$
where the integral is taken over the interval of all possible population values, provided that the integral exists. (For many of the distributions used in statistical work the population mean $\mu$ exists; Student's t distribution with one degree of freedom is a well-known exception.)]
Describing sample variation and spread.
The usual definition of the sample variance is $S^2=\frac{1}{n-1}\sum_{i-1}^n (X_i - \bar X)^2.$ [In a few textbooks the denominator $n$ is used.] The units of the sample variance are the square of the units of the sample. [So if the sample is heights
of students in inches, then the units of the sample variance are square inches.]
The sample variance describes the variation of a sample, A related descriptive
statistic for sample variation is the sample standard deviation
$S = \sqrt{\frac{1}{n-1}\sum_{i-1}^n (X_i - \bar X)^2}.$ its units are the same as the units of the sample.
Some alternative ways to describe the variation of a sample are the sample range (largest sample value minus smallest) and the midrange, which is the range of the
middle half of the data (upper quartile minus lower quartile). [There are still other
descriptions of sample variation; some are based on medians.]
For the sample of seven test scores above, the variance and standard deviation are
as follows:
var(x); sd(x)
[1] 224.619
[1] 14.9873
From the summary above, the range is (96 - 51) = 45, and the interquartile range (IQR) is
$(90 - 76.4) = 13.6.$
diff(range(x)); IQR(x)
[1] 45
[1] 13.5
(A peculiarity of R is that range returns min and max, so we get the usual sample range by subtraction.)
Estimation of parameters.
Depending on the shape of a population distribution, it may be appropriate to
estimate the population mean $\mu$ by the sample mean $\bar X,$ or to estimate
the population median $\eta$ (half of the probability on either side) by the
sample median. Also, it may be appropriate to estimate the population variance $\sigma^2$ by the sample variance $S^2,$ or to estimate the population standard
deviation by $\sigma$ by $S.$
Among many, a couple of criteria for a desirable estimator is that it unbiased
and that it have the smallest possible variance. Roughly speaking, this
amounts to ensuring that on average the estimator is aimed at the right target (unbiasedness) and that the aim is optimally precise (small variance).
This is not the place for a detailed discussion of estimation. However, it is
worth mentioning that, for normal data, $S^2$ as defined above is an unbiased
estimator for $\sigma^2,$ while the maximum likelihood estimator $\widehat{\sigma^2} = \frac 1 n\sum_{i=1}^n(X_i-\bar X)^2$, with denominator $n,$ has a downward bias, systematically underestimating $\sigma^2.$ Therefore many (but not all) statistics tests use $S^2$ (denominator $n-1)$
as the estimator of $\sigma^2.$ (Perhaps see this related Q&A.)
[As @Dave (+1) makes clear in his Answer, your equation (2), with $N$ in the denominator is the the formula for
$\sigma^2$ of a finite population consisting of $N$ possible values, for which the population mean $\mu$ is known.]
|
When we calculate mean and variance, do we assume data are normally distributed?
You are mixing descriptive statistics of a sample (such as $\bar X, S)$ with parameters of a population (such as $\mu, \sigma),$
and description of a sample with estimation of parameters.
Describing s
|
12,456
|
When we calculate mean and variance, do we assume data are normally distributed?
|
Normality is an ideal case for the ordinary sample mean and variance (as well as other common statistics like least squares regression estimates), but it is certainly not a requirement. After all, normality is never true in practice for any any real data-generating process, nor is it ever true for actual data. So if normality were an absolute requirement, we would never ever ever use the sample mean, and variance, and many other common statistics.
There are things you can say about the usual sample mean and variance under non-normality; for example, Chebychev's inequality tells you that at least $75\%$ of your $x_i$ will be within your $\mu \pm 2\sigma$ range (assuming your equation (2) is called $\sigma^2$), at least $88.9\%$ will be within the $\mu \pm 3\sigma$ range, and in general, at least $100(1 - 1/k^2)\%$ will be within the $\mu \pm k\sigma$ range. These facts do not depend on the source of the $x_i$ data; in fact, the data need not come from any probability model whatsoever.
Additionally, the Central Limit Theorem applies to the sample mean when the data come from a non-normal distribution; this allows you to use the usual normality-assuming confidence interval formula, which involves your "$\mu$" and "$\sigma$," to construct a valid large-sample confidence interval for the mean of the data-generating process, even when that process is non-normal (as long as its variance is finite).
|
When we calculate mean and variance, do we assume data are normally distributed?
|
Normality is an ideal case for the ordinary sample mean and variance (as well as other common statistics like least squares regression estimates), but it is certainly not a requirement. After all, nor
|
When we calculate mean and variance, do we assume data are normally distributed?
Normality is an ideal case for the ordinary sample mean and variance (as well as other common statistics like least squares regression estimates), but it is certainly not a requirement. After all, normality is never true in practice for any any real data-generating process, nor is it ever true for actual data. So if normality were an absolute requirement, we would never ever ever use the sample mean, and variance, and many other common statistics.
There are things you can say about the usual sample mean and variance under non-normality; for example, Chebychev's inequality tells you that at least $75\%$ of your $x_i$ will be within your $\mu \pm 2\sigma$ range (assuming your equation (2) is called $\sigma^2$), at least $88.9\%$ will be within the $\mu \pm 3\sigma$ range, and in general, at least $100(1 - 1/k^2)\%$ will be within the $\mu \pm k\sigma$ range. These facts do not depend on the source of the $x_i$ data; in fact, the data need not come from any probability model whatsoever.
Additionally, the Central Limit Theorem applies to the sample mean when the data come from a non-normal distribution; this allows you to use the usual normality-assuming confidence interval formula, which involves your "$\mu$" and "$\sigma$," to construct a valid large-sample confidence interval for the mean of the data-generating process, even when that process is non-normal (as long as its variance is finite).
|
When we calculate mean and variance, do we assume data are normally distributed?
Normality is an ideal case for the ordinary sample mean and variance (as well as other common statistics like least squares regression estimates), but it is certainly not a requirement. After all, nor
|
12,457
|
When we calculate mean and variance, do we assume data are normally distributed?
|
$\mu$ is, indeed, the value that maximizes the Gaussian likelihood, but you have to assume Gaussianity first. You could assume other distributions instead.
Assume you are flipping coins, and you want to estimate the probability $p$ of heads.
You toss it $n$ times, and measure $\hat p \times n$ tails.
This process assumes a Bernoulli distribution, which likelihood can be stated as:
$$\mathcal L_{\mathcal B} \propto p^{\hat p \times n}(1-p)^{(1-\hat p) \times n}$$
The maximum likelihood estimator for $p$ is $\hat p = (1/n)\sum_i^n t_i = \mathbb E(T)$, where $t_i$ is the result of each toss (1 for heads, 0 for tails).
Here, we are using the expected value to maximize a Bernoulli likelihood.
Distributions have quantities called moments attached to them.
The $n$-th order moment about a value $c$ is defined as, given a probability density described by $f$:
$$\mu_n(c) = \int_{-\infty}^{+\infty} (x-c)^n f(x) dx$$
The mean is the first raw moment (moment about the origin) while the variance is the second central moment (moment about the mean).
\begin{cases}\mathbb E(X) = \mu=\mu_1(\mathbf 0)\\\operatorname{Var}(X)=\mu_2(\mu)=\mu_ 2(\mathbf 0)-\mu^2=\mathbb E(X^2)-\mathbb E(X)^2\end{cases}
These are important quantities defined for any distribution described by $f$, irrespective of if it's Gaussian or not.
|
When we calculate mean and variance, do we assume data are normally distributed?
|
$\mu$ is, indeed, the value that maximizes the Gaussian likelihood, but you have to assume Gaussianity first. You could assume other distributions instead.
Assume you are flipping coins, and you want
|
When we calculate mean and variance, do we assume data are normally distributed?
$\mu$ is, indeed, the value that maximizes the Gaussian likelihood, but you have to assume Gaussianity first. You could assume other distributions instead.
Assume you are flipping coins, and you want to estimate the probability $p$ of heads.
You toss it $n$ times, and measure $\hat p \times n$ tails.
This process assumes a Bernoulli distribution, which likelihood can be stated as:
$$\mathcal L_{\mathcal B} \propto p^{\hat p \times n}(1-p)^{(1-\hat p) \times n}$$
The maximum likelihood estimator for $p$ is $\hat p = (1/n)\sum_i^n t_i = \mathbb E(T)$, where $t_i$ is the result of each toss (1 for heads, 0 for tails).
Here, we are using the expected value to maximize a Bernoulli likelihood.
Distributions have quantities called moments attached to them.
The $n$-th order moment about a value $c$ is defined as, given a probability density described by $f$:
$$\mu_n(c) = \int_{-\infty}^{+\infty} (x-c)^n f(x) dx$$
The mean is the first raw moment (moment about the origin) while the variance is the second central moment (moment about the mean).
\begin{cases}\mathbb E(X) = \mu=\mu_1(\mathbf 0)\\\operatorname{Var}(X)=\mu_2(\mu)=\mu_ 2(\mathbf 0)-\mu^2=\mathbb E(X^2)-\mathbb E(X)^2\end{cases}
These are important quantities defined for any distribution described by $f$, irrespective of if it's Gaussian or not.
|
When we calculate mean and variance, do we assume data are normally distributed?
$\mu$ is, indeed, the value that maximizes the Gaussian likelihood, but you have to assume Gaussianity first. You could assume other distributions instead.
Assume you are flipping coins, and you want
|
12,458
|
When we calculate mean and variance, do we assume data are normally distributed?
|
One thing that's only been touched on in the answers so far is the (widespread) use of sample mean & variance to estimate their population analogues without making the assumption that the data are from a distribution in any particular parametric family.
For independently, identically distributed observations from distributions in some big non-parametric families (e.g. the family of all continuous distributions having a mean & variance), the order statistic, i.e. the observations put in order from lowest to highest, is complete &
minimally sufficient—a rough & ready way of putting this is that reducing the data thus keeps all the information about which distribution they come from while squeezing out all the noise. The sample mean & variance are functions of the order statistic—they're permutation-invariant, they remain the same however you order the observations— & also unbiased: therefore by the Lehmann–Scheffé Theorem they're uniformly minimum-variance unbiased (UMVUE) estimators.† They enjoy this property in small samples as much as in large samples where the CLT may justify the approximation of their distribution by a Gaussian (for the construction of tests & confidence intervals).
† Lehmann & Casella (1998), Theory of Point Estimation 2nd edn, Ch.3 "Unbiasedness", §4 "Nonparametric families"
|
When we calculate mean and variance, do we assume data are normally distributed?
|
One thing that's only been touched on in the answers so far is the (widespread) use of sample mean & variance to estimate their population analogues without making the assumption that the data are fro
|
When we calculate mean and variance, do we assume data are normally distributed?
One thing that's only been touched on in the answers so far is the (widespread) use of sample mean & variance to estimate their population analogues without making the assumption that the data are from a distribution in any particular parametric family.
For independently, identically distributed observations from distributions in some big non-parametric families (e.g. the family of all continuous distributions having a mean & variance), the order statistic, i.e. the observations put in order from lowest to highest, is complete &
minimally sufficient—a rough & ready way of putting this is that reducing the data thus keeps all the information about which distribution they come from while squeezing out all the noise. The sample mean & variance are functions of the order statistic—they're permutation-invariant, they remain the same however you order the observations— & also unbiased: therefore by the Lehmann–Scheffé Theorem they're uniformly minimum-variance unbiased (UMVUE) estimators.† They enjoy this property in small samples as much as in large samples where the CLT may justify the approximation of their distribution by a Gaussian (for the construction of tests & confidence intervals).
† Lehmann & Casella (1998), Theory of Point Estimation 2nd edn, Ch.3 "Unbiasedness", §4 "Nonparametric families"
|
When we calculate mean and variance, do we assume data are normally distributed?
One thing that's only been touched on in the answers so far is the (widespread) use of sample mean & variance to estimate their population analogues without making the assumption that the data are fro
|
12,459
|
When we calculate mean and variance, do we assume data are normally distributed?
|
Method of moments
The expressions on the right are sample moments and on the left are parameters of a distribution (in terms of moments of the distribution).
$$\begin{array}{ccl}
\overbrace{\mu}^{\substack{\text{parameters of}\\\text{population distribution}\\\text{in terms of moments}}} &=& \overbrace{\frac{1}{N}\sum_{i=1}^N{x_i}}^{\text{sample moments}}\\
\sigma^2 &=& \frac{1}{N}\sum_{i=1}^N{(x_i-\mu)^2}
\end{array}$$
Whenever you are setting these two equal then you are employing the method of moments.
You can use this method also when you are not dealing with a normal distribution.
Example: betabinomial distribution
Say we have a population that follows a betabinomial distribution with a fixed size parameter $n$ and unknown parameters $\alpha$ and $\beta$. For this case we can also parameterize the distribution in terms of the mean and variance
$$\begin{array}{rcl}
\frac{n \alpha}{\alpha + \beta} &=& \mu\\
\frac{n\alpha\beta(n+\alpha+\beta)}{(\alpha +\beta)^2(\alpha+\beta+1)} &=& \sigma^2
\end{array}$$
and set it equal to the sample moments
$$\begin{array}{rcccccl}
\frac{n \hat\alpha}{\hat\alpha + \hat\beta}&=& \hat{\mu} &=& \bar{x} &=&\frac{1}{N}\sum_{i=1}^N{x_i}\\
\frac{n\hat\alpha\hat\beta(n+\hat\alpha+\hat\beta)}{(\hat\alpha +\hat\beta)^2(\hat\alpha+\hat\beta+1)}&=& \hat{\sigma}^2 &=& s^2 &=&\frac{1}{N}\sum_{i=1}^N{(x_i-\bar{x})^2}
\end{array}$$
From which estimates for the distribution follow
$$\begin{array}{rcl}
\hat\alpha &=& \frac{ n\hat{x}-s^2-\hat{x}^2 }{n ( \frac {s^2}{\hat{x}}-1 ) +\hat{x}} \\
\hat\beta &=&\frac{( n-\hat{x} ) ( n-{\frac {s^2+\hat{x}^2}{\hat{x}}}
)}{n ( \frac {s^2}{\hat{x}}-1 ) +\hat{x}}
\end{array}$$
With the above estimates $\hat{\alpha}$ and $\hat{\beta}$ the estimated population has the same mean and variance as the sample.
Note
In the case of estimating the parameters of a normal distribution, then the method of moments coincides with the maximum likelihood method.
|
When we calculate mean and variance, do we assume data are normally distributed?
|
Method of moments
The expressions on the right are sample moments and on the left are parameters of a distribution (in terms of moments of the distribution).
$$\begin{array}{ccl}
\overbrace{\mu}^{\sub
|
When we calculate mean and variance, do we assume data are normally distributed?
Method of moments
The expressions on the right are sample moments and on the left are parameters of a distribution (in terms of moments of the distribution).
$$\begin{array}{ccl}
\overbrace{\mu}^{\substack{\text{parameters of}\\\text{population distribution}\\\text{in terms of moments}}} &=& \overbrace{\frac{1}{N}\sum_{i=1}^N{x_i}}^{\text{sample moments}}\\
\sigma^2 &=& \frac{1}{N}\sum_{i=1}^N{(x_i-\mu)^2}
\end{array}$$
Whenever you are setting these two equal then you are employing the method of moments.
You can use this method also when you are not dealing with a normal distribution.
Example: betabinomial distribution
Say we have a population that follows a betabinomial distribution with a fixed size parameter $n$ and unknown parameters $\alpha$ and $\beta$. For this case we can also parameterize the distribution in terms of the mean and variance
$$\begin{array}{rcl}
\frac{n \alpha}{\alpha + \beta} &=& \mu\\
\frac{n\alpha\beta(n+\alpha+\beta)}{(\alpha +\beta)^2(\alpha+\beta+1)} &=& \sigma^2
\end{array}$$
and set it equal to the sample moments
$$\begin{array}{rcccccl}
\frac{n \hat\alpha}{\hat\alpha + \hat\beta}&=& \hat{\mu} &=& \bar{x} &=&\frac{1}{N}\sum_{i=1}^N{x_i}\\
\frac{n\hat\alpha\hat\beta(n+\hat\alpha+\hat\beta)}{(\hat\alpha +\hat\beta)^2(\hat\alpha+\hat\beta+1)}&=& \hat{\sigma}^2 &=& s^2 &=&\frac{1}{N}\sum_{i=1}^N{(x_i-\bar{x})^2}
\end{array}$$
From which estimates for the distribution follow
$$\begin{array}{rcl}
\hat\alpha &=& \frac{ n\hat{x}-s^2-\hat{x}^2 }{n ( \frac {s^2}{\hat{x}}-1 ) +\hat{x}} \\
\hat\beta &=&\frac{( n-\hat{x} ) ( n-{\frac {s^2+\hat{x}^2}{\hat{x}}}
)}{n ( \frac {s^2}{\hat{x}}-1 ) +\hat{x}}
\end{array}$$
With the above estimates $\hat{\alpha}$ and $\hat{\beta}$ the estimated population has the same mean and variance as the sample.
Note
In the case of estimating the parameters of a normal distribution, then the method of moments coincides with the maximum likelihood method.
|
When we calculate mean and variance, do we assume data are normally distributed?
Method of moments
The expressions on the right are sample moments and on the left are parameters of a distribution (in terms of moments of the distribution).
$$\begin{array}{ccl}
\overbrace{\mu}^{\sub
|
12,460
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
|
You will need matrix arithmetic. I'm not sure how Excel will go with that. Anyway, here are the details.
Suppose your regression is written as $\mathbf{y} = \mathbf{X}\mathbf{\beta} + \mathbf{e}$.
Let $\mathbf{X}^*$ be a row vector containing the values of the predictors for the forecasts (in the same format as $\mathbf{X}$). Then the forecast is given by
$$
\hat{y} = \mathbf{X}^*\hat{\mathbf{\beta}} = \mathbf{X}^*(\mathbf{X}'\mathbf{X})^{-1}\mathbf{X}'\mathbf{Y}
$$
with an associated variance
$$
\sigma^2 \left[1 + \mathbf{X}^* (\mathbf{X}'\mathbf{X})^{-1} (\mathbf{X}^*)'\right].
$$
Then a 95% prediction interval can be calculated (assuming normally distributed errors) as
$$
\hat{y} \pm 1.96 \hat{\sigma} \sqrt{1 + \mathbf{X}^* (\mathbf{X}'\mathbf{X})^{-1} (\mathbf{X}^*)'}.
$$
This takes account of the uncertainty due to the error term $e$ and the uncertainty in the coefficient estimates. However, it ignores any errors in $\mathbf{X}^*$. So if the future values of the predictors are uncertain, then the prediction interval calculated using this expression will be too narrow.
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
|
You will need matrix arithmetic. I'm not sure how Excel will go with that. Anyway, here are the details.
Suppose your regression is written as $\mathbf{y} = \mathbf{X}\mathbf{\beta} + \mathbf{e}$.
Let
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
You will need matrix arithmetic. I'm not sure how Excel will go with that. Anyway, here are the details.
Suppose your regression is written as $\mathbf{y} = \mathbf{X}\mathbf{\beta} + \mathbf{e}$.
Let $\mathbf{X}^*$ be a row vector containing the values of the predictors for the forecasts (in the same format as $\mathbf{X}$). Then the forecast is given by
$$
\hat{y} = \mathbf{X}^*\hat{\mathbf{\beta}} = \mathbf{X}^*(\mathbf{X}'\mathbf{X})^{-1}\mathbf{X}'\mathbf{Y}
$$
with an associated variance
$$
\sigma^2 \left[1 + \mathbf{X}^* (\mathbf{X}'\mathbf{X})^{-1} (\mathbf{X}^*)'\right].
$$
Then a 95% prediction interval can be calculated (assuming normally distributed errors) as
$$
\hat{y} \pm 1.96 \hat{\sigma} \sqrt{1 + \mathbf{X}^* (\mathbf{X}'\mathbf{X})^{-1} (\mathbf{X}^*)'}.
$$
This takes account of the uncertainty due to the error term $e$ and the uncertainty in the coefficient estimates. However, it ignores any errors in $\mathbf{X}^*$. So if the future values of the predictors are uncertain, then the prediction interval calculated using this expression will be too narrow.
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
You will need matrix arithmetic. I'm not sure how Excel will go with that. Anyway, here are the details.
Suppose your regression is written as $\mathbf{y} = \mathbf{X}\mathbf{\beta} + \mathbf{e}$.
Let
|
12,461
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
|
Are you by chance after the different types of prediction intervals? The predict.lm manual page has
## S3 method for class 'lm'
predict(object, newdata, se.fit = FALSE, scale = NULL, df = Inf,
interval = c("none", "confidence", "prediction"),
level = 0.95, type = c("response", "terms"),
terms = NULL, na.action = na.pass,
pred.var = res.var/weights, weights = 1, ...)
and
Setting
‘intervals’ specifies computation of confidence or prediction
(tolerance) intervals at the specified ‘level’, sometimes referred
to as narrow vs. wide intervals.
Is that what you had in mind?
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
|
Are you by chance after the different types of prediction intervals? The predict.lm manual page has
## S3 method for class 'lm'
predict(object, newdata, se.fit = FALSE, scale = NULL, df = Inf,
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
Are you by chance after the different types of prediction intervals? The predict.lm manual page has
## S3 method for class 'lm'
predict(object, newdata, se.fit = FALSE, scale = NULL, df = Inf,
interval = c("none", "confidence", "prediction"),
level = 0.95, type = c("response", "terms"),
terms = NULL, na.action = na.pass,
pred.var = res.var/weights, weights = 1, ...)
and
Setting
‘intervals’ specifies computation of confidence or prediction
(tolerance) intervals at the specified ‘level’, sometimes referred
to as narrow vs. wide intervals.
Is that what you had in mind?
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
Are you by chance after the different types of prediction intervals? The predict.lm manual page has
## S3 method for class 'lm'
predict(object, newdata, se.fit = FALSE, scale = NULL, df = Inf,
|
12,462
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
|
@Tal: Might I suggest Kutner et al as a fabulous source for linear models.
There is the distinction between
a prediction of $Y$ from an individual new observation $X_{vec}$,
the expected value of a $Y$ conditioned on $X_{vec}$, $E(Y|X_{vec})$ and
$Y$ from several instances of $x_{vec}$
They are all covered in detail in the text.
I think you are looking for the formula for the confidence interval around $E(Y|X_{vec})$ and that is $\hat{Y} \pm t_{1-\alpha/2}s_{\hat{Y}}$ where $t$ has $n-2$ d.f. and $s_{\hat{Y}}$ is the standard error of $\hat{Y}$, $\frac{\sigma^{2}}{n} +(X_{vec}-\bar{X})^{2}\frac{\sigma^{2}}{\sum(X_{i}-\bar{X})^{2}}$
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
|
@Tal: Might I suggest Kutner et al as a fabulous source for linear models.
There is the distinction between
a prediction of $Y$ from an individual new observation $X_{vec}$,
the expected value of a $
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
@Tal: Might I suggest Kutner et al as a fabulous source for linear models.
There is the distinction between
a prediction of $Y$ from an individual new observation $X_{vec}$,
the expected value of a $Y$ conditioned on $X_{vec}$, $E(Y|X_{vec})$ and
$Y$ from several instances of $x_{vec}$
They are all covered in detail in the text.
I think you are looking for the formula for the confidence interval around $E(Y|X_{vec})$ and that is $\hat{Y} \pm t_{1-\alpha/2}s_{\hat{Y}}$ where $t$ has $n-2$ d.f. and $s_{\hat{Y}}$ is the standard error of $\hat{Y}$, $\frac{\sigma^{2}}{n} +(X_{vec}-\bar{X})^{2}\frac{\sigma^{2}}{\sum(X_{i}-\bar{X})^{2}}$
|
Obtaining a formula for prediction limits in a linear model (i.e.: prediction intervals)
@Tal: Might I suggest Kutner et al as a fabulous source for linear models.
There is the distinction between
a prediction of $Y$ from an individual new observation $X_{vec}$,
the expected value of a $
|
12,463
|
Alternatives to Bayesian statistics when distributions are unknown
|
From what you’re saying is that you want something Bayesian, but you can’t define the likelihood. For such cases there is approximate Bayesian computation (see abc), where in place of likelihood you use some summary statistics.
As a side note, for using proper Bayesian analysis you don’t need to know the “exact” distribution. We nearly never do. You need to use some distribution that relatively well approximates the distribution of the data. This is how is it done in most of the statistics. We don’t use Gaussian, Poisson, etc distributions because they are the exact distributions of the observed data, but they are good enough approximations for the purpose. Same you do with loss function, you don’t use squared error because it has some deep meaning for your data, but because it works well enough.
|
Alternatives to Bayesian statistics when distributions are unknown
|
From what you’re saying is that you want something Bayesian, but you can’t define the likelihood. For such cases there is approximate Bayesian computation (see abc), where in place of likelihood you u
|
Alternatives to Bayesian statistics when distributions are unknown
From what you’re saying is that you want something Bayesian, but you can’t define the likelihood. For such cases there is approximate Bayesian computation (see abc), where in place of likelihood you use some summary statistics.
As a side note, for using proper Bayesian analysis you don’t need to know the “exact” distribution. We nearly never do. You need to use some distribution that relatively well approximates the distribution of the data. This is how is it done in most of the statistics. We don’t use Gaussian, Poisson, etc distributions because they are the exact distributions of the observed data, but they are good enough approximations for the purpose. Same you do with loss function, you don’t use squared error because it has some deep meaning for your data, but because it works well enough.
|
Alternatives to Bayesian statistics when distributions are unknown
From what you’re saying is that you want something Bayesian, but you can’t define the likelihood. For such cases there is approximate Bayesian computation (see abc), where in place of likelihood you u
|
12,464
|
Alternatives to Bayesian statistics when distributions are unknown
|
If the distribution of the data is unknown, the Bayesian way of handling this uncertainty is to put a prior on it. There exists a huge literature on Bayesian non-parametrics, including the Fundamentals of Nonparametric Bayesian inference by Ghosal and van der Vaart. The default priors in such settings are distributions on distributions, like Dirichlet processes. Check e.g. the webpage Tutorials on Bayesian Nonparametrics, maintained by Peter Orbanz. Here is a list of seminal papers given to our students.
Concerning MCMC, there exist MCMC algorithms that handle Bayesian nonparametrics as well. See e.g. this book by Dey et al. Check also the dirichlet-process tag on this forum.
A milder solution is to use Bayesian model averaging, that is, to list all (!) the plausible families that could fit the data, choose a reference prior on each, and use the posterior mixture for quantities of interest [common to all families].
|
Alternatives to Bayesian statistics when distributions are unknown
|
If the distribution of the data is unknown, the Bayesian way of handling this uncertainty is to put a prior on it. There exists a huge literature on Bayesian non-parametrics, including the Fundamental
|
Alternatives to Bayesian statistics when distributions are unknown
If the distribution of the data is unknown, the Bayesian way of handling this uncertainty is to put a prior on it. There exists a huge literature on Bayesian non-parametrics, including the Fundamentals of Nonparametric Bayesian inference by Ghosal and van der Vaart. The default priors in such settings are distributions on distributions, like Dirichlet processes. Check e.g. the webpage Tutorials on Bayesian Nonparametrics, maintained by Peter Orbanz. Here is a list of seminal papers given to our students.
Concerning MCMC, there exist MCMC algorithms that handle Bayesian nonparametrics as well. See e.g. this book by Dey et al. Check also the dirichlet-process tag on this forum.
A milder solution is to use Bayesian model averaging, that is, to list all (!) the plausible families that could fit the data, choose a reference prior on each, and use the posterior mixture for quantities of interest [common to all families].
|
Alternatives to Bayesian statistics when distributions are unknown
If the distribution of the data is unknown, the Bayesian way of handling this uncertainty is to put a prior on it. There exists a huge literature on Bayesian non-parametrics, including the Fundamental
|
12,465
|
Alternatives to Bayesian statistics when distributions are unknown
|
Although the other answers are ok, I think they might be overkill for yours or for many other problems.
Without changing the paradigm, if you know the distribution has heavier tails than Gaussian, you can fit t-distribution with either fixed heaviness of tails or with the heaviness of tails that are estimated from the data possibly with a prior information.
If a distribution is skewed and has heavier tails, you can fit a SHASH distribution which has four parameters parametrizing location, scale, skewness, and kurtosis of the distribution with the normal distribution as its special case.
|
Alternatives to Bayesian statistics when distributions are unknown
|
Although the other answers are ok, I think they might be overkill for yours or for many other problems.
Without changing the paradigm, if you know the distribution has heavier tails than Gaussian, you
|
Alternatives to Bayesian statistics when distributions are unknown
Although the other answers are ok, I think they might be overkill for yours or for many other problems.
Without changing the paradigm, if you know the distribution has heavier tails than Gaussian, you can fit t-distribution with either fixed heaviness of tails or with the heaviness of tails that are estimated from the data possibly with a prior information.
If a distribution is skewed and has heavier tails, you can fit a SHASH distribution which has four parameters parametrizing location, scale, skewness, and kurtosis of the distribution with the normal distribution as its special case.
|
Alternatives to Bayesian statistics when distributions are unknown
Although the other answers are ok, I think they might be overkill for yours or for many other problems.
Without changing the paradigm, if you know the distribution has heavier tails than Gaussian, you
|
12,466
|
Alternatives to Bayesian statistics when distributions are unknown
|
I suggest as alternative bootstrap based methods, which can be parametric and not, and works with very few assumptions and very few data (only 5-7 samples suffice); it works on non gaussian distributions and for many measures (eg., mean, etc). One can "rebuild" a distribution by bootstraping the mean, if it makes sense in the given context. The Davison1 is good for introducting the bootstrap in general.
Many papers were published on the volatility smile analysed throught bootstrap based methods [0].
https://scholar.google.com/scholar?q=bootstrap+volatility+smile
Davison, A.C. and Hinkley, D.V., 1997. Bootstrap methods and their application (No. 1). Cambridge university press.
The Non-parametric Bootstrap as a Bayesian Model
|
Alternatives to Bayesian statistics when distributions are unknown
|
I suggest as alternative bootstrap based methods, which can be parametric and not, and works with very few assumptions and very few data (only 5-7 samples suffice); it works on non gaussian distributi
|
Alternatives to Bayesian statistics when distributions are unknown
I suggest as alternative bootstrap based methods, which can be parametric and not, and works with very few assumptions and very few data (only 5-7 samples suffice); it works on non gaussian distributions and for many measures (eg., mean, etc). One can "rebuild" a distribution by bootstraping the mean, if it makes sense in the given context. The Davison1 is good for introducting the bootstrap in general.
Many papers were published on the volatility smile analysed throught bootstrap based methods [0].
https://scholar.google.com/scholar?q=bootstrap+volatility+smile
Davison, A.C. and Hinkley, D.V., 1997. Bootstrap methods and their application (No. 1). Cambridge university press.
The Non-parametric Bootstrap as a Bayesian Model
|
Alternatives to Bayesian statistics when distributions are unknown
I suggest as alternative bootstrap based methods, which can be parametric and not, and works with very few assumptions and very few data (only 5-7 samples suffice); it works on non gaussian distributi
|
12,467
|
Why does feature engineering work ?
|
You question title and the content seems mismatched to me. If you are using linear model, add a total feature in addition to attack and defense will make things worse.
First I would answer why feature engineering work in general.
A picture is worth a thousand words. This figure may tell you some insights on feature engineering and why it works (picture source):
The data in Cartesian coordinates is more complicated, and it is relatively hard to write a rule / build a model to classify two types.
The data in Polar coordinates is much easy:, we can write a simple rule on $r$ to classify two types.
This tell us that the representation of the data matters a lot. In certain space, it is much easier to do certain tasks than other spaces.
Here I answer the question mentioned in your example (total on attack and defense)
In fact, the feature engineering mentioned in this sum of attack and defense example, will not work well for many models such as linear model and it will cause some problems. See Multicollinearity. On the other hand, such feature engineering may work on other models, such as decision tree / random forest. See @Imran's answer for details.
So, the answer is that depending on the model you use, some feature engineering will help on some models, but not for other models.
|
Why does feature engineering work ?
|
You question title and the content seems mismatched to me. If you are using linear model, add a total feature in addition to attack and defense will make things worse.
First I would answer why feature
|
Why does feature engineering work ?
You question title and the content seems mismatched to me. If you are using linear model, add a total feature in addition to attack and defense will make things worse.
First I would answer why feature engineering work in general.
A picture is worth a thousand words. This figure may tell you some insights on feature engineering and why it works (picture source):
The data in Cartesian coordinates is more complicated, and it is relatively hard to write a rule / build a model to classify two types.
The data in Polar coordinates is much easy:, we can write a simple rule on $r$ to classify two types.
This tell us that the representation of the data matters a lot. In certain space, it is much easier to do certain tasks than other spaces.
Here I answer the question mentioned in your example (total on attack and defense)
In fact, the feature engineering mentioned in this sum of attack and defense example, will not work well for many models such as linear model and it will cause some problems. See Multicollinearity. On the other hand, such feature engineering may work on other models, such as decision tree / random forest. See @Imran's answer for details.
So, the answer is that depending on the model you use, some feature engineering will help on some models, but not for other models.
|
Why does feature engineering work ?
You question title and the content seems mismatched to me. If you are using linear model, add a total feature in addition to attack and defense will make things worse.
First I would answer why feature
|
12,468
|
Why does feature engineering work ?
|
The type of model we are using might not be very efficient at learning certain combinations of existing features.
For example, consider your example where features are a and d, and we are using a decision tree to predict a binary outcome that happens to be $0$ if $a+d<0$ and $1$ if $a+d\geq0$.
Since decision trees can only split along individual feature axes, our model will end up trying to build a staircase to fit a line, which will look something like this:
As you can see this will not generalize perfectly to new data. We can have circles above the true decision line that are under our decision boundary and vice versa for crosses.
However, if we add a+d as a feature then the problem becomes trivial for a decision tree. It can ignore the individual a and d features and solve the problem with a single a+d<0 decision stump.
However, if you were using linear regression, then your model would be perfectly capable of learning $a+d$ without adding an additional feature.
In summary, certain additional features can help depending on the type of model you are using, and you should be careful to consider both the data and the model when engineering features.
|
Why does feature engineering work ?
|
The type of model we are using might not be very efficient at learning certain combinations of existing features.
For example, consider your example where features are a and d, and we are using a deci
|
Why does feature engineering work ?
The type of model we are using might not be very efficient at learning certain combinations of existing features.
For example, consider your example where features are a and d, and we are using a decision tree to predict a binary outcome that happens to be $0$ if $a+d<0$ and $1$ if $a+d\geq0$.
Since decision trees can only split along individual feature axes, our model will end up trying to build a staircase to fit a line, which will look something like this:
As you can see this will not generalize perfectly to new data. We can have circles above the true decision line that are under our decision boundary and vice versa for crosses.
However, if we add a+d as a feature then the problem becomes trivial for a decision tree. It can ignore the individual a and d features and solve the problem with a single a+d<0 decision stump.
However, if you were using linear regression, then your model would be perfectly capable of learning $a+d$ without adding an additional feature.
In summary, certain additional features can help depending on the type of model you are using, and you should be careful to consider both the data and the model when engineering features.
|
Why does feature engineering work ?
The type of model we are using might not be very efficient at learning certain combinations of existing features.
For example, consider your example where features are a and d, and we are using a deci
|
12,469
|
Why does feature engineering work ?
|
A constructed feature like total can still be predictively useful if it isn't strongly correlated with other features in the same model. total in particular need not be strongly correlated with attack or defense. For example, if attack is (8, 0, 4) and defense is (1, 9, 6), then the correlation of total with attack is 0 and the correlation of total with defense is $\frac{1}{7}$.
Additionally, is that not a problem, for classificators such as kNN, that "total" will be always bigger than "attack" or "defense"? Thus, even after standarization we will have features containing values from different ranges?
If you want to standardize your predictors, you should do it after they've all been constructed.
|
Why does feature engineering work ?
|
A constructed feature like total can still be predictively useful if it isn't strongly correlated with other features in the same model. total in particular need not be strongly correlated with attack
|
Why does feature engineering work ?
A constructed feature like total can still be predictively useful if it isn't strongly correlated with other features in the same model. total in particular need not be strongly correlated with attack or defense. For example, if attack is (8, 0, 4) and defense is (1, 9, 6), then the correlation of total with attack is 0 and the correlation of total with defense is $\frac{1}{7}$.
Additionally, is that not a problem, for classificators such as kNN, that "total" will be always bigger than "attack" or "defense"? Thus, even after standarization we will have features containing values from different ranges?
If you want to standardize your predictors, you should do it after they've all been constructed.
|
Why does feature engineering work ?
A constructed feature like total can still be predictively useful if it isn't strongly correlated with other features in the same model. total in particular need not be strongly correlated with attack
|
12,470
|
Why does feature engineering work ?
|
To give a general answer, feature engineering in most cases is about extracting meaningful features from your data, so if you give more information to your model, it obviously should behave better. Say that your data consists of e-mail addresses in form ‘name.surname@domain.country-code’. If you used them as-is in your model, each person would be characterized by a unique e-mail, so this wouldn’t tell us much. It would tell us only that one e-mail possibly belongs to different person then another. With feature engineering, from such addresses you could extract information about possible gender (name), family background and ethnicity (surname), nationality (domain) and many more - it gives you pretty much information, doesn’t it?
|
Why does feature engineering work ?
|
To give a general answer, feature engineering in most cases is about extracting meaningful features from your data, so if you give more information to your model, it obviously should behave better. Sa
|
Why does feature engineering work ?
To give a general answer, feature engineering in most cases is about extracting meaningful features from your data, so if you give more information to your model, it obviously should behave better. Say that your data consists of e-mail addresses in form ‘name.surname@domain.country-code’. If you used them as-is in your model, each person would be characterized by a unique e-mail, so this wouldn’t tell us much. It would tell us only that one e-mail possibly belongs to different person then another. With feature engineering, from such addresses you could extract information about possible gender (name), family background and ethnicity (surname), nationality (domain) and many more - it gives you pretty much information, doesn’t it?
|
Why does feature engineering work ?
To give a general answer, feature engineering in most cases is about extracting meaningful features from your data, so if you give more information to your model, it obviously should behave better. Sa
|
12,471
|
Why does feature engineering work ?
|
What are you trying to accomplish with your "feature" total? If you're merely comparing heroes, attack and defense might be more useful. If you would find the type of build (how offensively-oriented versus how defensively-oriented) to be useful, perhaps attack / defense would be more useful. Or maybe MyAttack - YourDefense is more useful.
It really depends on your goal and it boils down to you injecting additional knowledge into the problem so you can get better answers. You may have heard people throwing around log and squared and ratio and all kinds of ways you could make features, but the bottom line is that "useful" depends on the task at hand and involves transforming the data you have into a domain where decisions are simpler.
|
Why does feature engineering work ?
|
What are you trying to accomplish with your "feature" total? If you're merely comparing heroes, attack and defense might be more useful. If you would find the type of build (how offensively-oriented v
|
Why does feature engineering work ?
What are you trying to accomplish with your "feature" total? If you're merely comparing heroes, attack and defense might be more useful. If you would find the type of build (how offensively-oriented versus how defensively-oriented) to be useful, perhaps attack / defense would be more useful. Or maybe MyAttack - YourDefense is more useful.
It really depends on your goal and it boils down to you injecting additional knowledge into the problem so you can get better answers. You may have heard people throwing around log and squared and ratio and all kinds of ways you could make features, but the bottom line is that "useful" depends on the task at hand and involves transforming the data you have into a domain where decisions are simpler.
|
Why does feature engineering work ?
What are you trying to accomplish with your "feature" total? If you're merely comparing heroes, attack and defense might be more useful. If you would find the type of build (how offensively-oriented v
|
12,472
|
Paired versus unpaired t-test
|
I agree with the points that both Frank and Peter make but I think there is a simple formula that gets to the heart of the issue and may be worthwhile for the OP to consider.
Let $X$ and $Y$ be two random variables whose correlation is unknown.
Let $Z=X-Y$
What is the variance of $Z$?
Here is the simple formula:
$$
\text{Var}(Z)=\text{Var}(X) + \text{Var}(Y) - 2 \text{Cov}(X,Y).
$$
What if $\text{Cov}(X,Y)>0$ (i.e., $X$ and $Y$ are positively correlated)?
Then $\text{Var}(Z)\lt \text{Var}(X)+\text{Var}(Y)$. In this case if the pairing is made because of positive correlation such as when you are dealing with the same subject before and after intervention pairing helps because the independent paired difference has lower variance than the variance you get for the unpaired case. The method reduced variance. The test is more powerful. This can be dramatically shown with cyclic data. I saw an example in a book where they wanted to see if the temperature in Washington DC is higher than in New York City. So they took average monthly temperature in both cities for say 2 years. Of course there is a huge difference over the course of the year because of the four seasons. This variation is too large for an unpaired t test to detect a difference. However pairing based on the same month in the same year eliminates this seasonal effect and the paired $t$-test clearly showed that the average temperature in DC tended to be higher than in New York. $X_i$ (temperature at NY in month $A$) and $Y_i$ (temperature in DC in month $A$)
are positively correlated because the seasons are the same in NY and DC and the cities are close enough that they will often experience the same weather systems that affect temperature. DC may be a little warmer because it is further south.
Note that the large the covariance or correlation the greater is the reduction in variance.
Now suppose $\text{Cov}(X,Y)$ is negative.
Then $\text{Var}(Z) \gt \text{Var}(X)+\text{Var}(Y)$. Now pairing will be worse than not pairing because the variance is actually increased!
When $X$ and $Y$ are uncorrelated then it probably doesn't matter which method you use. Peter's random pairing case is like this situation.
|
Paired versus unpaired t-test
|
I agree with the points that both Frank and Peter make but I think there is a simple formula that gets to the heart of the issue and may be worthwhile for the OP to consider.
Let $X$ and $Y$ be two ra
|
Paired versus unpaired t-test
I agree with the points that both Frank and Peter make but I think there is a simple formula that gets to the heart of the issue and may be worthwhile for the OP to consider.
Let $X$ and $Y$ be two random variables whose correlation is unknown.
Let $Z=X-Y$
What is the variance of $Z$?
Here is the simple formula:
$$
\text{Var}(Z)=\text{Var}(X) + \text{Var}(Y) - 2 \text{Cov}(X,Y).
$$
What if $\text{Cov}(X,Y)>0$ (i.e., $X$ and $Y$ are positively correlated)?
Then $\text{Var}(Z)\lt \text{Var}(X)+\text{Var}(Y)$. In this case if the pairing is made because of positive correlation such as when you are dealing with the same subject before and after intervention pairing helps because the independent paired difference has lower variance than the variance you get for the unpaired case. The method reduced variance. The test is more powerful. This can be dramatically shown with cyclic data. I saw an example in a book where they wanted to see if the temperature in Washington DC is higher than in New York City. So they took average monthly temperature in both cities for say 2 years. Of course there is a huge difference over the course of the year because of the four seasons. This variation is too large for an unpaired t test to detect a difference. However pairing based on the same month in the same year eliminates this seasonal effect and the paired $t$-test clearly showed that the average temperature in DC tended to be higher than in New York. $X_i$ (temperature at NY in month $A$) and $Y_i$ (temperature in DC in month $A$)
are positively correlated because the seasons are the same in NY and DC and the cities are close enough that they will often experience the same weather systems that affect temperature. DC may be a little warmer because it is further south.
Note that the large the covariance or correlation the greater is the reduction in variance.
Now suppose $\text{Cov}(X,Y)$ is negative.
Then $\text{Var}(Z) \gt \text{Var}(X)+\text{Var}(Y)$. Now pairing will be worse than not pairing because the variance is actually increased!
When $X$ and $Y$ are uncorrelated then it probably doesn't matter which method you use. Peter's random pairing case is like this situation.
|
Paired versus unpaired t-test
I agree with the points that both Frank and Peter make but I think there is a simple formula that gets to the heart of the issue and may be worthwhile for the OP to consider.
Let $X$ and $Y$ be two ra
|
12,473
|
Paired versus unpaired t-test
|
Rather than pairing it is probably better to understand the underlying data model. If pairing is done to deal with uncontrolled heterogeneity, it is usually the case (except in twin studies) that the pairing only partially controls this source of variability and multiple regression would do better. This is because matching on continuous variables frequently results in residual variability because of not being able to do exact matching on such variables.
|
Paired versus unpaired t-test
|
Rather than pairing it is probably better to understand the underlying data model. If pairing is done to deal with uncontrolled heterogeneity, it is usually the case (except in twin studies) that the
|
Paired versus unpaired t-test
Rather than pairing it is probably better to understand the underlying data model. If pairing is done to deal with uncontrolled heterogeneity, it is usually the case (except in twin studies) that the pairing only partially controls this source of variability and multiple regression would do better. This is because matching on continuous variables frequently results in residual variability because of not being able to do exact matching on such variables.
|
Paired versus unpaired t-test
Rather than pairing it is probably better to understand the underlying data model. If pairing is done to deal with uncontrolled heterogeneity, it is usually the case (except in twin studies) that the
|
12,474
|
Paired versus unpaired t-test
|
The two tests (paired and unpaired) ask different questions so they can get different answers. Correct pairing nearly always is more powerful than unpaired - that's really the point of pairing. So, since you say the pairing is correct, it is likely that the p-value for your paired test is lower than for the same data unpaired. You could, of course, do both and see for yourself.
Therefore, the answer to your dilemma is substantive, not statistical. Is your pairing right?
Could you get a more significant result from random pairing than from a unpaired test? Let's see:
set.seed(2910110192)
x <- rnorm(100, 10, 2)
y <- rnorm(100, 10, 2)
t.test(x, y)
t.test(x, y, paired = T)
Yes you can, although here the difference is very small, the paired had a lower p. I ran that code several times. Not surprisingly, sometimes one p is lower, sometimes the other, but the difference was small in all cases. However, I am sure that in some situations the difference in p values could be large.
|
Paired versus unpaired t-test
|
The two tests (paired and unpaired) ask different questions so they can get different answers. Correct pairing nearly always is more powerful than unpaired - that's really the point of pairing. So, si
|
Paired versus unpaired t-test
The two tests (paired and unpaired) ask different questions so they can get different answers. Correct pairing nearly always is more powerful than unpaired - that's really the point of pairing. So, since you say the pairing is correct, it is likely that the p-value for your paired test is lower than for the same data unpaired. You could, of course, do both and see for yourself.
Therefore, the answer to your dilemma is substantive, not statistical. Is your pairing right?
Could you get a more significant result from random pairing than from a unpaired test? Let's see:
set.seed(2910110192)
x <- rnorm(100, 10, 2)
y <- rnorm(100, 10, 2)
t.test(x, y)
t.test(x, y, paired = T)
Yes you can, although here the difference is very small, the paired had a lower p. I ran that code several times. Not surprisingly, sometimes one p is lower, sometimes the other, but the difference was small in all cases. However, I am sure that in some situations the difference in p values could be large.
|
Paired versus unpaired t-test
The two tests (paired and unpaired) ask different questions so they can get different answers. Correct pairing nearly always is more powerful than unpaired - that's really the point of pairing. So, si
|
12,475
|
Paired versus unpaired t-test
|
I now understand much better what was worrying me about paired versus unpaired t-tests, and associated p-values. Finding out has been an interesting journey, and there have been many surprises along the way. One surprise has resulted from an investigation of Michael's contribution. This is irreproachable in terms of practical advice. Moreover, he says what I think virtually all statisticians believe, and he has several upvotes to back this up. However, as a piece of theory, it is not literally correct. I discovered this by working out the formulas for the p-values, and then thinking carefully how to use the formulas to lead to counter-examples. I'm a mathematician by training, and the counter-example is a "mathematician's counter-example". It's not something you would come across in practical statistics, but it was the kind of thing I was trying to find out about when I asked my original question.
Here is the R-code that gives the counter-example:
vLength <- 10; meanDiff <-10^9; numSamples <- 3;
pv <- function(vLength,meanDiff) {
X <- rnorm(vLength)
Y <- X - meanDiff + rnorm(vLength,sd=0.0001)
Paired <- t.test(X,Y,var.equal=T,paired=T)
NotPaired <- t.test(X,Y,var.equal=T,paired=F)
c(Paired$p.value,NotPaired$p.value,cov(X,Y))
}
ans <- replicate(numSamples,pv(vLength,meanDiff))
Note the following features: X and Y are two 10-tuples whose difference is huge and very nearly constant. To many significant figures, the correlation is 1.000.... The p-value for the unpaired test is around 10^40 times smaller than the p-value for the paired test. So this contradicts Michael's account, provided that one reads his account literally, mathematician-style. Here ends the part of my answer related to Michael's answer.
Here are the thoughts prompted by Peter's answer.
During the discussion of my original question, I conjectured in a comment that two particular distributions of p-values that sound different are in fact the same. I can now prove this. What is more important is that the proof reveals the fundamental nature of a p-value, so fundamental that no text (that I've come across) bothers to explain. Maybe all professional statisticians know the secret, but to me, the definition of p-value always seemed strange and artificial. Before giving away the statistician's secret, let me specify the question.
Let $n>1$ and choose randomly and independently two random $n$-tuples from some normal distribution. There are two ways of getting a p-value from this choice. One is to use an unpaired t-test, and the other is to use a paired t-test. My conjecture was that the distribution of p-values that one gets is the same in the two cases. When I first started to think about it, I decided that this conjecture had been foolhardy and was false: the unpaired test is associated to a t-statistic on $2(n-1)$ degrees of freedom, and the paired test to a t-statistic on $n-1$ degrees of freedom. These two distributions are different, so how on earth could the associated distributions of p-values be the same? Only after much further thought did I realize that this obvious dismissal of my conjecture was too facile.
The answer comes from the following considerations. Suppose $f:(0,\infty)\to (0,\infty)$ is a continuous pdf (that is, its integral has value one). A change of coordinates converts the associated distribution into the uniform distribution on $[0,1]$. The formula is
$$p=\int_t^\infty f(s)\,ds$$
and this much is explained in many texts. What the texts fail to point out in the context of p-values is that this is exactly the formula that gives the p-value from the t-statistic, when $f$ is the pdf for the t-distribution. (I'm trying to keep the discussion as simple as I can, because it really is simple. A fuller discussion would treat one-sided and two-sided t-tests slightly differently, factors of 2 might arise, and the t-statistic might lie in $(-\infty,\infty)$ instead of in $[0,\infty)$. I omit all that clutter.)
Exactly the same discussion applies when finding the p-value associated with any of the other standard distributions in statistics. Once again, if the data is randomly distributed (this time according to some different distribution), then the resulting p-values will be distributed uniformly in $[0,1]$.
How does this apply to our paired and unpaired t-tests? The point is in the paired t-test, with samples chosen independently and randomly, as in my code above, the value of t does indeed follow a t-distribution (with $n-1$ degrees of freedom). So the p-values that result from replicating the choice of X and Y many times follow the uniform distribution on $[0,1]$. The same is true for the unpaired t-test, though this time the t-distribution has $2(n-1)$ degrees of freedom. Nevertheless, the p-values that result also have a uniform distribution on $[0,1]$, by the general argument I gave above. If Peter's code above is applied to determine p-values, then we get two distinct methods of drawing a random sample from the uniform distribution on $[0,1]$. However the two answers are not independent.
|
Paired versus unpaired t-test
|
I now understand much better what was worrying me about paired versus unpaired t-tests, and associated p-values. Finding out has been an interesting journey, and there have been many surprises along t
|
Paired versus unpaired t-test
I now understand much better what was worrying me about paired versus unpaired t-tests, and associated p-values. Finding out has been an interesting journey, and there have been many surprises along the way. One surprise has resulted from an investigation of Michael's contribution. This is irreproachable in terms of practical advice. Moreover, he says what I think virtually all statisticians believe, and he has several upvotes to back this up. However, as a piece of theory, it is not literally correct. I discovered this by working out the formulas for the p-values, and then thinking carefully how to use the formulas to lead to counter-examples. I'm a mathematician by training, and the counter-example is a "mathematician's counter-example". It's not something you would come across in practical statistics, but it was the kind of thing I was trying to find out about when I asked my original question.
Here is the R-code that gives the counter-example:
vLength <- 10; meanDiff <-10^9; numSamples <- 3;
pv <- function(vLength,meanDiff) {
X <- rnorm(vLength)
Y <- X - meanDiff + rnorm(vLength,sd=0.0001)
Paired <- t.test(X,Y,var.equal=T,paired=T)
NotPaired <- t.test(X,Y,var.equal=T,paired=F)
c(Paired$p.value,NotPaired$p.value,cov(X,Y))
}
ans <- replicate(numSamples,pv(vLength,meanDiff))
Note the following features: X and Y are two 10-tuples whose difference is huge and very nearly constant. To many significant figures, the correlation is 1.000.... The p-value for the unpaired test is around 10^40 times smaller than the p-value for the paired test. So this contradicts Michael's account, provided that one reads his account literally, mathematician-style. Here ends the part of my answer related to Michael's answer.
Here are the thoughts prompted by Peter's answer.
During the discussion of my original question, I conjectured in a comment that two particular distributions of p-values that sound different are in fact the same. I can now prove this. What is more important is that the proof reveals the fundamental nature of a p-value, so fundamental that no text (that I've come across) bothers to explain. Maybe all professional statisticians know the secret, but to me, the definition of p-value always seemed strange and artificial. Before giving away the statistician's secret, let me specify the question.
Let $n>1$ and choose randomly and independently two random $n$-tuples from some normal distribution. There are two ways of getting a p-value from this choice. One is to use an unpaired t-test, and the other is to use a paired t-test. My conjecture was that the distribution of p-values that one gets is the same in the two cases. When I first started to think about it, I decided that this conjecture had been foolhardy and was false: the unpaired test is associated to a t-statistic on $2(n-1)$ degrees of freedom, and the paired test to a t-statistic on $n-1$ degrees of freedom. These two distributions are different, so how on earth could the associated distributions of p-values be the same? Only after much further thought did I realize that this obvious dismissal of my conjecture was too facile.
The answer comes from the following considerations. Suppose $f:(0,\infty)\to (0,\infty)$ is a continuous pdf (that is, its integral has value one). A change of coordinates converts the associated distribution into the uniform distribution on $[0,1]$. The formula is
$$p=\int_t^\infty f(s)\,ds$$
and this much is explained in many texts. What the texts fail to point out in the context of p-values is that this is exactly the formula that gives the p-value from the t-statistic, when $f$ is the pdf for the t-distribution. (I'm trying to keep the discussion as simple as I can, because it really is simple. A fuller discussion would treat one-sided and two-sided t-tests slightly differently, factors of 2 might arise, and the t-statistic might lie in $(-\infty,\infty)$ instead of in $[0,\infty)$. I omit all that clutter.)
Exactly the same discussion applies when finding the p-value associated with any of the other standard distributions in statistics. Once again, if the data is randomly distributed (this time according to some different distribution), then the resulting p-values will be distributed uniformly in $[0,1]$.
How does this apply to our paired and unpaired t-tests? The point is in the paired t-test, with samples chosen independently and randomly, as in my code above, the value of t does indeed follow a t-distribution (with $n-1$ degrees of freedom). So the p-values that result from replicating the choice of X and Y many times follow the uniform distribution on $[0,1]$. The same is true for the unpaired t-test, though this time the t-distribution has $2(n-1)$ degrees of freedom. Nevertheless, the p-values that result also have a uniform distribution on $[0,1]$, by the general argument I gave above. If Peter's code above is applied to determine p-values, then we get two distinct methods of drawing a random sample from the uniform distribution on $[0,1]$. However the two answers are not independent.
|
Paired versus unpaired t-test
I now understand much better what was worrying me about paired versus unpaired t-tests, and associated p-values. Finding out has been an interesting journey, and there have been many surprises along t
|
12,476
|
Paired versus unpaired t-test
|
I would offer another perspective. Often, pairing is done do reduce bias. Suppose that you are interested in whether exposure E is a risk factor for a continuous outcome Y. For each E+ subject, you get an age and sex matched subject who is E-. Now, we could do either a paired t-test or an unpaired t-test. I think we should account for matching explicitly and conduct a paired t-test. It is more principled in that it takes the design into account. Whether to take matching into account in the analysis is an issue of the bias-variance tradeoff. Accounting for matching in the analysis provides more protection against bias, but can increase variance. Doing an unpaired t-test may be more efficient, but it would not provide any protection against bias.
|
Paired versus unpaired t-test
|
I would offer another perspective. Often, pairing is done do reduce bias. Suppose that you are interested in whether exposure E is a risk factor for a continuous outcome Y. For each E+ subject, you
|
Paired versus unpaired t-test
I would offer another perspective. Often, pairing is done do reduce bias. Suppose that you are interested in whether exposure E is a risk factor for a continuous outcome Y. For each E+ subject, you get an age and sex matched subject who is E-. Now, we could do either a paired t-test or an unpaired t-test. I think we should account for matching explicitly and conduct a paired t-test. It is more principled in that it takes the design into account. Whether to take matching into account in the analysis is an issue of the bias-variance tradeoff. Accounting for matching in the analysis provides more protection against bias, but can increase variance. Doing an unpaired t-test may be more efficient, but it would not provide any protection against bias.
|
Paired versus unpaired t-test
I would offer another perspective. Often, pairing is done do reduce bias. Suppose that you are interested in whether exposure E is a risk factor for a continuous outcome Y. For each E+ subject, you
|
12,477
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
|
Here's one:
$y=\frac{1}{1+\left ( \frac{x}{1-x} \right )^{-\beta}}$
where $\beta$ is $>0$
]2
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
|
Here's one:
$y=\frac{1}{1+\left ( \frac{x}{1-x} \right )^{-\beta}}$
where $\beta$ is $>0$
]2
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
Here's one:
$y=\frac{1}{1+\left ( \frac{x}{1-x} \right )^{-\beta}}$
where $\beta$ is $>0$
]2
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
Here's one:
$y=\frac{1}{1+\left ( \frac{x}{1-x} \right )^{-\beta}}$
where $\beta$ is $>0$
]2
|
12,478
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
|
What you're trying to use this for is not particularly clear to me so I can't say whether it makes sense to do but fulfilling all your criteria seems to be fairly trivial.
s-shaped curve
parametric function
0 maps to 0, 1 maps to 1, strictly increasing
simple derivative
So why not just take any convenient specific family of continuous unimodal* distribution functions on [0,1] whose pdf is "simple"? That seems to fulfill every part of what you list there.
* (whose mode is bounded away from the endpoints)
s-shaped curve - guaranteed by unimodality (with mode not at endpoints)
parametric - by giving any specific family which has parameters
0 maps to 0, 1 maps to 1 strictly increasing - that's what distribution functions on [0,1] do; you just need the density to be >0 in (0,1)
simple derivative -- that's the pdf, so if the pdf is "simple" by whatever criterion suits you, you're done.
There are (as Alex R stated) an infinite number of these. The beta he mentions is an obvious one, but the cdf is the incomplete beta function, so you'd need something to evaluate that --- it's a standard function in many packages (including almost all decent stats packages) so I doubt that will be difficult. Note however that not all betas are unimodal (with mode not at the ends), so the family also encompasses cdfs that are not "s" shaped.
Here are pictures of three reasonably simple families:
There are many other choices and new ones can easily be constructed.
--
In response to the edit to the question:
Note that all three of the families I drew pictures of have a a simple way to obtain left-right shifts (i) for the triangular distribution, the parameter directly moves the curve left or right (i.e. controls the degree of asymmetry, $c=\frac12$ is the symmetric case); for the logitnormal the $\mu$ parameter controls the asymmetry; for the beta distribution, the sign of ${\alpha-\beta}$ (equivalently, the sign of $\frac{\alpha}{\alpha+\beta}-\frac12$) controls it.
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
|
What you're trying to use this for is not particularly clear to me so I can't say whether it makes sense to do but fulfilling all your criteria seems to be fairly trivial.
s-shaped curve
parametric
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
What you're trying to use this for is not particularly clear to me so I can't say whether it makes sense to do but fulfilling all your criteria seems to be fairly trivial.
s-shaped curve
parametric function
0 maps to 0, 1 maps to 1, strictly increasing
simple derivative
So why not just take any convenient specific family of continuous unimodal* distribution functions on [0,1] whose pdf is "simple"? That seems to fulfill every part of what you list there.
* (whose mode is bounded away from the endpoints)
s-shaped curve - guaranteed by unimodality (with mode not at endpoints)
parametric - by giving any specific family which has parameters
0 maps to 0, 1 maps to 1 strictly increasing - that's what distribution functions on [0,1] do; you just need the density to be >0 in (0,1)
simple derivative -- that's the pdf, so if the pdf is "simple" by whatever criterion suits you, you're done.
There are (as Alex R stated) an infinite number of these. The beta he mentions is an obvious one, but the cdf is the incomplete beta function, so you'd need something to evaluate that --- it's a standard function in many packages (including almost all decent stats packages) so I doubt that will be difficult. Note however that not all betas are unimodal (with mode not at the ends), so the family also encompasses cdfs that are not "s" shaped.
Here are pictures of three reasonably simple families:
There are many other choices and new ones can easily be constructed.
--
In response to the edit to the question:
Note that all three of the families I drew pictures of have a a simple way to obtain left-right shifts (i) for the triangular distribution, the parameter directly moves the curve left or right (i.e. controls the degree of asymmetry, $c=\frac12$ is the symmetric case); for the logitnormal the $\mu$ parameter controls the asymmetry; for the beta distribution, the sign of ${\alpha-\beta}$ (equivalently, the sign of $\frac{\alpha}{\alpha+\beta}-\frac12$) controls it.
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
What you're trying to use this for is not particularly clear to me so I can't say whether it makes sense to do but fulfilling all your criteria seems to be fairly trivial.
s-shaped curve
parametric
|
12,479
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
|
As already commented by @whuber the function $ f(x)=x $ satisfies the three requirements you mentioned (i.e. 0 maps to 0, 1 maps to 1 and the function is strictly increasing). In the title of your question, you seem to indicate that you are also interested in the function being S-shaped, as in Sigmoid/Logistic curve. Is this correct? In that case, you should certainly try the following logistic function which will approximately meet all 4 criteria you specified: $$\frac{1}{1+e^{-k(x-0.5)}}$$.
The $k$ in this equation will control the slope of your curve. Changing $k$ will also allow you to control how close $f(0)$ and $f(1)$ are to 0 and 1, respectively. For example for $k=20$, $f(0)=4.539787e-05$ and $f(1)=0.9999546$.
The derivative of this function is easily computed as:$$\frac{ke^{-k(x-0.5)}}{(1+e^{-k(x-0.5)})^2}$$
Further information on this function can be found at https://en.wikipedia.org/wiki/Logistic_function
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
|
As already commented by @whuber the function $ f(x)=x $ satisfies the three requirements you mentioned (i.e. 0 maps to 0, 1 maps to 1 and the function is strictly increasing). In the title of your qu
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
As already commented by @whuber the function $ f(x)=x $ satisfies the three requirements you mentioned (i.e. 0 maps to 0, 1 maps to 1 and the function is strictly increasing). In the title of your question, you seem to indicate that you are also interested in the function being S-shaped, as in Sigmoid/Logistic curve. Is this correct? In that case, you should certainly try the following logistic function which will approximately meet all 4 criteria you specified: $$\frac{1}{1+e^{-k(x-0.5)}}$$.
The $k$ in this equation will control the slope of your curve. Changing $k$ will also allow you to control how close $f(0)$ and $f(1)$ are to 0 and 1, respectively. For example for $k=20$, $f(0)=4.539787e-05$ and $f(1)=0.9999546$.
The derivative of this function is easily computed as:$$\frac{ke^{-k(x-0.5)}}{(1+e^{-k(x-0.5)})^2}$$
Further information on this function can be found at https://en.wikipedia.org/wiki/Logistic_function
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
As already commented by @whuber the function $ f(x)=x $ satisfies the three requirements you mentioned (i.e. 0 maps to 0, 1 maps to 1 and the function is strictly increasing). In the title of your qu
|
12,480
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
|
Let me offer the most general solution consistent with the requirements: that will give you the most flexibility to choose and optimize.
We may interpret "S-shaped" as a monotonically increasing curve (because the transformation ought to be one-to-one) consisting of one part that is concave upwards and another part that is concave downwards. We may focus on making the left half concave down, because the other type (with left half concave up) is obtained through inverting such transformations.
Since the transformation $f$ is supposed to be differentiable, it must therefore have a decreasing derivative $f^\prime$ in the left half and an increasing derivative in the right half. Regardless, the derivative must be nonnegative and can be zero only at an isolated point (if at all: the minimum value of the derivative gives the least slope of the transformation.)
It is not required that the derivative be differentiable, but as a practical matter we may suppose that it is differentiable almost everywhere with derivative $f^{\prime\prime}$.
This second derivative can do practically anything: all we require is that
it is integrable,
is less than or equal to zero for all values in some left-hand interval $[0, k)$, and
is greater than or equal to zero for all values in the right hand interval $(k, 1]$.
Such functions $f^{\prime\prime}$ (and their inverses) parameterize the set of all solutions. (There is some redundancy: it is taken care of by a final normalization step described below.)
The Fundamental Theorem of Calculus enables us to recover $f$ from any such specification. That is,
$$f^\prime(x) = \int_0^x f^{\prime\prime}(t) dt$$
and
$$f(x) = \int_0^x f^\prime(t) dt.$$
The conditions on $f^{\prime\prime}$ guarantee that $f$ rises monotonically from its minimim $f(0)$ to some maximum $f(1) = C$. Finally, normalize $f$ by dividing the values of the preceding integral by $C$.
Here is an illustration starting with a version of a random walk for the second derivative. In it, the derivatives have not been normalized, but the transformation $f$ has been.
To apply this approach, you may begin with an analytic expression for $f^{\prime\prime}$, perhaps varied by a finite number of parameters. You may also specify it by giving some points along its graph and interpolating among them--provided that the interpolator respects the negativity of the values on $[0,k)$ and the positivity on $(k,1]$. The latter is the method used to generate the illustration. The corresponding R code (below) provides the details of the calculation.
This approach enables you to design any transformation you like. You could begin by sketching the S-curve, estimating its (relative) slopes $f^\prime$, and from that estimating its slopes. Specify some $f^{\prime\prime}$ to match that latter picture, then proceed to compute $f^\prime$ and then $f$.
Note that $f$ that are first concave up and then concave down can also be obtained by negating $f^{\prime\prime}$ at the outset. The critical condition for creating an S-shaped curve is that (apart from possible excursions on a set of measure zero) $f^{\prime\prime}$ may actually cross zero at most once.
Incidentally, the solution $f(x)=x$ arises by setting $f^{\prime\prime}(x)=0$ almost everywhere, making $f^\prime$ constant and positive, whence $f$ is linear; normalization assures the slope is $1$ and the intercept is $0$. (Making $f^\prime$ constant and negative produces the solution $f(x)=1-x$.)
n <- 51 # Number of interpolation points
k.1 <- floor(n * 2/3) # Width of the left-hand interval
k.2 <- n - k.1 # ............ right-hand interval
x <- seq(0, 1, length.out=n) # x coordinates
set.seed(17)
# Generate random values of the second derivative that are first negative,
# then positive. Modify to suit.
y.2 <- (c(runif(k.1, -1, 0), 0.5*runif(k.2, 0, 1))) *
abs(cos(3*pi * x)) +
c(rep(-.1, k.1), rep(.5,k.2))
# Recover the first derivative and then the transformation.
# Control the
# minimum slope of the transformation.
y.1 <- cumsum(y.2)
y.1 <- y.1 - min(y.1) + 0.005 * diff(range(y.1))
y <- cumsum(y.1)
y <- (y - y[1]) / (y[n] - y[1]) # Normalize the
# transformation
#
# Plot the graphs.
par(mfrow=c(1,3))
plot(x, y.2, type="l", bty="n", main="Second derivative")
points(x, y.2, pch=20, cex=0.5)
abline(h=0, col="Red", lty=3)
plot(x, y.1, type="l", bty="n", lwd=2, main="First
derivative")
abline(h=0, col="Red", lty=3)
plot(x, y, type="l", lwd=2, main="Transformation")
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
|
Let me offer the most general solution consistent with the requirements: that will give you the most flexibility to choose and optimize.
We may interpret "S-shaped" as a monotonically increasing curve
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
Let me offer the most general solution consistent with the requirements: that will give you the most flexibility to choose and optimize.
We may interpret "S-shaped" as a monotonically increasing curve (because the transformation ought to be one-to-one) consisting of one part that is concave upwards and another part that is concave downwards. We may focus on making the left half concave down, because the other type (with left half concave up) is obtained through inverting such transformations.
Since the transformation $f$ is supposed to be differentiable, it must therefore have a decreasing derivative $f^\prime$ in the left half and an increasing derivative in the right half. Regardless, the derivative must be nonnegative and can be zero only at an isolated point (if at all: the minimum value of the derivative gives the least slope of the transformation.)
It is not required that the derivative be differentiable, but as a practical matter we may suppose that it is differentiable almost everywhere with derivative $f^{\prime\prime}$.
This second derivative can do practically anything: all we require is that
it is integrable,
is less than or equal to zero for all values in some left-hand interval $[0, k)$, and
is greater than or equal to zero for all values in the right hand interval $(k, 1]$.
Such functions $f^{\prime\prime}$ (and their inverses) parameterize the set of all solutions. (There is some redundancy: it is taken care of by a final normalization step described below.)
The Fundamental Theorem of Calculus enables us to recover $f$ from any such specification. That is,
$$f^\prime(x) = \int_0^x f^{\prime\prime}(t) dt$$
and
$$f(x) = \int_0^x f^\prime(t) dt.$$
The conditions on $f^{\prime\prime}$ guarantee that $f$ rises monotonically from its minimim $f(0)$ to some maximum $f(1) = C$. Finally, normalize $f$ by dividing the values of the preceding integral by $C$.
Here is an illustration starting with a version of a random walk for the second derivative. In it, the derivatives have not been normalized, but the transformation $f$ has been.
To apply this approach, you may begin with an analytic expression for $f^{\prime\prime}$, perhaps varied by a finite number of parameters. You may also specify it by giving some points along its graph and interpolating among them--provided that the interpolator respects the negativity of the values on $[0,k)$ and the positivity on $(k,1]$. The latter is the method used to generate the illustration. The corresponding R code (below) provides the details of the calculation.
This approach enables you to design any transformation you like. You could begin by sketching the S-curve, estimating its (relative) slopes $f^\prime$, and from that estimating its slopes. Specify some $f^{\prime\prime}$ to match that latter picture, then proceed to compute $f^\prime$ and then $f$.
Note that $f$ that are first concave up and then concave down can also be obtained by negating $f^{\prime\prime}$ at the outset. The critical condition for creating an S-shaped curve is that (apart from possible excursions on a set of measure zero) $f^{\prime\prime}$ may actually cross zero at most once.
Incidentally, the solution $f(x)=x$ arises by setting $f^{\prime\prime}(x)=0$ almost everywhere, making $f^\prime$ constant and positive, whence $f$ is linear; normalization assures the slope is $1$ and the intercept is $0$. (Making $f^\prime$ constant and negative produces the solution $f(x)=1-x$.)
n <- 51 # Number of interpolation points
k.1 <- floor(n * 2/3) # Width of the left-hand interval
k.2 <- n - k.1 # ............ right-hand interval
x <- seq(0, 1, length.out=n) # x coordinates
set.seed(17)
# Generate random values of the second derivative that are first negative,
# then positive. Modify to suit.
y.2 <- (c(runif(k.1, -1, 0), 0.5*runif(k.2, 0, 1))) *
abs(cos(3*pi * x)) +
c(rep(-.1, k.1), rep(.5,k.2))
# Recover the first derivative and then the transformation.
# Control the
# minimum slope of the transformation.
y.1 <- cumsum(y.2)
y.1 <- y.1 - min(y.1) + 0.005 * diff(range(y.1))
y <- cumsum(y.1)
y <- (y - y[1]) / (y[n] - y[1]) # Normalize the
# transformation
#
# Plot the graphs.
par(mfrow=c(1,3))
plot(x, y.2, type="l", bty="n", main="Second derivative")
points(x, y.2, pch=20, cex=0.5)
abline(h=0, col="Red", lty=3)
plot(x, y.1, type="l", bty="n", lwd=2, main="First
derivative")
abline(h=0, col="Red", lty=3)
plot(x, y, type="l", lwd=2, main="Transformation")
|
Is there a formula for an s-shaped curve with domain and range [0,1]?
Let me offer the most general solution consistent with the requirements: that will give you the most flexibility to choose and optimize.
We may interpret "S-shaped" as a monotonically increasing curve
|
12,481
|
What does " Y axis" mean in continuous probability distribution?
|
There are two common ways to represent a probability distribution, the probability density function (PDF) and cumulative distribution function (CDF). I suspect you're wondering most about the former. For the latter, the distribution is plotted as cumulative from zero to one, so the y-axis is the sum of the distribution up to a given value of x.
For a probability density function, there's a big hint in the name: it's a density. You're right, though, that we don't often think of this Y-axis as all that important. PDFs are plotted all the time without any labeled Y-axis. But if you were to label it, you would read it as a density: the sum probability of some unit range in X. You can consider the range in some infinitely narrow range of X, but that infinitely narrow range still has units in X to give a density.
|
What does " Y axis" mean in continuous probability distribution?
|
There are two common ways to represent a probability distribution, the probability density function (PDF) and cumulative distribution function (CDF). I suspect you're wondering most about the former.
|
What does " Y axis" mean in continuous probability distribution?
There are two common ways to represent a probability distribution, the probability density function (PDF) and cumulative distribution function (CDF). I suspect you're wondering most about the former. For the latter, the distribution is plotted as cumulative from zero to one, so the y-axis is the sum of the distribution up to a given value of x.
For a probability density function, there's a big hint in the name: it's a density. You're right, though, that we don't often think of this Y-axis as all that important. PDFs are plotted all the time without any labeled Y-axis. But if you were to label it, you would read it as a density: the sum probability of some unit range in X. You can consider the range in some infinitely narrow range of X, but that infinitely narrow range still has units in X to give a density.
|
What does " Y axis" mean in continuous probability distribution?
There are two common ways to represent a probability distribution, the probability density function (PDF) and cumulative distribution function (CDF). I suspect you're wondering most about the former.
|
12,482
|
What does " Y axis" mean in continuous probability distribution?
|
I suppose you have a moderately large or large random sample from a continuous distribution, and that you want to make a plot of the data
that suggests the shape of the population distribution.
Then a starting point would be to make a 'density' histogram in which the total area of all bars adds to unity $(1).$ [Similarly, the total area beneath a density curve is unity.]
Here is a sample of size $n = 1000$ from the slightly right-skewed gamma
distribution, $\mathsf{Gamma}(\mathrm{shape}=5,\mathrm{rate}=0.1),$
which has $\mu = 50, \sigma^2 = 500, \sigma= 22.36,$ as simulated in R.
set.seed(2020)
x = rgamma(1000, 5, 0.1)
summary(x); sd(x)
Min. 1st Qu. Median Mean 3rd Qu. Max.
6.637 33.938 46.370 49.928 61.942 163.680
[1] 22.61689 # sample SD
hist(x, prob=T, br=20, col="skyblue2")
lines(density(x), lwd=2, col="orange")
curve(dgamma(x, 5, .1), add=T, lwd=2, lty="dotted")
In the figure, the dotted black curve is the density curve (PDF)
of $\mathsf{Gamma}(5, 0.1),$ the histogram bars are plotted on a
density scale, and the orange curve is the default 'kernel density
estimator' (KDE) in R. For a sample of size as large as $n=1000$ it
is not surprising that the histogram is a reasonably good fit to
the population PDF or that the KDE is very nearly the same as the PDF.
By contrast, if I look at only the first 100 of the $n=1000$ observations
above, the histogram and the KDE still approximate the PDF, but not quite
as well. Individual tick marks show the exact positions of the 100 points.
set.seed(2020)
x = rgamma(100, 5, 0.1)
summary(x); sd(x)
Min. 1st Qu. Median Mean 3rd Qu. Max.
15.92 33.50 47.82 51.76 61.39 163.68
[1] 27.4087
hist(x, prob=T, ylim=c(0,.02), col="skyblue2")
rug(x)
lines(density(x), lwd=2, col="orange")
curve(dgamma(x, 5, .1), add=T, lwd=2, lty="dotted")
Note: For small samples, it is feasible to sort the data into appropriate intervals and draw the corresponding histogram by hand, but making a useful KDE is probably best left to software.
|
What does " Y axis" mean in continuous probability distribution?
|
I suppose you have a moderately large or large random sample from a continuous distribution, and that you want to make a plot of the data
that suggests the shape of the population distribution.
Then a
|
What does " Y axis" mean in continuous probability distribution?
I suppose you have a moderately large or large random sample from a continuous distribution, and that you want to make a plot of the data
that suggests the shape of the population distribution.
Then a starting point would be to make a 'density' histogram in which the total area of all bars adds to unity $(1).$ [Similarly, the total area beneath a density curve is unity.]
Here is a sample of size $n = 1000$ from the slightly right-skewed gamma
distribution, $\mathsf{Gamma}(\mathrm{shape}=5,\mathrm{rate}=0.1),$
which has $\mu = 50, \sigma^2 = 500, \sigma= 22.36,$ as simulated in R.
set.seed(2020)
x = rgamma(1000, 5, 0.1)
summary(x); sd(x)
Min. 1st Qu. Median Mean 3rd Qu. Max.
6.637 33.938 46.370 49.928 61.942 163.680
[1] 22.61689 # sample SD
hist(x, prob=T, br=20, col="skyblue2")
lines(density(x), lwd=2, col="orange")
curve(dgamma(x, 5, .1), add=T, lwd=2, lty="dotted")
In the figure, the dotted black curve is the density curve (PDF)
of $\mathsf{Gamma}(5, 0.1),$ the histogram bars are plotted on a
density scale, and the orange curve is the default 'kernel density
estimator' (KDE) in R. For a sample of size as large as $n=1000$ it
is not surprising that the histogram is a reasonably good fit to
the population PDF or that the KDE is very nearly the same as the PDF.
By contrast, if I look at only the first 100 of the $n=1000$ observations
above, the histogram and the KDE still approximate the PDF, but not quite
as well. Individual tick marks show the exact positions of the 100 points.
set.seed(2020)
x = rgamma(100, 5, 0.1)
summary(x); sd(x)
Min. 1st Qu. Median Mean 3rd Qu. Max.
15.92 33.50 47.82 51.76 61.39 163.68
[1] 27.4087
hist(x, prob=T, ylim=c(0,.02), col="skyblue2")
rug(x)
lines(density(x), lwd=2, col="orange")
curve(dgamma(x, 5, .1), add=T, lwd=2, lty="dotted")
Note: For small samples, it is feasible to sort the data into appropriate intervals and draw the corresponding histogram by hand, but making a useful KDE is probably best left to software.
|
What does " Y axis" mean in continuous probability distribution?
I suppose you have a moderately large or large random sample from a continuous distribution, and that you want to make a plot of the data
that suggests the shape of the population distribution.
Then a
|
12,483
|
What does " Y axis" mean in continuous probability distribution?
|
Probability density is a density, and may be understood as such.
Although this way of thinking is touched on in other answers, and at greater length in other threads, I find it helpful when trying to teach the topic, and to build on what people should already know about density generally and indeed long since.
Thus in (high school?) physics or other subjects, people should have met density meaning mass per unit volume. In ecology, epidemiology, demography, geography and many social sciences, population density is number of people (or organisms) per unit area. The same idea is easily applied to counting facilities in an area $-$ or along a route, say the number of Starbucks along a road inside a city.
Density has a reciprocal, which is often as interesting or useful. The reciprocal of population density is area per person or organism. The reciprocal of density along a line is the typical distance between objects, both being captured in statements such as there being one Starbucks on average every 200 m.
I can think of another example that is perhaps esoteric, but you should have no difficulty grasping it: drainage density is total length of streams in a region (often, but not necessarily, a basin, catchment or watershed) divided by the area of that region. (Small print: measuring the length of a wiggly line is far from obvious.)
With a little abstraction we can identify the family resemblance as how much stuff there is in a given space.
Time to focus on a concrete example:
This is close to default as a common-or-garden histogram in my usual statistical environment. It shows a variable, miles per gallon for a bundle of cars, on the horizontal or $x$ axis and has a (probability) density scale on the vertical or $y$ axis.
Now comes the numerical crunch in three parts:
The total probability is 1 and is given by the total area of the bars.
The range of the variable on the $x$ axis is about 40 (miles per gallon). Rough mental calculations are fine here.
So for that to happen the average height of the bars must be about 1/40, because we can think of an implied rectangle with area given by
average height of bars $\times$ range on $x$ axis $\equiv$ 1.
So, the average height of bars should be about 0.025, which checks out when we look at the graph. (There may be a little arm-waving at this point, but usually the listener can see that the number has the right order of magnitude.)
The units (of measurement) of probability density follow from the fact that probability has no units, so
units of probability density $\quad \equiv \quad$ 1 / units on $x$ axis
Here the units are simple, gallons per mile, but that is often not so.
Clearly, the story gets more complicated, but not different in principle, if talking about the bivariate or multivariate density of two or more variables considered together.
What doesn't help here is (so far as I can see) an almost universal habit of never specifying units of measurement on a probability density axis. There seem to be three reasons for that:
They would often just look odd. Thus hydrologists and many others get used to think of river discharge in cubic metres per second (so $\text{m}^3 \text{s}^{-1}$), but they might blench at being told that probability density for discharge has units $\text{m}^{-3} \text{s}$. (Using non-metric rather than metric units doesn't help.)
The units for probability density are just implicit as the reciprocal of the units on the $x$ axis.
Nobody else does it, so why should we?
David Finney (1917$-$2018) wrote a splendid article on dimensions in statistics. You may have access to https://www.jstor.org/stable/2346969
I've also found even that people whose other education was strong in mathematics or physical science don't automatically think about what they are doing in statistics in terms of dimensions and units of measurement (even though the point does arise, e.g. in explaining why the standard deviation can be easier to think about than the variance). In particular, frequent puzzlement that a density exceeds 1 somewhere is eased by underlining that probability density usually has quite different units from probability itself.
|
What does " Y axis" mean in continuous probability distribution?
|
Probability density is a density, and may be understood as such.
Although this way of thinking is touched on in other answers, and at greater length in other threads, I find it helpful when trying to
|
What does " Y axis" mean in continuous probability distribution?
Probability density is a density, and may be understood as such.
Although this way of thinking is touched on in other answers, and at greater length in other threads, I find it helpful when trying to teach the topic, and to build on what people should already know about density generally and indeed long since.
Thus in (high school?) physics or other subjects, people should have met density meaning mass per unit volume. In ecology, epidemiology, demography, geography and many social sciences, population density is number of people (or organisms) per unit area. The same idea is easily applied to counting facilities in an area $-$ or along a route, say the number of Starbucks along a road inside a city.
Density has a reciprocal, which is often as interesting or useful. The reciprocal of population density is area per person or organism. The reciprocal of density along a line is the typical distance between objects, both being captured in statements such as there being one Starbucks on average every 200 m.
I can think of another example that is perhaps esoteric, but you should have no difficulty grasping it: drainage density is total length of streams in a region (often, but not necessarily, a basin, catchment or watershed) divided by the area of that region. (Small print: measuring the length of a wiggly line is far from obvious.)
With a little abstraction we can identify the family resemblance as how much stuff there is in a given space.
Time to focus on a concrete example:
This is close to default as a common-or-garden histogram in my usual statistical environment. It shows a variable, miles per gallon for a bundle of cars, on the horizontal or $x$ axis and has a (probability) density scale on the vertical or $y$ axis.
Now comes the numerical crunch in three parts:
The total probability is 1 and is given by the total area of the bars.
The range of the variable on the $x$ axis is about 40 (miles per gallon). Rough mental calculations are fine here.
So for that to happen the average height of the bars must be about 1/40, because we can think of an implied rectangle with area given by
average height of bars $\times$ range on $x$ axis $\equiv$ 1.
So, the average height of bars should be about 0.025, which checks out when we look at the graph. (There may be a little arm-waving at this point, but usually the listener can see that the number has the right order of magnitude.)
The units (of measurement) of probability density follow from the fact that probability has no units, so
units of probability density $\quad \equiv \quad$ 1 / units on $x$ axis
Here the units are simple, gallons per mile, but that is often not so.
Clearly, the story gets more complicated, but not different in principle, if talking about the bivariate or multivariate density of two or more variables considered together.
What doesn't help here is (so far as I can see) an almost universal habit of never specifying units of measurement on a probability density axis. There seem to be three reasons for that:
They would often just look odd. Thus hydrologists and many others get used to think of river discharge in cubic metres per second (so $\text{m}^3 \text{s}^{-1}$), but they might blench at being told that probability density for discharge has units $\text{m}^{-3} \text{s}$. (Using non-metric rather than metric units doesn't help.)
The units for probability density are just implicit as the reciprocal of the units on the $x$ axis.
Nobody else does it, so why should we?
David Finney (1917$-$2018) wrote a splendid article on dimensions in statistics. You may have access to https://www.jstor.org/stable/2346969
I've also found even that people whose other education was strong in mathematics or physical science don't automatically think about what they are doing in statistics in terms of dimensions and units of measurement (even though the point does arise, e.g. in explaining why the standard deviation can be easier to think about than the variance). In particular, frequent puzzlement that a density exceeds 1 somewhere is eased by underlining that probability density usually has quite different units from probability itself.
|
What does " Y axis" mean in continuous probability distribution?
Probability density is a density, and may be understood as such.
Although this way of thinking is touched on in other answers, and at greater length in other threads, I find it helpful when trying to
|
12,484
|
What does " Y axis" mean in continuous probability distribution?
|
Just to make it clear with an equation, the probability density function (PDF) $f_X(x)$ of a random variable $X$ is defined as:
$$ dP_X(x) \equiv f_X(x) dx,$$
where $dP_X(x)$ is the infinitesimal probability that the random variable $X$ takes the value $x$ and $dx$ is a differential of the random variable $X$. In other words, the value of the PDF $f_X(x)$ multiplied by $dx$, which is the infinitesimal area under the curve of your plot at $X = x$, is equal to the infinitesimal probability $dP_X(x)$ that the random variable takes the value $X = x$.
You can extend this idea taking $X$ in some range: $a \leq X \leq b$, then the probability to find the random variable $X$ in this interval is:
$$ P_X(a \leq X \leq b) = \int_{a}^b f_X(x) dx,$$
i.e., the area under the curve $f_X(x)$ from $x = a$ to $x = b$.
Basically, we can understand the PDF like an intensive expression or a density of the probability: it gives the probability per unit of the random variable. For example, it is analogous to the concept of mass density in physics, which is defined as mass per unit volume. In order to find the mass, we need to multiply the density by a volume. Here, in order to find the probability we need to multiply the PDF by a range of the random variable.
|
What does " Y axis" mean in continuous probability distribution?
|
Just to make it clear with an equation, the probability density function (PDF) $f_X(x)$ of a random variable $X$ is defined as:
$$ dP_X(x) \equiv f_X(x) dx,$$
where $dP_X(x)$ is the infinitesimal prob
|
What does " Y axis" mean in continuous probability distribution?
Just to make it clear with an equation, the probability density function (PDF) $f_X(x)$ of a random variable $X$ is defined as:
$$ dP_X(x) \equiv f_X(x) dx,$$
where $dP_X(x)$ is the infinitesimal probability that the random variable $X$ takes the value $x$ and $dx$ is a differential of the random variable $X$. In other words, the value of the PDF $f_X(x)$ multiplied by $dx$, which is the infinitesimal area under the curve of your plot at $X = x$, is equal to the infinitesimal probability $dP_X(x)$ that the random variable takes the value $X = x$.
You can extend this idea taking $X$ in some range: $a \leq X \leq b$, then the probability to find the random variable $X$ in this interval is:
$$ P_X(a \leq X \leq b) = \int_{a}^b f_X(x) dx,$$
i.e., the area under the curve $f_X(x)$ from $x = a$ to $x = b$.
Basically, we can understand the PDF like an intensive expression or a density of the probability: it gives the probability per unit of the random variable. For example, it is analogous to the concept of mass density in physics, which is defined as mass per unit volume. In order to find the mass, we need to multiply the density by a volume. Here, in order to find the probability we need to multiply the PDF by a range of the random variable.
|
What does " Y axis" mean in continuous probability distribution?
Just to make it clear with an equation, the probability density function (PDF) $f_X(x)$ of a random variable $X$ is defined as:
$$ dP_X(x) \equiv f_X(x) dx,$$
where $dP_X(x)$ is the infinitesimal prob
|
12,485
|
What does " Y axis" mean in continuous probability distribution?
|
PDF is the derivative of CDF, i.e., the rate of CDF's change, just like speed is the derivative of moving distance. When you are driving a car, at any particular time moment the passing distance is zero, but the speed (i.e. the rate of the distance's change) is not zero. Do you think that speed is a meaningful measure ?
|
What does " Y axis" mean in continuous probability distribution?
|
PDF is the derivative of CDF, i.e., the rate of CDF's change, just like speed is the derivative of moving distance. When you are driving a car, at any particular time moment the passing distance is ze
|
What does " Y axis" mean in continuous probability distribution?
PDF is the derivative of CDF, i.e., the rate of CDF's change, just like speed is the derivative of moving distance. When you are driving a car, at any particular time moment the passing distance is zero, but the speed (i.e. the rate of the distance's change) is not zero. Do you think that speed is a meaningful measure ?
|
What does " Y axis" mean in continuous probability distribution?
PDF is the derivative of CDF, i.e., the rate of CDF's change, just like speed is the derivative of moving distance. When you are driving a car, at any particular time moment the passing distance is ze
|
12,486
|
PCA and k-fold cross-validation in caret package in R
|
I didn't see the lecture, so I can't comment on what was said.
My $0.02: If you want to get good estimates of performance using resampling, you should really do all of the operations during resampling instead of prior. This is really true of feature selection [1] as well as non-trivial operations like PCA. If it adds uncertainty to the results, include it in resampling.
Think about principal component regression: PCA followed by linear regression on some of the components. PCA estimates parameters (with noise) and the number of components must also be chosen (different values will result in different results => more noise).
Say we used 10 fold CV with scheme 1:
conduct PCA
pick the number of components
for each fold:
split data
fit linear regression on the 90% used for training
predict the 10% held out
end:
or scheme 2:
for each fold:
split data
conduct PCA on the 90% used for training
pick the number of components
fit linear regression
predict the 10% held out
end:
It should be clear than the second approach should produce error estimates that reflect the uncertainty caused by PCA, selection of the number of components and the linear regression. In effect, the CV in the first scheme has no idea what preceded it.
I'm guilty of not always doing all the operations w/in resampling, but only when I don't really care about performance estimates (which is unusual).
Is there much difference between the two schemes? It depends on the data and the pre-processing. If you are only centering and scaling, probably not. If you have a ton of data, probably not. As the training set size goes down, the risk of getting poor estimates goes up, especially if n is close to p.
I can say with certainty from experience that not including supervised feature selection within resampling is a really bad idea (without large training sets). I don't see why pre-processing would be immune to this (to some degree).
@mchangun: I think that the number of components is a tuning parameter and you would probably want to pick it using performance estimates that are generalizable. You could automatically pick K such that at least X% of the variance is explained and include that process within resampling so we account for the noise in that process.
Max
[1] Ambroise, C., & McLachlan, G. (2002). Selection bias in gene extraction on the basis of microarray gene-expression data. Proceedings of the National Academy of Sciences, 99(10), 6562–6566.
|
PCA and k-fold cross-validation in caret package in R
|
I didn't see the lecture, so I can't comment on what was said.
My $0.02: If you want to get good estimates of performance using resampling, you should really do all of the operations during resamplin
|
PCA and k-fold cross-validation in caret package in R
I didn't see the lecture, so I can't comment on what was said.
My $0.02: If you want to get good estimates of performance using resampling, you should really do all of the operations during resampling instead of prior. This is really true of feature selection [1] as well as non-trivial operations like PCA. If it adds uncertainty to the results, include it in resampling.
Think about principal component regression: PCA followed by linear regression on some of the components. PCA estimates parameters (with noise) and the number of components must also be chosen (different values will result in different results => more noise).
Say we used 10 fold CV with scheme 1:
conduct PCA
pick the number of components
for each fold:
split data
fit linear regression on the 90% used for training
predict the 10% held out
end:
or scheme 2:
for each fold:
split data
conduct PCA on the 90% used for training
pick the number of components
fit linear regression
predict the 10% held out
end:
It should be clear than the second approach should produce error estimates that reflect the uncertainty caused by PCA, selection of the number of components and the linear regression. In effect, the CV in the first scheme has no idea what preceded it.
I'm guilty of not always doing all the operations w/in resampling, but only when I don't really care about performance estimates (which is unusual).
Is there much difference between the two schemes? It depends on the data and the pre-processing. If you are only centering and scaling, probably not. If you have a ton of data, probably not. As the training set size goes down, the risk of getting poor estimates goes up, especially if n is close to p.
I can say with certainty from experience that not including supervised feature selection within resampling is a really bad idea (without large training sets). I don't see why pre-processing would be immune to this (to some degree).
@mchangun: I think that the number of components is a tuning parameter and you would probably want to pick it using performance estimates that are generalizable. You could automatically pick K such that at least X% of the variance is explained and include that process within resampling so we account for the noise in that process.
Max
[1] Ambroise, C., & McLachlan, G. (2002). Selection bias in gene extraction on the basis of microarray gene-expression data. Proceedings of the National Academy of Sciences, 99(10), 6562–6566.
|
PCA and k-fold cross-validation in caret package in R
I didn't see the lecture, so I can't comment on what was said.
My $0.02: If you want to get good estimates of performance using resampling, you should really do all of the operations during resamplin
|
12,487
|
PCA and k-fold cross-validation in caret package in R
|
Don't preProcess the data prior to running the train function! Use the preProcess argument for the train function, and the pre-processing will be applied to each re-sampling iteration.
e.g. don't do this:
library(caret)
dat <- iris
pp <- preProcess(dat[,-5], method="pca")
dat[,-5] <- predict(pp, dat[,-5])
knnFit1 <- train(Species~., dat, method = "knn", preProcess=c("pca"),
trControl = trainControl(method = "cv"))
do this!
dat <- iris
knnFit2 <- train(Species~., dat, method = "knn", preProcess=c("pca"),
trControl = trainControl(method = "cv"))
|
PCA and k-fold cross-validation in caret package in R
|
Don't preProcess the data prior to running the train function! Use the preProcess argument for the train function, and the pre-processing will be applied to each re-sampling iteration.
e.g. don't do
|
PCA and k-fold cross-validation in caret package in R
Don't preProcess the data prior to running the train function! Use the preProcess argument for the train function, and the pre-processing will be applied to each re-sampling iteration.
e.g. don't do this:
library(caret)
dat <- iris
pp <- preProcess(dat[,-5], method="pca")
dat[,-5] <- predict(pp, dat[,-5])
knnFit1 <- train(Species~., dat, method = "knn", preProcess=c("pca"),
trControl = trainControl(method = "cv"))
do this!
dat <- iris
knnFit2 <- train(Species~., dat, method = "knn", preProcess=c("pca"),
trControl = trainControl(method = "cv"))
|
PCA and k-fold cross-validation in caret package in R
Don't preProcess the data prior to running the train function! Use the preProcess argument for the train function, and the pre-processing will be applied to each re-sampling iteration.
e.g. don't do
|
12,488
|
Does random forest need input variables to be scaled or centered?
|
No.
Random Forests are based on tree partitioning algorithms.
As such, there's no analogue to a coefficient one obtain in general regression strategies, which would depend on the units of the independent variables. Instead, one obtain a collection of partition rules, basically a decision given a threshold, and this shouldn't change with scaling. In other words, the trees only see ranks in the features.
Basically, any monotonic transformation of your data shouldn't change the forest at all (in the most common implementations).
Also, decision trees are usually robust to numerical instabilities that sometimes impair convergence and precision in other algorithms.
|
Does random forest need input variables to be scaled or centered?
|
No.
Random Forests are based on tree partitioning algorithms.
As such, there's no analogue to a coefficient one obtain in general regression strategies, which would depend on the units of the independ
|
Does random forest need input variables to be scaled or centered?
No.
Random Forests are based on tree partitioning algorithms.
As such, there's no analogue to a coefficient one obtain in general regression strategies, which would depend on the units of the independent variables. Instead, one obtain a collection of partition rules, basically a decision given a threshold, and this shouldn't change with scaling. In other words, the trees only see ranks in the features.
Basically, any monotonic transformation of your data shouldn't change the forest at all (in the most common implementations).
Also, decision trees are usually robust to numerical instabilities that sometimes impair convergence and precision in other algorithms.
|
Does random forest need input variables to be scaled or centered?
No.
Random Forests are based on tree partitioning algorithms.
As such, there's no analogue to a coefficient one obtain in general regression strategies, which would depend on the units of the independ
|
12,489
|
Does random forest need input variables to be scaled or centered?
|
Overall I agree with Firebug, but there could be some value in standardizing your variables if you're interested in predictor importance scores. RF will tend to favour highly variable continuous predictors because there are more opportunities to partition the data. A better way to deal with this issue, however, is to use particular approaches (ie sampling without replacement using conditional forests) that are more robust to this bias. See https://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-8-25
|
Does random forest need input variables to be scaled or centered?
|
Overall I agree with Firebug, but there could be some value in standardizing your variables if you're interested in predictor importance scores. RF will tend to favour highly variable continuous predi
|
Does random forest need input variables to be scaled or centered?
Overall I agree with Firebug, but there could be some value in standardizing your variables if you're interested in predictor importance scores. RF will tend to favour highly variable continuous predictors because there are more opportunities to partition the data. A better way to deal with this issue, however, is to use particular approaches (ie sampling without replacement using conditional forests) that are more robust to this bias. See https://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-8-25
|
Does random forest need input variables to be scaled or centered?
Overall I agree with Firebug, but there could be some value in standardizing your variables if you're interested in predictor importance scores. RF will tend to favour highly variable continuous predi
|
12,490
|
Regression in $p>n$ setting: how to choose regularization method (Lasso, PLS, PCR, ridge)?
|
I think there is no single answer to your question - it depends upon many situation, data and what you are trying to do. Some of the modification can be or should be modified to achieve the goal. However the following general discussion can help.
Before jumping to into the more advanced methods let's discussion of basic model first: Least Squares (LS) regression. There are two reasons why a least squares estimate of the parameters in the full model is unsatisfying:
Prediction quality: Least squares estimates often have a small bias but a high variance. The prediction quality can sometimes be improved by shrinkage of the regression coefficients or by setting some coefficients equal to zero. This way the bias increases, but the variance of the prediction reduces significantly which leads to an overall improved prediction. This tradeoff between bias and variance can be easily seen by decomposing the mean squared error (MSE). A smaller MSE lead to a better prediction of new values.
Interpretability: If many predictor variables are available, it makes sense to identify the ones who have the largest influence, and to set the ones to zero that are not relevant for the prediction. Thus we eliminate variables that will only explain some details, but we keep those which allow for the major explanation of the response variable.
Thus variable selection methods come into the scene. With variable selection only a subset of all input variables is used, the rest is eliminated from the model. Best subset regression finds the subset of size $k$ for each $k \in \{0, 1, ... , p\}$ that gives the smallest RSS. An efficient algorithm is the so-called Leaps and Bounds algorithm which can handle up to $30$ or $40$ regressor variables. With data sets larger than $40$ input variables a search through all possible subsets becomes infeasible. Thus Forward stepwise selection and Backward stepwise selection are useful. Backward selection can only be used when $n > p$ in order to have a well defined model. The computation efficiency of these methods is questionable when $p$ is very high.
In many situations we have a large number of inputs (as yours), often highly correlated (as in your case). In case of highly correlated regressors, OLS leads to a numerically instable parameters, i.e. unreliable $\beta$ estimates. To avoid this problem, we use methods that use derived input directions. These methods produce a small number of linear combinations $z_k, k = 1, 2, ... , q$ of the original inputs $x_j$ which are then used as inputs in the regression.
The methods differ in how the linear combinations are constructed. Principal components regression (PCR) looks for transformations of the original data into a new set of uncorrelated variables called principal components.
Partial Least Squares (PLS) regression - this technique also constructs a set of linear combinations of the inputs for regression, but unlike principal components regression it uses $y$ in addition to $X$ for this construction. We assume that both $y$ and $X$ are centered. Instead of calculating the parameters $\beta$ in the linear model, we estimate the parameters $\gamma$ in the so-called latent variable mode. We assume the new coefficients $\gamma$ are of dimension $q \le p$. PLS does a regression on a weighted version of $X$ which contains incomplete or partial information. Since PLS uses also $y$ to determine the PLS-directions, this method is supposed to have better prediction performance than for instance PCR. In contrast to PCR, PLS is looking for directions with high variance and large correlation with $y$.
Shrinkage methods keep all variables in the model and assign different (continuous) weights. In this way we obtain a smoother procedure with a smaller variability. Ridge regression shrinks the coefficients by imposing a penalty on their size. The ridge coefficients minimize a penalized residual sum of squares. Here $\lambda \ge 0$ is a complexity parameter that controls the amount of shrinkage: the larger the value of $\lambda$, the greater the amount of shrinkage. The coefficients are shrunk towards zero (and towards each other).
By penalizing the RSS we try to avoid that highly correlated regressors cancel each other. An especially large positive coefficient $\beta$ can be canceled by a similarly large negative coefficient $\beta$. By imposing a size constraint on the coefficients this phenomenon can be prevented.
It can be shown that PCR is very similar to ridge regression: both methods use the principal components of the input matrix $X$. Ridge regression shrinks the coefficients of the principal components, the shrinkage depends on the corresponding eigenvalues; PCR completely discards the components to the smallest $p - q$ eigenvalues.
The lasso is a shrinkage method like ridge, but the L1 norm rather than the L2 norm is used in the constraints. L1-norm loss function is also known as least absolute deviations (LAD), least absolute errors (LAE). It is basically minimizing the sum of the absolute differences between the target value and the estimated values. L2-norm loss function is also known as least squares error (LSE). It is basically minimizing the sum of the square of the differences between the target value ($Y_i$) and the estimated values. The difference between the L1 and L2 is just that L2 is the sum of the square of the weights, while L1 is just the sum of the weights. L1-norm tends to produces sparse coefficients and has Built-in feature selection. L1-norm does not have an analytical solution, but L2-norm does. This allows the L2-norm solutions to be calculated computationally efficiently. L2-norm has unique solutions while L1-norm does not.
Lasso and ridge differ in their penalty term. The lasso solutions are nonlinear and a quadratic programming algorithm is used to compute them. Because of the nature of the constraint, making $s$ sufficiently small will cause some of the coefficients to be exactly $0$. Thus the lasso does a kind of continuous subset selection. Like the subset size in subset selection, or the penalty in ridge regression, $s$ should be adaptly chosen to minimize an estimate of expected prediction error.
When $p\gg N$ , high variance and over fitting are a major concern in this setting. As a result, simple, highly regularized approaches often become the methods of choice.
Principal components analysis is an effective method for finding linear combinations of features that exhibit large variation in a dataset. But what we seek here are linear combinations with both high variance and significant correlation with the outcome. Hence we want to encourage principal component analysis to find linear combinations of features that have high correlation with the outcome - supervised principal components (see page 678, Algorithm 18.1, in the book Elements of Statistical Learning).
Partial least squares down weights noisy features, but does not throw them away; as a result a large number of noisy features can contaminate the predictions. Thresholded PLS can be viewed as a noisy version of supervised principal components, and hence we might not expect it to work as well in practice. Supervised principal components can yield lower test errors than Threshold PLS. However, it does not always produce a sparse model involving only a small number of features.
The lasso on the other hand, produces a sparse model from the data. Ridge can always perform average. I think lasso is good choice when there are large number $p$. Supervised principal component can also work well.
|
Regression in $p>n$ setting: how to choose regularization method (Lasso, PLS, PCR, ridge)?
|
I think there is no single answer to your question - it depends upon many situation, data and what you are trying to do. Some of the modification can be or should be modified to achieve the goal. How
|
Regression in $p>n$ setting: how to choose regularization method (Lasso, PLS, PCR, ridge)?
I think there is no single answer to your question - it depends upon many situation, data and what you are trying to do. Some of the modification can be or should be modified to achieve the goal. However the following general discussion can help.
Before jumping to into the more advanced methods let's discussion of basic model first: Least Squares (LS) regression. There are two reasons why a least squares estimate of the parameters in the full model is unsatisfying:
Prediction quality: Least squares estimates often have a small bias but a high variance. The prediction quality can sometimes be improved by shrinkage of the regression coefficients or by setting some coefficients equal to zero. This way the bias increases, but the variance of the prediction reduces significantly which leads to an overall improved prediction. This tradeoff between bias and variance can be easily seen by decomposing the mean squared error (MSE). A smaller MSE lead to a better prediction of new values.
Interpretability: If many predictor variables are available, it makes sense to identify the ones who have the largest influence, and to set the ones to zero that are not relevant for the prediction. Thus we eliminate variables that will only explain some details, but we keep those which allow for the major explanation of the response variable.
Thus variable selection methods come into the scene. With variable selection only a subset of all input variables is used, the rest is eliminated from the model. Best subset regression finds the subset of size $k$ for each $k \in \{0, 1, ... , p\}$ that gives the smallest RSS. An efficient algorithm is the so-called Leaps and Bounds algorithm which can handle up to $30$ or $40$ regressor variables. With data sets larger than $40$ input variables a search through all possible subsets becomes infeasible. Thus Forward stepwise selection and Backward stepwise selection are useful. Backward selection can only be used when $n > p$ in order to have a well defined model. The computation efficiency of these methods is questionable when $p$ is very high.
In many situations we have a large number of inputs (as yours), often highly correlated (as in your case). In case of highly correlated regressors, OLS leads to a numerically instable parameters, i.e. unreliable $\beta$ estimates. To avoid this problem, we use methods that use derived input directions. These methods produce a small number of linear combinations $z_k, k = 1, 2, ... , q$ of the original inputs $x_j$ which are then used as inputs in the regression.
The methods differ in how the linear combinations are constructed. Principal components regression (PCR) looks for transformations of the original data into a new set of uncorrelated variables called principal components.
Partial Least Squares (PLS) regression - this technique also constructs a set of linear combinations of the inputs for regression, but unlike principal components regression it uses $y$ in addition to $X$ for this construction. We assume that both $y$ and $X$ are centered. Instead of calculating the parameters $\beta$ in the linear model, we estimate the parameters $\gamma$ in the so-called latent variable mode. We assume the new coefficients $\gamma$ are of dimension $q \le p$. PLS does a regression on a weighted version of $X$ which contains incomplete or partial information. Since PLS uses also $y$ to determine the PLS-directions, this method is supposed to have better prediction performance than for instance PCR. In contrast to PCR, PLS is looking for directions with high variance and large correlation with $y$.
Shrinkage methods keep all variables in the model and assign different (continuous) weights. In this way we obtain a smoother procedure with a smaller variability. Ridge regression shrinks the coefficients by imposing a penalty on their size. The ridge coefficients minimize a penalized residual sum of squares. Here $\lambda \ge 0$ is a complexity parameter that controls the amount of shrinkage: the larger the value of $\lambda$, the greater the amount of shrinkage. The coefficients are shrunk towards zero (and towards each other).
By penalizing the RSS we try to avoid that highly correlated regressors cancel each other. An especially large positive coefficient $\beta$ can be canceled by a similarly large negative coefficient $\beta$. By imposing a size constraint on the coefficients this phenomenon can be prevented.
It can be shown that PCR is very similar to ridge regression: both methods use the principal components of the input matrix $X$. Ridge regression shrinks the coefficients of the principal components, the shrinkage depends on the corresponding eigenvalues; PCR completely discards the components to the smallest $p - q$ eigenvalues.
The lasso is a shrinkage method like ridge, but the L1 norm rather than the L2 norm is used in the constraints. L1-norm loss function is also known as least absolute deviations (LAD), least absolute errors (LAE). It is basically minimizing the sum of the absolute differences between the target value and the estimated values. L2-norm loss function is also known as least squares error (LSE). It is basically minimizing the sum of the square of the differences between the target value ($Y_i$) and the estimated values. The difference between the L1 and L2 is just that L2 is the sum of the square of the weights, while L1 is just the sum of the weights. L1-norm tends to produces sparse coefficients and has Built-in feature selection. L1-norm does not have an analytical solution, but L2-norm does. This allows the L2-norm solutions to be calculated computationally efficiently. L2-norm has unique solutions while L1-norm does not.
Lasso and ridge differ in their penalty term. The lasso solutions are nonlinear and a quadratic programming algorithm is used to compute them. Because of the nature of the constraint, making $s$ sufficiently small will cause some of the coefficients to be exactly $0$. Thus the lasso does a kind of continuous subset selection. Like the subset size in subset selection, or the penalty in ridge regression, $s$ should be adaptly chosen to minimize an estimate of expected prediction error.
When $p\gg N$ , high variance and over fitting are a major concern in this setting. As a result, simple, highly regularized approaches often become the methods of choice.
Principal components analysis is an effective method for finding linear combinations of features that exhibit large variation in a dataset. But what we seek here are linear combinations with both high variance and significant correlation with the outcome. Hence we want to encourage principal component analysis to find linear combinations of features that have high correlation with the outcome - supervised principal components (see page 678, Algorithm 18.1, in the book Elements of Statistical Learning).
Partial least squares down weights noisy features, but does not throw them away; as a result a large number of noisy features can contaminate the predictions. Thresholded PLS can be viewed as a noisy version of supervised principal components, and hence we might not expect it to work as well in practice. Supervised principal components can yield lower test errors than Threshold PLS. However, it does not always produce a sparse model involving only a small number of features.
The lasso on the other hand, produces a sparse model from the data. Ridge can always perform average. I think lasso is good choice when there are large number $p$. Supervised principal component can also work well.
|
Regression in $p>n$ setting: how to choose regularization method (Lasso, PLS, PCR, ridge)?
I think there is no single answer to your question - it depends upon many situation, data and what you are trying to do. Some of the modification can be or should be modified to achieve the goal. How
|
12,491
|
Two negative main effects yet positive interaction effect?
|
This situation is certainly possible. As a simple example, consider an experiment where you are adding certain volumes of hot (V1) and cold (V2) water to a fish tank that begins at the correct temperature. The response variable (V3) is the number of fish that survive after a day. Intuitively, if you add only hot water (V1 increases), lots of fish will die (V3 goes down). If you add only cold water (V2 increases), lots of fish will die (V3 goes down). But if you add both hot and cold water (Both V1 and V2 increase, thus V1*V2 increases), the fish will be fine (V3 stays high), so the interaction must counteract the two main effects and be positive.
Below, I made up 18 data points mimicking the above situation and fit multiple linear regression in R and included the output. You can see the two negative main effects and positive interaction in the last line. You can let V1 = Liters of hot water, V2 = Liters of cold water, and V3 = Number of fish alive after one day.
V1 V2 V3
1 0 0 100
2 0 1 90
3 1 0 89
4 1 1 99
5 2 0 79
6 0 2 80
7 2 1 91
8 1 2 92
9 2 2 99
10 3 3 100
11 2 3 88
12 3 2 91
13 0 3 70
14 3 0 69
15 3 3 100
16 4 0 61
17 0 4 60
18 4 2 82
A = matrix(c(0,0,100, 0,1,90, 1,0,89, 1,1,99, 2,0,79, 0,2,80, 2,1,91, 1,2,92,
2,2,99, 3,3,100, 2,3,88, 3,2,91, 0,3,70, 3,0,69, 3,3,100, 4,0,61, 0,4,60,
4,2, 82), byrow=T, ncol=3)
A = as.data.frame(A)
summary(lm(V3 ~ V1 + V2 + V1:V2 , data=A))
Coefficients:
(Intercept) V1 V2 V1:V2
103.568 -10.853 -10.214 6.563
|
Two negative main effects yet positive interaction effect?
|
This situation is certainly possible. As a simple example, consider an experiment where you are adding certain volumes of hot (V1) and cold (V2) water to a fish tank that begins at the correct temper
|
Two negative main effects yet positive interaction effect?
This situation is certainly possible. As a simple example, consider an experiment where you are adding certain volumes of hot (V1) and cold (V2) water to a fish tank that begins at the correct temperature. The response variable (V3) is the number of fish that survive after a day. Intuitively, if you add only hot water (V1 increases), lots of fish will die (V3 goes down). If you add only cold water (V2 increases), lots of fish will die (V3 goes down). But if you add both hot and cold water (Both V1 and V2 increase, thus V1*V2 increases), the fish will be fine (V3 stays high), so the interaction must counteract the two main effects and be positive.
Below, I made up 18 data points mimicking the above situation and fit multiple linear regression in R and included the output. You can see the two negative main effects and positive interaction in the last line. You can let V1 = Liters of hot water, V2 = Liters of cold water, and V3 = Number of fish alive after one day.
V1 V2 V3
1 0 0 100
2 0 1 90
3 1 0 89
4 1 1 99
5 2 0 79
6 0 2 80
7 2 1 91
8 1 2 92
9 2 2 99
10 3 3 100
11 2 3 88
12 3 2 91
13 0 3 70
14 3 0 69
15 3 3 100
16 4 0 61
17 0 4 60
18 4 2 82
A = matrix(c(0,0,100, 0,1,90, 1,0,89, 1,1,99, 2,0,79, 0,2,80, 2,1,91, 1,2,92,
2,2,99, 3,3,100, 2,3,88, 3,2,91, 0,3,70, 3,0,69, 3,3,100, 4,0,61, 0,4,60,
4,2, 82), byrow=T, ncol=3)
A = as.data.frame(A)
summary(lm(V3 ~ V1 + V2 + V1:V2 , data=A))
Coefficients:
(Intercept) V1 V2 V1:V2
103.568 -10.853 -10.214 6.563
|
Two negative main effects yet positive interaction effect?
This situation is certainly possible. As a simple example, consider an experiment where you are adding certain volumes of hot (V1) and cold (V2) water to a fish tank that begins at the correct temper
|
12,492
|
Two negative main effects yet positive interaction effect?
|
An alternative way of looking at the situation to @underminer's brilliant example is to note that under least squares regression, your fitted values satisfy "correlation constraints"
$$\sum_{ i=1}^nx_{ik}\hat{y}_i=\sum_{ i=1}^nx_{ik}y_i$$
Where $ x_{ik} $ is the value of the kth (independent/explanatory/predictor/etc) variable on the ith observation. Note that the right hand side does not depend on what other variables are in the model. So if "y" generally increases/decreases with the kth variable then the fitted values also will. This is easy to see through the betas when only main effects are present, but confusing when interactions are present.
Note how interactions generally "ruin" the typical interpretation of betas as "effect on the response by increasing that variable by one unit with all other variables held constant ". This is a useless interpretation when interactions are present as we know that varying a single variable will alter the values for the interaction terms as well as the main effects. In the most simple case given by your example you have that changing $V1$ by one will alter the fitted value by
$$\beta_1 + V2\beta_{1*2} $$
Clearly just looking at $\beta_1 $ won't give you the proper "effect" of $ V1 $ on the response.
|
Two negative main effects yet positive interaction effect?
|
An alternative way of looking at the situation to @underminer's brilliant example is to note that under least squares regression, your fitted values satisfy "correlation constraints"
$$\sum_{ i=1}^nx_
|
Two negative main effects yet positive interaction effect?
An alternative way of looking at the situation to @underminer's brilliant example is to note that under least squares regression, your fitted values satisfy "correlation constraints"
$$\sum_{ i=1}^nx_{ik}\hat{y}_i=\sum_{ i=1}^nx_{ik}y_i$$
Where $ x_{ik} $ is the value of the kth (independent/explanatory/predictor/etc) variable on the ith observation. Note that the right hand side does not depend on what other variables are in the model. So if "y" generally increases/decreases with the kth variable then the fitted values also will. This is easy to see through the betas when only main effects are present, but confusing when interactions are present.
Note how interactions generally "ruin" the typical interpretation of betas as "effect on the response by increasing that variable by one unit with all other variables held constant ". This is a useless interpretation when interactions are present as we know that varying a single variable will alter the values for the interaction terms as well as the main effects. In the most simple case given by your example you have that changing $V1$ by one will alter the fitted value by
$$\beta_1 + V2\beta_{1*2} $$
Clearly just looking at $\beta_1 $ won't give you the proper "effect" of $ V1 $ on the response.
|
Two negative main effects yet positive interaction effect?
An alternative way of looking at the situation to @underminer's brilliant example is to note that under least squares regression, your fitted values satisfy "correlation constraints"
$$\sum_{ i=1}^nx_
|
12,493
|
How does the standard error work?
|
Yes, the standard error of the mean (SEM) is the standard deviation (SD) of the means. (Standard error is another way to say SD of a sampling distribution. In this case, the sampling distribution is means for samples of a fixed size, say N.) There is a mathematical relationship between the SEM and the population SD: SEM = population SD / the square root of N. This mathematical relationship is very helpful, since we almost never have a direct estimate of the SEM but we do have an estimate of the population SD (namely the SD of our sample). As to your second question, if you were to collect multiple samples of size N and calculate the mean for each sample you could estimate the SEM simply by calculating the SD of the means. So the formula for SEM does indeed mirror the formula for the SD of a single sample.
|
How does the standard error work?
|
Yes, the standard error of the mean (SEM) is the standard deviation (SD) of the means. (Standard error is another way to say SD of a sampling distribution. In this case, the sampling distribution is
|
How does the standard error work?
Yes, the standard error of the mean (SEM) is the standard deviation (SD) of the means. (Standard error is another way to say SD of a sampling distribution. In this case, the sampling distribution is means for samples of a fixed size, say N.) There is a mathematical relationship between the SEM and the population SD: SEM = population SD / the square root of N. This mathematical relationship is very helpful, since we almost never have a direct estimate of the SEM but we do have an estimate of the population SD (namely the SD of our sample). As to your second question, if you were to collect multiple samples of size N and calculate the mean for each sample you could estimate the SEM simply by calculating the SD of the means. So the formula for SEM does indeed mirror the formula for the SD of a single sample.
|
How does the standard error work?
Yes, the standard error of the mean (SEM) is the standard deviation (SD) of the means. (Standard error is another way to say SD of a sampling distribution. In this case, the sampling distribution is
|
12,494
|
How does the standard error work?
|
Suppose $X_1, X_2, \ldots, X_n$ are independent and identically distributed. This is the situation I am pretty sure you are referring to. Let their common mean be $\mu$ and their common variance be $\sigma^2$.
Now the sample mean is $X_b=\sum_i X_i/n$. Linearity of expectation shows that the mean of $X_b$ is also $\mu$. The independence assumption implies the variance of $X_b$ is the sum of the variances of its terms. Each such term $X_i/n$ has variance $\sigma^2/n^2$ (because the variance of a constant times a random variable is the constant squared times the variance of the random variable). We have $n$ identically distributed such variables to sum, so each term has that same variance. As a result, we get $n \sigma^2/n^2 = \sigma^2/n$ for the variance of the sample mean.
Usually we do not know $\sigma^2$ and so we must estimate it from the data. Depending on the setting, there are various ways to do this. The two most common, general-purpose estimates of $\sigma^2$ are the sample variance $s^2 = \frac{1}{n}\sum_i(X_i-X_b)^2$ and a small multiple of it, $s_u^2 = \frac{n}{n-1}s^2$ (which is an unbiased estimator of $\sigma^2$). Using either one of these in place of $\sigma^2$ in the preceding paragraph and taking the square root gives the standard error in the form of $s/\sqrt{n}$ or $s_u/\sqrt{n}$.
|
How does the standard error work?
|
Suppose $X_1, X_2, \ldots, X_n$ are independent and identically distributed. This is the situation I am pretty sure you are referring to. Let their common mean be $\mu$ and their common variance be $
|
How does the standard error work?
Suppose $X_1, X_2, \ldots, X_n$ are independent and identically distributed. This is the situation I am pretty sure you are referring to. Let their common mean be $\mu$ and their common variance be $\sigma^2$.
Now the sample mean is $X_b=\sum_i X_i/n$. Linearity of expectation shows that the mean of $X_b$ is also $\mu$. The independence assumption implies the variance of $X_b$ is the sum of the variances of its terms. Each such term $X_i/n$ has variance $\sigma^2/n^2$ (because the variance of a constant times a random variable is the constant squared times the variance of the random variable). We have $n$ identically distributed such variables to sum, so each term has that same variance. As a result, we get $n \sigma^2/n^2 = \sigma^2/n$ for the variance of the sample mean.
Usually we do not know $\sigma^2$ and so we must estimate it from the data. Depending on the setting, there are various ways to do this. The two most common, general-purpose estimates of $\sigma^2$ are the sample variance $s^2 = \frac{1}{n}\sum_i(X_i-X_b)^2$ and a small multiple of it, $s_u^2 = \frac{n}{n-1}s^2$ (which is an unbiased estimator of $\sigma^2$). Using either one of these in place of $\sigma^2$ in the preceding paragraph and taking the square root gives the standard error in the form of $s/\sqrt{n}$ or $s_u/\sqrt{n}$.
|
How does the standard error work?
Suppose $X_1, X_2, \ldots, X_n$ are independent and identically distributed. This is the situation I am pretty sure you are referring to. Let their common mean be $\mu$ and their common variance be $
|
12,495
|
How does the standard error work?
|
+1 to both @JoelW. & @MichaelChernick. I want to add a detail to @JoelW.'s answer. He notes that "we almost never have a direct estimate of the SEM", which is essentially true, but it's worth explicitly recognizing a caveat to that statement. Specifically, when a study compares multiple groups / treatments (for example, placebo vs. standard drug vs. new drug), an ANOVA is typically used to see if they are all equal. The null hypothesis is that each group has been drawn from the same population, and thus, all three means are estimates of the population mean. That is, the null hypothesis in a standard ANOVA assumes that you do have a direct estimate of the SEM. Consider the equation for the variance of the sampling distribution of means:
$$
\sigma^2_{\bar x}=\frac{\sigma^2_{pop}}{n_j},
$$
where $\sigma^2_{pop}$ is the population variance, and $n_j$ is the number of groups. Although we don't usually perform the calculations in this way, we could simply use standard formulas to plug in estimated values, and with minimal algebraic reshuffling, form the $F$ statistic like so:
$$
F=\frac{n_j\times s^2_{\bar x}}{s^2_{\text{pooled within group}}}
$$
In this case, we really would be using the standard formula (only applied over the group means), that is:
$$
s^2_{\bar x}=\frac{\sum_{j=1}^{n_j}(\bar x_j-\bar x_.)^2}{n_j-1},
$$
with $x_.$ being the mean of the group means.
In that we typically believe the null hypothesis is not true, @JoelW.'s point is right, but I work through this point, because I think the clarity it affords is helpful for understanding these issues.
|
How does the standard error work?
|
+1 to both @JoelW. & @MichaelChernick. I want to add a detail to @JoelW.'s answer. He notes that "we almost never have a direct estimate of the SEM", which is essentially true, but it's worth explic
|
How does the standard error work?
+1 to both @JoelW. & @MichaelChernick. I want to add a detail to @JoelW.'s answer. He notes that "we almost never have a direct estimate of the SEM", which is essentially true, but it's worth explicitly recognizing a caveat to that statement. Specifically, when a study compares multiple groups / treatments (for example, placebo vs. standard drug vs. new drug), an ANOVA is typically used to see if they are all equal. The null hypothesis is that each group has been drawn from the same population, and thus, all three means are estimates of the population mean. That is, the null hypothesis in a standard ANOVA assumes that you do have a direct estimate of the SEM. Consider the equation for the variance of the sampling distribution of means:
$$
\sigma^2_{\bar x}=\frac{\sigma^2_{pop}}{n_j},
$$
where $\sigma^2_{pop}$ is the population variance, and $n_j$ is the number of groups. Although we don't usually perform the calculations in this way, we could simply use standard formulas to plug in estimated values, and with minimal algebraic reshuffling, form the $F$ statistic like so:
$$
F=\frac{n_j\times s^2_{\bar x}}{s^2_{\text{pooled within group}}}
$$
In this case, we really would be using the standard formula (only applied over the group means), that is:
$$
s^2_{\bar x}=\frac{\sum_{j=1}^{n_j}(\bar x_j-\bar x_.)^2}{n_j-1},
$$
with $x_.$ being the mean of the group means.
In that we typically believe the null hypothesis is not true, @JoelW.'s point is right, but I work through this point, because I think the clarity it affords is helpful for understanding these issues.
|
How does the standard error work?
+1 to both @JoelW. & @MichaelChernick. I want to add a detail to @JoelW.'s answer. He notes that "we almost never have a direct estimate of the SEM", which is essentially true, but it's worth explic
|
12,496
|
Typical set concept
|
I know you have explicitly asked for an intuitive explanation and to leave out the formal definition, but I think they are rather related, so let me recall the definition of typical set:
$X_1, X_2 ,... $ are i.i.d. random variables $\sim $ $p(x)$ then the typical set $A_\epsilon^{(n)} $ with respect to $p(x)$ is the set of sequences $(x_1,x_2,...,x_n) \in \chi^n$ with the property
$$2^{-n(H(X)+\epsilon)}\le p(x_1,x_2,...,x_n) \le 2^{-n(H(X)-\epsilon)} \tag{1}$$
This means that for a fixed $\epsilon$, the typical set is composed of all the sequences whose probabilities are close to $2^{-nH(X)}$. So in order for a sequence to belong to the typical set, it just has to have a probability close to $2^{-nH(X)}$, it usually does not though. To understand why, let me rewrite the equation 1 by applying $log_2$ on it.
$$H(X)-\epsilon\le \frac{1}{n}\log_2\left(\frac{1}{p(x_1,x_2,...,x_n)}\right) \le H(X)+\epsilon \tag{2}$$
Now the typical set definition is more directly related to the concept of entropy, or stated another way, the average information of the random variable. The middle term can be thought as the sample entropy of the sequence, thus the typical set is made by all the sequences that are giving us an amount of information close to the average information of the random variable $X$. The most probable sequence usually gives us less information than the average. Remember that, the lower the probability of an outcome is, the higher the information it gives us will be. To understand why let me give an example:
Let's suppose that you live in a city whose weather is highly likely to be sunny and warm, between 24°C and 26°C. You may watch the weather report every morning but you wouldn't care much about it, I mean, it is always sunny and warm. But what if someday the weather man/woman tells you that today will be rainy and cold, that is a game changer. You will have to use some different clothes and take an umbrella and do other things that you usually don't, so the weather man has given you a real important information.
To sum up, the intuitive definition of the typical set is that it consists of sequences that give us an amount of information close to the expected one of the source (random variable).
|
Typical set concept
|
I know you have explicitly asked for an intuitive explanation and to leave out the formal definition, but I think they are rather related, so let me recall the definition of typical set:
$X_1, X_2 ,..
|
Typical set concept
I know you have explicitly asked for an intuitive explanation and to leave out the formal definition, but I think they are rather related, so let me recall the definition of typical set:
$X_1, X_2 ,... $ are i.i.d. random variables $\sim $ $p(x)$ then the typical set $A_\epsilon^{(n)} $ with respect to $p(x)$ is the set of sequences $(x_1,x_2,...,x_n) \in \chi^n$ with the property
$$2^{-n(H(X)+\epsilon)}\le p(x_1,x_2,...,x_n) \le 2^{-n(H(X)-\epsilon)} \tag{1}$$
This means that for a fixed $\epsilon$, the typical set is composed of all the sequences whose probabilities are close to $2^{-nH(X)}$. So in order for a sequence to belong to the typical set, it just has to have a probability close to $2^{-nH(X)}$, it usually does not though. To understand why, let me rewrite the equation 1 by applying $log_2$ on it.
$$H(X)-\epsilon\le \frac{1}{n}\log_2\left(\frac{1}{p(x_1,x_2,...,x_n)}\right) \le H(X)+\epsilon \tag{2}$$
Now the typical set definition is more directly related to the concept of entropy, or stated another way, the average information of the random variable. The middle term can be thought as the sample entropy of the sequence, thus the typical set is made by all the sequences that are giving us an amount of information close to the average information of the random variable $X$. The most probable sequence usually gives us less information than the average. Remember that, the lower the probability of an outcome is, the higher the information it gives us will be. To understand why let me give an example:
Let's suppose that you live in a city whose weather is highly likely to be sunny and warm, between 24°C and 26°C. You may watch the weather report every morning but you wouldn't care much about it, I mean, it is always sunny and warm. But what if someday the weather man/woman tells you that today will be rainy and cold, that is a game changer. You will have to use some different clothes and take an umbrella and do other things that you usually don't, so the weather man has given you a real important information.
To sum up, the intuitive definition of the typical set is that it consists of sequences that give us an amount of information close to the expected one of the source (random variable).
|
Typical set concept
I know you have explicitly asked for an intuitive explanation and to leave out the formal definition, but I think they are rather related, so let me recall the definition of typical set:
$X_1, X_2 ,..
|
12,497
|
Typical set concept
|
Diegobatt's answer does a good job of explaining intuitively what the typical set is. This answer will address the OP's other question, echoed by @tomwesolowski: why would you define the typical set in a way that can exclude the most probable elements?
The short answer is that the typical set is primarily a theoretical tool. It was defined to help prove something, and this definition is the most convenient one for the proof. It is a good example of how theoretical needs can sometimes trump intuitive preferences in mathematics.
The typical set was defined by the father of information theory, Claude Shannon. He wanted to determine how efficiently one could possibly encode a stream of symbols from a fixed alphabet, assuming each symbol is an i.i.d. random sample from some distribution. His key insights were that:
There is an easily identifiable, relatively small set of "typical" sequences that show up disproportionately often in the stream.
Assigning this "typical set" of sequences the shortest encodings yields an optimally efficient encoding (asymptotically, as the stream's output grows arbitrarily long).
The typical set Shannon discovered is composed precisely of the sequences whose self-information, or "surprising-ness", is about the same as the self-information expected, on average, for the stream's source distribution. Such sequences are "typical" in the sense that their information is about average, but this definition implicitly excludes those sequences which have significantly less information than average. These less-informative sequences are also the most probable ones.
As the OP notes, this is not intuitively appealing! On its face, the typical set sounds like it should contain all the most probable sequences up to some threshold. That would better represent what is typically seen in the stream.
But Shannon did not want the most "typical" possible typical set; he wanted one that made it easy to prove the result he wanted to prove. The typical set defined by Shannon is guaranteed to exist, it is guaranteed to be small, and it is guaranteed to be about as small as any other set you might propose, as this answer points out. Adding the most likely elements makes the set more likely, which is good, but it also makes the set bigger, which is bad. The net effect on the soundness of the proof isn't immediately clear; it could make the proof more complicated* to finish. Best not to fix what isn't broken.
If you have different objectives than Shannon, your preferred concept of typicality might be different as well. For example, in Huffman coding, the most probable symbols (or symbol sequences) get the shortest codes. In a certain technical sense, Huffman coding is the optimal solution to Shannon's original problem, and it better captures our intuition about typicality. On the other hand, Shannon's definition of typicality is more convenient for proving things.
*Given a typical set, you could add the most probable element and drop the least probable element. This would keep the set the same size and increase its probability, so the proof should still work with this new set. You could repeat this as many times as you wanted, until the typical set contains all the most probable elements. But this step has no direct value to the proof, so why bother?
|
Typical set concept
|
Diegobatt's answer does a good job of explaining intuitively what the typical set is. This answer will address the OP's other question, echoed by @tomwesolowski: why would you define the typical set i
|
Typical set concept
Diegobatt's answer does a good job of explaining intuitively what the typical set is. This answer will address the OP's other question, echoed by @tomwesolowski: why would you define the typical set in a way that can exclude the most probable elements?
The short answer is that the typical set is primarily a theoretical tool. It was defined to help prove something, and this definition is the most convenient one for the proof. It is a good example of how theoretical needs can sometimes trump intuitive preferences in mathematics.
The typical set was defined by the father of information theory, Claude Shannon. He wanted to determine how efficiently one could possibly encode a stream of symbols from a fixed alphabet, assuming each symbol is an i.i.d. random sample from some distribution. His key insights were that:
There is an easily identifiable, relatively small set of "typical" sequences that show up disproportionately often in the stream.
Assigning this "typical set" of sequences the shortest encodings yields an optimally efficient encoding (asymptotically, as the stream's output grows arbitrarily long).
The typical set Shannon discovered is composed precisely of the sequences whose self-information, or "surprising-ness", is about the same as the self-information expected, on average, for the stream's source distribution. Such sequences are "typical" in the sense that their information is about average, but this definition implicitly excludes those sequences which have significantly less information than average. These less-informative sequences are also the most probable ones.
As the OP notes, this is not intuitively appealing! On its face, the typical set sounds like it should contain all the most probable sequences up to some threshold. That would better represent what is typically seen in the stream.
But Shannon did not want the most "typical" possible typical set; he wanted one that made it easy to prove the result he wanted to prove. The typical set defined by Shannon is guaranteed to exist, it is guaranteed to be small, and it is guaranteed to be about as small as any other set you might propose, as this answer points out. Adding the most likely elements makes the set more likely, which is good, but it also makes the set bigger, which is bad. The net effect on the soundness of the proof isn't immediately clear; it could make the proof more complicated* to finish. Best not to fix what isn't broken.
If you have different objectives than Shannon, your preferred concept of typicality might be different as well. For example, in Huffman coding, the most probable symbols (or symbol sequences) get the shortest codes. In a certain technical sense, Huffman coding is the optimal solution to Shannon's original problem, and it better captures our intuition about typicality. On the other hand, Shannon's definition of typicality is more convenient for proving things.
*Given a typical set, you could add the most probable element and drop the least probable element. This would keep the set the same size and increase its probability, so the proof should still work with this new set. You could repeat this as many times as you wanted, until the typical set contains all the most probable elements. But this step has no direct value to the proof, so why bother?
|
Typical set concept
Diegobatt's answer does a good job of explaining intuitively what the typical set is. This answer will address the OP's other question, echoed by @tomwesolowski: why would you define the typical set i
|
12,498
|
Typical set concept
|
According to theorem 6.3 in these lecture notes no matter if we take subset of sequences with highest probability or those with probability close to $2^{-nH(X)}$ (from typical set) we have to take approximately $2^{nH}$ to make sure that chosen subset contains random sequence with high probability. We usually take typical set elements, because we can bound the size of it more easily.
|
Typical set concept
|
According to theorem 6.3 in these lecture notes no matter if we take subset of sequences with highest probability or those with probability close to $2^{-nH(X)}$ (from typical set) we have to take app
|
Typical set concept
According to theorem 6.3 in these lecture notes no matter if we take subset of sequences with highest probability or those with probability close to $2^{-nH(X)}$ (from typical set) we have to take approximately $2^{nH}$ to make sure that chosen subset contains random sequence with high probability. We usually take typical set elements, because we can bound the size of it more easily.
|
Typical set concept
According to theorem 6.3 in these lecture notes no matter if we take subset of sequences with highest probability or those with probability close to $2^{-nH(X)}$ (from typical set) we have to take app
|
12,499
|
Typical set concept
|
The idea of a typical set implicitly treats the outcome sequences as multisets, ie it assumes you just care about the histogram of each sequence, eg you consider all 10 coin toss sequences with 7 heads and 3 tails as equivalent.
Imagine you have a very biased coin, say $p(H) = .9$. This is just the binomial distribution. The most probable 100-toss sequence is 100 heads, but there is only 1 100 head sequence. There are exponentially many more sequences that contain 10 tails, but these are much less probable individually. The the greatest number sequences is with half heads & half tails, but these are even less probable. So there is a tension between the probability of individual sequences and the number of equivalent sequences in a class. Maximum probability is reached when the frequencies in the sequences match the probabilities.
The important result is that for sufficiently long sequences almost all sampled sequences will have be arbitrarilly close to the expected frequencies, ie the distribution becomes extremely peaked as the length of sequences considered increases.
For example observed $10^5$ toss sequences of the $P(H)=.9$ coin will get sequences with $10^4{+/-}300$ tails 99% of the time since the standard deviation on the number of tails in a sequnce is approximately 100. The probability of all heads is negligible despite that being the most probable specific sequence.
Typical set is a more general, information theoretically defined version of this idea.
|
Typical set concept
|
The idea of a typical set implicitly treats the outcome sequences as multisets, ie it assumes you just care about the histogram of each sequence, eg you consider all 10 coin toss sequences with 7 head
|
Typical set concept
The idea of a typical set implicitly treats the outcome sequences as multisets, ie it assumes you just care about the histogram of each sequence, eg you consider all 10 coin toss sequences with 7 heads and 3 tails as equivalent.
Imagine you have a very biased coin, say $p(H) = .9$. This is just the binomial distribution. The most probable 100-toss sequence is 100 heads, but there is only 1 100 head sequence. There are exponentially many more sequences that contain 10 tails, but these are much less probable individually. The the greatest number sequences is with half heads & half tails, but these are even less probable. So there is a tension between the probability of individual sequences and the number of equivalent sequences in a class. Maximum probability is reached when the frequencies in the sequences match the probabilities.
The important result is that for sufficiently long sequences almost all sampled sequences will have be arbitrarilly close to the expected frequencies, ie the distribution becomes extremely peaked as the length of sequences considered increases.
For example observed $10^5$ toss sequences of the $P(H)=.9$ coin will get sequences with $10^4{+/-}300$ tails 99% of the time since the standard deviation on the number of tails in a sequnce is approximately 100. The probability of all heads is negligible despite that being the most probable specific sequence.
Typical set is a more general, information theoretically defined version of this idea.
|
Typical set concept
The idea of a typical set implicitly treats the outcome sequences as multisets, ie it assumes you just care about the histogram of each sequence, eg you consider all 10 coin toss sequences with 7 head
|
12,500
|
Typical set concept
|
Consider a biased coin that has a 60% probability of landing heads. If this coin is flipped 100 times, the most likely sequence would be 100 heads, but that isn't "typical". Typical sequences would have about 60 heads.
|
Typical set concept
|
Consider a biased coin that has a 60% probability of landing heads. If this coin is flipped 100 times, the most likely sequence would be 100 heads, but that isn't "typical". Typical sequences would ha
|
Typical set concept
Consider a biased coin that has a 60% probability of landing heads. If this coin is flipped 100 times, the most likely sequence would be 100 heads, but that isn't "typical". Typical sequences would have about 60 heads.
|
Typical set concept
Consider a biased coin that has a 60% probability of landing heads. If this coin is flipped 100 times, the most likely sequence would be 100 heads, but that isn't "typical". Typical sequences would ha
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.