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
|
|---|---|---|---|---|---|---|
8,401
|
Expectation of 500 coin flips after 500 realizations
|
Different schools of probability is a bit confusing, so let's do that on the computer as experiments.
What your confusion is that
If I have (say) 300 tails in the first 500 flips, should I expect 200 tails in the next 500 flips?
If I have (say) 200 tails in the first 200 flips, should I expect (only) 300 tails in the next 800 flips?
If I have $x$ tails in the first $y$ flips, should I expect (only) $500-x$ tails in the next $1000-y$ flips?
Or if we set tail to be -1 and head to be +1:
If I have in the first $y$ flips the sum is $s_1 = x$, should I expect in the next $n-y$ flips the sum to be $s_2 = -x\frac{y}{n-y}$?
If we flip many many runs, with each run $n$ flips, and we plot $s_1$ and $s_2$, if your statement is true, we should see a nice line for fixed $y$, for $s_2 = -s_1 \frac{y}{n-y}$.
Here is a python code for your problem:
import random
from matplotlib import pyplot as plt
def run():
n_trial = 1000
flip = 1000
deviation = []
prediction = []
for trial in range(n_trial):
result = [random.choice([-1, 1]) for _ in range(flip)]
current = 500
deviation.append(sum(result[:current]))
prediction.append(sum(result[current:]))
return deviation, prediction
deviation, prediction = run()
plt.scatter(deviation, prediction)
plt.show()
The result is a giant ball of mess.
which means that they are unrelated, even from a "experimental" point of view.
|
Expectation of 500 coin flips after 500 realizations
|
Different schools of probability is a bit confusing, so let's do that on the computer as experiments.
What your confusion is that
If I have (say) 300 tails in the first 500 flips, should I expect 2
|
Expectation of 500 coin flips after 500 realizations
Different schools of probability is a bit confusing, so let's do that on the computer as experiments.
What your confusion is that
If I have (say) 300 tails in the first 500 flips, should I expect 200 tails in the next 500 flips?
If I have (say) 200 tails in the first 200 flips, should I expect (only) 300 tails in the next 800 flips?
If I have $x$ tails in the first $y$ flips, should I expect (only) $500-x$ tails in the next $1000-y$ flips?
Or if we set tail to be -1 and head to be +1:
If I have in the first $y$ flips the sum is $s_1 = x$, should I expect in the next $n-y$ flips the sum to be $s_2 = -x\frac{y}{n-y}$?
If we flip many many runs, with each run $n$ flips, and we plot $s_1$ and $s_2$, if your statement is true, we should see a nice line for fixed $y$, for $s_2 = -s_1 \frac{y}{n-y}$.
Here is a python code for your problem:
import random
from matplotlib import pyplot as plt
def run():
n_trial = 1000
flip = 1000
deviation = []
prediction = []
for trial in range(n_trial):
result = [random.choice([-1, 1]) for _ in range(flip)]
current = 500
deviation.append(sum(result[:current]))
prediction.append(sum(result[current:]))
return deviation, prediction
deviation, prediction = run()
plt.scatter(deviation, prediction)
plt.show()
The result is a giant ball of mess.
which means that they are unrelated, even from a "experimental" point of view.
|
Expectation of 500 coin flips after 500 realizations
Different schools of probability is a bit confusing, so let's do that on the computer as experiments.
What your confusion is that
If I have (say) 300 tails in the first 500 flips, should I expect 2
|
8,402
|
Expectation of 500 coin flips after 500 realizations
|
Whether you flipped a coin many times in the past is irrelevant. Every time you throw a coin the expectation is there is a 50% chance it will be heads. If you are going to throw it 500 times it should be heads about 250 times. But there is no guarantee. All 500 times could be heads, or 0 times.
Taken altogether, after you finished with your 1000th throw you could have had heads from 500 to 1000 times. The precise combination of heads and tails you got had the same chances of occurring, even if the first 500 flips were heads.
To visualize it lets say you were flipping it 4 times. Your first two flips were H, H. Your outcome could then be:
H, H, H, H
H, H, H, T
H, H, T, H
H, H, T, T
You can see the heads and tails have a 50% chance. Let's say the outcome was H, H, H, T. That outcome was one of a possible
H, H, H, H
H, H, H, T <---yours
H, H, T, H
H, H, T, T
H, T, H, H
H, T, H, T
H, T, T, H
H, T, T, T
T, H, H, H
T, H, H, T
T, H, T, T
T, H, T, T
T, T, H, H
T, T, H, T
T, T, T, H
T, T, T, T
so 16 combinations. Any of those could have happened and one of them did. Just because you say the first two were H, H doesn't change the outcome of the last two. The first two could have been T, T or T, H and the outcome of the last two would have still being independent.
|
Expectation of 500 coin flips after 500 realizations
|
Whether you flipped a coin many times in the past is irrelevant. Every time you throw a coin the expectation is there is a 50% chance it will be heads. If you are going to throw it 500 times it shou
|
Expectation of 500 coin flips after 500 realizations
Whether you flipped a coin many times in the past is irrelevant. Every time you throw a coin the expectation is there is a 50% chance it will be heads. If you are going to throw it 500 times it should be heads about 250 times. But there is no guarantee. All 500 times could be heads, or 0 times.
Taken altogether, after you finished with your 1000th throw you could have had heads from 500 to 1000 times. The precise combination of heads and tails you got had the same chances of occurring, even if the first 500 flips were heads.
To visualize it lets say you were flipping it 4 times. Your first two flips were H, H. Your outcome could then be:
H, H, H, H
H, H, H, T
H, H, T, H
H, H, T, T
You can see the heads and tails have a 50% chance. Let's say the outcome was H, H, H, T. That outcome was one of a possible
H, H, H, H
H, H, H, T <---yours
H, H, T, H
H, H, T, T
H, T, H, H
H, T, H, T
H, T, T, H
H, T, T, T
T, H, H, H
T, H, H, T
T, H, T, T
T, H, T, T
T, T, H, H
T, T, H, T
T, T, T, H
T, T, T, T
so 16 combinations. Any of those could have happened and one of them did. Just because you say the first two were H, H doesn't change the outcome of the last two. The first two could have been T, T or T, H and the outcome of the last two would have still being independent.
|
Expectation of 500 coin flips after 500 realizations
Whether you flipped a coin many times in the past is irrelevant. Every time you throw a coin the expectation is there is a 50% chance it will be heads. If you are going to throw it 500 times it shou
|
8,403
|
What does 'highly non linear' mean?
|
I don't think there's a formal definition. It's my impression that it simply means that not only is it non-linear, but attempting to model it with a linear approximation won't yield reasonable results and may even cause instability in the fitting method. Someone may also use it to simply mean that small input changes can result in counter-intuitively large changes in output.
|
What does 'highly non linear' mean?
|
I don't think there's a formal definition. It's my impression that it simply means that not only is it non-linear, but attempting to model it with a linear approximation won't yield reasonable results
|
What does 'highly non linear' mean?
I don't think there's a formal definition. It's my impression that it simply means that not only is it non-linear, but attempting to model it with a linear approximation won't yield reasonable results and may even cause instability in the fitting method. Someone may also use it to simply mean that small input changes can result in counter-intuitively large changes in output.
|
What does 'highly non linear' mean?
I don't think there's a formal definition. It's my impression that it simply means that not only is it non-linear, but attempting to model it with a linear approximation won't yield reasonable results
|
8,404
|
What does 'highly non linear' mean?
|
In a formal sense, I believe one could say that the second derivative differs substantially from zero. If 0 were a "reasonable" approximation to the second derivative over the domain of interest, it is close to linear, but if it's not, the nonlinear effects become very important to capture.
I've rarely heard terms like this apply to relatively simple polynomials, often in practical use it seems to apply to divergent dynamical systems (chaos-theory sort of things), or very non-smooth functions (where much higher-order derivatives are nonzero).
|
What does 'highly non linear' mean?
|
In a formal sense, I believe one could say that the second derivative differs substantially from zero. If 0 were a "reasonable" approximation to the second derivative over the domain of interest, it
|
What does 'highly non linear' mean?
In a formal sense, I believe one could say that the second derivative differs substantially from zero. If 0 were a "reasonable" approximation to the second derivative over the domain of interest, it is close to linear, but if it's not, the nonlinear effects become very important to capture.
I've rarely heard terms like this apply to relatively simple polynomials, often in practical use it seems to apply to divergent dynamical systems (chaos-theory sort of things), or very non-smooth functions (where much higher-order derivatives are nonzero).
|
What does 'highly non linear' mean?
In a formal sense, I believe one could say that the second derivative differs substantially from zero. If 0 were a "reasonable" approximation to the second derivative over the domain of interest, it
|
8,405
|
What does 'highly non linear' mean?
|
The important aspect missing from the other excellent answers is the domain.
E.g., $f(x)=x^2$ is
highly non-linear on $[-10;10]$ but
not on either half of the domain (i.e., on both $[-10;0]$ and $[0;10]$ one can possibly use a linear approximation of $f$ without an immediate disaster).
Another example is $f(x)=x^3-x$ which is
highly non-linear on $[-1;1]$ but
not on the larger domain $[-10;;10]$
|
What does 'highly non linear' mean?
|
The important aspect missing from the other excellent answers is the domain.
E.g., $f(x)=x^2$ is
highly non-linear on $[-10;10]$ but
not on either half of the domain (i.e., on both $[-10;0]$ and $[
|
What does 'highly non linear' mean?
The important aspect missing from the other excellent answers is the domain.
E.g., $f(x)=x^2$ is
highly non-linear on $[-10;10]$ but
not on either half of the domain (i.e., on both $[-10;0]$ and $[0;10]$ one can possibly use a linear approximation of $f$ without an immediate disaster).
Another example is $f(x)=x^3-x$ which is
highly non-linear on $[-1;1]$ but
not on the larger domain $[-10;;10]$
|
What does 'highly non linear' mean?
The important aspect missing from the other excellent answers is the domain.
E.g., $f(x)=x^2$ is
highly non-linear on $[-10;10]$ but
not on either half of the domain (i.e., on both $[-10;0]$ and $[
|
8,406
|
What does 'highly non linear' mean?
|
As other mentioned, I don't think there's a formal definition. I would define it as a function which can not be approximated linearly in the typical range of disturbances to the argument. For instance, you have $y=f(x)$, and $\sigma^2=var[x]$. Then if the approximation $f(x+\sigma)\approx f(x)+f'(x)\sigma$ breaks down, then it's highly non-linear. For instance, $f(x)=exp(x^2)$ would be highly non-linear for any $x$ around zero, because its Taylor series are $1+x^2+x^4/2+O(x^5)$.
|
What does 'highly non linear' mean?
|
As other mentioned, I don't think there's a formal definition. I would define it as a function which can not be approximated linearly in the typical range of disturbances to the argument. For instance
|
What does 'highly non linear' mean?
As other mentioned, I don't think there's a formal definition. I would define it as a function which can not be approximated linearly in the typical range of disturbances to the argument. For instance, you have $y=f(x)$, and $\sigma^2=var[x]$. Then if the approximation $f(x+\sigma)\approx f(x)+f'(x)\sigma$ breaks down, then it's highly non-linear. For instance, $f(x)=exp(x^2)$ would be highly non-linear for any $x$ around zero, because its Taylor series are $1+x^2+x^4/2+O(x^5)$.
|
What does 'highly non linear' mean?
As other mentioned, I don't think there's a formal definition. I would define it as a function which can not be approximated linearly in the typical range of disturbances to the argument. For instance
|
8,407
|
What does 'highly non linear' mean?
|
Informally ... "highly non linear" means "even a blind man can see its not a straight line!" ;) Personally I take it as a danger sign, that it will somehow "blow up in your face" when used with real world examples.
The Tower of Hanoi could be called an example of highly non linear ... the legend being when the monks finish a 64 disk stack, the world will end. If you count total time spent in training, feeding, housing, and motivating everyone to support a thankless boring pointless multi-generational task, I would expect the total cost in man hours to really blow out!
|
What does 'highly non linear' mean?
|
Informally ... "highly non linear" means "even a blind man can see its not a straight line!" ;) Personally I take it as a danger sign, that it will somehow "blow up in your face" when used with real w
|
What does 'highly non linear' mean?
Informally ... "highly non linear" means "even a blind man can see its not a straight line!" ;) Personally I take it as a danger sign, that it will somehow "blow up in your face" when used with real world examples.
The Tower of Hanoi could be called an example of highly non linear ... the legend being when the monks finish a 64 disk stack, the world will end. If you count total time spent in training, feeding, housing, and motivating everyone to support a thankless boring pointless multi-generational task, I would expect the total cost in man hours to really blow out!
|
What does 'highly non linear' mean?
Informally ... "highly non linear" means "even a blind man can see its not a straight line!" ;) Personally I take it as a danger sign, that it will somehow "blow up in your face" when used with real w
|
8,408
|
What does 'highly non linear' mean?
|
As professional mathematician I can confirm that "highly nonlinear" is not a mathematical precisely defined term. :)
And none of "highly anything" I can think of.
Nonlinear is precise and opposite of linear (obviously).
But linear occurs in two different meanings:
$f(x) = ax+b$ is called linear function
only function $f(x) = ax$ (with no constant term $b$) is called linear
To emphasize the difference and presence of the constant term, the first function $(ax + b)$ is also called affine
|
What does 'highly non linear' mean?
|
As professional mathematician I can confirm that "highly nonlinear" is not a mathematical precisely defined term. :)
And none of "highly anything" I can think of.
Nonlinear is precise and opposite of
|
What does 'highly non linear' mean?
As professional mathematician I can confirm that "highly nonlinear" is not a mathematical precisely defined term. :)
And none of "highly anything" I can think of.
Nonlinear is precise and opposite of linear (obviously).
But linear occurs in two different meanings:
$f(x) = ax+b$ is called linear function
only function $f(x) = ax$ (with no constant term $b$) is called linear
To emphasize the difference and presence of the constant term, the first function $(ax + b)$ is also called affine
|
What does 'highly non linear' mean?
As professional mathematician I can confirm that "highly nonlinear" is not a mathematical precisely defined term. :)
And none of "highly anything" I can think of.
Nonlinear is precise and opposite of
|
8,409
|
What does 'highly non linear' mean?
|
For smooth functions, we usually say that something is "highly" nonlinear if the magnitude of the second derivative (or perhaps the curvature) is high. A linear function has zero second derivative and zero curvature, so it represents the extreme of low curvature.
|
What does 'highly non linear' mean?
|
For smooth functions, we usually say that something is "highly" nonlinear if the magnitude of the second derivative (or perhaps the curvature) is high. A linear function has zero second derivative an
|
What does 'highly non linear' mean?
For smooth functions, we usually say that something is "highly" nonlinear if the magnitude of the second derivative (or perhaps the curvature) is high. A linear function has zero second derivative and zero curvature, so it represents the extreme of low curvature.
|
What does 'highly non linear' mean?
For smooth functions, we usually say that something is "highly" nonlinear if the magnitude of the second derivative (or perhaps the curvature) is high. A linear function has zero second derivative an
|
8,410
|
What does 'highly non linear' mean?
|
As other answers said, there isn't a formal definition of the term from the mathematical point of view. But it has to do with the existence of the non zero derivative (the order) of the function.
A function that can be defined as being linear is some function $f(x)$ that can be described by a polynomial $P_n(x)$, even if the degree $n$ of the polynomial is big. That's because the total number of derivatives of the function that can be defined are finite (because the degree of the polynomial is finite).
But those functions that can only be described by other functions with infinite derivatives (infinite order) are said to be "highly nonlinear". For instance a function described by a exponential function who's derivatives of all orders are defined.
The word "highly" is prefixed to differentiate the function with regular polynomials of degree major or equal than 2 that are considered non linear functions (although polynomials of degree equal or major than 2 are considered "linear" from the linear algebra point of view given that they can be expressed in terms of a linear combination of the polynomial basis).
Related to all this has to do the domain of the function. As others said some functions are "more linear" in some intervals than in others. That's because the polynomial approximation theorem. Every real function can be exactly reproduced by a polynomial but that approximation at times involves a greater degree, some times the degree tends to infinity as with a power series. In that later case the function is said to be "highly nonlinear" because the existence of its infinite derivatives.
|
What does 'highly non linear' mean?
|
As other answers said, there isn't a formal definition of the term from the mathematical point of view. But it has to do with the existence of the non zero derivative (the order) of the function.
A fu
|
What does 'highly non linear' mean?
As other answers said, there isn't a formal definition of the term from the mathematical point of view. But it has to do with the existence of the non zero derivative (the order) of the function.
A function that can be defined as being linear is some function $f(x)$ that can be described by a polynomial $P_n(x)$, even if the degree $n$ of the polynomial is big. That's because the total number of derivatives of the function that can be defined are finite (because the degree of the polynomial is finite).
But those functions that can only be described by other functions with infinite derivatives (infinite order) are said to be "highly nonlinear". For instance a function described by a exponential function who's derivatives of all orders are defined.
The word "highly" is prefixed to differentiate the function with regular polynomials of degree major or equal than 2 that are considered non linear functions (although polynomials of degree equal or major than 2 are considered "linear" from the linear algebra point of view given that they can be expressed in terms of a linear combination of the polynomial basis).
Related to all this has to do the domain of the function. As others said some functions are "more linear" in some intervals than in others. That's because the polynomial approximation theorem. Every real function can be exactly reproduced by a polynomial but that approximation at times involves a greater degree, some times the degree tends to infinity as with a power series. In that later case the function is said to be "highly nonlinear" because the existence of its infinite derivatives.
|
What does 'highly non linear' mean?
As other answers said, there isn't a formal definition of the term from the mathematical point of view. But it has to do with the existence of the non zero derivative (the order) of the function.
A fu
|
8,411
|
Why does basic hypothesis testing focus on the mean and not on the median?
|
Because Alan Turing was born after Ronald Fisher.
In the old days, before computers, all this stuff had to be done by hand or, at best, with what we would now call calculators. Tests for comparing means can be done this way - it's laborious, but possible. Tests for quantiles (such as the median) would be pretty much impossible to do this way.
For example, quantile regression relies on minimizing a relatively complicated function.This would not be possible by hand. It is possible with programming. See e.g. Koenker or Wikipedia.
Quantile regression has fewer assumptions than OLS regression and provides more information.
|
Why does basic hypothesis testing focus on the mean and not on the median?
|
Because Alan Turing was born after Ronald Fisher.
In the old days, before computers, all this stuff had to be done by hand or, at best, with what we would now call calculators. Tests for comparing me
|
Why does basic hypothesis testing focus on the mean and not on the median?
Because Alan Turing was born after Ronald Fisher.
In the old days, before computers, all this stuff had to be done by hand or, at best, with what we would now call calculators. Tests for comparing means can be done this way - it's laborious, but possible. Tests for quantiles (such as the median) would be pretty much impossible to do this way.
For example, quantile regression relies on minimizing a relatively complicated function.This would not be possible by hand. It is possible with programming. See e.g. Koenker or Wikipedia.
Quantile regression has fewer assumptions than OLS regression and provides more information.
|
Why does basic hypothesis testing focus on the mean and not on the median?
Because Alan Turing was born after Ronald Fisher.
In the old days, before computers, all this stuff had to be done by hand or, at best, with what we would now call calculators. Tests for comparing me
|
8,412
|
Why does basic hypothesis testing focus on the mean and not on the median?
|
I would like to add a third reason to the correct reasons given by Harrell and Flom. The reason is that we use Euclidean distance (or L2) and not Manhattan distance (or L1) as our standard measure of closeness or error. If one has a number of data points $x_1, \ldots x_n$ and one wants a single number $\theta$ to estimate it, an obvious notion is to find the number that minimizes the 'error' that number creates the smallest difference between the chosen number and the numbers that constitute the data. In mathematical notation, for a given error function E, one wants to find $min_{\theta \in \Bbb{R}}
(E(\theta,x_1, \ldots x_n) = min_{\theta \in \Bbb{R}}(\sum_{i=1}^{i=n} E(\theta,x_i)) $ . If one takes for E(x,y) the L2 norm or distance, that is $E(x,y) = (x-y)^2 $ then the minimizer over all $\theta \in \Bbb{R}$ is the mean. If one takes the L1 or Manhattan distance, the minimizer over all $\theta \in \Bbb{R}$ is the median. Thus the mean is the natural mathematical choice - if one is using L2 distance !
|
Why does basic hypothesis testing focus on the mean and not on the median?
|
I would like to add a third reason to the correct reasons given by Harrell and Flom. The reason is that we use Euclidean distance (or L2) and not Manhattan distance (or L1) as our standard measure o
|
Why does basic hypothesis testing focus on the mean and not on the median?
I would like to add a third reason to the correct reasons given by Harrell and Flom. The reason is that we use Euclidean distance (or L2) and not Manhattan distance (or L1) as our standard measure of closeness or error. If one has a number of data points $x_1, \ldots x_n$ and one wants a single number $\theta$ to estimate it, an obvious notion is to find the number that minimizes the 'error' that number creates the smallest difference between the chosen number and the numbers that constitute the data. In mathematical notation, for a given error function E, one wants to find $min_{\theta \in \Bbb{R}}
(E(\theta,x_1, \ldots x_n) = min_{\theta \in \Bbb{R}}(\sum_{i=1}^{i=n} E(\theta,x_i)) $ . If one takes for E(x,y) the L2 norm or distance, that is $E(x,y) = (x-y)^2 $ then the minimizer over all $\theta \in \Bbb{R}$ is the mean. If one takes the L1 or Manhattan distance, the minimizer over all $\theta \in \Bbb{R}$ is the median. Thus the mean is the natural mathematical choice - if one is using L2 distance !
|
Why does basic hypothesis testing focus on the mean and not on the median?
I would like to add a third reason to the correct reasons given by Harrell and Flom. The reason is that we use Euclidean distance (or L2) and not Manhattan distance (or L1) as our standard measure o
|
8,413
|
Why does basic hypothesis testing focus on the mean and not on the median?
|
Often the mean is chosen over the median not because it's more representative, robust, or meaningful but because people confuse estimator with estimand. Put another way, some choose the population mean as the quantity of interest because with a normal distribution the sample mean is more precise than the sample median. Instead they should think more, as you have done, about the true quantity of interest.
One sidebar: we have a nonparametric confidence interval for the population median but there is no nonparametric method (other than perhaps the numerically intensive empirical likelihood method) to get a confidence interval for the population mean. If you want to stay distribution-free you might concentrate on the median.
Note that the central limit theorem is far less useful than it seems, as been discussed elsewhere on this site. It effectively assumes that the variance is known or that the distribution is symmetric and has a shape such that the sample variance is a competitive estimator of dispersion.
|
Why does basic hypothesis testing focus on the mean and not on the median?
|
Often the mean is chosen over the median not because it's more representative, robust, or meaningful but because people confuse estimator with estimand. Put another way, some choose the population me
|
Why does basic hypothesis testing focus on the mean and not on the median?
Often the mean is chosen over the median not because it's more representative, robust, or meaningful but because people confuse estimator with estimand. Put another way, some choose the population mean as the quantity of interest because with a normal distribution the sample mean is more precise than the sample median. Instead they should think more, as you have done, about the true quantity of interest.
One sidebar: we have a nonparametric confidence interval for the population median but there is no nonparametric method (other than perhaps the numerically intensive empirical likelihood method) to get a confidence interval for the population mean. If you want to stay distribution-free you might concentrate on the median.
Note that the central limit theorem is far less useful than it seems, as been discussed elsewhere on this site. It effectively assumes that the variance is known or that the distribution is symmetric and has a shape such that the sample variance is a competitive estimator of dispersion.
|
Why does basic hypothesis testing focus on the mean and not on the median?
Often the mean is chosen over the median not because it's more representative, robust, or meaningful but because people confuse estimator with estimand. Put another way, some choose the population me
|
8,414
|
Why is a comma a bad record separator/delimiter in CSV files?
|
CSV format specification is defined in RFC 4180. This specification was published because
there is no formal specification in existence, which allows for a wide
variety of interpretations of CSV files
Unfortunately, since 2005 (date of publishing the RFC), nothing has changed. We still have a wide variety of implementations. The general approach defined in RFC 4180 is to enclose fields containing characters such as commas in quotation marks, this recommendation however is not always meet by different software.
The problem is that in various European locales comma character serves as the decimal point, so you write 0,005 instead of 0.005. Yet in other cases, commas are used instead of spaces to signal digit groups, e.g. 4,000,000.00 (see here). In both cases using commas would possibly lead to errors in reading data from csv files because your software does not really know if 0,005, 0,1 are two numbers or four different numbers (see example here).
Last but not least, if you store text in your data file, then commas are much more common in text than, for example, semicolons, so if your text is not enclosed in quotation marks, that such data can also be easily read with errors.
Nothing makes commas better, or worse field separators as far as CSV files are used in accordance with recommendations as RFC 4180 that guard from the problems described above. However if there is a risk of using the simplified CSV format that does not enclose fields in quotation marks, or the recommendation could be used inconsistently, then other separators (e.g. semicolon) seem to be safer approach.
|
Why is a comma a bad record separator/delimiter in CSV files?
|
CSV format specification is defined in RFC 4180. This specification was published because
there is no formal specification in existence, which allows for a wide
variety of interpretations of CSV file
|
Why is a comma a bad record separator/delimiter in CSV files?
CSV format specification is defined in RFC 4180. This specification was published because
there is no formal specification in existence, which allows for a wide
variety of interpretations of CSV files
Unfortunately, since 2005 (date of publishing the RFC), nothing has changed. We still have a wide variety of implementations. The general approach defined in RFC 4180 is to enclose fields containing characters such as commas in quotation marks, this recommendation however is not always meet by different software.
The problem is that in various European locales comma character serves as the decimal point, so you write 0,005 instead of 0.005. Yet in other cases, commas are used instead of spaces to signal digit groups, e.g. 4,000,000.00 (see here). In both cases using commas would possibly lead to errors in reading data from csv files because your software does not really know if 0,005, 0,1 are two numbers or four different numbers (see example here).
Last but not least, if you store text in your data file, then commas are much more common in text than, for example, semicolons, so if your text is not enclosed in quotation marks, that such data can also be easily read with errors.
Nothing makes commas better, or worse field separators as far as CSV files are used in accordance with recommendations as RFC 4180 that guard from the problems described above. However if there is a risk of using the simplified CSV format that does not enclose fields in quotation marks, or the recommendation could be used inconsistently, then other separators (e.g. semicolon) seem to be safer approach.
|
Why is a comma a bad record separator/delimiter in CSV files?
CSV format specification is defined in RFC 4180. This specification was published because
there is no formal specification in existence, which allows for a wide
variety of interpretations of CSV file
|
8,415
|
Why is a comma a bad record separator/delimiter in CSV files?
|
Technically comma is as good as any other character to be used as a separator. The name of the format directly refers that values are comma separated (Comma-Separated Values).
The description of CSV format is using comma as an separator.
Any field containing comma should be double-quoted. So that does not cause a problem for reading data in. See the point 6 from the description:
Fields containing line breaks (CRLF), double quotes, and commas
should be enclosed in double-quotes.
For example the functions read.csv and write.csv from R by default are using comma as a separator.
|
Why is a comma a bad record separator/delimiter in CSV files?
|
Technically comma is as good as any other character to be used as a separator. The name of the format directly refers that values are comma separated (Comma-Separated Values).
The description of CSV f
|
Why is a comma a bad record separator/delimiter in CSV files?
Technically comma is as good as any other character to be used as a separator. The name of the format directly refers that values are comma separated (Comma-Separated Values).
The description of CSV format is using comma as an separator.
Any field containing comma should be double-quoted. So that does not cause a problem for reading data in. See the point 6 from the description:
Fields containing line breaks (CRLF), double quotes, and commas
should be enclosed in double-quotes.
For example the functions read.csv and write.csv from R by default are using comma as a separator.
|
Why is a comma a bad record separator/delimiter in CSV files?
Technically comma is as good as any other character to be used as a separator. The name of the format directly refers that values are comma separated (Comma-Separated Values).
The description of CSV f
|
8,416
|
Why is a comma a bad record separator/delimiter in CSV files?
|
In addition to being a digit separator in numbers, it is also forms part of address (such as customer address etc) in many countries. While some countries have short well-define addresses, many others have, long-winding addresses including, sometimes two commas in the same line. Good CSV files enclose all such data in double quotes. But over-simplistic, poorly written parsers don't provide for reading and differentiating such. (Then, there is the problem of using double quotes as part of the data, such as quote from a poem).
|
Why is a comma a bad record separator/delimiter in CSV files?
|
In addition to being a digit separator in numbers, it is also forms part of address (such as customer address etc) in many countries. While some countries have short well-define addresses, many others
|
Why is a comma a bad record separator/delimiter in CSV files?
In addition to being a digit separator in numbers, it is also forms part of address (such as customer address etc) in many countries. While some countries have short well-define addresses, many others have, long-winding addresses including, sometimes two commas in the same line. Good CSV files enclose all such data in double quotes. But over-simplistic, poorly written parsers don't provide for reading and differentiating such. (Then, there is the problem of using double quotes as part of the data, such as quote from a poem).
|
Why is a comma a bad record separator/delimiter in CSV files?
In addition to being a digit separator in numbers, it is also forms part of address (such as customer address etc) in many countries. While some countries have short well-define addresses, many others
|
8,417
|
Why is a comma a bad record separator/delimiter in CSV files?
|
While @Tim s answer is correct - I would like to add that "csv" as a whole has no common standard - especially the escaping rules are not defined at all, leading to "formats" which are readable in one program, but not another. This is excarberated by the fact that every "programmer" under the sun just thinks "oooh csv- I will build my own parser!" and then misses all of the edge cases.
Moreover, csv totally lacks the abillity to store metadata or even the data type of a column - leading to at several documents which you must read to unterstand the data.
|
Why is a comma a bad record separator/delimiter in CSV files?
|
While @Tim s answer is correct - I would like to add that "csv" as a whole has no common standard - especially the escaping rules are not defined at all, leading to "formats" which are readable in one
|
Why is a comma a bad record separator/delimiter in CSV files?
While @Tim s answer is correct - I would like to add that "csv" as a whole has no common standard - especially the escaping rules are not defined at all, leading to "formats" which are readable in one program, but not another. This is excarberated by the fact that every "programmer" under the sun just thinks "oooh csv- I will build my own parser!" and then misses all of the edge cases.
Moreover, csv totally lacks the abillity to store metadata or even the data type of a column - leading to at several documents which you must read to unterstand the data.
|
Why is a comma a bad record separator/delimiter in CSV files?
While @Tim s answer is correct - I would like to add that "csv" as a whole has no common standard - especially the escaping rules are not defined at all, leading to "formats" which are readable in one
|
8,418
|
Why is a comma a bad record separator/delimiter in CSV files?
|
If you can ditch the comma delimiter and use a tab character you will have much better success. You can leave the file named .CSV and importing into most programs is usually not a problem. Just specify TAB delimited rather than comma when you import your file. If there are commas in your data you WILL have a problem when specifying comma delimited as you are well aware.
|
Why is a comma a bad record separator/delimiter in CSV files?
|
If you can ditch the comma delimiter and use a tab character you will have much better success. You can leave the file named .CSV and importing into most programs is usually not a problem. Just speci
|
Why is a comma a bad record separator/delimiter in CSV files?
If you can ditch the comma delimiter and use a tab character you will have much better success. You can leave the file named .CSV and importing into most programs is usually not a problem. Just specify TAB delimited rather than comma when you import your file. If there are commas in your data you WILL have a problem when specifying comma delimited as you are well aware.
|
Why is a comma a bad record separator/delimiter in CSV files?
If you can ditch the comma delimiter and use a tab character you will have much better success. You can leave the file named .CSV and importing into most programs is usually not a problem. Just speci
|
8,419
|
Why is a comma a bad record separator/delimiter in CSV files?
|
ASCII provides us with four "separator" characters, as shown below in a snippet from the ascii(7) *nix man page:
Oct Dec Hex Char
----------------------
034 28 1C FS (file separator)
035 29 1D GS (group separator)
036 30 1E RS (record separator)
037 31 1F US (unit separator)
This answer provides a decent overview of their intended usage.
Of course, these control codes lack the human-friendliness (readability and input) of more popular delimiters, but are acceptable choices for internal and/or ephemeral exchange of data between programs.
|
Why is a comma a bad record separator/delimiter in CSV files?
|
ASCII provides us with four "separator" characters, as shown below in a snippet from the ascii(7) *nix man page:
Oct Dec Hex Char
----------------------
034 28 1C FS (file sepa
|
Why is a comma a bad record separator/delimiter in CSV files?
ASCII provides us with four "separator" characters, as shown below in a snippet from the ascii(7) *nix man page:
Oct Dec Hex Char
----------------------
034 28 1C FS (file separator)
035 29 1D GS (group separator)
036 30 1E RS (record separator)
037 31 1F US (unit separator)
This answer provides a decent overview of their intended usage.
Of course, these control codes lack the human-friendliness (readability and input) of more popular delimiters, but are acceptable choices for internal and/or ephemeral exchange of data between programs.
|
Why is a comma a bad record separator/delimiter in CSV files?
ASCII provides us with four "separator" characters, as shown below in a snippet from the ascii(7) *nix man page:
Oct Dec Hex Char
----------------------
034 28 1C FS (file sepa
|
8,420
|
Why is a comma a bad record separator/delimiter in CSV files?
|
The problem is not the comma; the problem is quoting. Regardless of which record and field delimiters you use, you need to be prepared for meeting them in the content. So you need a quoting mechanism. AND THEN you need a way for the quoting character(s) to appear too.
Following the RFC 4180 standard makes everything simpler for everybody.
I have personally had to write a script to probably fix the output from a program that got this wrong, so I am a bit militant about it. "probably fix" means that it worked for MY data, but I can see situations where it would fail. (In that program's defense, it was written before the standard.)
|
Why is a comma a bad record separator/delimiter in CSV files?
|
The problem is not the comma; the problem is quoting. Regardless of which record and field delimiters you use, you need to be prepared for meeting them in the content. So you need a quoting mechanis
|
Why is a comma a bad record separator/delimiter in CSV files?
The problem is not the comma; the problem is quoting. Regardless of which record and field delimiters you use, you need to be prepared for meeting them in the content. So you need a quoting mechanism. AND THEN you need a way for the quoting character(s) to appear too.
Following the RFC 4180 standard makes everything simpler for everybody.
I have personally had to write a script to probably fix the output from a program that got this wrong, so I am a bit militant about it. "probably fix" means that it worked for MY data, but I can see situations where it would fail. (In that program's defense, it was written before the standard.)
|
Why is a comma a bad record separator/delimiter in CSV files?
The problem is not the comma; the problem is quoting. Regardless of which record and field delimiters you use, you need to be prepared for meeting them in the content. So you need a quoting mechanis
|
8,421
|
Problems with pie charts
|
I wouldn't say there's an increasing interest or debate about the use of pie charts. They are just found everywhere on the web and in so-called "predictive analytic" solutions.
I guess you know Tufte's work (he also discussed the use of multiple pie charts), but more funny is the fact that the second chapter of Wilkinson's Grammar of Graphics starts with "How to make a pie chart?".
You're probably also aware that Cleveland's dotplot, or even a barchart, will convey much more precise information. The problem seems to really stem from the way our visual system is able to deal with spatial information. It is even quoted in the R software; from the on-line help for pie,
Cleveland (1985), page 264: “Data that
can be shown by pie charts always can
be shown by a dot chart. This means
that judgements of position along a
common scale can be made instead of
the less accurate angle judgements.”
This statement is based on the
empirical investigations of Cleveland
and McGill as well as investigations
by perceptual psychologists.
Cleveland, W. S. (1985) The elements
of graphing data. Wadsworth:
Monterey, CA, USA.
There are variations of pie charts (e.g., donut-like charts) that all raise the same problems: We are not good at evaluating angle and area. Even the ones used in "corrgram", as described in Friendly, Corrgrams: Exploratory displays for correlation matrices, American Statistician (2002) 56:316, are hard to read, IMHO.
At some point, however, I wondered whether they might still be useful, for example (1) displaying two classes is fine but increasing the number of categories generally worsen the reading (especially with strong imbalance between %), (2) relative judgments are better than absolute ones, that is displaying two pie charts side by side should favor a better appreciation of the results than a simple estimate from, say a pie chart mixing all results (e.g. a two-way cross-classification table). Incidentally, I asked a similar question to Hadley Wickham who kindly pointed me to the following articles:
Spence, I. (2005). No Humble Pie: The Origins and Usage of a Statistical Chart. Journal of Educational and Behavioral Statistics, 30(4), 353–368.
Heer, J. and Bostock, M. (2010). Crowdsourcing Graphical Perception: Using Mechanical Turk to Assess Visualization Design. CHI 2010, April 10–15, 2010, Atlanta, Georgia, USA.
In sum, I think they are just good for grossly depicting the distribution of 2 to 3 classes (I use them, from time to time, to show the distribution of males and females in a sample on top of an histogram of ages), but they must be accompanied by relative frequencies or counts for being really informative. A table would still do a better job since you can add margins, and go beyond 2-way classifications.
Finally, there are alternative displays that are built upon the idea of pie chart. I can think of square pie or waffle chart, described by Robert Kosara in Understanding Pie Charts.
|
Problems with pie charts
|
I wouldn't say there's an increasing interest or debate about the use of pie charts. They are just found everywhere on the web and in so-called "predictive analytic" solutions.
I guess you know Tufte
|
Problems with pie charts
I wouldn't say there's an increasing interest or debate about the use of pie charts. They are just found everywhere on the web and in so-called "predictive analytic" solutions.
I guess you know Tufte's work (he also discussed the use of multiple pie charts), but more funny is the fact that the second chapter of Wilkinson's Grammar of Graphics starts with "How to make a pie chart?".
You're probably also aware that Cleveland's dotplot, or even a barchart, will convey much more precise information. The problem seems to really stem from the way our visual system is able to deal with spatial information. It is even quoted in the R software; from the on-line help for pie,
Cleveland (1985), page 264: “Data that
can be shown by pie charts always can
be shown by a dot chart. This means
that judgements of position along a
common scale can be made instead of
the less accurate angle judgements.”
This statement is based on the
empirical investigations of Cleveland
and McGill as well as investigations
by perceptual psychologists.
Cleveland, W. S. (1985) The elements
of graphing data. Wadsworth:
Monterey, CA, USA.
There are variations of pie charts (e.g., donut-like charts) that all raise the same problems: We are not good at evaluating angle and area. Even the ones used in "corrgram", as described in Friendly, Corrgrams: Exploratory displays for correlation matrices, American Statistician (2002) 56:316, are hard to read, IMHO.
At some point, however, I wondered whether they might still be useful, for example (1) displaying two classes is fine but increasing the number of categories generally worsen the reading (especially with strong imbalance between %), (2) relative judgments are better than absolute ones, that is displaying two pie charts side by side should favor a better appreciation of the results than a simple estimate from, say a pie chart mixing all results (e.g. a two-way cross-classification table). Incidentally, I asked a similar question to Hadley Wickham who kindly pointed me to the following articles:
Spence, I. (2005). No Humble Pie: The Origins and Usage of a Statistical Chart. Journal of Educational and Behavioral Statistics, 30(4), 353–368.
Heer, J. and Bostock, M. (2010). Crowdsourcing Graphical Perception: Using Mechanical Turk to Assess Visualization Design. CHI 2010, April 10–15, 2010, Atlanta, Georgia, USA.
In sum, I think they are just good for grossly depicting the distribution of 2 to 3 classes (I use them, from time to time, to show the distribution of males and females in a sample on top of an histogram of ages), but they must be accompanied by relative frequencies or counts for being really informative. A table would still do a better job since you can add margins, and go beyond 2-way classifications.
Finally, there are alternative displays that are built upon the idea of pie chart. I can think of square pie or waffle chart, described by Robert Kosara in Understanding Pie Charts.
|
Problems with pie charts
I wouldn't say there's an increasing interest or debate about the use of pie charts. They are just found everywhere on the web and in so-called "predictive analytic" solutions.
I guess you know Tufte
|
8,422
|
Problems with pie charts
|
My personal problem with pie charts is while they may be useful to show differences like this:
way too many people use it to show that:
|
Problems with pie charts
|
My personal problem with pie charts is while they may be useful to show differences like this:
way too many people use it to show that:
|
Problems with pie charts
My personal problem with pie charts is while they may be useful to show differences like this:
way too many people use it to show that:
|
Problems with pie charts
My personal problem with pie charts is while they may be useful to show differences like this:
way too many people use it to show that:
|
8,423
|
Problems with pie charts
|
Pie charts, like pie, may be delicious but they are not nutritious.
In addition to points made already, one is that rotating a pie chart changes perception of the size of the angles, as does changing the color.
If a pie chart has only a few categories, make a table. If it has a LOT of categories, then the slices will be too thin to see (much less to label accurately).
I wrote about this on my blog. A link via the wayback machine.
|
Problems with pie charts
|
Pie charts, like pie, may be delicious but they are not nutritious.
In addition to points made already, one is that rotating a pie chart changes perception of the size of the angles, as does changing
|
Problems with pie charts
Pie charts, like pie, may be delicious but they are not nutritious.
In addition to points made already, one is that rotating a pie chart changes perception of the size of the angles, as does changing the color.
If a pie chart has only a few categories, make a table. If it has a LOT of categories, then the slices will be too thin to see (much less to label accurately).
I wrote about this on my blog. A link via the wayback machine.
|
Problems with pie charts
Pie charts, like pie, may be delicious but they are not nutritious.
In addition to points made already, one is that rotating a pie chart changes perception of the size of the angles, as does changing
|
8,424
|
Problems with pie charts
|
I think you've answered your own question for the 2nd bullet point. If you want to take up valuable real estate, so be it! However the first bullet is more important. With a bar chart the observer needs to estimate relative proportion based upon only 1 axis. With a pie chart judging along at least 2 axes are involved. And one axis is curved.
I think that pie charts are used most effectively when you have many categories in the pie, with a legend, and it is not all that important to judge proportion.
|
Problems with pie charts
|
I think you've answered your own question for the 2nd bullet point. If you want to take up valuable real estate, so be it! However the first bullet is more important. With a bar chart the observer n
|
Problems with pie charts
I think you've answered your own question for the 2nd bullet point. If you want to take up valuable real estate, so be it! However the first bullet is more important. With a bar chart the observer needs to estimate relative proportion based upon only 1 axis. With a pie chart judging along at least 2 axes are involved. And one axis is curved.
I think that pie charts are used most effectively when you have many categories in the pie, with a legend, and it is not all that important to judge proportion.
|
Problems with pie charts
I think you've answered your own question for the 2nd bullet point. If you want to take up valuable real estate, so be it! However the first bullet is more important. With a bar chart the observer n
|
8,425
|
Problems with pie charts
|
I can think of almost no case in which a pie chart is better than a bar chart or stacked bar if you want to convey information.
I do have a theory or two on how pie charts got to be so popular. My first thought is related to PC commercials. Early PCs had text screens (24 x 80 characters), often green like old mainframe CRTs. To show off the new graphics screens that had a Red-Green-Blue pixel basis, a pie chart was ideal. A text screen could do a bar chart after a fashion, but couldn't do a remotely credible pie chart. Pie charts looked a lot more serious than showing a Mario Brothers screen, regardless of how the PC would actually be used. Thus, it seemed like every PC commercial in the late 1980s and early 1990s showed a pie chart on the monitor.
A second theory is that a bar chart or stacked bar is better if you want to convey information. But what if you don't? Then a pie chart works -- and charts with 3-D effects work even better.
|
Problems with pie charts
|
I can think of almost no case in which a pie chart is better than a bar chart or stacked bar if you want to convey information.
I do have a theory or two on how pie charts got to be so popular. My fi
|
Problems with pie charts
I can think of almost no case in which a pie chart is better than a bar chart or stacked bar if you want to convey information.
I do have a theory or two on how pie charts got to be so popular. My first thought is related to PC commercials. Early PCs had text screens (24 x 80 characters), often green like old mainframe CRTs. To show off the new graphics screens that had a Red-Green-Blue pixel basis, a pie chart was ideal. A text screen could do a bar chart after a fashion, but couldn't do a remotely credible pie chart. Pie charts looked a lot more serious than showing a Mario Brothers screen, regardless of how the PC would actually be used. Thus, it seemed like every PC commercial in the late 1980s and early 1990s showed a pie chart on the monitor.
A second theory is that a bar chart or stacked bar is better if you want to convey information. But what if you don't? Then a pie chart works -- and charts with 3-D effects work even better.
|
Problems with pie charts
I can think of almost no case in which a pie chart is better than a bar chart or stacked bar if you want to convey information.
I do have a theory or two on how pie charts got to be so popular. My fi
|
8,426
|
Problems with pie charts
|
Your waffle chart needs the red and blue values switched. As to the question of pie vs waffle, I lean toward waffle. With waffle charts you can still get the information across at small sizes even if the blocks blend together, the color still represents the regions.
|
Problems with pie charts
|
Your waffle chart needs the red and blue values switched. As to the question of pie vs waffle, I lean toward waffle. With waffle charts you can still get the information across at small sizes even if
|
Problems with pie charts
Your waffle chart needs the red and blue values switched. As to the question of pie vs waffle, I lean toward waffle. With waffle charts you can still get the information across at small sizes even if the blocks blend together, the color still represents the regions.
|
Problems with pie charts
Your waffle chart needs the red and blue values switched. As to the question of pie vs waffle, I lean toward waffle. With waffle charts you can still get the information across at small sizes even if
|
8,427
|
How can we explain the "bad reputation" of higher-order polynomials?
|
High degree polynomials do not overfit the data
This is a common misconception which is nonetheless found in many textbooks.
In general, in order to specify a statistical model, it is necessary to specify both a hypothesis class and a fitting procedure. In order to define the Variance of the model ("variance" here in the sense of Bias-Variance Tradeoff), it is necessary to know how to fit the model, so claiming that a hypothesis class (like polynomials) can overfit the data is simply a category error.
To illustrate this point, consider that the Lagrange interpolation method is only one of several ways to fit a polynomial to a collection of points. Another method is to use Bernstein polynomials. Given $n$ observation points $x_i=i/n$ and $y_i=f(x_i)+\epsilon_i$, the Bernstein approximant is, like the Lagrange approximant, a polynomial of degree $n-1$ (i.e., as many degrees of freedom as there are data points). However, we can see that the fitted Bernstein polynomials do not exhibit the wild oscillations that the Lagrange polynomials do. Even more strikingly, the variance of the Bernstein fits actually decreases as we add more points (and thus increase the degree of the polynomials).
As you can see, the Bernstein polynomial does not pass through each point. This reflects the fact that it uses a different fitting procedure than the Lagrange polynomial. But both models have the exact same hypothesis class (the set of degree $n-1$ polynomials), which underscores that it is incoherent to talk about statistical properties of a hypothesis class without also specifying the loss function and fitting procedure.
As a second example, it is also possible to exactly interpolate the training data using a polynomial without wild oscillations, assuming we are working over complex numbers. If the observation points $x_i$ lie along the unit circle $x_i=e^{2\pi i\sqrt{-1}/N}$, then fitting a polynomial $y_i=\sum_d c_dx_i^d$ basically comes down to computing the inverse Fourier transform of $y_i$. Below I plot the complex polynomial interpolant as a function of the complex argument $i/N$. Moreover, it turns out that the variance of this interpolant is constant as a function of $n$.
Code for these simulations can be found at the end of this answer.
In summary,
It is simply false that including higher degree polynomials will increase the variance of the model, or make it more prone to overfit
As a consequence, any explanation of why Lagrange interpolants do in fact overfit will need to use the actual structure of the model and fitting procedure, and cannot be based on general parameter-counting arguments.
Fortunately, it is not too hard to mathematically show why Lagrange interpolants do exhibit this overfitting. What is basically comes down to is that fitting the Lagrange interpolant requires inversion of a Vandermonde matrix, which are often ill-conditioned.
More formally, what we want to do is to show that the variance of the Lagrange interpolants grows very quickly as a function of $n$, the number of data points. It is not too hard to establish the following quantiative bound:
proposition
Let $x_i=i/n$ for $i=1,\dots,n$. Let $\epsilon_i\sim N(0,1)$ be iid noise, and let $p_{\epsilon}(x)$ be the interpolating polynomial through the points $(x_i,y_i+\epsilon_i)$. Then the average variance $\int_0^1 Var_{\epsilon}p_{\epsilon}(x)dx$ grows at least as $O(e^{(1.5-\log 4)n})$.
proof of proposition
Let our interpolating polynomial be given by $p(x)=\sum_{d=0}^{n-1}w_d x^d$. Evidently p must satisfy $y_i=p(x_i)=\sum_{d=0}^{n-1}w_d x_i^d=(Vw)_i$ where the vandermonde matrix $V$ is defined by $V_{ij}=x_i^{j-1}$.
So we have the formula $w=V^{-1}y$ for the coefficients of the interpolating polynomial. As a warmup, we'll first consider the variance of the coefficient vector $w$, and then generalize the argument to analyze the variance of the polynomial $p(x)$.
coefficient variance
We want to compute the variance of $w$, that is
$$Var(w):= E_{\epsilon} \|w-E_{\epsilon} w\|^2$$
If we write $w=V^{-1}y+V^{-1}\epsilon$, then the first term is constant (does not depend on epsilon), while the second term has zero mean. Because the variance is translation invariant,
$$Var(w)=E_{\epsilon} \|V^{-1}\epsilon\|^2=E_{\epsilon} \epsilon^t (V^{-1})^tV^{-1}\epsilon=Tr( (V^{-1})^t V^{-1})=Tr((VV^t)^{-1})$$
Thus the variance of the coefficients is directly related to the eigenvalues of the matrix $VV^t$- the smaller these eigenvalues, the larger the variance. Now it becomes clear why the conditioning of $V$ is so important.
In the above discussion, the values of the $x_i$s was arbitrary, but let us now assume that they are evenly spaced in the unit interval: $x_i=i/n$. In this case, we can work out an explicit lower bound for the variance.
Firstly, note that $Tr(M)/n\geq det(M)^{1/n}$ for any symmetric positive definite matrix (this follows immediately from the AMGM inequality). In our case,
$$Var(w)\geq n |det(V)|^{-2/n}$$
Now, the determinant of a vandermonde matrix has the well-known formula $det(V)=\prod_{i<j} x_j-x_i$. Under our definition of $x_i$, this is
$$det(V)=\prod_{i<j}(j-i)/n=n^{-(n^2-n)/2}\prod_{i<j}j-i=n^{-(n^2-n)/2} \prod_{i=1}^{n-1} i!$$
(To see the last step, note that there are $n-1$ pairs $i,j$ such that $j-i=1$, there are $n-2$ pairs such that $j-i=2$ etc. )
The product of factorials is called the \textit{superfactorial}. Similarly to how the factorials are interpolated by the gamma function, the superfactorials are interpolated by an analytic function called the Barnes G function, $G$. More precisely, we have $G(n+1)= \prod_{i=1}^{n-1} i!$ when $n$ is a positive integer. Furthermore, there is an analogue of Stirling's formula:
$$\log G(n+1)= .5*n^2\log n-.75*n^2+n\log \sqrt{2\pi}+O(log(n))$$
So the determinant goes like
$$\log |Det(V)|\sim -(n^2-n)/2\log n+(n^2/2)\log n-3n^2/4+n\log \sqrt{2\pi}+...=-3n^2/4-(n/2)\log n+n\log \sqrt{2\pi}+...$$
So by the inequality for the variance,
$$\log Var(w)\geq \log n -(2/n)\log |det(V)|=3n/2+2log n-\log 2\pi$$
Or said a bit more succinctly, $Var(w)=O(e^{3n/2})$, that is the variance grows exponentially.
prediction variance
To bound the variance of the model predictions, which is what we ultimately care about, it is necessary to modify the above argument only slightly.
As a bit of notation, define $pow(x)$ to be the vector $pow(x)_i=x^{i-1}$. Observing as before that $w$ decomposes into a constant $V^{-1}y$ and a mean-zero term $V^{-1}\epsilon$, we have that
$$Var(x)=Var_{\epsilon} \sum_d (V^{-1}\epsilon)_d x^d=Var_{\epsilon}pow(x)^t (V^{-1}\epsilon)=\|V^{-1}pow(x)\|^2$$
Integrating over $x$,
\begin{eqnarray*}
Var&=&\int Var(x)dx=\int Tr(V^{-1}pow(x)pow(x)^t(V^{-1})^t))dx\\
&=& Tr(V^{-1}(\int pow(x)pow(x)^tdx)(V^{-1})^t))\\
& = & Tr(V^{-1}H_n(V^{-1})^t)
\end{eqnarray*}
where $H_n$ is the Hilbert matrix given by $(H_n)_{ij}=1/(i+j-1)=\int_0^1 x^{i+j-2}dx$.
We want to bound this from below, arguing as before we can reduce this to a determinant calculation:
$$Var=Tr(V^{-1}H_n(V^{-1})^t)\geq n det (V^{-1}H_n(V^{-1})^t)^{1/n}=n |det V|^{-2/n}|det H|^{1/n}$$
Now, the Hilbert determinant has a well-known asumptotic expansion:
$$\log det (H)\sim -n^2 \log(4)+n\log 2\pi +...$$
Thus the dominant term in $|det(H)|^{1/n}$ will be $e^{-n \log 4}$.
On the other hand, we saw above that $n |det(V)|^{-n/2}$ has dominant term $e^{3n/2}$.
Thus we can conclude that $Var=O(e^{(3/2-\log 4)n})$. Note crucially that $3/2>\log 4$, so that the variance indeed increases exponentially. This concludes the proof.
Edit: analysis of Bernstein variance
As an interesting comparison, it is not too hard to work out the variance for the Bernstein approximator. This polynomial is defined by $\hat{B}(x)=\sum_i b_{i,n}(x)y_i$, where $b_{i,n}$ are the Bernstein basis polynomials, as defined in the Wikipedia link. Arguing similarly as before, the variance with respect to different samplings of $y$ is $\sum_i b_{i,n}(x)^2$. As in the simulation, I'll average over $x\in [0,1]$. Evidently $\int_0^1 b_{i,n}(x)^2dx={n\choose i}^2B(2i+1,2n-2i+1)$, with $B$ the beta function. We have to sum this over $i$. I claim the sum comes to: $$\int_0^1 Var(\hat{B}(x))dx={\frac {4^n}{(2n+1){2n\choose n}}}$$
(proof is below)
This formula does indeed closely match the empirical results from the simulation (note that for direct comparison, you will have to multiply by $.1^2$, which was the noise variance used in the simulation). By Stirling's formula, the variance of the Bernstein approximator goes as $O(n^{-.5})$.
Proof of variance formula
The first step is to use the identity $B(2i+1,2n-2i+1)=(2i)!(2n-2i)!/(2n)!$. So we get
\begin{eqnarray*}
{n\choose i}^2 B(2i+1,2n-2i+1) & = & {\frac {(n!)^2}{(i!)^2(n-i)!^2}}{\frac {(2i)!(2n-2i)!}{(2n+1)!}}\\
& = & {\frac 1 {2n+1}}{2n\choose n}^{-1}{2i\choose i}{2n-2i\choose n-i}
\end{eqnarray*}
Using the generating function $\sum_{i=0}^{\infty} {2i\choose i}x^i=(1-4x)^{-1/2}$, we see that $\sum_{i=0}^n {2i\choose i}{2n-2i\choose n-i}$ is the coefficient of $x^n$ in $((1-4x)^{-1/2})^2=(1-4x)^{-1}$, that is $4^n$. Summing over $i$ we get the claimed formula for the variance.
Edit: effect of distribution of x points on Lagrange variance
As shown in the very interesting answer of Robert Mastragostino, the bad behavior of the Lagrange polynomial can be avoided through judicious choice of $x_i$. This raises the possibility that the lagrange polynomial does uncharacteristically badly for uniformly sampled points. In principle, given iid sample points $x_i\sim \mu$ it is possible that the lagrange polynomials behave sensibly for most choices of $\mu$, with the uniform distribution being just an ``unlucky choice". However, this is not the case, and it turns out that the Lagrange variance still grows exponentially for any choice of $\mu$, with the single exception of the arcsine distribution $d\mu(x)=\textbf{1}_{(-1,1)}\pi^{-1}(1-x^2)^{-1/2}dx$. Note that in Robert Mastragostino's answer, the $x_i$ points are chosen to be Chebyshev nodes. As $n\to\infty$, the density of these points converges to none other than the arcsine distribution. So in a sense, the situation in his answer is the only exception to the rule of exponential growth of the variance.
More precisely,take any continuous distribution $\mu(dx)=p(x)dx$ supported on $(-1,1)$ and consider an infinite sequence of points $\{(x_i,f(x_i)+\epsilon_i)\}_{i=1,\infty}$ where $x_i\sim \mu$ are iid, $f$ is a continuous function and $\epsilon_i$ are iid normal samples. Let $\hat{f_n}(x)$ denote the Lagrange interpolant fitted on the first $n$ points. And let $V_n=\int Var(\hat{f_n})(x)p(x)dx$ denote the corresponding average variance.
Claim: Assume that (1): $p(x)>0$ for all $x\in (-1,1)$ and (2): $\int p(x)^2\sqrt{1-x^2}dx<\infty$. Then $V_n$ grows at least like $O(e^{\epsilon n})$ for some $\epsilon>0$, unless $p$ is the arcsine distribution.
To prove this, note that, as before, $Var(\hat{f_n}(x))=\sum_{i=1}^nl_{i,n}^2$, where now $l_{i,n}$ denotes the ith Lagrange basis polynomial wrt the first $n$ points. Now,
\begin{eqnarray*}
\log \int l_{i,n}^2(x)d\mu(x)&\geq& 2\int \log |l_{i,n}(x)|p(x)dx\\
& = & 2\int \sum_{j\neq i, j\leq n} \left(\log |x-x_j|-\log |x_i-x_j|\right)p(x)dx
\end{eqnarray*}
where we used Jensen's inequality in the first line, and the definition of $l_{i,n}$ in the second.
Let us introduce the following notation:
\begin{eqnarray*}
f_p(x)&=&\int \log|x-y|p(y)dy\\
c_p& = & \int \log |x-y|p(x)p(y)dxdy
\end{eqnarray*}
Then we get
\begin{eqnarray*}\lim\inf n^{-1}\log \int l_{i,n}^2(x)p(x)dx&\geq& 2\lim\inf_n n^{-1}\int \sum_{j\neq i, j\leq n} \left(\log |x-x_j|-\log |x_i-x_j|\right)p(x)dx\\
& \geq & 2 \int \lim\inf_n n^{-1}\sum_{j\neq i, 1,j\leq n} \left(\log |x-x_j|-\log |x_i-x_j|\right)p(x)dx\\
& = & 2\int \left(f_p(x)-f_p(x_i)\right)p(x)dx\\
& = & 2(c_p-f_p(x_i))
\end{eqnarray*}
using Fatou's lemma, and then the strong law of large numbers.
Note that $f_p'(x)=H_p(x)$, where $H_p(x)=\int {\frac {p(y)}{x-y}}dy$ is the Hilbert transform of $p$. In particular, $f_p$ is continuous. Now, suppose it is the case that $f_p(x)$ is non-constant. In this case, there exists $\epsilon>0$ as well as an interval $[a,b]$ such that $\inf_{x'\in [a,b]}c_p-f_p(x')\geq\epsilon/2$. By assumption (1), $\int_a^b p(x)dx>0$, so accordingly, $P(\exists i: x_i\in [a,b])=1$. We can reorder finitely many samples without changing the distribution, so WLOG we may assume that $x_1\in [a,b]$. As a consequence $2(c_p-f_p(x_1))\geq\epsilon$.
Combining with the above, we get
$$n^{-1}\log \int l_{1,n}^2(x)p(x)dx\geq \epsilon$$
for all $n$ sufficiently large. By simple rearrangement, this is equivalent to $\int l_{1,n}^2(x)p(x)dx\geq e^{n\epsilon}$ and since $V_n=\int \sum_{i=1}^n l_{i,n}^2(x)p(x)dx \geq \int l_{1,n}^2(x)p(x)dx$ we get the claimed exponential growth, assuming $f_p$ is non-constant.
So the last step is to show that $f_p$ is non-constant if $p$ is not the arcsine distribution, or equivalently, that the hilbert transform $H_p$ is not identically zero. Under assumption (2), this follows from a theorem of Tricomi. Thus we have proved the Claim.
Code for Bernstein polynomials
from scipy.special import binom
import numpy as np
import matplotlib.pyplot as plt
variances=[]
n_range=[5,10,20,50,100]
for n in n_range:
preds=[]
for _ in range(1000):
xs=np.linspace(0,1,100)
X=np.linspace(0,1,n+1)
Y=np.sin(8*X)+np.random.randn(n+1)*.1
nu=np.arange(n+1)
bern=binom(n,nu)[:,None]*(xs[None,:])**(nu[:,None])*(1-xs[None,:])**(n-nu[:,None])*Y[:,None]
pred=bern.sum(0)
preds.append(pred)
preds=np.array(preds)
variances.append(preds.var(0).mean())
variances=np.array(variances)
plt.scatter(n_range,variances)
plt.xlabel('n')
plt.ylabel('variance')
plt.ylim(0,.005)
plt.title('bernstein polynomial variance')
Code for complex polynomials
n=64
xarg=np.linspace(0,2*np.pi,n+1,endpoint=True)[:n]
y=np.sin(2.5*xarg)+.25*np.random.randn(n)
xcomp=np.exp(1j*xarg)
xs=np.linspace(0,2*np.pi,200)
ys=np.sin(2.5*xs)
X=np.array([xcomp**i for i in range(len(xarg))])
w=np.linalg.solve(X,y)
#only need to go up to middle frequency, bc later ones are complex conjugates
interp=2*np.dot(w[1:n//2+1],np.array([np.exp(1j*xs*i) for i in range(1,n//2+1)]))+w2[0]
plt.plot(xs,interp.real,label='complex polynomial interp')
plt.plot(xs,ys,c='gray',linestyle='--',label='true function')
plt.scatter(xarg,y)
plt.xlabel('complex argument')
plt.legend()
|
How can we explain the "bad reputation" of higher-order polynomials?
|
High degree polynomials do not overfit the data
This is a common misconception which is nonetheless found in many textbooks.
In general, in order to specify a statistical model, it is necessary to spe
|
How can we explain the "bad reputation" of higher-order polynomials?
High degree polynomials do not overfit the data
This is a common misconception which is nonetheless found in many textbooks.
In general, in order to specify a statistical model, it is necessary to specify both a hypothesis class and a fitting procedure. In order to define the Variance of the model ("variance" here in the sense of Bias-Variance Tradeoff), it is necessary to know how to fit the model, so claiming that a hypothesis class (like polynomials) can overfit the data is simply a category error.
To illustrate this point, consider that the Lagrange interpolation method is only one of several ways to fit a polynomial to a collection of points. Another method is to use Bernstein polynomials. Given $n$ observation points $x_i=i/n$ and $y_i=f(x_i)+\epsilon_i$, the Bernstein approximant is, like the Lagrange approximant, a polynomial of degree $n-1$ (i.e., as many degrees of freedom as there are data points). However, we can see that the fitted Bernstein polynomials do not exhibit the wild oscillations that the Lagrange polynomials do. Even more strikingly, the variance of the Bernstein fits actually decreases as we add more points (and thus increase the degree of the polynomials).
As you can see, the Bernstein polynomial does not pass through each point. This reflects the fact that it uses a different fitting procedure than the Lagrange polynomial. But both models have the exact same hypothesis class (the set of degree $n-1$ polynomials), which underscores that it is incoherent to talk about statistical properties of a hypothesis class without also specifying the loss function and fitting procedure.
As a second example, it is also possible to exactly interpolate the training data using a polynomial without wild oscillations, assuming we are working over complex numbers. If the observation points $x_i$ lie along the unit circle $x_i=e^{2\pi i\sqrt{-1}/N}$, then fitting a polynomial $y_i=\sum_d c_dx_i^d$ basically comes down to computing the inverse Fourier transform of $y_i$. Below I plot the complex polynomial interpolant as a function of the complex argument $i/N$. Moreover, it turns out that the variance of this interpolant is constant as a function of $n$.
Code for these simulations can be found at the end of this answer.
In summary,
It is simply false that including higher degree polynomials will increase the variance of the model, or make it more prone to overfit
As a consequence, any explanation of why Lagrange interpolants do in fact overfit will need to use the actual structure of the model and fitting procedure, and cannot be based on general parameter-counting arguments.
Fortunately, it is not too hard to mathematically show why Lagrange interpolants do exhibit this overfitting. What is basically comes down to is that fitting the Lagrange interpolant requires inversion of a Vandermonde matrix, which are often ill-conditioned.
More formally, what we want to do is to show that the variance of the Lagrange interpolants grows very quickly as a function of $n$, the number of data points. It is not too hard to establish the following quantiative bound:
proposition
Let $x_i=i/n$ for $i=1,\dots,n$. Let $\epsilon_i\sim N(0,1)$ be iid noise, and let $p_{\epsilon}(x)$ be the interpolating polynomial through the points $(x_i,y_i+\epsilon_i)$. Then the average variance $\int_0^1 Var_{\epsilon}p_{\epsilon}(x)dx$ grows at least as $O(e^{(1.5-\log 4)n})$.
proof of proposition
Let our interpolating polynomial be given by $p(x)=\sum_{d=0}^{n-1}w_d x^d$. Evidently p must satisfy $y_i=p(x_i)=\sum_{d=0}^{n-1}w_d x_i^d=(Vw)_i$ where the vandermonde matrix $V$ is defined by $V_{ij}=x_i^{j-1}$.
So we have the formula $w=V^{-1}y$ for the coefficients of the interpolating polynomial. As a warmup, we'll first consider the variance of the coefficient vector $w$, and then generalize the argument to analyze the variance of the polynomial $p(x)$.
coefficient variance
We want to compute the variance of $w$, that is
$$Var(w):= E_{\epsilon} \|w-E_{\epsilon} w\|^2$$
If we write $w=V^{-1}y+V^{-1}\epsilon$, then the first term is constant (does not depend on epsilon), while the second term has zero mean. Because the variance is translation invariant,
$$Var(w)=E_{\epsilon} \|V^{-1}\epsilon\|^2=E_{\epsilon} \epsilon^t (V^{-1})^tV^{-1}\epsilon=Tr( (V^{-1})^t V^{-1})=Tr((VV^t)^{-1})$$
Thus the variance of the coefficients is directly related to the eigenvalues of the matrix $VV^t$- the smaller these eigenvalues, the larger the variance. Now it becomes clear why the conditioning of $V$ is so important.
In the above discussion, the values of the $x_i$s was arbitrary, but let us now assume that they are evenly spaced in the unit interval: $x_i=i/n$. In this case, we can work out an explicit lower bound for the variance.
Firstly, note that $Tr(M)/n\geq det(M)^{1/n}$ for any symmetric positive definite matrix (this follows immediately from the AMGM inequality). In our case,
$$Var(w)\geq n |det(V)|^{-2/n}$$
Now, the determinant of a vandermonde matrix has the well-known formula $det(V)=\prod_{i<j} x_j-x_i$. Under our definition of $x_i$, this is
$$det(V)=\prod_{i<j}(j-i)/n=n^{-(n^2-n)/2}\prod_{i<j}j-i=n^{-(n^2-n)/2} \prod_{i=1}^{n-1} i!$$
(To see the last step, note that there are $n-1$ pairs $i,j$ such that $j-i=1$, there are $n-2$ pairs such that $j-i=2$ etc. )
The product of factorials is called the \textit{superfactorial}. Similarly to how the factorials are interpolated by the gamma function, the superfactorials are interpolated by an analytic function called the Barnes G function, $G$. More precisely, we have $G(n+1)= \prod_{i=1}^{n-1} i!$ when $n$ is a positive integer. Furthermore, there is an analogue of Stirling's formula:
$$\log G(n+1)= .5*n^2\log n-.75*n^2+n\log \sqrt{2\pi}+O(log(n))$$
So the determinant goes like
$$\log |Det(V)|\sim -(n^2-n)/2\log n+(n^2/2)\log n-3n^2/4+n\log \sqrt{2\pi}+...=-3n^2/4-(n/2)\log n+n\log \sqrt{2\pi}+...$$
So by the inequality for the variance,
$$\log Var(w)\geq \log n -(2/n)\log |det(V)|=3n/2+2log n-\log 2\pi$$
Or said a bit more succinctly, $Var(w)=O(e^{3n/2})$, that is the variance grows exponentially.
prediction variance
To bound the variance of the model predictions, which is what we ultimately care about, it is necessary to modify the above argument only slightly.
As a bit of notation, define $pow(x)$ to be the vector $pow(x)_i=x^{i-1}$. Observing as before that $w$ decomposes into a constant $V^{-1}y$ and a mean-zero term $V^{-1}\epsilon$, we have that
$$Var(x)=Var_{\epsilon} \sum_d (V^{-1}\epsilon)_d x^d=Var_{\epsilon}pow(x)^t (V^{-1}\epsilon)=\|V^{-1}pow(x)\|^2$$
Integrating over $x$,
\begin{eqnarray*}
Var&=&\int Var(x)dx=\int Tr(V^{-1}pow(x)pow(x)^t(V^{-1})^t))dx\\
&=& Tr(V^{-1}(\int pow(x)pow(x)^tdx)(V^{-1})^t))\\
& = & Tr(V^{-1}H_n(V^{-1})^t)
\end{eqnarray*}
where $H_n$ is the Hilbert matrix given by $(H_n)_{ij}=1/(i+j-1)=\int_0^1 x^{i+j-2}dx$.
We want to bound this from below, arguing as before we can reduce this to a determinant calculation:
$$Var=Tr(V^{-1}H_n(V^{-1})^t)\geq n det (V^{-1}H_n(V^{-1})^t)^{1/n}=n |det V|^{-2/n}|det H|^{1/n}$$
Now, the Hilbert determinant has a well-known asumptotic expansion:
$$\log det (H)\sim -n^2 \log(4)+n\log 2\pi +...$$
Thus the dominant term in $|det(H)|^{1/n}$ will be $e^{-n \log 4}$.
On the other hand, we saw above that $n |det(V)|^{-n/2}$ has dominant term $e^{3n/2}$.
Thus we can conclude that $Var=O(e^{(3/2-\log 4)n})$. Note crucially that $3/2>\log 4$, so that the variance indeed increases exponentially. This concludes the proof.
Edit: analysis of Bernstein variance
As an interesting comparison, it is not too hard to work out the variance for the Bernstein approximator. This polynomial is defined by $\hat{B}(x)=\sum_i b_{i,n}(x)y_i$, where $b_{i,n}$ are the Bernstein basis polynomials, as defined in the Wikipedia link. Arguing similarly as before, the variance with respect to different samplings of $y$ is $\sum_i b_{i,n}(x)^2$. As in the simulation, I'll average over $x\in [0,1]$. Evidently $\int_0^1 b_{i,n}(x)^2dx={n\choose i}^2B(2i+1,2n-2i+1)$, with $B$ the beta function. We have to sum this over $i$. I claim the sum comes to: $$\int_0^1 Var(\hat{B}(x))dx={\frac {4^n}{(2n+1){2n\choose n}}}$$
(proof is below)
This formula does indeed closely match the empirical results from the simulation (note that for direct comparison, you will have to multiply by $.1^2$, which was the noise variance used in the simulation). By Stirling's formula, the variance of the Bernstein approximator goes as $O(n^{-.5})$.
Proof of variance formula
The first step is to use the identity $B(2i+1,2n-2i+1)=(2i)!(2n-2i)!/(2n)!$. So we get
\begin{eqnarray*}
{n\choose i}^2 B(2i+1,2n-2i+1) & = & {\frac {(n!)^2}{(i!)^2(n-i)!^2}}{\frac {(2i)!(2n-2i)!}{(2n+1)!}}\\
& = & {\frac 1 {2n+1}}{2n\choose n}^{-1}{2i\choose i}{2n-2i\choose n-i}
\end{eqnarray*}
Using the generating function $\sum_{i=0}^{\infty} {2i\choose i}x^i=(1-4x)^{-1/2}$, we see that $\sum_{i=0}^n {2i\choose i}{2n-2i\choose n-i}$ is the coefficient of $x^n$ in $((1-4x)^{-1/2})^2=(1-4x)^{-1}$, that is $4^n$. Summing over $i$ we get the claimed formula for the variance.
Edit: effect of distribution of x points on Lagrange variance
As shown in the very interesting answer of Robert Mastragostino, the bad behavior of the Lagrange polynomial can be avoided through judicious choice of $x_i$. This raises the possibility that the lagrange polynomial does uncharacteristically badly for uniformly sampled points. In principle, given iid sample points $x_i\sim \mu$ it is possible that the lagrange polynomials behave sensibly for most choices of $\mu$, with the uniform distribution being just an ``unlucky choice". However, this is not the case, and it turns out that the Lagrange variance still grows exponentially for any choice of $\mu$, with the single exception of the arcsine distribution $d\mu(x)=\textbf{1}_{(-1,1)}\pi^{-1}(1-x^2)^{-1/2}dx$. Note that in Robert Mastragostino's answer, the $x_i$ points are chosen to be Chebyshev nodes. As $n\to\infty$, the density of these points converges to none other than the arcsine distribution. So in a sense, the situation in his answer is the only exception to the rule of exponential growth of the variance.
More precisely,take any continuous distribution $\mu(dx)=p(x)dx$ supported on $(-1,1)$ and consider an infinite sequence of points $\{(x_i,f(x_i)+\epsilon_i)\}_{i=1,\infty}$ where $x_i\sim \mu$ are iid, $f$ is a continuous function and $\epsilon_i$ are iid normal samples. Let $\hat{f_n}(x)$ denote the Lagrange interpolant fitted on the first $n$ points. And let $V_n=\int Var(\hat{f_n})(x)p(x)dx$ denote the corresponding average variance.
Claim: Assume that (1): $p(x)>0$ for all $x\in (-1,1)$ and (2): $\int p(x)^2\sqrt{1-x^2}dx<\infty$. Then $V_n$ grows at least like $O(e^{\epsilon n})$ for some $\epsilon>0$, unless $p$ is the arcsine distribution.
To prove this, note that, as before, $Var(\hat{f_n}(x))=\sum_{i=1}^nl_{i,n}^2$, where now $l_{i,n}$ denotes the ith Lagrange basis polynomial wrt the first $n$ points. Now,
\begin{eqnarray*}
\log \int l_{i,n}^2(x)d\mu(x)&\geq& 2\int \log |l_{i,n}(x)|p(x)dx\\
& = & 2\int \sum_{j\neq i, j\leq n} \left(\log |x-x_j|-\log |x_i-x_j|\right)p(x)dx
\end{eqnarray*}
where we used Jensen's inequality in the first line, and the definition of $l_{i,n}$ in the second.
Let us introduce the following notation:
\begin{eqnarray*}
f_p(x)&=&\int \log|x-y|p(y)dy\\
c_p& = & \int \log |x-y|p(x)p(y)dxdy
\end{eqnarray*}
Then we get
\begin{eqnarray*}\lim\inf n^{-1}\log \int l_{i,n}^2(x)p(x)dx&\geq& 2\lim\inf_n n^{-1}\int \sum_{j\neq i, j\leq n} \left(\log |x-x_j|-\log |x_i-x_j|\right)p(x)dx\\
& \geq & 2 \int \lim\inf_n n^{-1}\sum_{j\neq i, 1,j\leq n} \left(\log |x-x_j|-\log |x_i-x_j|\right)p(x)dx\\
& = & 2\int \left(f_p(x)-f_p(x_i)\right)p(x)dx\\
& = & 2(c_p-f_p(x_i))
\end{eqnarray*}
using Fatou's lemma, and then the strong law of large numbers.
Note that $f_p'(x)=H_p(x)$, where $H_p(x)=\int {\frac {p(y)}{x-y}}dy$ is the Hilbert transform of $p$. In particular, $f_p$ is continuous. Now, suppose it is the case that $f_p(x)$ is non-constant. In this case, there exists $\epsilon>0$ as well as an interval $[a,b]$ such that $\inf_{x'\in [a,b]}c_p-f_p(x')\geq\epsilon/2$. By assumption (1), $\int_a^b p(x)dx>0$, so accordingly, $P(\exists i: x_i\in [a,b])=1$. We can reorder finitely many samples without changing the distribution, so WLOG we may assume that $x_1\in [a,b]$. As a consequence $2(c_p-f_p(x_1))\geq\epsilon$.
Combining with the above, we get
$$n^{-1}\log \int l_{1,n}^2(x)p(x)dx\geq \epsilon$$
for all $n$ sufficiently large. By simple rearrangement, this is equivalent to $\int l_{1,n}^2(x)p(x)dx\geq e^{n\epsilon}$ and since $V_n=\int \sum_{i=1}^n l_{i,n}^2(x)p(x)dx \geq \int l_{1,n}^2(x)p(x)dx$ we get the claimed exponential growth, assuming $f_p$ is non-constant.
So the last step is to show that $f_p$ is non-constant if $p$ is not the arcsine distribution, or equivalently, that the hilbert transform $H_p$ is not identically zero. Under assumption (2), this follows from a theorem of Tricomi. Thus we have proved the Claim.
Code for Bernstein polynomials
from scipy.special import binom
import numpy as np
import matplotlib.pyplot as plt
variances=[]
n_range=[5,10,20,50,100]
for n in n_range:
preds=[]
for _ in range(1000):
xs=np.linspace(0,1,100)
X=np.linspace(0,1,n+1)
Y=np.sin(8*X)+np.random.randn(n+1)*.1
nu=np.arange(n+1)
bern=binom(n,nu)[:,None]*(xs[None,:])**(nu[:,None])*(1-xs[None,:])**(n-nu[:,None])*Y[:,None]
pred=bern.sum(0)
preds.append(pred)
preds=np.array(preds)
variances.append(preds.var(0).mean())
variances=np.array(variances)
plt.scatter(n_range,variances)
plt.xlabel('n')
plt.ylabel('variance')
plt.ylim(0,.005)
plt.title('bernstein polynomial variance')
Code for complex polynomials
n=64
xarg=np.linspace(0,2*np.pi,n+1,endpoint=True)[:n]
y=np.sin(2.5*xarg)+.25*np.random.randn(n)
xcomp=np.exp(1j*xarg)
xs=np.linspace(0,2*np.pi,200)
ys=np.sin(2.5*xs)
X=np.array([xcomp**i for i in range(len(xarg))])
w=np.linalg.solve(X,y)
#only need to go up to middle frequency, bc later ones are complex conjugates
interp=2*np.dot(w[1:n//2+1],np.array([np.exp(1j*xs*i) for i in range(1,n//2+1)]))+w2[0]
plt.plot(xs,interp.real,label='complex polynomial interp')
plt.plot(xs,ys,c='gray',linestyle='--',label='true function')
plt.scatter(xarg,y)
plt.xlabel('complex argument')
plt.legend()
|
How can we explain the "bad reputation" of higher-order polynomials?
High degree polynomials do not overfit the data
This is a common misconception which is nonetheless found in many textbooks.
In general, in order to specify a statistical model, it is necessary to spe
|
8,428
|
How can we explain the "bad reputation" of higher-order polynomials?
|
Before I attempt to answer this, I'd like to just point out that what you are observing here (overfitting in a linear regression) is just a specific example of a more general phenomenon, bias-variance trade-off, which is also observed in more "modern" machine learning contexts as well as the "classical" setting of regression fitting. Your question could probably be expanded and rephrased more generally as something like, "why do high complexity models (e.g., those with larger numbers of adjustable parameters, such as higher degree polynomials) usually exhibit higher variance?" I've never seen a really good general mathematical explanation or "proof" of this phenomenon; most discussion that I've encountered seems to treat it as more of an empirical observation rather than theoretical result. This may be related to the fact that the field has a huge number of alternative model selection criteria currently in widespread use, indicating that there isn't really a good theoretical consensus yet on how to properly quantify a model's complexity (nor the closely related bias-variance trade-off) in the first place.
With those preliminary remarks out of the way, what do we mean by the term "overfitting" in the context of a statistical regression against a high degree polynomial? I submit that it may be broken down into two separate phenomena:
As the degree of the polynomial in the regression increases, the resulting curve fits each data point ever more closely
Simultaneously, the oscillations between the data points become more numerous and larger in amplitude--meaning that if we later acquire new data points by making additional observations, those new data points will generally tend to fit the previously fitted curves more and more poorly, as the degree of the fit model increases
How might we explain the above two points, mathematically?
For a polynomial curve fit model specifically, one way of understanding bullet one mathematically is to observe that a lower degree polynomial model is just a higher degree polynomial in which most of the fitted coefficients have been artificially pre-constrained to be equal to zero. For example, if we model a data set using a polynomial of degree 2:
$$
f(x) = C_{0} + C_{1} x + C_{2} x^{2}
$$
adjusting the parameters $C_{0}, C_{1}, C_{2}$ to result in the best possible fit, it is in some sense equivalent to saying that we have modeled it using a degree 100 polynomial:
$$
f(x) = C_{0} + C_{1} x + C_{2} x^{2} + C_{3} x^{3} + ... + C_{100} x^{100}
$$
in which the upper 98 coefficents have all been constrained such that:
$$
C_{3} = C_{4} = ... C_{99} = C_{100} = 0
$$
Now, looking at it from that point of view, consider what happens when we add a degree to our polynomial model function, increasing from degree 2 to degree 3: it is in some sense like removing a constraint: where $C_{3}$ was previously forced to be $0$, now the fit algorithm is free to adjust it. Essentially, adding another adjustable parameter gives the fitter an additional "knob" that can be adjusted to allow the resulting fitted curve to more closely track the underlying data. Another crucial point to bear in mind: by removing the constraint that $C_{3} = 0$, you also allow the fitter a slightly wider latitude to adjust the original three parameters, $C_{0}, C_{1}, C_{2}$, across a wider range of potential values, because there are more opportunities for additional new adjustments to compensate or partially cancel each other out. So bullet number one (the phenomenon that higher degree polynomials more closely reproduce the observation data) may be understood as a simple result of the fact that fewer constraints and more "adjustable dials" means more opportunities to adjust all the parameter values "just so" in order to obtain a nearly perfect fit to the existing observed data.
But what about all of the wildly gyrating oscillations--how may we understand those, mathematically? Well, consider that the locations of the local minima / maxima for a polynomial of degree $n$ are obtained by solving the following equation:
$$
\frac{d f(x)}{dx} = 0
$$
or equivalently,
$$
C_{1} + 2 C_{2} x + 3 C_{3} x^{2} + ... + n C_{n} x^{n-1} = 0
$$
In general, a polynomial of degree $n$ may have up to $n-1$ unique local minima / maxima, because the algebraic equation above may have up to $n-1$ unique, real-valued (i.e., non-complex) roots. Because each local minimum / maximum in this case corresponds to one oscillation, it means that in the absence of a regularization constraint, increasing the degree of the fit model will naturally tend to increase the number of oscillations.
Additional bonus comment: if you program in R, there is an example script published with this question which facilitates experimenting with the practical effects of fitting real data with very high degree polynomials.
|
How can we explain the "bad reputation" of higher-order polynomials?
|
Before I attempt to answer this, I'd like to just point out that what you are observing here (overfitting in a linear regression) is just a specific example of a more general phenomenon, bias-variance
|
How can we explain the "bad reputation" of higher-order polynomials?
Before I attempt to answer this, I'd like to just point out that what you are observing here (overfitting in a linear regression) is just a specific example of a more general phenomenon, bias-variance trade-off, which is also observed in more "modern" machine learning contexts as well as the "classical" setting of regression fitting. Your question could probably be expanded and rephrased more generally as something like, "why do high complexity models (e.g., those with larger numbers of adjustable parameters, such as higher degree polynomials) usually exhibit higher variance?" I've never seen a really good general mathematical explanation or "proof" of this phenomenon; most discussion that I've encountered seems to treat it as more of an empirical observation rather than theoretical result. This may be related to the fact that the field has a huge number of alternative model selection criteria currently in widespread use, indicating that there isn't really a good theoretical consensus yet on how to properly quantify a model's complexity (nor the closely related bias-variance trade-off) in the first place.
With those preliminary remarks out of the way, what do we mean by the term "overfitting" in the context of a statistical regression against a high degree polynomial? I submit that it may be broken down into two separate phenomena:
As the degree of the polynomial in the regression increases, the resulting curve fits each data point ever more closely
Simultaneously, the oscillations between the data points become more numerous and larger in amplitude--meaning that if we later acquire new data points by making additional observations, those new data points will generally tend to fit the previously fitted curves more and more poorly, as the degree of the fit model increases
How might we explain the above two points, mathematically?
For a polynomial curve fit model specifically, one way of understanding bullet one mathematically is to observe that a lower degree polynomial model is just a higher degree polynomial in which most of the fitted coefficients have been artificially pre-constrained to be equal to zero. For example, if we model a data set using a polynomial of degree 2:
$$
f(x) = C_{0} + C_{1} x + C_{2} x^{2}
$$
adjusting the parameters $C_{0}, C_{1}, C_{2}$ to result in the best possible fit, it is in some sense equivalent to saying that we have modeled it using a degree 100 polynomial:
$$
f(x) = C_{0} + C_{1} x + C_{2} x^{2} + C_{3} x^{3} + ... + C_{100} x^{100}
$$
in which the upper 98 coefficents have all been constrained such that:
$$
C_{3} = C_{4} = ... C_{99} = C_{100} = 0
$$
Now, looking at it from that point of view, consider what happens when we add a degree to our polynomial model function, increasing from degree 2 to degree 3: it is in some sense like removing a constraint: where $C_{3}$ was previously forced to be $0$, now the fit algorithm is free to adjust it. Essentially, adding another adjustable parameter gives the fitter an additional "knob" that can be adjusted to allow the resulting fitted curve to more closely track the underlying data. Another crucial point to bear in mind: by removing the constraint that $C_{3} = 0$, you also allow the fitter a slightly wider latitude to adjust the original three parameters, $C_{0}, C_{1}, C_{2}$, across a wider range of potential values, because there are more opportunities for additional new adjustments to compensate or partially cancel each other out. So bullet number one (the phenomenon that higher degree polynomials more closely reproduce the observation data) may be understood as a simple result of the fact that fewer constraints and more "adjustable dials" means more opportunities to adjust all the parameter values "just so" in order to obtain a nearly perfect fit to the existing observed data.
But what about all of the wildly gyrating oscillations--how may we understand those, mathematically? Well, consider that the locations of the local minima / maxima for a polynomial of degree $n$ are obtained by solving the following equation:
$$
\frac{d f(x)}{dx} = 0
$$
or equivalently,
$$
C_{1} + 2 C_{2} x + 3 C_{3} x^{2} + ... + n C_{n} x^{n-1} = 0
$$
In general, a polynomial of degree $n$ may have up to $n-1$ unique local minima / maxima, because the algebraic equation above may have up to $n-1$ unique, real-valued (i.e., non-complex) roots. Because each local minimum / maximum in this case corresponds to one oscillation, it means that in the absence of a regularization constraint, increasing the degree of the fit model will naturally tend to increase the number of oscillations.
Additional bonus comment: if you program in R, there is an example script published with this question which facilitates experimenting with the practical effects of fitting real data with very high degree polynomials.
|
How can we explain the "bad reputation" of higher-order polynomials?
Before I attempt to answer this, I'd like to just point out that what you are observing here (overfitting in a linear regression) is just a specific example of a more general phenomenon, bias-variance
|
8,429
|
How can we explain the "bad reputation" of higher-order polynomials?
|
It isn't something special about higher-order polynomials: the same effect happens for other sets of functions with many degrees of freedom.
For example, let's call a function "special" if its graph consists of a horizontal segment, followed by a segment which slopes upwards at 45 degrees, followed by a straight line segment which is exactly twice as long as the previous segment but can be at any angle, followed by a straight line segment which can be of any angle and length, followed by a segment which slopes downwards at 60 degrees, followed by a quarter-circle arc of any size, followed by a segment which slopes upwards at 10 degrees, followed by a semicircular arc of any size, followed by another horizontal segment. When choosing a "special" function you have so many degrees of freedom that you likely can find one which closely fits your data. This is not an indication that special functions are a good modelling choice.
Similarly, with higher-order polynomials you have so many coefficients to play with that it just isn't very impressive that by picking them correctly you can achieve a close fit.
|
How can we explain the "bad reputation" of higher-order polynomials?
|
It isn't something special about higher-order polynomials: the same effect happens for other sets of functions with many degrees of freedom.
For example, let's call a function "special" if its graph c
|
How can we explain the "bad reputation" of higher-order polynomials?
It isn't something special about higher-order polynomials: the same effect happens for other sets of functions with many degrees of freedom.
For example, let's call a function "special" if its graph consists of a horizontal segment, followed by a segment which slopes upwards at 45 degrees, followed by a straight line segment which is exactly twice as long as the previous segment but can be at any angle, followed by a straight line segment which can be of any angle and length, followed by a segment which slopes downwards at 60 degrees, followed by a quarter-circle arc of any size, followed by a segment which slopes upwards at 10 degrees, followed by a semicircular arc of any size, followed by another horizontal segment. When choosing a "special" function you have so many degrees of freedom that you likely can find one which closely fits your data. This is not an indication that special functions are a good modelling choice.
Similarly, with higher-order polynomials you have so many coefficients to play with that it just isn't very impressive that by picking them correctly you can achieve a close fit.
|
How can we explain the "bad reputation" of higher-order polynomials?
It isn't something special about higher-order polynomials: the same effect happens for other sets of functions with many degrees of freedom.
For example, let's call a function "special" if its graph c
|
8,430
|
How can we explain the "bad reputation" of higher-order polynomials?
|
You have more problems than just Runge's phenomenon. Below is an example for fitting a tenth degree polynomial to 21 data points that follow the curve
$$y = sin(6\pi x^2)$$
Runge's phenomenon: The black broken line is the least-squares fit to these 21 points if there is no noise. You see some larger error towards the edges, but when you only interpolate then it is not incredibly large.
Variance and overfitting. On top of that phenomenon, you get that when we add noise, then the variance of the function in between data points becomes very large.
In the image we show this by computing the standard deviation for the sample distribution of the estimate when there is white noise with variance of $\sigma = 0.2, 0.4 \text{ or } 0.6$
In this case with fitting a 10h order polynomial you see that the error due to sample variation is relatively constant over all values for $x$. It is only for extrapolation that there is a large influence.
So this matter of overfitting does not seem to be much like Runge's phenomenon.
I have to explain the graphs a bit better. But, below is the R-code that allows to see what I did.
### create data
set.seed(1)
sigma = 0.2
### fine grained data
xs = seq(-0.1, 1.1, 0.001)
ys = sin(xs^2*6*pi)
### 21 data points
x = seq(0,1,0.05)
y = sin(x^2*6*pi)
### polynomials for modelling
M = as.data.frame(poly(x,10))
Ms = as.data.frame(predict(poly(x,10), xs))
### model of fit without noise
mod1 <- lm(y ~ ., data = M)
plot(xs,ys, type = "l", ylim = c(-2,2), lwd = 2,
xlab = "x", ylab = "y", xlim = c(0,1))
### add confidence intervals at three levels of sigma
for (sig in 1:3) {
pred = predict(mod1, newdata = Ms)+cor1
### the error of the coefficients is sigma * I because
### (X^tX)^-1 is equal to the identity matrix
sigerr = sqrt(rowSums(Ms^2))*sigma*sig
polygon(c(rev(xs), xs), c(rev(pred+sigerr),pred-sigerr),
col = rgb(1,0,0,0.3), border = NA)
}
### true data
lines(xs,ys, lwd = 2)
### use this to simulate multiple fits
#for (i in 1:1000) {
# q = y+rnorm(21,0,sigma)
# mod <- lm(q ~ ., data = M)
# lines(xs, predict(mod, newdata = Ms)+cor1, lty = 1, lwd = 1, col = rgb(1,0,0,0.01))
#}
### fit of model to 21 points
lines(xs, predict(mod1, newdata = Ms), lty = 2, lwd = 2)
## data points
points(x,y, pch = 21, col = 1, bg = 0)
title(expression(sin(6 * pi * x^2) * " with least squares fit to 21 points"))
legend(0,-1.2, c("true function with noisless data points",
"fit of noisless data points"),
lty = c(1,2), lwd = 2, pch = c(21,NA), pt.bg = c(0,0), cex = 0.8)
|
How can we explain the "bad reputation" of higher-order polynomials?
|
You have more problems than just Runge's phenomenon. Below is an example for fitting a tenth degree polynomial to 21 data points that follow the curve
$$y = sin(6\pi x^2)$$
Runge's phenomenon: The b
|
How can we explain the "bad reputation" of higher-order polynomials?
You have more problems than just Runge's phenomenon. Below is an example for fitting a tenth degree polynomial to 21 data points that follow the curve
$$y = sin(6\pi x^2)$$
Runge's phenomenon: The black broken line is the least-squares fit to these 21 points if there is no noise. You see some larger error towards the edges, but when you only interpolate then it is not incredibly large.
Variance and overfitting. On top of that phenomenon, you get that when we add noise, then the variance of the function in between data points becomes very large.
In the image we show this by computing the standard deviation for the sample distribution of the estimate when there is white noise with variance of $\sigma = 0.2, 0.4 \text{ or } 0.6$
In this case with fitting a 10h order polynomial you see that the error due to sample variation is relatively constant over all values for $x$. It is only for extrapolation that there is a large influence.
So this matter of overfitting does not seem to be much like Runge's phenomenon.
I have to explain the graphs a bit better. But, below is the R-code that allows to see what I did.
### create data
set.seed(1)
sigma = 0.2
### fine grained data
xs = seq(-0.1, 1.1, 0.001)
ys = sin(xs^2*6*pi)
### 21 data points
x = seq(0,1,0.05)
y = sin(x^2*6*pi)
### polynomials for modelling
M = as.data.frame(poly(x,10))
Ms = as.data.frame(predict(poly(x,10), xs))
### model of fit without noise
mod1 <- lm(y ~ ., data = M)
plot(xs,ys, type = "l", ylim = c(-2,2), lwd = 2,
xlab = "x", ylab = "y", xlim = c(0,1))
### add confidence intervals at three levels of sigma
for (sig in 1:3) {
pred = predict(mod1, newdata = Ms)+cor1
### the error of the coefficients is sigma * I because
### (X^tX)^-1 is equal to the identity matrix
sigerr = sqrt(rowSums(Ms^2))*sigma*sig
polygon(c(rev(xs), xs), c(rev(pred+sigerr),pred-sigerr),
col = rgb(1,0,0,0.3), border = NA)
}
### true data
lines(xs,ys, lwd = 2)
### use this to simulate multiple fits
#for (i in 1:1000) {
# q = y+rnorm(21,0,sigma)
# mod <- lm(q ~ ., data = M)
# lines(xs, predict(mod, newdata = Ms)+cor1, lty = 1, lwd = 1, col = rgb(1,0,0,0.01))
#}
### fit of model to 21 points
lines(xs, predict(mod1, newdata = Ms), lty = 2, lwd = 2)
## data points
points(x,y, pch = 21, col = 1, bg = 0)
title(expression(sin(6 * pi * x^2) * " with least squares fit to 21 points"))
legend(0,-1.2, c("true function with noisless data points",
"fit of noisless data points"),
lty = c(1,2), lwd = 2, pch = c(21,NA), pt.bg = c(0,0), cex = 0.8)
|
How can we explain the "bad reputation" of higher-order polynomials?
You have more problems than just Runge's phenomenon. Below is an example for fitting a tenth degree polynomial to 21 data points that follow the curve
$$y = sin(6\pi x^2)$$
Runge's phenomenon: The b
|
8,431
|
How can we explain the "bad reputation" of higher-order polynomials?
|
It's much worse than just overfitting.
The problems with polynomials don't become clear in examples with only 10 or 20 parameters, so I'll examine a function that we want to fit with 200,000 parameters, where 200,000 parameters really is the correct number - we aren't overfitting.
Our function is a 10 second audio clip, with pressure sampled 20,000 times per second. If we use linear interpolation, then we can interpret our function as a linear combination of 200,000 little bumps. All these bumps behave basically the same, and if we need more parameters we can just make more. We are dealing with lots of parameters, but adding 10 more parameters isn't that much harder than adding the first 10. A 5 cent computer embedded in a happy meal toy can handle this to play back a cow mooing.
Another classic approach would be to represent our function as a linear combination of sine waves. Finding 200,000 reasonable sine waves is easy enough, and using a fourier transform we can do this computation on any phone processor, without much fuss. sin(2x) isn't really that different from sin(200,000x.)
Now, if we want to model our audio clip as a polynomial, then we have to model it as a linear combination of 200,000 monomials. While finding 200,000 well behaved bumps was easy, and finding 200,000 chill sine waves was a breeze, finding 200,000 well behaved monomials is much harder! $1$ and $x$ were easy enough to work with. We start to run into trouble with $x^{20}$, but with some careful work we could wrangle it into representing audio. By the time we are dealing with $x^{1000}$ we are pulling our hair out- when we put in 0, 1, 2, it puts out 0, 1, 1.071509e+301, which barely even fits in a 64 bit floating point number. $x^{20,000}$ is not a reasonable function to work with, and yet when we resort to recruiting it, we have 180,000 functions still to go. $x^{200,000}$ is right out.
tldr: When representing a complicated thing as a linear combination of building blocks, you need a large collection of reasonable building blocks. There aren't very many reasonable monomials.
|
How can we explain the "bad reputation" of higher-order polynomials?
|
It's much worse than just overfitting.
The problems with polynomials don't become clear in examples with only 10 or 20 parameters, so I'll examine a function that we want to fit with 200,000 parameter
|
How can we explain the "bad reputation" of higher-order polynomials?
It's much worse than just overfitting.
The problems with polynomials don't become clear in examples with only 10 or 20 parameters, so I'll examine a function that we want to fit with 200,000 parameters, where 200,000 parameters really is the correct number - we aren't overfitting.
Our function is a 10 second audio clip, with pressure sampled 20,000 times per second. If we use linear interpolation, then we can interpret our function as a linear combination of 200,000 little bumps. All these bumps behave basically the same, and if we need more parameters we can just make more. We are dealing with lots of parameters, but adding 10 more parameters isn't that much harder than adding the first 10. A 5 cent computer embedded in a happy meal toy can handle this to play back a cow mooing.
Another classic approach would be to represent our function as a linear combination of sine waves. Finding 200,000 reasonable sine waves is easy enough, and using a fourier transform we can do this computation on any phone processor, without much fuss. sin(2x) isn't really that different from sin(200,000x.)
Now, if we want to model our audio clip as a polynomial, then we have to model it as a linear combination of 200,000 monomials. While finding 200,000 well behaved bumps was easy, and finding 200,000 chill sine waves was a breeze, finding 200,000 well behaved monomials is much harder! $1$ and $x$ were easy enough to work with. We start to run into trouble with $x^{20}$, but with some careful work we could wrangle it into representing audio. By the time we are dealing with $x^{1000}$ we are pulling our hair out- when we put in 0, 1, 2, it puts out 0, 1, 1.071509e+301, which barely even fits in a 64 bit floating point number. $x^{20,000}$ is not a reasonable function to work with, and yet when we resort to recruiting it, we have 180,000 functions still to go. $x^{200,000}$ is right out.
tldr: When representing a complicated thing as a linear combination of building blocks, you need a large collection of reasonable building blocks. There aren't very many reasonable monomials.
|
How can we explain the "bad reputation" of higher-order polynomials?
It's much worse than just overfitting.
The problems with polynomials don't become clear in examples with only 10 or 20 parameters, so I'll examine a function that we want to fit with 200,000 parameter
|
8,432
|
How can we explain the "bad reputation" of higher-order polynomials?
|
The ringing is an artifact of using uniformly spaced points, because the lagrange polynomials for this spacing are not tightly concentrated around the points they are trying to fit. E.g. for 11 evenly-spaced points on the interval [0,1], here is the degree 10 polynomial that is used to fit the value at x=0.4 (is zero at all other sample points):
Clearly nudging the value at x=0.4 will wildly change the fitted function at unrelated locations. As the Chebfun package (and Trefethen's other work) shows, this problem disappears when using well chosen sampling points over the interval, based on the roots of Chebyshev polynomials. The lagrange polynomials (i.e. basis functions) in this case naturally look closer to smooth kernels. With this choice of fitting points/polynomial basis the polynomial attempting to fit x=0.4 is in fact maximized at this location.
The tradeoff is that you have to fix your desired fitting interval in advance. As we can see in the example the 'concentration' property drops off very sharply outside of [0,1].
So the wild overfitting isn't really about polynomials: the issue is that on evenly spaced points the mapping between curve-distance over the interval and sample-distance on the sampled points is near-degenerate. While we intuitively think of high-degree polynomials as smooth interpolants, this is not automatically true of high-order polynomials and you have forgotten to inform your fitting procedure about what a normal measure of function-distance looks like. This is completely fixable by switching basis, and once this is done you can do very reliable numerical interpolation with 100+ degree polynomials. Of course, this solution is better suited to working numerically with in-principle continuous quantities, rather than for discrete data where we don't get to choose our sample points.
|
How can we explain the "bad reputation" of higher-order polynomials?
|
The ringing is an artifact of using uniformly spaced points, because the lagrange polynomials for this spacing are not tightly concentrated around the points they are trying to fit. E.g. for 11 evenly
|
How can we explain the "bad reputation" of higher-order polynomials?
The ringing is an artifact of using uniformly spaced points, because the lagrange polynomials for this spacing are not tightly concentrated around the points they are trying to fit. E.g. for 11 evenly-spaced points on the interval [0,1], here is the degree 10 polynomial that is used to fit the value at x=0.4 (is zero at all other sample points):
Clearly nudging the value at x=0.4 will wildly change the fitted function at unrelated locations. As the Chebfun package (and Trefethen's other work) shows, this problem disappears when using well chosen sampling points over the interval, based on the roots of Chebyshev polynomials. The lagrange polynomials (i.e. basis functions) in this case naturally look closer to smooth kernels. With this choice of fitting points/polynomial basis the polynomial attempting to fit x=0.4 is in fact maximized at this location.
The tradeoff is that you have to fix your desired fitting interval in advance. As we can see in the example the 'concentration' property drops off very sharply outside of [0,1].
So the wild overfitting isn't really about polynomials: the issue is that on evenly spaced points the mapping between curve-distance over the interval and sample-distance on the sampled points is near-degenerate. While we intuitively think of high-degree polynomials as smooth interpolants, this is not automatically true of high-order polynomials and you have forgotten to inform your fitting procedure about what a normal measure of function-distance looks like. This is completely fixable by switching basis, and once this is done you can do very reliable numerical interpolation with 100+ degree polynomials. Of course, this solution is better suited to working numerically with in-principle continuous quantities, rather than for discrete data where we don't get to choose our sample points.
|
How can we explain the "bad reputation" of higher-order polynomials?
The ringing is an artifact of using uniformly spaced points, because the lagrange polynomials for this spacing are not tightly concentrated around the points they are trying to fit. E.g. for 11 evenly
|
8,433
|
How can we explain the "bad reputation" of higher-order polynomials?
|
Is there any mathematical justification as to why (higher degree) polynomial functions overfit the data?
Sure. As others mentioned, particularly stachyra and fblundun, it's about the complexity of the hypothesis class relative to the amount of data you have. A highly complex model will always find a way to explain a small amount of data, regardless of whether that explanation generalizes correctly. A simple model won't be able to fit the training data unless it actually explains the underlying relationship.
Imagine that my data distribution looks like this: for each $x$, I pick $y$ uniformly at random from $\{0,1\}$. No model in the world will be able to predict the next data point. It's totally random.
But suppose you plan to draw $10$ training data points and fit a degree-$10$ polynomial. I can already tell you in advance what will happen: you will be able to fit the data perfectly. In other words, your approach can't tell whether you're going to generalize well or not. It always has zero training error even when the next prediction will be very bad.
Whereas with a degree-$3$ polynomial, you will immediately notice a poor fit and conclude that you will not generalize. A simple model can detect whether or not it is fitting the data. A complex one will always fit the data regardless of how it's generated.
Intuition like this is formalized by VC-dimension, a measure of complexity of hypothesis classes for binary classification (but there are versions for regression as well, psuedo-dimension). The theory promises that for a simple model class, if we draw relatively few data points, then the fit to the training data is representative of the fit to the actual generative model. Whereas for a more complex model class, it may fit the training data significantly better than the test data.
|
How can we explain the "bad reputation" of higher-order polynomials?
|
Is there any mathematical justification as to why (higher degree) polynomial functions overfit the data?
Sure. As others mentioned, particularly stachyra and fblundun, it's about the complexity of th
|
How can we explain the "bad reputation" of higher-order polynomials?
Is there any mathematical justification as to why (higher degree) polynomial functions overfit the data?
Sure. As others mentioned, particularly stachyra and fblundun, it's about the complexity of the hypothesis class relative to the amount of data you have. A highly complex model will always find a way to explain a small amount of data, regardless of whether that explanation generalizes correctly. A simple model won't be able to fit the training data unless it actually explains the underlying relationship.
Imagine that my data distribution looks like this: for each $x$, I pick $y$ uniformly at random from $\{0,1\}$. No model in the world will be able to predict the next data point. It's totally random.
But suppose you plan to draw $10$ training data points and fit a degree-$10$ polynomial. I can already tell you in advance what will happen: you will be able to fit the data perfectly. In other words, your approach can't tell whether you're going to generalize well or not. It always has zero training error even when the next prediction will be very bad.
Whereas with a degree-$3$ polynomial, you will immediately notice a poor fit and conclude that you will not generalize. A simple model can detect whether or not it is fitting the data. A complex one will always fit the data regardless of how it's generated.
Intuition like this is formalized by VC-dimension, a measure of complexity of hypothesis classes for binary classification (but there are versions for regression as well, psuedo-dimension). The theory promises that for a simple model class, if we draw relatively few data points, then the fit to the training data is representative of the fit to the actual generative model. Whereas for a more complex model class, it may fit the training data significantly better than the test data.
|
How can we explain the "bad reputation" of higher-order polynomials?
Is there any mathematical justification as to why (higher degree) polynomial functions overfit the data?
Sure. As others mentioned, particularly stachyra and fblundun, it's about the complexity of th
|
8,434
|
How can we explain the "bad reputation" of higher-order polynomials?
|
Using more terms means more degrees of freedom, hence more overfitting, but the real question is -- why are high order terms like $x^5$ so bad?
If you had enough data to estimate one parameter $a$, and no special knowledge about the domain, a practitioner would always start with $ax$ rather than $a x^5$ in their model exploration. Is it purely empirical, or is there some mathematical way to justify this choice?
When fitting discrete data you can show that low order terms are preferable to high order terms using worst case analysis.
https://arxiv.org/pdf/math/0410076.pdf
For random binary vectors of the form $\langle x_0,x_1,\ldots,x_n\rangle$, you can show that the best model relying on $k$ features of the form $\{x_i\}$ (first order) will result in a better expected fit when true generating distribution is picked adversarially, after your choice of features is revealed, than the best model relying on $k$ features of the form $\{x_i x_j\}$ (second order). I'm not aware of similar results for real valued $x$. The big obstacle is that for real-valued $x$ is that there is no longer agreement as to which measure to use over this space. Different choices of measure lead to different conclusions.
Perhaps there is some universality principle which suggests that low order terms are preferable for a typical case, which more relevant for real world, rather than "adversarial case" which is what is analysed in the paper.
|
How can we explain the "bad reputation" of higher-order polynomials?
|
Using more terms means more degrees of freedom, hence more overfitting, but the real question is -- why are high order terms like $x^5$ so bad?
If you had enough data to estimate one parameter $a$, an
|
How can we explain the "bad reputation" of higher-order polynomials?
Using more terms means more degrees of freedom, hence more overfitting, but the real question is -- why are high order terms like $x^5$ so bad?
If you had enough data to estimate one parameter $a$, and no special knowledge about the domain, a practitioner would always start with $ax$ rather than $a x^5$ in their model exploration. Is it purely empirical, or is there some mathematical way to justify this choice?
When fitting discrete data you can show that low order terms are preferable to high order terms using worst case analysis.
https://arxiv.org/pdf/math/0410076.pdf
For random binary vectors of the form $\langle x_0,x_1,\ldots,x_n\rangle$, you can show that the best model relying on $k$ features of the form $\{x_i\}$ (first order) will result in a better expected fit when true generating distribution is picked adversarially, after your choice of features is revealed, than the best model relying on $k$ features of the form $\{x_i x_j\}$ (second order). I'm not aware of similar results for real valued $x$. The big obstacle is that for real-valued $x$ is that there is no longer agreement as to which measure to use over this space. Different choices of measure lead to different conclusions.
Perhaps there is some universality principle which suggests that low order terms are preferable for a typical case, which more relevant for real world, rather than "adversarial case" which is what is analysed in the paper.
|
How can we explain the "bad reputation" of higher-order polynomials?
Using more terms means more degrees of freedom, hence more overfitting, but the real question is -- why are high order terms like $x^5$ so bad?
If you had enough data to estimate one parameter $a$, an
|
8,435
|
How can we explain the "bad reputation" of higher-order polynomials?
|
The blog post that you are discussing here and the chart have little to do with polynomial regressions per se. The author simply used polynomials to demonstrate the overfitting idea: i.e. fitting to the noise. When you leave no degrees of freedom, your fit become very rigid, i.e. very sensitive to both errors in y's and to a choice of x's in your sample. You could use any number of other basis functions to get to about the same result, it didn't have to be polynomials.
So, if you have 10 observation and use 9th order polynomial, then you leave no degrees of freedom. This polynomial will have 10 coefficients for your 10 sample points. So, your fitted curve will have to go through every point in your sample. This means that every measurement error in every Y will be in your model coefficients. You packed all the errors into your coefficients, then inevitably out of sample fit will be awful, or as ML people say "model won't generalize."
Again, this will happen with any model, not only polynomial regression. This doesn't mean that high degree polynomials don't have issues. They do, and some of them are real and some of them are due to lack of knowledge of people mis-using them, but this example is not a demonstration of these issues.
|
How can we explain the "bad reputation" of higher-order polynomials?
|
The blog post that you are discussing here and the chart have little to do with polynomial regressions per se. The author simply used polynomials to demonstrate the overfitting idea: i.e. fitting to t
|
How can we explain the "bad reputation" of higher-order polynomials?
The blog post that you are discussing here and the chart have little to do with polynomial regressions per se. The author simply used polynomials to demonstrate the overfitting idea: i.e. fitting to the noise. When you leave no degrees of freedom, your fit become very rigid, i.e. very sensitive to both errors in y's and to a choice of x's in your sample. You could use any number of other basis functions to get to about the same result, it didn't have to be polynomials.
So, if you have 10 observation and use 9th order polynomial, then you leave no degrees of freedom. This polynomial will have 10 coefficients for your 10 sample points. So, your fitted curve will have to go through every point in your sample. This means that every measurement error in every Y will be in your model coefficients. You packed all the errors into your coefficients, then inevitably out of sample fit will be awful, or as ML people say "model won't generalize."
Again, this will happen with any model, not only polynomial regression. This doesn't mean that high degree polynomials don't have issues. They do, and some of them are real and some of them are due to lack of knowledge of people mis-using them, but this example is not a demonstration of these issues.
|
How can we explain the "bad reputation" of higher-order polynomials?
The blog post that you are discussing here and the chart have little to do with polynomial regressions per se. The author simply used polynomials to demonstrate the overfitting idea: i.e. fitting to t
|
8,436
|
Is logistic regression a specific case of a neural network?
|
You have to be very specific about what you mean. We can show mathematically that a certain neural network architecture trained with a certain loss coincides exactly with logistic regression at the optimal parameters. Other neural networks will not.
A binary logistic regression makes predictions $\hat{y}$ using this equation:
$$
\hat{y}=\sigma(X \beta + \beta_0)
$$
where $X$ is a $n \times p$ matrix of features (predictors, independent variables) and vector $\beta$ is the vector of $p$ coefficients and $\beta_0$ is the intercept and $\sigma(z)=\frac{1}{\exp(-z)+1}$. Conventionally in a logistic regression, we would roll the $\beta_0$ scalar into the vector $\beta$ and append a column of 1s to $X$, but I've moved it out of $\beta$ for clarity of exposition.
A neural network with no hidden layers and one output neuron with a sigmoid activation makes predictions using the equation
$$
\hat{y}=\sigma(X \beta + \beta_0)
$$
with $\hat{y},\sigma,X, \beta, \beta_0$ as before. Clearly, the equation is exactly the same. In the neural-networks literature, $\beta_0$ is usually called a "bias," even though it has nothing to do with the statistical concept of bias. Otherwise, the terminology is identical.
A logistic regression has the Bernoulli likelihood as its objective function, or, equivalently, the Bernoulli log-likelihood function. This objective function is maximized:
$$
\arg\max_{\beta,\beta_0} \sum_i \left[ y_i \log(\hat{y_i}) + (1-y_i)\log(1-\hat{y_i})\right]
$$ where $y \in \{0,1\}$.
We can motivate this objective function from a Bernoulli probability model where the probability of success depends on $X$.
A neural network can, in principle, use any loss function we like. It might use the so-called "cross-entropy" function (even though the "cross-entropy" can motivate any number of loss functions; see How to construct a cross-entropy loss for general regression targets?), in which case the model minimizes this loss function:
$$
\arg\min_{\beta,\beta_0} -\sum_i \left[ y_i \log(\hat{y_i}) + (1-y_i)\log(1-\hat{y_i})\right]
$$
In both cases, these objective functions are strictly convex (concave) when certain conditions are met. Strict convexity implies that there is a single minimum and that this minimum is a global. Moreover, the objective functions are identical, since minimizing a strictly convex function $f$ is equivalent to maximizing $-f$. Therefore, these two models recover the same parameter estimates $\beta, \beta_0$. As long as the model attains the single optimum, it doesn't matter what optimizer is used, because there is only one optimum for these specific models.
However, a neural network is not required to optimize this specific loss function; for instance, a triplet-loss for this same model would likely recover different estimates $\beta,\beta_0$. And the MSE/least squares loss is not convex in this problem, so that neural network would differ from logistic regression as well (see: What is happening here, when I use squared loss in logistic regression setting?).
|
Is logistic regression a specific case of a neural network?
|
You have to be very specific about what you mean. We can show mathematically that a certain neural network architecture trained with a certain loss coincides exactly with logistic regression at the op
|
Is logistic regression a specific case of a neural network?
You have to be very specific about what you mean. We can show mathematically that a certain neural network architecture trained with a certain loss coincides exactly with logistic regression at the optimal parameters. Other neural networks will not.
A binary logistic regression makes predictions $\hat{y}$ using this equation:
$$
\hat{y}=\sigma(X \beta + \beta_0)
$$
where $X$ is a $n \times p$ matrix of features (predictors, independent variables) and vector $\beta$ is the vector of $p$ coefficients and $\beta_0$ is the intercept and $\sigma(z)=\frac{1}{\exp(-z)+1}$. Conventionally in a logistic regression, we would roll the $\beta_0$ scalar into the vector $\beta$ and append a column of 1s to $X$, but I've moved it out of $\beta$ for clarity of exposition.
A neural network with no hidden layers and one output neuron with a sigmoid activation makes predictions using the equation
$$
\hat{y}=\sigma(X \beta + \beta_0)
$$
with $\hat{y},\sigma,X, \beta, \beta_0$ as before. Clearly, the equation is exactly the same. In the neural-networks literature, $\beta_0$ is usually called a "bias," even though it has nothing to do with the statistical concept of bias. Otherwise, the terminology is identical.
A logistic regression has the Bernoulli likelihood as its objective function, or, equivalently, the Bernoulli log-likelihood function. This objective function is maximized:
$$
\arg\max_{\beta,\beta_0} \sum_i \left[ y_i \log(\hat{y_i}) + (1-y_i)\log(1-\hat{y_i})\right]
$$ where $y \in \{0,1\}$.
We can motivate this objective function from a Bernoulli probability model where the probability of success depends on $X$.
A neural network can, in principle, use any loss function we like. It might use the so-called "cross-entropy" function (even though the "cross-entropy" can motivate any number of loss functions; see How to construct a cross-entropy loss for general regression targets?), in which case the model minimizes this loss function:
$$
\arg\min_{\beta,\beta_0} -\sum_i \left[ y_i \log(\hat{y_i}) + (1-y_i)\log(1-\hat{y_i})\right]
$$
In both cases, these objective functions are strictly convex (concave) when certain conditions are met. Strict convexity implies that there is a single minimum and that this minimum is a global. Moreover, the objective functions are identical, since minimizing a strictly convex function $f$ is equivalent to maximizing $-f$. Therefore, these two models recover the same parameter estimates $\beta, \beta_0$. As long as the model attains the single optimum, it doesn't matter what optimizer is used, because there is only one optimum for these specific models.
However, a neural network is not required to optimize this specific loss function; for instance, a triplet-loss for this same model would likely recover different estimates $\beta,\beta_0$. And the MSE/least squares loss is not convex in this problem, so that neural network would differ from logistic regression as well (see: What is happening here, when I use squared loss in logistic regression setting?).
|
Is logistic regression a specific case of a neural network?
You have to be very specific about what you mean. We can show mathematically that a certain neural network architecture trained with a certain loss coincides exactly with logistic regression at the op
|
8,437
|
Is logistic regression a specific case of a neural network?
|
Architecture-wise, yes, it's a special case of neural net. A logistic regression model can be constructed via neural network libraries. In the end, both have neurons having the same computations if the same activation and loss is chosen. This makes it a special NN, but since logistic regression is the simplest model, it's possible to train it using second-order methods, e.g. newton. Second order methods use Hessian matrix, in addition to gradients. But, this computation is not efficient for larger NNs and libraries prefer to use gradient descent alternatives or quasi-newton methods, that are either entirely first-order or approximate second-order methods. So, the slight difference lies in the possible optimisers, though this doesn't mean you'll get different solutions due to convexity properties of the problem (at least numerically).
|
Is logistic regression a specific case of a neural network?
|
Architecture-wise, yes, it's a special case of neural net. A logistic regression model can be constructed via neural network libraries. In the end, both have neurons having the same computations if th
|
Is logistic regression a specific case of a neural network?
Architecture-wise, yes, it's a special case of neural net. A logistic regression model can be constructed via neural network libraries. In the end, both have neurons having the same computations if the same activation and loss is chosen. This makes it a special NN, but since logistic regression is the simplest model, it's possible to train it using second-order methods, e.g. newton. Second order methods use Hessian matrix, in addition to gradients. But, this computation is not efficient for larger NNs and libraries prefer to use gradient descent alternatives or quasi-newton methods, that are either entirely first-order or approximate second-order methods. So, the slight difference lies in the possible optimisers, though this doesn't mean you'll get different solutions due to convexity properties of the problem (at least numerically).
|
Is logistic regression a specific case of a neural network?
Architecture-wise, yes, it's a special case of neural net. A logistic regression model can be constructed via neural network libraries. In the end, both have neurons having the same computations if th
|
8,438
|
Is logistic regression a specific case of a neural network?
|
If you have logistic activation function in the output layer and you are trying to maximise the log-likelihood of observations belonging to their corresponding classes (e.g. via its negative as the cost function), then yes, each output-layer neuron can be said to be an implementation of a logistic model over its inputs (which can be outputs of the neurons from the hidden layers).
In the simplest case, when you have a "network" of only one neuron with logistic activation function, and assuming you maximise the log-likelihood, then you are performing logistic regression.
|
Is logistic regression a specific case of a neural network?
|
If you have logistic activation function in the output layer and you are trying to maximise the log-likelihood of observations belonging to their corresponding classes (e.g. via its negative as the co
|
Is logistic regression a specific case of a neural network?
If you have logistic activation function in the output layer and you are trying to maximise the log-likelihood of observations belonging to their corresponding classes (e.g. via its negative as the cost function), then yes, each output-layer neuron can be said to be an implementation of a logistic model over its inputs (which can be outputs of the neurons from the hidden layers).
In the simplest case, when you have a "network" of only one neuron with logistic activation function, and assuming you maximise the log-likelihood, then you are performing logistic regression.
|
Is logistic regression a specific case of a neural network?
If you have logistic activation function in the output layer and you are trying to maximise the log-likelihood of observations belonging to their corresponding classes (e.g. via its negative as the co
|
8,439
|
Why does finding small effects in large studies indicate publication bias?
|
The answers here are good, +1 to all. I just wanted to show how this effect might look in funnel plot terms in an extreme case. Below I simulate a small effect as $N(.01, .1)$ and draw samples between 2 and 2000 observations in size.
The grey points in the plot would not be published under a strict $p < .05$ regime. The grey line is a regression of effect size on sample size including the "bad p-value" studies, while the red one excludes these. The black line shows the true effect.
As you can see, under publication bias there is a strong tendency for small studies to overestimate effect sizes and for the larger ones to report effect sizes closer to the truth.
set.seed(20-02-19)
n_studies <- 1000
sample_size <- sample(2:2000, n_studies, replace=T)
studies <- plyr::aaply(sample_size, 1, function(size) {
dat <- rnorm(size, mean = .01, sd = .1)
c(effect_size=mean(dat), p_value=t.test(dat)$p.value)
})
studies <- cbind(studies, sample_size=log(sample_size))
include <- studies[, "p_value"] < .05
plot(studies[, "sample_size"], studies[, "effect_size"],
xlab = "log(sample size)", ylab="effect size",
col=ifelse(include, "black", "grey"), pch=20)
lines(lowess(x = studies[, "sample_size"], studies[, "effect_size"]), col="grey", lwd=2)
lines(lowess(x = studies[include, "sample_size"], studies[include, "effect_size"]), col="red", lwd=2)
abline(h=.01)
Created on 2019-02-20 by the reprex package (v0.2.1)
|
Why does finding small effects in large studies indicate publication bias?
|
The answers here are good, +1 to all. I just wanted to show how this effect might look in funnel plot terms in an extreme case. Below I simulate a small effect as $N(.01, .1)$ and draw samples between
|
Why does finding small effects in large studies indicate publication bias?
The answers here are good, +1 to all. I just wanted to show how this effect might look in funnel plot terms in an extreme case. Below I simulate a small effect as $N(.01, .1)$ and draw samples between 2 and 2000 observations in size.
The grey points in the plot would not be published under a strict $p < .05$ regime. The grey line is a regression of effect size on sample size including the "bad p-value" studies, while the red one excludes these. The black line shows the true effect.
As you can see, under publication bias there is a strong tendency for small studies to overestimate effect sizes and for the larger ones to report effect sizes closer to the truth.
set.seed(20-02-19)
n_studies <- 1000
sample_size <- sample(2:2000, n_studies, replace=T)
studies <- plyr::aaply(sample_size, 1, function(size) {
dat <- rnorm(size, mean = .01, sd = .1)
c(effect_size=mean(dat), p_value=t.test(dat)$p.value)
})
studies <- cbind(studies, sample_size=log(sample_size))
include <- studies[, "p_value"] < .05
plot(studies[, "sample_size"], studies[, "effect_size"],
xlab = "log(sample size)", ylab="effect size",
col=ifelse(include, "black", "grey"), pch=20)
lines(lowess(x = studies[, "sample_size"], studies[, "effect_size"]), col="grey", lwd=2)
lines(lowess(x = studies[include, "sample_size"], studies[include, "effect_size"]), col="red", lwd=2)
abline(h=.01)
Created on 2019-02-20 by the reprex package (v0.2.1)
|
Why does finding small effects in large studies indicate publication bias?
The answers here are good, +1 to all. I just wanted to show how this effect might look in funnel plot terms in an extreme case. Below I simulate a small effect as $N(.01, .1)$ and draw samples between
|
8,440
|
Why does finding small effects in large studies indicate publication bias?
|
First, we need think about what "publication bias" is, and how it will affect what actually makes it into the literature.
A fairly simple model for publication bias is that we collect some data and if $p < 0.05$, we publish. Otherwise, we don't. So how does this affect what we see in the literature? Well, for one, it guarantees that $|\hat \theta |/ SE(\hat \theta) >1.96$ (assuming a Wald statistic is used). The key point being made is that if $n$ is really small, then $SE(\hat \theta)$ is relatively large and a large $|\hat \theta|$ is required for publication.
Now suppose that in reality, $\theta$ is relatively small. Suppose we run 200 experiments, 100 with really small sample sizes and 100 with really large sample sizes. Note that of 100 really small sample size experiments, the only ones that will get published by our simple publication bias model is those with large values of $|\hat \theta|$ just due to random error. However, in our 100 experiments with large sample sizes, much smaller values of $\hat \theta$ will be published. So if the larger experiments systematically show smaller effect than the smaller experiments, this suggests that perhaps $|\theta|$ is actually significantly smaller than what we typically see from the smaller experiments that actually make it into publication.
Technical note: it's true that either having a large $|\hat \theta|$ and/or small $SE(\hat \theta)$ will lead to $p < 0.05$. However, since effect sizes are typically thought of as relative to standard deviation of error term, these two conditions are essentially equivalent.
|
Why does finding small effects in large studies indicate publication bias?
|
First, we need think about what "publication bias" is, and how it will affect what actually makes it into the literature.
A fairly simple model for publication bias is that we collect some data and i
|
Why does finding small effects in large studies indicate publication bias?
First, we need think about what "publication bias" is, and how it will affect what actually makes it into the literature.
A fairly simple model for publication bias is that we collect some data and if $p < 0.05$, we publish. Otherwise, we don't. So how does this affect what we see in the literature? Well, for one, it guarantees that $|\hat \theta |/ SE(\hat \theta) >1.96$ (assuming a Wald statistic is used). The key point being made is that if $n$ is really small, then $SE(\hat \theta)$ is relatively large and a large $|\hat \theta|$ is required for publication.
Now suppose that in reality, $\theta$ is relatively small. Suppose we run 200 experiments, 100 with really small sample sizes and 100 with really large sample sizes. Note that of 100 really small sample size experiments, the only ones that will get published by our simple publication bias model is those with large values of $|\hat \theta|$ just due to random error. However, in our 100 experiments with large sample sizes, much smaller values of $\hat \theta$ will be published. So if the larger experiments systematically show smaller effect than the smaller experiments, this suggests that perhaps $|\theta|$ is actually significantly smaller than what we typically see from the smaller experiments that actually make it into publication.
Technical note: it's true that either having a large $|\hat \theta|$ and/or small $SE(\hat \theta)$ will lead to $p < 0.05$. However, since effect sizes are typically thought of as relative to standard deviation of error term, these two conditions are essentially equivalent.
|
Why does finding small effects in large studies indicate publication bias?
First, we need think about what "publication bias" is, and how it will affect what actually makes it into the literature.
A fairly simple model for publication bias is that we collect some data and i
|
8,441
|
Why does finding small effects in large studies indicate publication bias?
|
Read this statement a different way:
If there is no publication bias, effect size should be independent of study size.
That is, if you are studying one phenomenon, the effect size is a property of the phenomenon, not the sample/study.
Estimates of effect size could (and will) vary across studies, but if there is a systematic decreasing effect size with increasing study size, that suggests there is bias. The whole point is that this relationship suggests that there are additional small studies showing low effect size that have not been published, and if they were published and therefore could be included in a meta analysis, the overall impression would be that the effect size is smaller than what is estimated from the published subset of studies.
The variance of the effect size estimates across studies will depend on sample size, but you should see an equal number of under and over estimates at low sample sizes if there were no bias.
|
Why does finding small effects in large studies indicate publication bias?
|
Read this statement a different way:
If there is no publication bias, effect size should be independent of study size.
That is, if you are studying one phenomenon, the effect size is a property of the
|
Why does finding small effects in large studies indicate publication bias?
Read this statement a different way:
If there is no publication bias, effect size should be independent of study size.
That is, if you are studying one phenomenon, the effect size is a property of the phenomenon, not the sample/study.
Estimates of effect size could (and will) vary across studies, but if there is a systematic decreasing effect size with increasing study size, that suggests there is bias. The whole point is that this relationship suggests that there are additional small studies showing low effect size that have not been published, and if they were published and therefore could be included in a meta analysis, the overall impression would be that the effect size is smaller than what is estimated from the published subset of studies.
The variance of the effect size estimates across studies will depend on sample size, but you should see an equal number of under and over estimates at low sample sizes if there were no bias.
|
Why does finding small effects in large studies indicate publication bias?
Read this statement a different way:
If there is no publication bias, effect size should be independent of study size.
That is, if you are studying one phenomenon, the effect size is a property of the
|
8,442
|
Should I teach Bayesian or frequentist statistics first?
|
Both Bayesian statistics and frequentist statistics are based on probability theory, but I'd say that the former relies more heavily on the theory from the start. On the other hand, surely the concept of a credible interval is more intuitive than that of a confidence interval, once the student has a good understanding of the concept of probability. So, whatever you choose, I advocate first of all strengthening their grasp of probability concepts, with all those examples based on dice, cards, roulette, Monty Hall paradox, etc..
I would choose one approach or the other based on a purely utilitarian approach: are they more likely to study frequentist or Bayesian statistics at school? In my country, they would definitely learn the frequentist framework first (and last: never heard of high school students being taught Bayesian stats, the only chance is either at university or afterwards, by self-study). Maybe in yours it's different. Keep in mind that if they need to deal with NHST (Null Hypothesis Significance Testing), that more naturally arises in the context of frequentist statistics, IMO. Of course you can test hypotheses also in the Bayesian framework, but there are many leading Bayesian statisticians who advocate not using NHST at all, either under the frequentist or the Bayesian framework (for example, Andrew Gelman from Columbia University).
Finally, I don't know about the level of high school students in your country, but in mine it would be really difficult for a student to successfully assimilate (the basics of) probability theory and integral calculus at the same time. So, if you decide to go with Bayesian statistics, I'd really avoid the continuous random variable case, and stick to discrete random variables.
|
Should I teach Bayesian or frequentist statistics first?
|
Both Bayesian statistics and frequentist statistics are based on probability theory, but I'd say that the former relies more heavily on the theory from the start. On the other hand, surely the concept
|
Should I teach Bayesian or frequentist statistics first?
Both Bayesian statistics and frequentist statistics are based on probability theory, but I'd say that the former relies more heavily on the theory from the start. On the other hand, surely the concept of a credible interval is more intuitive than that of a confidence interval, once the student has a good understanding of the concept of probability. So, whatever you choose, I advocate first of all strengthening their grasp of probability concepts, with all those examples based on dice, cards, roulette, Monty Hall paradox, etc..
I would choose one approach or the other based on a purely utilitarian approach: are they more likely to study frequentist or Bayesian statistics at school? In my country, they would definitely learn the frequentist framework first (and last: never heard of high school students being taught Bayesian stats, the only chance is either at university or afterwards, by self-study). Maybe in yours it's different. Keep in mind that if they need to deal with NHST (Null Hypothesis Significance Testing), that more naturally arises in the context of frequentist statistics, IMO. Of course you can test hypotheses also in the Bayesian framework, but there are many leading Bayesian statisticians who advocate not using NHST at all, either under the frequentist or the Bayesian framework (for example, Andrew Gelman from Columbia University).
Finally, I don't know about the level of high school students in your country, but in mine it would be really difficult for a student to successfully assimilate (the basics of) probability theory and integral calculus at the same time. So, if you decide to go with Bayesian statistics, I'd really avoid the continuous random variable case, and stick to discrete random variables.
|
Should I teach Bayesian or frequentist statistics first?
Both Bayesian statistics and frequentist statistics are based on probability theory, but I'd say that the former relies more heavily on the theory from the start. On the other hand, surely the concept
|
8,443
|
Should I teach Bayesian or frequentist statistics first?
|
Bayesian and frequentist ask different questions. Bayesian asks what parameter values are credible, given the observed data. Frequentist asks about the probability of imaginary simulated data if some hypothetical parameter values were true. Frequentist decisions are motivated by controlling errors, Bayesian decisions are motivated by uncertainty in model descriptions.
So which should you teach first? Well, if one or the other of those questions is what you want to ask first, that's your answer. But in terms of approachability and pedagogy, I think that Bayesian is much easier to understand and is far more intuitive. The basic idea of Bayesian analysis is re-allocation of credibility across possibilities, just like Sherlock Holmes famously said, and which millions of readers have intuitively understood. But the basic idea of frequentist analysis is very challenging: The space of all possible sets of data that might have happened if a particular hypothesis were true, and the proportion of those imaginary data sets that have a summary statistic as or more extreme than the summary statistic that was actually observed.
A free introductory chapter about Bayesian ideas is here. An article that sets frequentist and Bayesian concepts side by side is here. The article explains frequentist and Bayesian approaches to hypothesis testing and to estimation (and a lot of other stuff). The framework of the article might be especially useful to beginners trying to get a view of the landscape.
|
Should I teach Bayesian or frequentist statistics first?
|
Bayesian and frequentist ask different questions. Bayesian asks what parameter values are credible, given the observed data. Frequentist asks about the probability of imaginary simulated data if some
|
Should I teach Bayesian or frequentist statistics first?
Bayesian and frequentist ask different questions. Bayesian asks what parameter values are credible, given the observed data. Frequentist asks about the probability of imaginary simulated data if some hypothetical parameter values were true. Frequentist decisions are motivated by controlling errors, Bayesian decisions are motivated by uncertainty in model descriptions.
So which should you teach first? Well, if one or the other of those questions is what you want to ask first, that's your answer. But in terms of approachability and pedagogy, I think that Bayesian is much easier to understand and is far more intuitive. The basic idea of Bayesian analysis is re-allocation of credibility across possibilities, just like Sherlock Holmes famously said, and which millions of readers have intuitively understood. But the basic idea of frequentist analysis is very challenging: The space of all possible sets of data that might have happened if a particular hypothesis were true, and the proportion of those imaginary data sets that have a summary statistic as or more extreme than the summary statistic that was actually observed.
A free introductory chapter about Bayesian ideas is here. An article that sets frequentist and Bayesian concepts side by side is here. The article explains frequentist and Bayesian approaches to hypothesis testing and to estimation (and a lot of other stuff). The framework of the article might be especially useful to beginners trying to get a view of the landscape.
|
Should I teach Bayesian or frequentist statistics first?
Bayesian and frequentist ask different questions. Bayesian asks what parameter values are credible, given the observed data. Frequentist asks about the probability of imaginary simulated data if some
|
8,444
|
Should I teach Bayesian or frequentist statistics first?
|
This question risks being opinion-based, so I'll try to be really brief with my opinion, then give you a book suggestion. Sometimes it's worth taking a particular approach because it's the approach that a particularly good book takes.
I would agree that Bayesian statistics are more intuitive. The Confidence Interval versus Credible Interval distinction pretty much sums it up: people naturally think in terms of "what is the chance that..." rather than the Confidence Interval approach. The Confidence Interval approach sounds a lot like it's saying the same thing as the Credible Interval except on general principle you can't take the last step from "95% of the time" to "95% chance", which seems very frequentist but you can't do it. It's not inconsistent, just not intuitive.
Balancing that out is the fact that most college courses they will take will use the less-intuitive frequentist approach.
That said I really like the book Statistical Rethinking: A Bayesian Course with Examples in R and Stan by Richard McElreath. It's not cheap, so please read about it and poke around in it on Amazon before you buy. I find it a particularly intuitive approach that takes advantage of the Bayesian approach, and is very hands-on. (And since R and Stan are excellent tools for Bayesian statistics and they're free, it's practical learning.)
EDIT: A couple of comments have mentioned that the book is probably beyond a High Schooler, even with an experienced tutor. So I'll have to place an even bigger caveat: it has a simple approach at the beginning, but ramps up quickly. It's an amazing book, but you really, really would have to poke through it on Amazon to get a feel for its initial assumptions and how quickly it ramps up. Beautiful analogies, great hands-on work in R, incredible flow and organization, but maybe not useful to you.
It assumes a basic knowledge of programming and R (free statistical package), and some exposure to the basics of probability and statistics. It's not random-access and each chapter builds on prior chapters. It starts out very simple, though the difficulty does ramp up in the middle -- it ends on multi-level regression. So you might want to preview some of it at Amazon, and decide if you can easily cover the basics or if it jumps in a bit too far down the road.
EDIT 2: The bottom line of my contribution here and attempt to turn it from pure opinion is that a good textbook may decide which approach you take. I'd prefer a Bayesian approach, and this book does that well, but perhaps at too fast a pace.
|
Should I teach Bayesian or frequentist statistics first?
|
This question risks being opinion-based, so I'll try to be really brief with my opinion, then give you a book suggestion. Sometimes it's worth taking a particular approach because it's the approach th
|
Should I teach Bayesian or frequentist statistics first?
This question risks being opinion-based, so I'll try to be really brief with my opinion, then give you a book suggestion. Sometimes it's worth taking a particular approach because it's the approach that a particularly good book takes.
I would agree that Bayesian statistics are more intuitive. The Confidence Interval versus Credible Interval distinction pretty much sums it up: people naturally think in terms of "what is the chance that..." rather than the Confidence Interval approach. The Confidence Interval approach sounds a lot like it's saying the same thing as the Credible Interval except on general principle you can't take the last step from "95% of the time" to "95% chance", which seems very frequentist but you can't do it. It's not inconsistent, just not intuitive.
Balancing that out is the fact that most college courses they will take will use the less-intuitive frequentist approach.
That said I really like the book Statistical Rethinking: A Bayesian Course with Examples in R and Stan by Richard McElreath. It's not cheap, so please read about it and poke around in it on Amazon before you buy. I find it a particularly intuitive approach that takes advantage of the Bayesian approach, and is very hands-on. (And since R and Stan are excellent tools for Bayesian statistics and they're free, it's practical learning.)
EDIT: A couple of comments have mentioned that the book is probably beyond a High Schooler, even with an experienced tutor. So I'll have to place an even bigger caveat: it has a simple approach at the beginning, but ramps up quickly. It's an amazing book, but you really, really would have to poke through it on Amazon to get a feel for its initial assumptions and how quickly it ramps up. Beautiful analogies, great hands-on work in R, incredible flow and organization, but maybe not useful to you.
It assumes a basic knowledge of programming and R (free statistical package), and some exposure to the basics of probability and statistics. It's not random-access and each chapter builds on prior chapters. It starts out very simple, though the difficulty does ramp up in the middle -- it ends on multi-level regression. So you might want to preview some of it at Amazon, and decide if you can easily cover the basics or if it jumps in a bit too far down the road.
EDIT 2: The bottom line of my contribution here and attempt to turn it from pure opinion is that a good textbook may decide which approach you take. I'd prefer a Bayesian approach, and this book does that well, but perhaps at too fast a pace.
|
Should I teach Bayesian or frequentist statistics first?
This question risks being opinion-based, so I'll try to be really brief with my opinion, then give you a book suggestion. Sometimes it's worth taking a particular approach because it's the approach th
|
8,445
|
Should I teach Bayesian or frequentist statistics first?
|
I have been taught the frequentist approach first, then the Bayesian one.
I am not a professional statistician.
I have to admit I didn't find my prior knowledge of the frequentist approach to be decisively useful in understanding the Bayesian approach.
I would dare to say it depends on what concrete applications you will be showing your pupils next, and how much time and effort you will be spending on them.
Having said this, I would start with Bayes.
|
Should I teach Bayesian or frequentist statistics first?
|
I have been taught the frequentist approach first, then the Bayesian one.
I am not a professional statistician.
I have to admit I didn't find my prior knowledge of the frequentist approach to be decis
|
Should I teach Bayesian or frequentist statistics first?
I have been taught the frequentist approach first, then the Bayesian one.
I am not a professional statistician.
I have to admit I didn't find my prior knowledge of the frequentist approach to be decisively useful in understanding the Bayesian approach.
I would dare to say it depends on what concrete applications you will be showing your pupils next, and how much time and effort you will be spending on them.
Having said this, I would start with Bayes.
|
Should I teach Bayesian or frequentist statistics first?
I have been taught the frequentist approach first, then the Bayesian one.
I am not a professional statistician.
I have to admit I didn't find my prior knowledge of the frequentist approach to be decis
|
8,446
|
Should I teach Bayesian or frequentist statistics first?
|
The Bayesian framework is tightly coupled to general critical thinking skills. It's what you need in the following situations:
You think about applying for a competitive job. What are your chances of getting in? What payoff do you expect from applying?
A headline tells you mobile phones cause cancer in humans in the long term. How much evidence do they have for this?
Which charity should you donate money to if you want it to have the greatest effect?
Someone offers to flip a coin with a bet of \$0.90 from you and \$1.10 from them. Would you give them the money? Why, why not?
You've lost your keys (or an atom bomb). Where do you start looking?
Also, this is much more interesting than memorising the formula for a two sample t-test :p. Which increases the chance that students will stay interested long enough to bother with increasingly technical material.
|
Should I teach Bayesian or frequentist statistics first?
|
The Bayesian framework is tightly coupled to general critical thinking skills. It's what you need in the following situations:
You think about applying for a competitive job. What are your chances of
|
Should I teach Bayesian or frequentist statistics first?
The Bayesian framework is tightly coupled to general critical thinking skills. It's what you need in the following situations:
You think about applying for a competitive job. What are your chances of getting in? What payoff do you expect from applying?
A headline tells you mobile phones cause cancer in humans in the long term. How much evidence do they have for this?
Which charity should you donate money to if you want it to have the greatest effect?
Someone offers to flip a coin with a bet of \$0.90 from you and \$1.10 from them. Would you give them the money? Why, why not?
You've lost your keys (or an atom bomb). Where do you start looking?
Also, this is much more interesting than memorising the formula for a two sample t-test :p. Which increases the chance that students will stay interested long enough to bother with increasingly technical material.
|
Should I teach Bayesian or frequentist statistics first?
The Bayesian framework is tightly coupled to general critical thinking skills. It's what you need in the following situations:
You think about applying for a competitive job. What are your chances of
|
8,447
|
Should I teach Bayesian or frequentist statistics first?
|
I would stay away from Bayesian, follow the giants.
Soviets had an excellent book series for secondary school students, roughly translated into English as "'Quant' little library." Kolmogorov contributed a book with co-authors titled "Introduction to a probability theory." I'm not sure it has ever been translated into English, but here's the link to its Russian original.
They approach explaining the probabilities through combinatorics, which I think is the great way to start. The book is very accessible for a high school student with decent maths. Note, that Soviets taught math rather extensively, so the average Western high school students may not be as well prepared, but with enough interest and will power can still handle the content, in my opinion.
The content is very interesting for students, it has random walks, limiting distributions, survival processes, law of large numbers etc. If you combine this approach with computer simulations, it becomes even more fun.
|
Should I teach Bayesian or frequentist statistics first?
|
I would stay away from Bayesian, follow the giants.
Soviets had an excellent book series for secondary school students, roughly translated into English as "'Quant' little library." Kolmogorov contribu
|
Should I teach Bayesian or frequentist statistics first?
I would stay away from Bayesian, follow the giants.
Soviets had an excellent book series for secondary school students, roughly translated into English as "'Quant' little library." Kolmogorov contributed a book with co-authors titled "Introduction to a probability theory." I'm not sure it has ever been translated into English, but here's the link to its Russian original.
They approach explaining the probabilities through combinatorics, which I think is the great way to start. The book is very accessible for a high school student with decent maths. Note, that Soviets taught math rather extensively, so the average Western high school students may not be as well prepared, but with enough interest and will power can still handle the content, in my opinion.
The content is very interesting for students, it has random walks, limiting distributions, survival processes, law of large numbers etc. If you combine this approach with computer simulations, it becomes even more fun.
|
Should I teach Bayesian or frequentist statistics first?
I would stay away from Bayesian, follow the giants.
Soviets had an excellent book series for secondary school students, roughly translated into English as "'Quant' little library." Kolmogorov contribu
|
8,448
|
Should I teach Bayesian or frequentist statistics first?
|
No one has mentioned likelihood, which is foundational to Bayesian statistics. An argument in favor of teaching Bayes first is that the flow from probability, to likelihood, to Bayes, is pretty seamless. Bayes can be motivated from likelihood by noting that (i) the likelihood function looks (and acts) like a probability distribution function, but is not because the area under the curve is not 1.0, and (ii) the crude, commonly-used Wald intervals assume a likelihood function that is proportional to a normal distribution, but Bayesian methods easily overcome this limitation.
Another argument favoring Bayes first is that the P(A|B) versus P(B|A) concern about p-values can be more easily explained, as mentioned by others.
Yet another argument favoring "Bayes first" is that it forces students to think more carefully about conditional probability models, which is useful elsewhere, e.g., in regression analysis.
Sorry for the self-promotion, but since it is entirely on-topic, I do not mind stating that this is precisely the approach that Keven Henning and I took in our book "Understanding Advanced Statistical Methods," (https://peterwestfall.wixsite.com/book-1) whose intended audience is non-statisticians.
|
Should I teach Bayesian or frequentist statistics first?
|
No one has mentioned likelihood, which is foundational to Bayesian statistics. An argument in favor of teaching Bayes first is that the flow from probability, to likelihood, to Bayes, is pretty seamle
|
Should I teach Bayesian or frequentist statistics first?
No one has mentioned likelihood, which is foundational to Bayesian statistics. An argument in favor of teaching Bayes first is that the flow from probability, to likelihood, to Bayes, is pretty seamless. Bayes can be motivated from likelihood by noting that (i) the likelihood function looks (and acts) like a probability distribution function, but is not because the area under the curve is not 1.0, and (ii) the crude, commonly-used Wald intervals assume a likelihood function that is proportional to a normal distribution, but Bayesian methods easily overcome this limitation.
Another argument favoring Bayes first is that the P(A|B) versus P(B|A) concern about p-values can be more easily explained, as mentioned by others.
Yet another argument favoring "Bayes first" is that it forces students to think more carefully about conditional probability models, which is useful elsewhere, e.g., in regression analysis.
Sorry for the self-promotion, but since it is entirely on-topic, I do not mind stating that this is precisely the approach that Keven Henning and I took in our book "Understanding Advanced Statistical Methods," (https://peterwestfall.wixsite.com/book-1) whose intended audience is non-statisticians.
|
Should I teach Bayesian or frequentist statistics first?
No one has mentioned likelihood, which is foundational to Bayesian statistics. An argument in favor of teaching Bayes first is that the flow from probability, to likelihood, to Bayes, is pretty seamle
|
8,449
|
Should I teach Bayesian or frequentist statistics first?
|
Are you teaching for fun and insight or for practical use? If it's about teaching and understanding, I'd go Bayes. If for practical purposes, I'd definitely go Frequentist.
In many fields -and I suppose most fields- of natural sciences, people are used to publish their papers with a p-value. Your "boys" will have to read other people's papers before they come to writing their own. To read other people's papers, at least in my field, they need to understand null hypotheses an p-values, no matter how stupid they may appear after Bayesian studies. And even when they are ready to publish their first paper, they will probably have some senior scientist leading the team and chances are, they prefer Frequentism.
That being said, I would like to concur with @Wayne , in that Statistical rethinking shows a very clear way towards Bayesian statistics as a first approach and not based on existing knowledge about Frequentism. It is great how this book does not try to convince you in a fight of the better or worse statistics. The stated argument of the author for Bayes is (IIRC) that he has been teaching both kinds and Bayes was easier to teach.
|
Should I teach Bayesian or frequentist statistics first?
|
Are you teaching for fun and insight or for practical use? If it's about teaching and understanding, I'd go Bayes. If for practical purposes, I'd definitely go Frequentist.
In many fields -and I supp
|
Should I teach Bayesian or frequentist statistics first?
Are you teaching for fun and insight or for practical use? If it's about teaching and understanding, I'd go Bayes. If for practical purposes, I'd definitely go Frequentist.
In many fields -and I suppose most fields- of natural sciences, people are used to publish their papers with a p-value. Your "boys" will have to read other people's papers before they come to writing their own. To read other people's papers, at least in my field, they need to understand null hypotheses an p-values, no matter how stupid they may appear after Bayesian studies. And even when they are ready to publish their first paper, they will probably have some senior scientist leading the team and chances are, they prefer Frequentism.
That being said, I would like to concur with @Wayne , in that Statistical rethinking shows a very clear way towards Bayesian statistics as a first approach and not based on existing knowledge about Frequentism. It is great how this book does not try to convince you in a fight of the better or worse statistics. The stated argument of the author for Bayes is (IIRC) that he has been teaching both kinds and Bayes was easier to teach.
|
Should I teach Bayesian or frequentist statistics first?
Are you teaching for fun and insight or for practical use? If it's about teaching and understanding, I'd go Bayes. If for practical purposes, I'd definitely go Frequentist.
In many fields -and I supp
|
8,450
|
What is "reduced-rank regression" all about?
|
1. What is reduced-rank regression (RRR)?
Consider multivariate multiple linear regression, i.e. regression with $p$ independent variables and $q$ dependent variables. Let $\mathbf X$ and $\mathbf Y$ be centered predictor ($n \times p$) and response ($n\times q$) datasets. Then usual ordinary least squares (OLS) regression can be formulated as minimizing the following cost function:
$$L=\|\mathbf Y-\mathbf X\mathbf B\|^2,$$
where $\mathbf B$ is a $p\times q$ matrix of regression weights. Its solution is given by $$\hat{\mathbf B}_\mathrm{OLS}=(\mathbf X^\top \mathbf X)^{-1}\mathbf X^\top \mathbf Y,$$ and it is easy to see that it is equivalent to doing $q$ separate OLS regressions, one for each dependent variable.
Reduced-rank regression introduces a rank constraint on $\mathbf B$, namely $L$ should be minimized with $\operatorname{rank}(\mathbf B)\le r$, where $r$ is the maximal allowed rank of $\mathbf B$.
2. How to obtain the RRR solution?
It turns out that RRR can be cast as an eigenvector problem. Indeed, using the fact that OLS is essentially orthogonal projection on the column space of $\mathbf X$, we can rewrite $L$ as $$L=\|\mathbf Y-\mathbf X\hat{\mathbf B}_\mathrm{OLS}\|^2+\|\mathbf X\hat{\mathbf B}_\mathrm{OLS}-\mathbf X\mathbf B\|^2.$$ The first term does not depend on $\mathbf B$ and the second term can be minimized by SVD/PCA of the fitted values $\hat{\mathbf Y}=\mathbf X\hat{\mathbf B}_\mathrm{OLS}$.
Specifically, if $\mathbf U_r$ are first $r$ principal axes of $\hat{\mathbf Y}$, then $$\hat{\mathbf B}_\mathrm{RRR}=\hat{\mathbf B}_\mathrm{OLS}\mathbf U_r\mathbf U_r^\top.$$
3. What is RRR good for?
There can be two reasons to use RRR.
First, one can use it for regularization purposes. Similarly to ridge regression (RR), lasso, etc., RRR introduces some "shrinkage" penalty on $\mathbf B$. The optimal rank $r$ can be found via cross-validation. In my experience, RRR easily outperforms OLS but tends to lose to RR. However, RRR+RR can perform (slightly) better than RR alone.
Second, one can use it as a dimensionality reduction / data exploration method. If we have a bunch of predictor variables and a bunch of dependent variables, then RRR will construct "latent factors" in the predictor space that do the best job of explaining the variance of DVs. One can then try to interpret these latent factors, plot them, etc. As far as I know, this is routinely done in ecology where RRR is known as redundancy analysis and is an example of what they call ordination methods (see @GavinSimpson's answer here).
4. Relationship to other dimensionality reduction methods
RRR is closely connected to other dimensionality reduction methods, such as CCA and PLS. I covered it a little bit in my answer to What is the connection between partial least squares, reduced rank regression, and principal component regression?
if $\mathbf X$ and $\mathbf Y$ are centered predictor ($n \times p$) and response ($n\times q$) datasets and if we look for the first pair of axes, $\mathbf w \in \mathbb R^p$ for $\mathbf X$ and $\mathbf v \in \mathbb R^q$ for $\mathbf Y$, then these methods maximize the following quantities:
\begin{align}
\mathrm{PCA:}&\quad \operatorname{Var}(\mathbf{Xw}) \\
\mathrm{RRR:}&\quad \phantom{\operatorname{Var}(\mathbf {Xw})\cdot{}}\operatorname{Corr}^2(\mathbf{Xw},\mathbf {Yv})\cdot\operatorname{Var}(\mathbf{Yv}) \\
\mathrm{PLS:}&\quad \operatorname{Var}(\mathbf{Xw})\cdot\operatorname{Corr}^2(\mathbf{Xw},\mathbf {Yv})\cdot\operatorname{Var}(\mathbf {Yv}) = \operatorname{Cov}^2(\mathbf{Xw},\mathbf {Yv})\\
\mathrm{CCA:}&\quad \phantom{\operatorname{Var}(\mathbf {Xw})\cdot {}}\operatorname{Corr}^2(\mathbf {Xw},\mathbf {Yv})
\end{align}
See there for some more details.
See Torre, 2009, A Least-Squares Framework for Component Analysis for a detailed treatment of how most of the common linear multivariate methods (e.g. PCA, CCA, LDA, -- but not PLS!) can be seen as RRR.
5. Why is this section in Hastie et al. so confusing?
Hastie et al. use the term RRR to refer to a slightly different thing! Instead of using the loss function $$L=\|\mathbf Y-\mathbf X \mathbf B\|^2,$$ they use $$L=\|(\mathbf Y-\mathbf X \mathbf B)(\mathbf Y^\top \mathbf Y)^{-1/2}\|^2,$$ as can be seen in their formula 3.68. This introduces a $\mathbf Y$-whitening factor into the loss function, essentially whitening the dependent variables. If you look at the comparison between CCA and RRR above, you will notice that if $\mathbf Y$ is whitened then the difference disappears. So what Hastie et al. call RRR is actually CCA in disguise (and indeed, see their 3.69).
None of that is properly explained in this section, hence the confusion.
See my answer to Friendly tutorial or introduction to reduced-rank regression for further reading.
|
What is "reduced-rank regression" all about?
|
1. What is reduced-rank regression (RRR)?
Consider multivariate multiple linear regression, i.e. regression with $p$ independent variables and $q$ dependent variables. Let $\mathbf X$ and $\mathbf Y$
|
What is "reduced-rank regression" all about?
1. What is reduced-rank regression (RRR)?
Consider multivariate multiple linear regression, i.e. regression with $p$ independent variables and $q$ dependent variables. Let $\mathbf X$ and $\mathbf Y$ be centered predictor ($n \times p$) and response ($n\times q$) datasets. Then usual ordinary least squares (OLS) regression can be formulated as minimizing the following cost function:
$$L=\|\mathbf Y-\mathbf X\mathbf B\|^2,$$
where $\mathbf B$ is a $p\times q$ matrix of regression weights. Its solution is given by $$\hat{\mathbf B}_\mathrm{OLS}=(\mathbf X^\top \mathbf X)^{-1}\mathbf X^\top \mathbf Y,$$ and it is easy to see that it is equivalent to doing $q$ separate OLS regressions, one for each dependent variable.
Reduced-rank regression introduces a rank constraint on $\mathbf B$, namely $L$ should be minimized with $\operatorname{rank}(\mathbf B)\le r$, where $r$ is the maximal allowed rank of $\mathbf B$.
2. How to obtain the RRR solution?
It turns out that RRR can be cast as an eigenvector problem. Indeed, using the fact that OLS is essentially orthogonal projection on the column space of $\mathbf X$, we can rewrite $L$ as $$L=\|\mathbf Y-\mathbf X\hat{\mathbf B}_\mathrm{OLS}\|^2+\|\mathbf X\hat{\mathbf B}_\mathrm{OLS}-\mathbf X\mathbf B\|^2.$$ The first term does not depend on $\mathbf B$ and the second term can be minimized by SVD/PCA of the fitted values $\hat{\mathbf Y}=\mathbf X\hat{\mathbf B}_\mathrm{OLS}$.
Specifically, if $\mathbf U_r$ are first $r$ principal axes of $\hat{\mathbf Y}$, then $$\hat{\mathbf B}_\mathrm{RRR}=\hat{\mathbf B}_\mathrm{OLS}\mathbf U_r\mathbf U_r^\top.$$
3. What is RRR good for?
There can be two reasons to use RRR.
First, one can use it for regularization purposes. Similarly to ridge regression (RR), lasso, etc., RRR introduces some "shrinkage" penalty on $\mathbf B$. The optimal rank $r$ can be found via cross-validation. In my experience, RRR easily outperforms OLS but tends to lose to RR. However, RRR+RR can perform (slightly) better than RR alone.
Second, one can use it as a dimensionality reduction / data exploration method. If we have a bunch of predictor variables and a bunch of dependent variables, then RRR will construct "latent factors" in the predictor space that do the best job of explaining the variance of DVs. One can then try to interpret these latent factors, plot them, etc. As far as I know, this is routinely done in ecology where RRR is known as redundancy analysis and is an example of what they call ordination methods (see @GavinSimpson's answer here).
4. Relationship to other dimensionality reduction methods
RRR is closely connected to other dimensionality reduction methods, such as CCA and PLS. I covered it a little bit in my answer to What is the connection between partial least squares, reduced rank regression, and principal component regression?
if $\mathbf X$ and $\mathbf Y$ are centered predictor ($n \times p$) and response ($n\times q$) datasets and if we look for the first pair of axes, $\mathbf w \in \mathbb R^p$ for $\mathbf X$ and $\mathbf v \in \mathbb R^q$ for $\mathbf Y$, then these methods maximize the following quantities:
\begin{align}
\mathrm{PCA:}&\quad \operatorname{Var}(\mathbf{Xw}) \\
\mathrm{RRR:}&\quad \phantom{\operatorname{Var}(\mathbf {Xw})\cdot{}}\operatorname{Corr}^2(\mathbf{Xw},\mathbf {Yv})\cdot\operatorname{Var}(\mathbf{Yv}) \\
\mathrm{PLS:}&\quad \operatorname{Var}(\mathbf{Xw})\cdot\operatorname{Corr}^2(\mathbf{Xw},\mathbf {Yv})\cdot\operatorname{Var}(\mathbf {Yv}) = \operatorname{Cov}^2(\mathbf{Xw},\mathbf {Yv})\\
\mathrm{CCA:}&\quad \phantom{\operatorname{Var}(\mathbf {Xw})\cdot {}}\operatorname{Corr}^2(\mathbf {Xw},\mathbf {Yv})
\end{align}
See there for some more details.
See Torre, 2009, A Least-Squares Framework for Component Analysis for a detailed treatment of how most of the common linear multivariate methods (e.g. PCA, CCA, LDA, -- but not PLS!) can be seen as RRR.
5. Why is this section in Hastie et al. so confusing?
Hastie et al. use the term RRR to refer to a slightly different thing! Instead of using the loss function $$L=\|\mathbf Y-\mathbf X \mathbf B\|^2,$$ they use $$L=\|(\mathbf Y-\mathbf X \mathbf B)(\mathbf Y^\top \mathbf Y)^{-1/2}\|^2,$$ as can be seen in their formula 3.68. This introduces a $\mathbf Y$-whitening factor into the loss function, essentially whitening the dependent variables. If you look at the comparison between CCA and RRR above, you will notice that if $\mathbf Y$ is whitened then the difference disappears. So what Hastie et al. call RRR is actually CCA in disguise (and indeed, see their 3.69).
None of that is properly explained in this section, hence the confusion.
See my answer to Friendly tutorial or introduction to reduced-rank regression for further reading.
|
What is "reduced-rank regression" all about?
1. What is reduced-rank regression (RRR)?
Consider multivariate multiple linear regression, i.e. regression with $p$ independent variables and $q$ dependent variables. Let $\mathbf X$ and $\mathbf Y$
|
8,451
|
What is "reduced-rank regression" all about?
|
Reduced Rank Regression is a model where there is not a single Y outcome, but multiple Y outcomes. Of course, you can just fit a separate multivariate linear regression for each response, but this seems inefficient when the functional relationship between the predictors and each response is clearly similar. See this kaggle exercise for a situation where I believe this obviously holds.
https://www.kaggle.com/c/bike-sharing-demand/data
There are several related techniques for approaching this problem that build "factors" or "components" out of the X variables that are then used for predicting the Ys.
This documentation page from SAS helped clear up the differences for me. Reduced Rank Regression seems to be about extracting components that maximally account for variation among the responses, in contrast to Partial Least Squares which extracts components that maximally account for variation among both the responses and predictors.
https://support.sas.com/documentation/cdl/en/statug/63347/HTML/default/viewer.htm#statug_pls_sect014.htm
|
What is "reduced-rank regression" all about?
|
Reduced Rank Regression is a model where there is not a single Y outcome, but multiple Y outcomes. Of course, you can just fit a separate multivariate linear regression for each response, but this see
|
What is "reduced-rank regression" all about?
Reduced Rank Regression is a model where there is not a single Y outcome, but multiple Y outcomes. Of course, you can just fit a separate multivariate linear regression for each response, but this seems inefficient when the functional relationship between the predictors and each response is clearly similar. See this kaggle exercise for a situation where I believe this obviously holds.
https://www.kaggle.com/c/bike-sharing-demand/data
There are several related techniques for approaching this problem that build "factors" or "components" out of the X variables that are then used for predicting the Ys.
This documentation page from SAS helped clear up the differences for me. Reduced Rank Regression seems to be about extracting components that maximally account for variation among the responses, in contrast to Partial Least Squares which extracts components that maximally account for variation among both the responses and predictors.
https://support.sas.com/documentation/cdl/en/statug/63347/HTML/default/viewer.htm#statug_pls_sect014.htm
|
What is "reduced-rank regression" all about?
Reduced Rank Regression is a model where there is not a single Y outcome, but multiple Y outcomes. Of course, you can just fit a separate multivariate linear regression for each response, but this see
|
8,452
|
Geometric interpretation of multiple correlation coefficient $R$ and coefficient of determination $R^2$
|
If there is a constant term in the model then $\mathbf{1_n}$ lies in the column space of $\mathbf{X}$ (as does $\bar{Y}\mathbf{1_n}$, which will come in useful later). The fitted $\mathbf{\hat{Y}}$ is the orthogonal projection of the observed $\mathbf{Y}$ onto the flat formed by that column space. This means the vector of residuals $\mathbf{e} = \mathbf{y} - \mathbf{\hat{y}}$ is perpendicular to the flat, and hence to $\mathbf{1_n}$. Considering the dot product we can see $\sum_{i=1}^n e_i = 0$, so the components of $\mathbf{e}$ must sum to zero. Since $Y_i = \hat{Y_i} + e_i$ we conclude that $\sum_{i=1}^n Y_i = \sum_{i=1}^n \hat{Y_i}$ so that both fitted and observed responses have mean $\bar{Y}$.
The dashed lines in the diagram represent $\mathbf{Y} - \bar{Y}\mathbf{1_n}$ and $\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}$, which are the centered vectors for the observed and fitted responses. The cosine of the angle $\theta$ between these vectors will therefore be the correlation of $Y$ and $\hat{Y}$, which by definition is the multiple correlation coefficient $R$. The triangle these vectors form with the vector of residuals is right-angled since $\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}$ lies in the flat but $\mathbf{e}$ is orthogonal to it. Hence:
$$R = \cos(\theta) = \frac{\text{adj}}{\text{hyp}} = \frac{\|\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}\|}{\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|} $$
We could also apply Pythagoras to the triangle:
$$\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|^2 =
\|\mathbf{Y} - \mathbf{\hat{Y}}\|^2 + \|\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}\|^2 $$
Which may be more familiar as:
$$\sum_{i=1}^{n} (Y_i - \bar{Y})^2 =
\sum_{i=1}^{n} (Y_i - \hat{Y}_i)^2 + \sum_{i=1}^{n} (\hat{Y}_i - \bar{Y})^2 $$
This is the decomposition of the sums of squares, $SS_{\text{total}} = SS_{\text{residual}} + SS_{\text{regression}}$.
The standard definition for the coefficient of determination is:
$$R^2 = 1 - \frac{SS_{\text{residual}}}{SS_{\text{total}}} = 1 - \frac{\sum_{i=1}^n (y_i - \hat{y}_i)^2}{\sum_{i=1}^n (y_i - \bar{y})^2} =
1 - \frac{\|\mathbf{Y} - \mathbf{\hat{Y}}\|^2}{\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|^2}$$
When the sums of squares can be partitioned, it takes some straightforward algebra to show this is equivalent to the "proportion of variance explained" formulation,
$$R^2 = \frac{SS_{\text{regression}}}{SS_{\text{total}}} =
\frac{\sum_{i=1}^n (\hat{y}_i - \bar{y})^2}{\sum_{i=1}^n (y_i - \bar{y})^2} =
\frac{\|\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}\|^2}{\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|^2}$$
There is a geometric way of seeing this from the triangle, with minimal algebra. The definitional formula gives $R^2 = 1 - \sin^2(\theta)$ and with basic trigonometry we can simplify this to $\cos^2(\theta)$. This is the link between $R^2$ and $R$.
Note how vital it was for this analysis to have fitted an intercept term, so that $\mathbf{1_n}$ was in the column space. Without this, the residuals would not have summed to zero, and the mean of the fitted values would not have coincided with the mean of $Y$. In that case we couldn't have drawn the triangle; the sums of squares would not have decomposed in a Pythagorean manner; $R^2$ would not have had the frequently-quoted form $SS_{\text{reg}}/SS_{\text{total}}$ nor be the square of $R$. In this situation, some software (including R) uses a different formula for $R^2$ altogether.
|
Geometric interpretation of multiple correlation coefficient $R$ and coefficient of determination $R
|
If there is a constant term in the model then $\mathbf{1_n}$ lies in the column space of $\mathbf{X}$ (as does $\bar{Y}\mathbf{1_n}$, which will come in useful later). The fitted $\mathbf{\hat{Y}}$ is
|
Geometric interpretation of multiple correlation coefficient $R$ and coefficient of determination $R^2$
If there is a constant term in the model then $\mathbf{1_n}$ lies in the column space of $\mathbf{X}$ (as does $\bar{Y}\mathbf{1_n}$, which will come in useful later). The fitted $\mathbf{\hat{Y}}$ is the orthogonal projection of the observed $\mathbf{Y}$ onto the flat formed by that column space. This means the vector of residuals $\mathbf{e} = \mathbf{y} - \mathbf{\hat{y}}$ is perpendicular to the flat, and hence to $\mathbf{1_n}$. Considering the dot product we can see $\sum_{i=1}^n e_i = 0$, so the components of $\mathbf{e}$ must sum to zero. Since $Y_i = \hat{Y_i} + e_i$ we conclude that $\sum_{i=1}^n Y_i = \sum_{i=1}^n \hat{Y_i}$ so that both fitted and observed responses have mean $\bar{Y}$.
The dashed lines in the diagram represent $\mathbf{Y} - \bar{Y}\mathbf{1_n}$ and $\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}$, which are the centered vectors for the observed and fitted responses. The cosine of the angle $\theta$ between these vectors will therefore be the correlation of $Y$ and $\hat{Y}$, which by definition is the multiple correlation coefficient $R$. The triangle these vectors form with the vector of residuals is right-angled since $\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}$ lies in the flat but $\mathbf{e}$ is orthogonal to it. Hence:
$$R = \cos(\theta) = \frac{\text{adj}}{\text{hyp}} = \frac{\|\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}\|}{\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|} $$
We could also apply Pythagoras to the triangle:
$$\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|^2 =
\|\mathbf{Y} - \mathbf{\hat{Y}}\|^2 + \|\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}\|^2 $$
Which may be more familiar as:
$$\sum_{i=1}^{n} (Y_i - \bar{Y})^2 =
\sum_{i=1}^{n} (Y_i - \hat{Y}_i)^2 + \sum_{i=1}^{n} (\hat{Y}_i - \bar{Y})^2 $$
This is the decomposition of the sums of squares, $SS_{\text{total}} = SS_{\text{residual}} + SS_{\text{regression}}$.
The standard definition for the coefficient of determination is:
$$R^2 = 1 - \frac{SS_{\text{residual}}}{SS_{\text{total}}} = 1 - \frac{\sum_{i=1}^n (y_i - \hat{y}_i)^2}{\sum_{i=1}^n (y_i - \bar{y})^2} =
1 - \frac{\|\mathbf{Y} - \mathbf{\hat{Y}}\|^2}{\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|^2}$$
When the sums of squares can be partitioned, it takes some straightforward algebra to show this is equivalent to the "proportion of variance explained" formulation,
$$R^2 = \frac{SS_{\text{regression}}}{SS_{\text{total}}} =
\frac{\sum_{i=1}^n (\hat{y}_i - \bar{y})^2}{\sum_{i=1}^n (y_i - \bar{y})^2} =
\frac{\|\mathbf{\hat{Y}} - \bar{Y}\mathbf{1_n}\|^2}{\|\mathbf{Y} - \bar{Y}\mathbf{1_n}\|^2}$$
There is a geometric way of seeing this from the triangle, with minimal algebra. The definitional formula gives $R^2 = 1 - \sin^2(\theta)$ and with basic trigonometry we can simplify this to $\cos^2(\theta)$. This is the link between $R^2$ and $R$.
Note how vital it was for this analysis to have fitted an intercept term, so that $\mathbf{1_n}$ was in the column space. Without this, the residuals would not have summed to zero, and the mean of the fitted values would not have coincided with the mean of $Y$. In that case we couldn't have drawn the triangle; the sums of squares would not have decomposed in a Pythagorean manner; $R^2$ would not have had the frequently-quoted form $SS_{\text{reg}}/SS_{\text{total}}$ nor be the square of $R$. In this situation, some software (including R) uses a different formula for $R^2$ altogether.
|
Geometric interpretation of multiple correlation coefficient $R$ and coefficient of determination $R
If there is a constant term in the model then $\mathbf{1_n}$ lies in the column space of $\mathbf{X}$ (as does $\bar{Y}\mathbf{1_n}$, which will come in useful later). The fitted $\mathbf{\hat{Y}}$ is
|
8,453
|
How can the regression error term ever be correlated with the explanatory variables?
|
You are conflating two types of "error" term. Wikipedia actually has an article devoted to this distinction between errors and residuals.
In an OLS regression, the residuals (your estimates of the error or disturbance term) $\hat \varepsilon$ are indeed guaranteed to be uncorrelated with the predictor variables, assuming the regression contains an intercept term.
But the "true" errors $\varepsilon$ may well be correlated with them, and this is what counts as endogeneity.
To keep things simple, consider the regression model (you might see this described as the underlying "data generating process" or "DGP", the theoretical model that we assume to generate the value of $y$):
$$y_i = \beta_1 + \beta_2 x_i + \varepsilon_i$$
There is no reason, in principle, why $x$ can't be correlated with $\varepsilon$ in our model, however much we would prefer it not to breach the standard OLS assumptions in this way. For example, it might be that $y$ depends on another variable that has been omitted from our model, and this has been incorporated into the disturbance term (the $\varepsilon$ is where we lump in all the things other than $x$ that affect $y$). If this omitted variable is also correlated with $x$, then $\varepsilon$ will in turn be correlated with $x$ and we have endogeneity (in particular, omitted-variable bias).
When you estimate your regression model on the available data, we get
$$y_i = \hat \beta_1 + \hat \beta_2 x_i + \hat \varepsilon_i$$
Because of the way OLS works*, the residuals $\hat \varepsilon$ will be uncorrelated with $x$. But that doesn't mean we have avoided endogeneity — it just means that we can't detect it by analysing the correlation between $\hat \varepsilon$ and $x$, which will be (up to numerical error) zero. And because the OLS assumptions have been breached, we are no longer guaranteed the nice properties, such as unbiasedness, we enjoy so much about OLS. Our estimate $\hat \beta_2$ will be biased.
$(*)$ The fact that $\hat \varepsilon$ is uncorrelated with $x$ follows immediately from the "normal equations" we use to choose our best estimates for the coefficients.
If you are not used to the matrix setting, and I stick to the bivariate model used in my example above, then the sum of squared residuals is $S(b_1, b_2) = \sum_{i=1}^n \varepsilon_i^2 = \sum_{i=1}^n (y_i-b_1 - b_2 x_i)^2$ and to find the optimal $b_1 = \hat \beta_1$ and $b_2 = \hat \beta_2$ that minimise this we find the normal equations, firstly the first-order condition for the estimated intercept:
$$\frac{\partial S}{\partial b_1} = \sum_{i=1}^n -2(y_i-b_1 - b_2 x_i) = -2 \sum_{i=1}^n \hat \varepsilon_i = 0$$
which shows that the sum (and hence mean) of the residuals is zero, so the formula for the covariance between $\hat \varepsilon$ and any variable $x$ then reduces to $\frac{1}{n-1} \sum_{i=1}^n x_i \hat \varepsilon_i$. We see this is zero by considering the first-order condition for the estimated slope, which is that
$$\frac{\partial S}{\partial b_2} = \sum_{i=1}^n -2 x_i (y_i-b_1 - b_2 x_i) = -2 \sum_{i=1}^n x_i \hat \varepsilon_i = 0$$
If you are used to working with matrices, we can generalise this to multiple regression by defining $S(b) = \varepsilon' \varepsilon = (y-Xb)'(y-Xb)$; the first-order condition to minimise $S(b)$ at optimal $b = \hat \beta$ is:
$$\frac{dS}{db}(\hat\beta) = \frac{d}{db}\bigg(y'y - b'X'y - y'Xb + b'X'Xb\bigg)\bigg|_{b=\hat\beta} = -2X'y + 2X'X\hat\beta = -2X'(y - X\hat\beta) = -2X'\hat \varepsilon = 0$$
This implies each row of $X'$, and hence each column of $X$, is orthogonal to $\hat \varepsilon$. Then if the design matrix $X$ has a column of ones (which happens if your model has an intercept term), we must have $\sum_{i=1}^n \hat \varepsilon_i = 0$ so the residuals have zero sum and zero mean. The covariance between $\hat \varepsilon$ and any variable $x$ is again $\frac{1}{n-1} \sum_{i=1}^n x_i \hat \varepsilon_i$ and for any variable $x$ included in our model we know this sum is zero, because $\hat \varepsilon$ is orthogonal to every column of the design matrix. Hence there is zero covariance, and zero correlation, between $\hat \varepsilon$ and any predictor variable $x$.
If you prefer a more geometric view of things, our desire that $\hat y$ lies as close as possible to $y$ in a Pythagorean kind of way, and the fact that $\hat y$ is constrained to the column space of the design matrix $X$, dictate that $\hat y$ should be the orthogonal projection of the observed $y$ onto that column space. Hence the vector of residuals $\hat \varepsilon = y - \hat y$ is orthogonal to every column of $X$, including the vector of ones $\mathbf{1_n}$ if an intercept term is included in the model. As before, this implies the sum of residuals is zero, whence the residual vector's orthogonality with the other columns of $X$ ensures it is uncorrelated with each of those predictors.
But nothing we have done here says anything about the true errors $\varepsilon$. Assuming there is an intercept term in our model, the residuals $\hat \varepsilon$ are only uncorrelated with $x$ as a mathematical consequence of the manner in which we chose to estimate regression coefficients $\hat \beta$. The way we selected our $\hat \beta$ affects our predicted values $\hat y$ and hence our residuals $\hat \varepsilon = y - \hat y$. If we choose $\hat \beta$ by OLS, we must solve the normal equations and these enforce that our estimated residuals $\hat \varepsilon$ are uncorrelated with $x$. Our choice of $\hat \beta$ affects $\hat y$ but not $\mathbb{E}(y)$ and hence imposes no conditions on the true errors $\varepsilon = y - \mathbb{E}(y)$. It would be a mistake to think that $\hat \varepsilon$ has somehow "inherited" its uncorrelatedness with $x$ from the OLS assumption that $\varepsilon$ should be uncorrelated with $x$. The uncorrelatedness arises from the normal equations.
|
How can the regression error term ever be correlated with the explanatory variables?
|
You are conflating two types of "error" term. Wikipedia actually has an article devoted to this distinction between errors and residuals.
In an OLS regression, the residuals (your estimates of the err
|
How can the regression error term ever be correlated with the explanatory variables?
You are conflating two types of "error" term. Wikipedia actually has an article devoted to this distinction between errors and residuals.
In an OLS regression, the residuals (your estimates of the error or disturbance term) $\hat \varepsilon$ are indeed guaranteed to be uncorrelated with the predictor variables, assuming the regression contains an intercept term.
But the "true" errors $\varepsilon$ may well be correlated with them, and this is what counts as endogeneity.
To keep things simple, consider the regression model (you might see this described as the underlying "data generating process" or "DGP", the theoretical model that we assume to generate the value of $y$):
$$y_i = \beta_1 + \beta_2 x_i + \varepsilon_i$$
There is no reason, in principle, why $x$ can't be correlated with $\varepsilon$ in our model, however much we would prefer it not to breach the standard OLS assumptions in this way. For example, it might be that $y$ depends on another variable that has been omitted from our model, and this has been incorporated into the disturbance term (the $\varepsilon$ is where we lump in all the things other than $x$ that affect $y$). If this omitted variable is also correlated with $x$, then $\varepsilon$ will in turn be correlated with $x$ and we have endogeneity (in particular, omitted-variable bias).
When you estimate your regression model on the available data, we get
$$y_i = \hat \beta_1 + \hat \beta_2 x_i + \hat \varepsilon_i$$
Because of the way OLS works*, the residuals $\hat \varepsilon$ will be uncorrelated with $x$. But that doesn't mean we have avoided endogeneity — it just means that we can't detect it by analysing the correlation between $\hat \varepsilon$ and $x$, which will be (up to numerical error) zero. And because the OLS assumptions have been breached, we are no longer guaranteed the nice properties, such as unbiasedness, we enjoy so much about OLS. Our estimate $\hat \beta_2$ will be biased.
$(*)$ The fact that $\hat \varepsilon$ is uncorrelated with $x$ follows immediately from the "normal equations" we use to choose our best estimates for the coefficients.
If you are not used to the matrix setting, and I stick to the bivariate model used in my example above, then the sum of squared residuals is $S(b_1, b_2) = \sum_{i=1}^n \varepsilon_i^2 = \sum_{i=1}^n (y_i-b_1 - b_2 x_i)^2$ and to find the optimal $b_1 = \hat \beta_1$ and $b_2 = \hat \beta_2$ that minimise this we find the normal equations, firstly the first-order condition for the estimated intercept:
$$\frac{\partial S}{\partial b_1} = \sum_{i=1}^n -2(y_i-b_1 - b_2 x_i) = -2 \sum_{i=1}^n \hat \varepsilon_i = 0$$
which shows that the sum (and hence mean) of the residuals is zero, so the formula for the covariance between $\hat \varepsilon$ and any variable $x$ then reduces to $\frac{1}{n-1} \sum_{i=1}^n x_i \hat \varepsilon_i$. We see this is zero by considering the first-order condition for the estimated slope, which is that
$$\frac{\partial S}{\partial b_2} = \sum_{i=1}^n -2 x_i (y_i-b_1 - b_2 x_i) = -2 \sum_{i=1}^n x_i \hat \varepsilon_i = 0$$
If you are used to working with matrices, we can generalise this to multiple regression by defining $S(b) = \varepsilon' \varepsilon = (y-Xb)'(y-Xb)$; the first-order condition to minimise $S(b)$ at optimal $b = \hat \beta$ is:
$$\frac{dS}{db}(\hat\beta) = \frac{d}{db}\bigg(y'y - b'X'y - y'Xb + b'X'Xb\bigg)\bigg|_{b=\hat\beta} = -2X'y + 2X'X\hat\beta = -2X'(y - X\hat\beta) = -2X'\hat \varepsilon = 0$$
This implies each row of $X'$, and hence each column of $X$, is orthogonal to $\hat \varepsilon$. Then if the design matrix $X$ has a column of ones (which happens if your model has an intercept term), we must have $\sum_{i=1}^n \hat \varepsilon_i = 0$ so the residuals have zero sum and zero mean. The covariance between $\hat \varepsilon$ and any variable $x$ is again $\frac{1}{n-1} \sum_{i=1}^n x_i \hat \varepsilon_i$ and for any variable $x$ included in our model we know this sum is zero, because $\hat \varepsilon$ is orthogonal to every column of the design matrix. Hence there is zero covariance, and zero correlation, between $\hat \varepsilon$ and any predictor variable $x$.
If you prefer a more geometric view of things, our desire that $\hat y$ lies as close as possible to $y$ in a Pythagorean kind of way, and the fact that $\hat y$ is constrained to the column space of the design matrix $X$, dictate that $\hat y$ should be the orthogonal projection of the observed $y$ onto that column space. Hence the vector of residuals $\hat \varepsilon = y - \hat y$ is orthogonal to every column of $X$, including the vector of ones $\mathbf{1_n}$ if an intercept term is included in the model. As before, this implies the sum of residuals is zero, whence the residual vector's orthogonality with the other columns of $X$ ensures it is uncorrelated with each of those predictors.
But nothing we have done here says anything about the true errors $\varepsilon$. Assuming there is an intercept term in our model, the residuals $\hat \varepsilon$ are only uncorrelated with $x$ as a mathematical consequence of the manner in which we chose to estimate regression coefficients $\hat \beta$. The way we selected our $\hat \beta$ affects our predicted values $\hat y$ and hence our residuals $\hat \varepsilon = y - \hat y$. If we choose $\hat \beta$ by OLS, we must solve the normal equations and these enforce that our estimated residuals $\hat \varepsilon$ are uncorrelated with $x$. Our choice of $\hat \beta$ affects $\hat y$ but not $\mathbb{E}(y)$ and hence imposes no conditions on the true errors $\varepsilon = y - \mathbb{E}(y)$. It would be a mistake to think that $\hat \varepsilon$ has somehow "inherited" its uncorrelatedness with $x$ from the OLS assumption that $\varepsilon$ should be uncorrelated with $x$. The uncorrelatedness arises from the normal equations.
|
How can the regression error term ever be correlated with the explanatory variables?
You are conflating two types of "error" term. Wikipedia actually has an article devoted to this distinction between errors and residuals.
In an OLS regression, the residuals (your estimates of the err
|
8,454
|
How can the regression error term ever be correlated with the explanatory variables?
|
Simple example:
Let $x_{i,1}$ be the number of burgers I buy on visit $i$
Let $x_{i,2}$ be the number of buns I buy.
Let $b_1$ be the price of a burger
Let $b_2$ be the price of a bun.
Independent of my burger and bun purchases, let me spend a random amount $a + \epsilon_i$ where $a$ is a scalar and $\epsilon_i$ is a mean zero random variable. We have $\operatorname{E}[\epsilon_i | X] = 0$.
Let $y_i$ be my spending on a trip to the grocery store.
The data generating process is:
$$ y_i = a + b_1x_{i,1} + b_2x_{i,2} + \epsilon_i$$
If we ran that regression, we would get estimates $\hat{a}$, $\hat{b}_1$, and $\hat{b}_2$, and with enough data, they would converge on $a$, $b_1$, and $b_2$ respectively.
(Technical note: We need a little randomness so we don't buy exactly one bun for each burger we buy at every visit to the grocery store. If we did this, $x_1$ and $x_2$ would be collinear.)
An example of omitted variable bias:
Now let's consider the model:
$$ y_i = a + b_1x_{i,1} + u_i $$
Observe that $u_i = b_2x_{i,2} + \epsilon_i$. Hence
\begin{align*}
\operatorname{Cov}(x_{1}, u) &= \operatorname{Cov}(x_1,b_2x_2 + \epsilon )\\
&= b_2 \operatorname{Cov}(x_{1},x_2) + \operatorname{Cov}(x_{1},\epsilon) \\
&= b_2 \operatorname{Cov}(x_{1},x_2)
\end{align*}
Is this zero? Almost certainly not! The purchase of burgers $x_1$ and the purchase of buns $x_2$ are almost certainly correlated! Hence $u$ and $x_1$ are correlated!
What happens if you tried to run the regression?
If you tried to run:
$$ y_i = \hat{a} + \hat{b}_1 x_{i,1} + \hat{u}_i $$
Your estimate $\hat{b}_1$ would almost certainly be a poor estimate of $b_1$ because the OLS regression estimates $\hat{a}, \hat{b}, \hat{u}$ would be constructed so that $\hat{u}$ and $x_1$ are uncorrelated in your sample. But the actual $u$ is correlated with $x_1$ in the population!
What would happen in practice if you did this? Your estimate $\hat{b}_1$ of the price of burgers would ALSO pickup the price of buns. Let's say every time you bought a \$1 burger you tended to buy a \$0.50 bun (but not all the time). Your estimate of the price of burgers might be \$1.40. You'd be picking up the burger channel and the bun channel in your estimate of the burger price.
|
How can the regression error term ever be correlated with the explanatory variables?
|
Simple example:
Let $x_{i,1}$ be the number of burgers I buy on visit $i$
Let $x_{i,2}$ be the number of buns I buy.
Let $b_1$ be the price of a burger
Let $b_2$ be the price of a bun.
Independent of
|
How can the regression error term ever be correlated with the explanatory variables?
Simple example:
Let $x_{i,1}$ be the number of burgers I buy on visit $i$
Let $x_{i,2}$ be the number of buns I buy.
Let $b_1$ be the price of a burger
Let $b_2$ be the price of a bun.
Independent of my burger and bun purchases, let me spend a random amount $a + \epsilon_i$ where $a$ is a scalar and $\epsilon_i$ is a mean zero random variable. We have $\operatorname{E}[\epsilon_i | X] = 0$.
Let $y_i$ be my spending on a trip to the grocery store.
The data generating process is:
$$ y_i = a + b_1x_{i,1} + b_2x_{i,2} + \epsilon_i$$
If we ran that regression, we would get estimates $\hat{a}$, $\hat{b}_1$, and $\hat{b}_2$, and with enough data, they would converge on $a$, $b_1$, and $b_2$ respectively.
(Technical note: We need a little randomness so we don't buy exactly one bun for each burger we buy at every visit to the grocery store. If we did this, $x_1$ and $x_2$ would be collinear.)
An example of omitted variable bias:
Now let's consider the model:
$$ y_i = a + b_1x_{i,1} + u_i $$
Observe that $u_i = b_2x_{i,2} + \epsilon_i$. Hence
\begin{align*}
\operatorname{Cov}(x_{1}, u) &= \operatorname{Cov}(x_1,b_2x_2 + \epsilon )\\
&= b_2 \operatorname{Cov}(x_{1},x_2) + \operatorname{Cov}(x_{1},\epsilon) \\
&= b_2 \operatorname{Cov}(x_{1},x_2)
\end{align*}
Is this zero? Almost certainly not! The purchase of burgers $x_1$ and the purchase of buns $x_2$ are almost certainly correlated! Hence $u$ and $x_1$ are correlated!
What happens if you tried to run the regression?
If you tried to run:
$$ y_i = \hat{a} + \hat{b}_1 x_{i,1} + \hat{u}_i $$
Your estimate $\hat{b}_1$ would almost certainly be a poor estimate of $b_1$ because the OLS regression estimates $\hat{a}, \hat{b}, \hat{u}$ would be constructed so that $\hat{u}$ and $x_1$ are uncorrelated in your sample. But the actual $u$ is correlated with $x_1$ in the population!
What would happen in practice if you did this? Your estimate $\hat{b}_1$ of the price of burgers would ALSO pickup the price of buns. Let's say every time you bought a \$1 burger you tended to buy a \$0.50 bun (but not all the time). Your estimate of the price of burgers might be \$1.40. You'd be picking up the burger channel and the bun channel in your estimate of the burger price.
|
How can the regression error term ever be correlated with the explanatory variables?
Simple example:
Let $x_{i,1}$ be the number of burgers I buy on visit $i$
Let $x_{i,2}$ be the number of buns I buy.
Let $b_1$ be the price of a burger
Let $b_2$ be the price of a bun.
Independent of
|
8,455
|
How can the regression error term ever be correlated with the explanatory variables?
|
Suppose that we're building a regression of the weight of an animal on its height. Clearly, the weight of a dolphin would be measured differently (in different procedure and using different instruments) from the weight of an elephant or a snake. This means that the model errors will be dependent on the height, i.e. explanatory variable. They could be dependent in many different ways. For instance, maybe we tend to slightly overestimate the elephant weights and slightly underestimate the snake's, etc.
So, here we established that it is easy to end up with a situation when the errors are correlated with the explanatory variables. Now, if we ignore this and proceed to regression as usual, we'll notice that the regression residuals are not correlated with the design matrix. This is because, by design the regression forces the residuals to be uncorrelated. Note, also that residuals are not the errors, they're the estimates of errors. So, regardless of whether the errors themselves are correlated or not with the independent variables the error estimates (residuals) will be uncorrelated by the construction of the regression equation solution.
|
How can the regression error term ever be correlated with the explanatory variables?
|
Suppose that we're building a regression of the weight of an animal on its height. Clearly, the weight of a dolphin would be measured differently (in different procedure and using different instrument
|
How can the regression error term ever be correlated with the explanatory variables?
Suppose that we're building a regression of the weight of an animal on its height. Clearly, the weight of a dolphin would be measured differently (in different procedure and using different instruments) from the weight of an elephant or a snake. This means that the model errors will be dependent on the height, i.e. explanatory variable. They could be dependent in many different ways. For instance, maybe we tend to slightly overestimate the elephant weights and slightly underestimate the snake's, etc.
So, here we established that it is easy to end up with a situation when the errors are correlated with the explanatory variables. Now, if we ignore this and proceed to regression as usual, we'll notice that the regression residuals are not correlated with the design matrix. This is because, by design the regression forces the residuals to be uncorrelated. Note, also that residuals are not the errors, they're the estimates of errors. So, regardless of whether the errors themselves are correlated or not with the independent variables the error estimates (residuals) will be uncorrelated by the construction of the regression equation solution.
|
How can the regression error term ever be correlated with the explanatory variables?
Suppose that we're building a regression of the weight of an animal on its height. Clearly, the weight of a dolphin would be measured differently (in different procedure and using different instrument
|
8,456
|
Produce a list of variable name in a for loop, then assign values to them
|
Your are looking for assign().
for(i in 1:3){
assign(paste("a", i, sep = ""), i)
}
gives
> ls()
[1] "a1" "a2" "a3"
and
> a1
[1] 1
> a2
[1] 2
> a3
[1] 3
Update
I agree that using loops is (very often) bad R coding style (see discussion above). Using list2env() (thanks to @mbq for mentioning it), this is another solution to @Han Lin Shang's question:
x <- as.list(rnorm(10000))
names(x) <- paste("a", 1:length(x), sep = "")
list2env(x , envir = .GlobalEnv)
|
Produce a list of variable name in a for loop, then assign values to them
|
Your are looking for assign().
for(i in 1:3){
assign(paste("a", i, sep = ""), i)
}
gives
> ls()
[1] "a1" "a2" "a3"
and
> a1
[1] 1
> a2
[1] 2
> a3
[1] 3
Update
I agree that
|
Produce a list of variable name in a for loop, then assign values to them
Your are looking for assign().
for(i in 1:3){
assign(paste("a", i, sep = ""), i)
}
gives
> ls()
[1] "a1" "a2" "a3"
and
> a1
[1] 1
> a2
[1] 2
> a3
[1] 3
Update
I agree that using loops is (very often) bad R coding style (see discussion above). Using list2env() (thanks to @mbq for mentioning it), this is another solution to @Han Lin Shang's question:
x <- as.list(rnorm(10000))
names(x) <- paste("a", 1:length(x), sep = "")
list2env(x , envir = .GlobalEnv)
|
Produce a list of variable name in a for loop, then assign values to them
Your are looking for assign().
for(i in 1:3){
assign(paste("a", i, sep = ""), i)
}
gives
> ls()
[1] "a1" "a2" "a3"
and
> a1
[1] 1
> a2
[1] 2
> a3
[1] 3
Update
I agree that
|
8,457
|
Produce a list of variable name in a for loop, then assign values to them
|
If the values are in vector, the loop is not necessary:
vals <- rnorm(3)
n <- length(vals)
lhs <- paste("a", 1:n, sep="")
rhs <- paste("vals[",1:n,"]", sep="")
eq <- paste(paste(lhs, rhs, sep="<-"), collapse=";")
eval(parse(text=eq))
As a side note, this is the reason why I love R.
|
Produce a list of variable name in a for loop, then assign values to them
|
If the values are in vector, the loop is not necessary:
vals <- rnorm(3)
n <- length(vals)
lhs <- paste("a", 1:n, sep="")
rhs <- paste("vals[",1:n,"]", sep="")
eq <- paste(paste(lhs, rhs
|
Produce a list of variable name in a for loop, then assign values to them
If the values are in vector, the loop is not necessary:
vals <- rnorm(3)
n <- length(vals)
lhs <- paste("a", 1:n, sep="")
rhs <- paste("vals[",1:n,"]", sep="")
eq <- paste(paste(lhs, rhs, sep="<-"), collapse=";")
eval(parse(text=eq))
As a side note, this is the reason why I love R.
|
Produce a list of variable name in a for loop, then assign values to them
If the values are in vector, the loop is not necessary:
vals <- rnorm(3)
n <- length(vals)
lhs <- paste("a", 1:n, sep="")
rhs <- paste("vals[",1:n,"]", sep="")
eq <- paste(paste(lhs, rhs
|
8,458
|
Are there default functions for discrete uniform distributions in R?
|
As nico wrote, they're not implemented in R. Assuming we work in 1..k, those functions should look like:
For random generation:
rdu<-function(n,k) sample(1:k,n,replace=T)
PDF:
ddu<-function(x,k) ifelse(x>=1 & x<=k & round(x)==x,1/k,0)
CDF:
pdu<-function(x,k) ifelse(x<1,0,ifelse(x<=k,floor(x)/k,1))
|
Are there default functions for discrete uniform distributions in R?
|
As nico wrote, they're not implemented in R. Assuming we work in 1..k, those functions should look like:
For random generation:
rdu<-function(n,k) sample(1:k,n,replace=T)
PDF:
ddu<-function(x,k) ifel
|
Are there default functions for discrete uniform distributions in R?
As nico wrote, they're not implemented in R. Assuming we work in 1..k, those functions should look like:
For random generation:
rdu<-function(n,k) sample(1:k,n,replace=T)
PDF:
ddu<-function(x,k) ifelse(x>=1 & x<=k & round(x)==x,1/k,0)
CDF:
pdu<-function(x,k) ifelse(x<1,0,ifelse(x<=k,floor(x)/k,1))
|
Are there default functions for discrete uniform distributions in R?
As nico wrote, they're not implemented in R. Assuming we work in 1..k, those functions should look like:
For random generation:
rdu<-function(n,k) sample(1:k,n,replace=T)
PDF:
ddu<-function(x,k) ifel
|
8,459
|
Are there default functions for discrete uniform distributions in R?
|
Here is the code for the discrete uniform distribution in the range [min, max], adapted from mbq's post:
dunifdisc<-function(x, min=0, max=1) ifelse(x>=min & x<=max & round(x)==x, 1/(max-min+1), 0)
punifdisc<-function(q, min=0, max=1) ifelse(q<min, 0, ifelse(q>=max, 1, (floor(q)-min+1)/(max-min+1)))
qunifdisc<-function(p, min=0, max=1) floor(p*(max-min+1))
runifdisc<-function(n, min=0, max=1) sample(min:max, n, replace=T)
|
Are there default functions for discrete uniform distributions in R?
|
Here is the code for the discrete uniform distribution in the range [min, max], adapted from mbq's post:
dunifdisc<-function(x, min=0, max=1) ifelse(x>=min & x<=max & round(x)==x, 1/(max-min+1), 0)
pu
|
Are there default functions for discrete uniform distributions in R?
Here is the code for the discrete uniform distribution in the range [min, max], adapted from mbq's post:
dunifdisc<-function(x, min=0, max=1) ifelse(x>=min & x<=max & round(x)==x, 1/(max-min+1), 0)
punifdisc<-function(q, min=0, max=1) ifelse(q<min, 0, ifelse(q>=max, 1, (floor(q)-min+1)/(max-min+1)))
qunifdisc<-function(p, min=0, max=1) floor(p*(max-min+1))
runifdisc<-function(n, min=0, max=1) sample(min:max, n, replace=T)
|
Are there default functions for discrete uniform distributions in R?
Here is the code for the discrete uniform distribution in the range [min, max], adapted from mbq's post:
dunifdisc<-function(x, min=0, max=1) ifelse(x>=min & x<=max & round(x)==x, 1/(max-min+1), 0)
pu
|
8,460
|
Are there default functions for discrete uniform distributions in R?
|
The CRAN Task View: Probability Distributions page says:
The discrete uniform distribution can be easily obtained with the basic functions.
I guess something on the lines of this should do:
a <- round(runif(1000, min=0, max=100))
EDIT
As csgillespie pointed out, this is not correct...
a <- ceiling(runif(1000, min=0, max=100))
will work though (note that the example will generate values between 1 and 100, not 0 and 100)
|
Are there default functions for discrete uniform distributions in R?
|
The CRAN Task View: Probability Distributions page says:
The discrete uniform distribution can be easily obtained with the basic functions.
I guess something on the lines of this should do:
a <- ro
|
Are there default functions for discrete uniform distributions in R?
The CRAN Task View: Probability Distributions page says:
The discrete uniform distribution can be easily obtained with the basic functions.
I guess something on the lines of this should do:
a <- round(runif(1000, min=0, max=100))
EDIT
As csgillespie pointed out, this is not correct...
a <- ceiling(runif(1000, min=0, max=100))
will work though (note that the example will generate values between 1 and 100, not 0 and 100)
|
Are there default functions for discrete uniform distributions in R?
The CRAN Task View: Probability Distributions page says:
The discrete uniform distribution can be easily obtained with the basic functions.
I guess something on the lines of this should do:
a <- ro
|
8,461
|
Are there default functions for discrete uniform distributions in R?
|
This function might be what you are looking for:
https://purrr.tidyverse.org/reference/rdunif.html
rdunif(n, b, a = 1)
|
Are there default functions for discrete uniform distributions in R?
|
This function might be what you are looking for:
https://purrr.tidyverse.org/reference/rdunif.html
rdunif(n, b, a = 1)
|
Are there default functions for discrete uniform distributions in R?
This function might be what you are looking for:
https://purrr.tidyverse.org/reference/rdunif.html
rdunif(n, b, a = 1)
|
Are there default functions for discrete uniform distributions in R?
This function might be what you are looking for:
https://purrr.tidyverse.org/reference/rdunif.html
rdunif(n, b, a = 1)
|
8,462
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
|
The Average Treatment Effect (ATE) and the Average Treatment Effect on Treated (ATT) are commonly defined across the different groups of individuals. In addition, ATE and ATT are often different because they might measure outcomes ($Y$) that are not affected from the treatment $D$ in the same manner.
First, some additional notation:
$Y^0$: population-level random variable for outcome $Y$ in control state.
$Y^1$: population-level random variable for outcome $Y$ in treatment state.
$\delta$: individual-level causal effect of the treatment.
$\pi$: proportion of population that takes treatment.
Given the above, the ATT is defined as: $\mathrm{E}[\delta|D=1]$ ie. what is the expected causal effect of the treatment for individuals in the treatment group. This can be decomposed more meaningfully as:
\begin{align}
\mathrm{E}[\delta|D=1] = & \mathrm{E}[Y^1 - Y^0|D=1] \\ & \mathrm{E}[Y^1|D=1] - \mathrm{E}[Y^0|D=1]
\end{align}
(Notice that $\mathrm{E}[Y^0|D=1]$ is unobserved so it refers to a counterfactual variable which is not realised in our observed sample.)
Similarly the ATE is defined as: $\mathrm{E}[\delta]$, ie. what is the expected causal effect of the treatment across all individuals in the population. Again we can decompose this more meaningfully as:
\begin{align}
\mathrm{E}[\delta] =& \{ \pi \mathrm{E}[Y^1|D=1] + (1-\pi) \mathrm{E}[Y^1|D=0] \} \\ -& \{ \pi \mathrm{E}[Y^0|D=1] + (1-\pi) \mathrm{E}[Y^0|D=0] \}
\end{align}
As you see the ATT and the more general ATE are referring by definition to different portions of the population of interest. More importantly, in the ideal scenario of a randomised control trial (RCT) ATE equals ATT because we assume that:
$\mathrm{E}[Y^0|D=1] = \mathrm{E}[Y^0|D=0]$ and
$\mathrm{E}[Y^1|D=1] = \mathrm{E}[Y^1|D=0]$,
ie. we have believe respectively that:
the baseline of the treatment group equals the baseline of the control group (layman terms: people in the treatment group would do as bad as the control group if they were not treated) and
the treatment effect on the treated group equals the treatment effect on the control group (layman terms: people in the control group would do as good as the treatment group if they were treated).
These are very strong assumptions which are commonly violated in observational studies and therefore the ATT and the ATE are not expected to be equal. (Notice that if only the baselines are equal, you can still get an ATT through simple differences: $\mathrm{E}[Y^1|D=1] - \mathrm{E}[Y^0|D=0]$.)
Especially in the cases where the individuals self-select to enter the treatment group or not (eg. an e-shop providing cash bonus where a customer can redeem a bonus coupon for $X$ amount given she shops items worth at least $Y$ amount) the baselines as well as the treatment effects can be different (eg. repeat buyers are more likely to redeem such a bonus, low-value customers might find the threshold $Y$ unrealistically high or high-value customers might be indifferent to the bonus amount $X$ - this also relates to SUTVA). In scenarios like this even talking about ATE is probably ill-defined (eg. it is unrealistic to expect that all the customers of an e-shop will ever shop items worth $Y$).
ATT being unequal to ATE is not unexpected. If ATT is smaller or greater than ATE is application specific. The inequality of the two suggests that the treatment assignment mechanism was potentially not random.
In general, in an observational study because the above-mentioned assumptions do not generally hold, we either partition our sample accordingly or we control for difference through "regression-like" techniques.
For a more detailed but easy to follow exposition of the matter I recommend looking into Morgan & Winship's Counterfactuals and Causal Inference.
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
|
The Average Treatment Effect (ATE) and the Average Treatment Effect on Treated (ATT) are commonly defined across the different groups of individuals. In addition, ATE and ATT are often different becau
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
The Average Treatment Effect (ATE) and the Average Treatment Effect on Treated (ATT) are commonly defined across the different groups of individuals. In addition, ATE and ATT are often different because they might measure outcomes ($Y$) that are not affected from the treatment $D$ in the same manner.
First, some additional notation:
$Y^0$: population-level random variable for outcome $Y$ in control state.
$Y^1$: population-level random variable for outcome $Y$ in treatment state.
$\delta$: individual-level causal effect of the treatment.
$\pi$: proportion of population that takes treatment.
Given the above, the ATT is defined as: $\mathrm{E}[\delta|D=1]$ ie. what is the expected causal effect of the treatment for individuals in the treatment group. This can be decomposed more meaningfully as:
\begin{align}
\mathrm{E}[\delta|D=1] = & \mathrm{E}[Y^1 - Y^0|D=1] \\ & \mathrm{E}[Y^1|D=1] - \mathrm{E}[Y^0|D=1]
\end{align}
(Notice that $\mathrm{E}[Y^0|D=1]$ is unobserved so it refers to a counterfactual variable which is not realised in our observed sample.)
Similarly the ATE is defined as: $\mathrm{E}[\delta]$, ie. what is the expected causal effect of the treatment across all individuals in the population. Again we can decompose this more meaningfully as:
\begin{align}
\mathrm{E}[\delta] =& \{ \pi \mathrm{E}[Y^1|D=1] + (1-\pi) \mathrm{E}[Y^1|D=0] \} \\ -& \{ \pi \mathrm{E}[Y^0|D=1] + (1-\pi) \mathrm{E}[Y^0|D=0] \}
\end{align}
As you see the ATT and the more general ATE are referring by definition to different portions of the population of interest. More importantly, in the ideal scenario of a randomised control trial (RCT) ATE equals ATT because we assume that:
$\mathrm{E}[Y^0|D=1] = \mathrm{E}[Y^0|D=0]$ and
$\mathrm{E}[Y^1|D=1] = \mathrm{E}[Y^1|D=0]$,
ie. we have believe respectively that:
the baseline of the treatment group equals the baseline of the control group (layman terms: people in the treatment group would do as bad as the control group if they were not treated) and
the treatment effect on the treated group equals the treatment effect on the control group (layman terms: people in the control group would do as good as the treatment group if they were treated).
These are very strong assumptions which are commonly violated in observational studies and therefore the ATT and the ATE are not expected to be equal. (Notice that if only the baselines are equal, you can still get an ATT through simple differences: $\mathrm{E}[Y^1|D=1] - \mathrm{E}[Y^0|D=0]$.)
Especially in the cases where the individuals self-select to enter the treatment group or not (eg. an e-shop providing cash bonus where a customer can redeem a bonus coupon for $X$ amount given she shops items worth at least $Y$ amount) the baselines as well as the treatment effects can be different (eg. repeat buyers are more likely to redeem such a bonus, low-value customers might find the threshold $Y$ unrealistically high or high-value customers might be indifferent to the bonus amount $X$ - this also relates to SUTVA). In scenarios like this even talking about ATE is probably ill-defined (eg. it is unrealistic to expect that all the customers of an e-shop will ever shop items worth $Y$).
ATT being unequal to ATE is not unexpected. If ATT is smaller or greater than ATE is application specific. The inequality of the two suggests that the treatment assignment mechanism was potentially not random.
In general, in an observational study because the above-mentioned assumptions do not generally hold, we either partition our sample accordingly or we control for difference through "regression-like" techniques.
For a more detailed but easy to follow exposition of the matter I recommend looking into Morgan & Winship's Counterfactuals and Causal Inference.
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
The Average Treatment Effect (ATE) and the Average Treatment Effect on Treated (ATT) are commonly defined across the different groups of individuals. In addition, ATE and ATT are often different becau
|
8,463
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
|
ATE is the average treatment effect, and ATT is the average treatment effect on the treated.
The ATT is the effect of the treatment actually applied. Medical studies typically use the ATT as the designated quantity of interest because they often only care about the causal effect of drugs for patients that receive or would receive the drugs.
For another example, ATT tells us how much the typical soldier gained or lost as a consequence of military service, while ATE tells us how much the typical applicant to the military gained or lost.
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
|
ATE is the average treatment effect, and ATT is the average treatment effect on the treated.
The ATT is the effect of the treatment actually applied. Medical studies typically use the ATT as the desi
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
ATE is the average treatment effect, and ATT is the average treatment effect on the treated.
The ATT is the effect of the treatment actually applied. Medical studies typically use the ATT as the designated quantity of interest because they often only care about the causal effect of drugs for patients that receive or would receive the drugs.
For another example, ATT tells us how much the typical soldier gained or lost as a consequence of military service, while ATE tells us how much the typical applicant to the military gained or lost.
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
ATE is the average treatment effect, and ATT is the average treatment effect on the treated.
The ATT is the effect of the treatment actually applied. Medical studies typically use the ATT as the desi
|
8,464
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
|
There seems to be something obvious not discussed above. If the treatment effect is constant over individuals $Y_i^1-Y_i^0=c$ for every $i$ then ATT and ATE as defined above should be equal.
This may be seen as there being no "effect modifiers". My intuition is that balancing effect modifiers between groups would also be sufficient for equality of ATT and ATE. The distribution of treatment effects would then be independent of treatment. Maybe someone already has this formalized?
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
|
There seems to be something obvious not discussed above. If the treatment effect is constant over individuals $Y_i^1-Y_i^0=c$ for every $i$ then ATT and ATE as defined above should be equal.
This may
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
There seems to be something obvious not discussed above. If the treatment effect is constant over individuals $Y_i^1-Y_i^0=c$ for every $i$ then ATT and ATE as defined above should be equal.
This may be seen as there being no "effect modifiers". My intuition is that balancing effect modifiers between groups would also be sufficient for equality of ATT and ATE. The distribution of treatment effects would then be independent of treatment. Maybe someone already has this formalized?
|
Why is Average Treatment Effect different from Average Treatment effect on the Treated?
There seems to be something obvious not discussed above. If the treatment effect is constant over individuals $Y_i^1-Y_i^0=c$ for every $i$ then ATT and ATE as defined above should be equal.
This may
|
8,465
|
How to include an interaction term in GAM?
|
The "a" in "gam" stands for "additive" which means no interactions, so if you fit interactions you are really not fitting a gam model any more.
That said, there are ways to get some interaction like terms within the additive terms in a gam, you are already using one of those by using the by argument to s. You could try extending this to having the argument by be a matrix with a function (sin, cos) of doy or tod. You could also just fit smoothing splines in a regular linear model that allows interactions (this does not give the backfitting that gam does, but could still be useful).
You might also look at projection pursuit regression as another fitting tool. Loess or more parametric models (with sin and/or cos) might also be useful.
Part of decision on what tool(s) to use is what question you are trying to answer. Are you just trying to find a model to predict future dates and times? are you trying to test to see if particular predictors are significant in the model? are you trying to understand the shape of the relationship between a predictor and the outcome? Something else?
|
How to include an interaction term in GAM?
|
The "a" in "gam" stands for "additive" which means no interactions, so if you fit interactions you are really not fitting a gam model any more.
That said, there are ways to get some interaction like t
|
How to include an interaction term in GAM?
The "a" in "gam" stands for "additive" which means no interactions, so if you fit interactions you are really not fitting a gam model any more.
That said, there are ways to get some interaction like terms within the additive terms in a gam, you are already using one of those by using the by argument to s. You could try extending this to having the argument by be a matrix with a function (sin, cos) of doy or tod. You could also just fit smoothing splines in a regular linear model that allows interactions (this does not give the backfitting that gam does, but could still be useful).
You might also look at projection pursuit regression as another fitting tool. Loess or more parametric models (with sin and/or cos) might also be useful.
Part of decision on what tool(s) to use is what question you are trying to answer. Are you just trying to find a model to predict future dates and times? are you trying to test to see if particular predictors are significant in the model? are you trying to understand the shape of the relationship between a predictor and the outcome? Something else?
|
How to include an interaction term in GAM?
The "a" in "gam" stands for "additive" which means no interactions, so if you fit interactions you are really not fitting a gam model any more.
That said, there are ways to get some interaction like t
|
8,466
|
How to include an interaction term in GAM?
|
For two continuous variables then you can do what you want (whether this is an interaction or not I'll leave others to discuss as per comments to @Greg's Answer) using:
mod1 <- gam(Temp ~ Loc + s(Doy, bs = "cc", k = 5) +
s(Doy, bs = "cc", by = Loc, k = 5, m = 1) +
s(Tod, bs = "cc", k = 5) +
s(Tod, bs = "cc", by = Loc, k = 5, m = 1) +
te(Tod, Doy, by = Loc, bs = rep("cc",2)),
data = DatNew, method = "ML")
The simpler model should then be nested within the more complex model above. That simpler model is:
mod0 <- gam(Temp ~ Loc + s(Doy, bs = "cc", k = 5) +
s(Doy, bs = "cc", by = Loc, k = 5, m = 1) +
s(Tod, bs = "cc", k = 5) +
s(Tod, bs = "cc", by = Loc, k = 5, m = 1),
data = DatNew, method = "ML")
Note two things here:
The basis-type for each smoother is stated. In this case we would expect that there are no discontinuities in Temp between 23:59 and 00:00 for Tod nor between Doy == 1 and Doy == 365.25. Hence cyclic cubic splines are appropriate, indicated here via bs = "cc".
The basis dimension is stated explicitly (k = 5). This matches the default basis dimension for each smooth in a te() term.
Together these features ensure that the simpler model really is nested within the more complex model.
For more see ?gam.models in mgcv.
|
How to include an interaction term in GAM?
|
For two continuous variables then you can do what you want (whether this is an interaction or not I'll leave others to discuss as per comments to @Greg's Answer) using:
mod1 <- gam(Temp ~ Loc + s(Doy,
|
How to include an interaction term in GAM?
For two continuous variables then you can do what you want (whether this is an interaction or not I'll leave others to discuss as per comments to @Greg's Answer) using:
mod1 <- gam(Temp ~ Loc + s(Doy, bs = "cc", k = 5) +
s(Doy, bs = "cc", by = Loc, k = 5, m = 1) +
s(Tod, bs = "cc", k = 5) +
s(Tod, bs = "cc", by = Loc, k = 5, m = 1) +
te(Tod, Doy, by = Loc, bs = rep("cc",2)),
data = DatNew, method = "ML")
The simpler model should then be nested within the more complex model above. That simpler model is:
mod0 <- gam(Temp ~ Loc + s(Doy, bs = "cc", k = 5) +
s(Doy, bs = "cc", by = Loc, k = 5, m = 1) +
s(Tod, bs = "cc", k = 5) +
s(Tod, bs = "cc", by = Loc, k = 5, m = 1),
data = DatNew, method = "ML")
Note two things here:
The basis-type for each smoother is stated. In this case we would expect that there are no discontinuities in Temp between 23:59 and 00:00 for Tod nor between Doy == 1 and Doy == 365.25. Hence cyclic cubic splines are appropriate, indicated here via bs = "cc".
The basis dimension is stated explicitly (k = 5). This matches the default basis dimension for each smooth in a te() term.
Together these features ensure that the simpler model really is nested within the more complex model.
For more see ?gam.models in mgcv.
|
How to include an interaction term in GAM?
For two continuous variables then you can do what you want (whether this is an interaction or not I'll leave others to discuss as per comments to @Greg's Answer) using:
mod1 <- gam(Temp ~ Loc + s(Doy,
|
8,467
|
Generating correlated binomial random variables
|
Binomial variables are usually created by summing independent Bernoulli variables. Let's see whether we can start with a pair of correlated Bernoulli variables $(X,Y)$ and do the same thing.
Suppose $X$ is a Bernoulli$(p)$ variable (that is, $\Pr(X=1)=p$ and $\Pr(X=0)=1-p$) and $Y$ is a Bernoulli$(q)$ variable. To pin down their joint distribution we need to specify all four combinations of outcomes. Writing $$\Pr((X,Y)=(0,0))=a,$$ we can readily figure out the rest from the axioms of probability: $$\Pr((X,Y)=(1,0))=1-q-a, \\\Pr((X,Y)=(0,1))=1-p-a, \\\Pr((X,Y)=(1,1))=a+p+q-1.$$
Plugging this into the formula for the correlation coefficient $\rho$ and solving gives $$a = (1-p)(1-q) + \rho\sqrt{{pq}{(1-p)(1-q)}}.\tag{1}$$
Provided all four probabilities are non-negative, this will give a valid joint distribution--and this solution parameterizes all bivariate Bernoulli distributions. (When $p=q$, there is a solution for all mathematically meaningful correlations between $-1$ and $1$.) When we sum $n$ of these variables, the correlation remains the same--but now the marginal distributions are Binomial$(n,p)$ and Binomial$(n,q)$, as desired.
Example
Let $n=10$, $p=1/3$, $q=3/4$, and we would like the correlation to be $\rho=-4/5$. The solution to $(1)$ is $a=0.00336735$ (and the other probabilities are around $0.247$, $0.663$, and $0.087$). Here is a plot of $1000$ realizations from the joint distribution:
The red lines indicate the means of the sample and the dotted line is the regression line. They are all close to their intended values. The points have been randomly jittered in this image to resolve the overlaps: after all, Binomial distributions only produce integral values, so there will be a great amount of overplotting.
One way to generate these variables is to sample $n$ times from $\{1,2,3,4\}$ with the chosen probabilities and then convert each $1$ into $(0,0)$, each $2$ into $(1,0)$, each $3$ into $(0,1)$, and each $4$ into $(1,1)$. Sum the results (as vectors) to obtain one realization of $(X,Y)$.
Code
Here is an R implementation.
#
# Compute Pr(0,0) from rho, p=Pr(X=1), and q=Pr(Y=1).
#
a <- function(rho, p, q) {
rho * sqrt(p*q*(1-p)*(1-q)) + (1-p)*(1-q)
}
#
# Specify the parameters.
#
n <- 10
p <- 1/3
q <- 3/4
rho <- -4/5
#
# Compute the four probabilities for the joint distribution.
#
a.0 <- a(rho, p, q)
prob <- c(`(0,0)`=a.0, `(1,0)`=1-q-a.0, `(0,1)`=1-p-a.0, `(1,1)`=a.0+p+q-1)
if (min(prob) < 0) {
print(prob)
stop("Error: a probability is negative.")
}
#
# Illustrate generation of correlated Binomial variables.
#
set.seed(17)
n.sim <- 1000
u <- sample.int(4, n.sim * n, replace=TRUE, prob=prob)
y <- floor((u-1)/2)
x <- 1 - u %% 2
x <- colSums(matrix(x, nrow=n)) # Sum in groups of `n`
y <- colSums(matrix(y, nrow=n)) # Sum in groups of `n`
#
# Plot the empirical bivariate distribution.
#
plot(x+rnorm(length(x), sd=1/8), y+rnorm(length(y), sd=1/8),
pch=19, cex=1/2, col="#00000010",
xlab="X", ylab="Y",
main=paste("Correlation is", signif(cor(x,y), 3)))
abline(v=mean(x), h=mean(y), col="Red")
abline(lm(y ~ x), lwd=2, lty=3)
|
Generating correlated binomial random variables
|
Binomial variables are usually created by summing independent Bernoulli variables. Let's see whether we can start with a pair of correlated Bernoulli variables $(X,Y)$ and do the same thing.
Suppose
|
Generating correlated binomial random variables
Binomial variables are usually created by summing independent Bernoulli variables. Let's see whether we can start with a pair of correlated Bernoulli variables $(X,Y)$ and do the same thing.
Suppose $X$ is a Bernoulli$(p)$ variable (that is, $\Pr(X=1)=p$ and $\Pr(X=0)=1-p$) and $Y$ is a Bernoulli$(q)$ variable. To pin down their joint distribution we need to specify all four combinations of outcomes. Writing $$\Pr((X,Y)=(0,0))=a,$$ we can readily figure out the rest from the axioms of probability: $$\Pr((X,Y)=(1,0))=1-q-a, \\\Pr((X,Y)=(0,1))=1-p-a, \\\Pr((X,Y)=(1,1))=a+p+q-1.$$
Plugging this into the formula for the correlation coefficient $\rho$ and solving gives $$a = (1-p)(1-q) + \rho\sqrt{{pq}{(1-p)(1-q)}}.\tag{1}$$
Provided all four probabilities are non-negative, this will give a valid joint distribution--and this solution parameterizes all bivariate Bernoulli distributions. (When $p=q$, there is a solution for all mathematically meaningful correlations between $-1$ and $1$.) When we sum $n$ of these variables, the correlation remains the same--but now the marginal distributions are Binomial$(n,p)$ and Binomial$(n,q)$, as desired.
Example
Let $n=10$, $p=1/3$, $q=3/4$, and we would like the correlation to be $\rho=-4/5$. The solution to $(1)$ is $a=0.00336735$ (and the other probabilities are around $0.247$, $0.663$, and $0.087$). Here is a plot of $1000$ realizations from the joint distribution:
The red lines indicate the means of the sample and the dotted line is the regression line. They are all close to their intended values. The points have been randomly jittered in this image to resolve the overlaps: after all, Binomial distributions only produce integral values, so there will be a great amount of overplotting.
One way to generate these variables is to sample $n$ times from $\{1,2,3,4\}$ with the chosen probabilities and then convert each $1$ into $(0,0)$, each $2$ into $(1,0)$, each $3$ into $(0,1)$, and each $4$ into $(1,1)$. Sum the results (as vectors) to obtain one realization of $(X,Y)$.
Code
Here is an R implementation.
#
# Compute Pr(0,0) from rho, p=Pr(X=1), and q=Pr(Y=1).
#
a <- function(rho, p, q) {
rho * sqrt(p*q*(1-p)*(1-q)) + (1-p)*(1-q)
}
#
# Specify the parameters.
#
n <- 10
p <- 1/3
q <- 3/4
rho <- -4/5
#
# Compute the four probabilities for the joint distribution.
#
a.0 <- a(rho, p, q)
prob <- c(`(0,0)`=a.0, `(1,0)`=1-q-a.0, `(0,1)`=1-p-a.0, `(1,1)`=a.0+p+q-1)
if (min(prob) < 0) {
print(prob)
stop("Error: a probability is negative.")
}
#
# Illustrate generation of correlated Binomial variables.
#
set.seed(17)
n.sim <- 1000
u <- sample.int(4, n.sim * n, replace=TRUE, prob=prob)
y <- floor((u-1)/2)
x <- 1 - u %% 2
x <- colSums(matrix(x, nrow=n)) # Sum in groups of `n`
y <- colSums(matrix(y, nrow=n)) # Sum in groups of `n`
#
# Plot the empirical bivariate distribution.
#
plot(x+rnorm(length(x), sd=1/8), y+rnorm(length(y), sd=1/8),
pch=19, cex=1/2, col="#00000010",
xlab="X", ylab="Y",
main=paste("Correlation is", signif(cor(x,y), 3)))
abline(v=mean(x), h=mean(y), col="Red")
abline(lm(y ~ x), lwd=2, lty=3)
|
Generating correlated binomial random variables
Binomial variables are usually created by summing independent Bernoulli variables. Let's see whether we can start with a pair of correlated Bernoulli variables $(X,Y)$ and do the same thing.
Suppose
|
8,468
|
Generating correlated binomial random variables
|
A Python (python3) implementation of @whuber's solution:
import numpy as np
def bernoulli_sample(n=100, p=0.5, q=0.5, rho=0):
p1 = rho * np.sqrt(p * q * (1 - p) * (1 - q)) + (1 - p) * (1 - q)
p2 = 1 - p - p1
p3 = 1 - q - p1
p4 = p1 + p + q - 1
samples = np.random.choice([0, 1, 2, 3], size=n, replace=True, p=[p1, p2, p3, p4])
samples = list(map(lambda x: np.array(tuple(np.binary_repr(x, width=2))).astype(np.int), samples))
return np.array(samples).sum(0)
def gen_correlated_bernoulli(size, n=100, p=0.5, q=0.5, rho=0):
return np.array([bernoulli_sample(n, p, q, rho) for _ in range(size)])
|
Generating correlated binomial random variables
|
A Python (python3) implementation of @whuber's solution:
import numpy as np
def bernoulli_sample(n=100, p=0.5, q=0.5, rho=0):
p1 = rho * np.sqrt(p * q * (1 - p) * (1 - q)) + (1 - p) * (1 - q)
|
Generating correlated binomial random variables
A Python (python3) implementation of @whuber's solution:
import numpy as np
def bernoulli_sample(n=100, p=0.5, q=0.5, rho=0):
p1 = rho * np.sqrt(p * q * (1 - p) * (1 - q)) + (1 - p) * (1 - q)
p2 = 1 - p - p1
p3 = 1 - q - p1
p4 = p1 + p + q - 1
samples = np.random.choice([0, 1, 2, 3], size=n, replace=True, p=[p1, p2, p3, p4])
samples = list(map(lambda x: np.array(tuple(np.binary_repr(x, width=2))).astype(np.int), samples))
return np.array(samples).sum(0)
def gen_correlated_bernoulli(size, n=100, p=0.5, q=0.5, rho=0):
return np.array([bernoulli_sample(n, p, q, rho) for _ in range(size)])
|
Generating correlated binomial random variables
A Python (python3) implementation of @whuber's solution:
import numpy as np
def bernoulli_sample(n=100, p=0.5, q=0.5, rho=0):
p1 = rho * np.sqrt(p * q * (1 - p) * (1 - q)) + (1 - p) * (1 - q)
|
8,469
|
Generating correlated binomial random variables
|
Using the method described by whuber in his excellent answer, I have programmed a function that generates pairs of correlated binomial random variables using the standard syntax for distributions in R. You can call this function to generate any desired number of correlated Bernoulli random variables, with specified probabilities prob1 and prob1 and specified correlation corr. Note that the correlation coefficient is the correlation of the individual Bernoulli values that sum to the binomial, not the correlation between the binomial values themselves.
rcorrbinom <- function(n, size = 1, prob1, prob2, corr = 0) {
#Check inputs
if (!is.numeric(n)) { stop('Error: n must be numeric') }
if (length(n) != 1) { stop('Error: n must be a single number') }
if (as.integer(n) != n) { stop('Error: n must be a positive integer') }
if (n < 1) { stop('Error: n must be a positive integer') }
if (!is.numeric(size)) { stop('Error: n must be numeric') }
if (length(size) != 1) { stop('Error: n must be a single number') }
if (as.integer(size) != size) { stop('Error: n must be a positive integer') }
if (size < 1) { stop('Error: n must be a positive integer') }
if (!is.numeric(prob1)) { stop('Error: prob1 must be numeric') }
if (length(prob1) != 1) { stop('Error: prob1 must be a single number') }
if (prob1 < 0) { stop('Error: prob1 must be between 0 and 1') }
if (prob1 > 1) { stop('Error: prob1 must be between 0 and 1') }
if (!is.numeric(prob2)) { stop('Error: prob2 must be numeric') }
if (length(prob2) != 1) { stop('Error: prob2 must be a single number') }
if (prob2 < 0) { stop('Error: prob2 must be between 0 and 1') }
if (prob2 > 1) { stop('Error: prob2 must be between 0 and 1') }
if (!is.numeric(corr)) { stop('Error: corr must be numeric') }
if (length(corr) != 1) { stop('Error: corr must be a single number') }
if (corr < -1) { stop('Error: corr must be between -1 and 1') }
if (corr > 1) { stop('Error: corr must be between -1 and 1') }
#Compute probabilities
P00 <- (1-prob1)*(1-prob2) + corr*sqrt(prob1*prob2*(1-prob1)*(1-prob2))
P01 <- 1 - prob1 - P00
P10 <- 1 - prob2 - P00
P11 <- P00 + prob1 + prob2 - 1
PROBS <- c(P00, P01, P10, P11)
if (min(PROBS) < 0) { stop('Error: corr is not in the allowable range') }
#Generate the output
RAND <- array(sample.int(4, size = n*size, replace = TRUE, prob = PROBS),
dim = c(n, size))
VALS <- array(0, dim = c(2, n, size))
OUT <- array(0, dim = c(2, n))
for (i in 1:n) {
for (j in 1:size) {
VALS[1,i,j] <- (RAND[i,j] %in% c(3, 4))
VALS[2,i,j] <- (RAND[i,j] %in% c(2, 4)) }
OUT[1, i] <- sum(VALS[1,i,])
OUT[2, i] <- sum(VALS[2,i,]) }
#Give output
OUT }
Here is an example of using this function to produce a sample array containing a large number of correlated Bernoulli random variables. We can confirm that, for a large sample, the sampled values have sample means and sample correlation that is close to the specified parameters.
#Set parameters
n <- 10^6;
PROB1 <- 0.3;
PROB2 <- 0.8;
CORR <- 0.2;
#Generate sample of correlated Bernoulli random variables
set.seed(1);
SAMPLE <- rcorrbinom(n = n, prob1 = PROB1, prob2 = PROB2, corr = CORR);
#Check the properties of the sample
str(SAMPLE);
num [1:2, 1:10000] 0 1 0 1 1 1 0 0 0 1 ...
mean(SAMPLE[1,]);
[1] 0.300122
mean(SAMPLE[2,]);
[1] 0.800145
cor(SAMPLE[1,], SAMPLE[2,]);
[1] 0.20018
|
Generating correlated binomial random variables
|
Using the method described by whuber in his excellent answer, I have programmed a function that generates pairs of correlated binomial random variables using the standard syntax for distributions in R
|
Generating correlated binomial random variables
Using the method described by whuber in his excellent answer, I have programmed a function that generates pairs of correlated binomial random variables using the standard syntax for distributions in R. You can call this function to generate any desired number of correlated Bernoulli random variables, with specified probabilities prob1 and prob1 and specified correlation corr. Note that the correlation coefficient is the correlation of the individual Bernoulli values that sum to the binomial, not the correlation between the binomial values themselves.
rcorrbinom <- function(n, size = 1, prob1, prob2, corr = 0) {
#Check inputs
if (!is.numeric(n)) { stop('Error: n must be numeric') }
if (length(n) != 1) { stop('Error: n must be a single number') }
if (as.integer(n) != n) { stop('Error: n must be a positive integer') }
if (n < 1) { stop('Error: n must be a positive integer') }
if (!is.numeric(size)) { stop('Error: n must be numeric') }
if (length(size) != 1) { stop('Error: n must be a single number') }
if (as.integer(size) != size) { stop('Error: n must be a positive integer') }
if (size < 1) { stop('Error: n must be a positive integer') }
if (!is.numeric(prob1)) { stop('Error: prob1 must be numeric') }
if (length(prob1) != 1) { stop('Error: prob1 must be a single number') }
if (prob1 < 0) { stop('Error: prob1 must be between 0 and 1') }
if (prob1 > 1) { stop('Error: prob1 must be between 0 and 1') }
if (!is.numeric(prob2)) { stop('Error: prob2 must be numeric') }
if (length(prob2) != 1) { stop('Error: prob2 must be a single number') }
if (prob2 < 0) { stop('Error: prob2 must be between 0 and 1') }
if (prob2 > 1) { stop('Error: prob2 must be between 0 and 1') }
if (!is.numeric(corr)) { stop('Error: corr must be numeric') }
if (length(corr) != 1) { stop('Error: corr must be a single number') }
if (corr < -1) { stop('Error: corr must be between -1 and 1') }
if (corr > 1) { stop('Error: corr must be between -1 and 1') }
#Compute probabilities
P00 <- (1-prob1)*(1-prob2) + corr*sqrt(prob1*prob2*(1-prob1)*(1-prob2))
P01 <- 1 - prob1 - P00
P10 <- 1 - prob2 - P00
P11 <- P00 + prob1 + prob2 - 1
PROBS <- c(P00, P01, P10, P11)
if (min(PROBS) < 0) { stop('Error: corr is not in the allowable range') }
#Generate the output
RAND <- array(sample.int(4, size = n*size, replace = TRUE, prob = PROBS),
dim = c(n, size))
VALS <- array(0, dim = c(2, n, size))
OUT <- array(0, dim = c(2, n))
for (i in 1:n) {
for (j in 1:size) {
VALS[1,i,j] <- (RAND[i,j] %in% c(3, 4))
VALS[2,i,j] <- (RAND[i,j] %in% c(2, 4)) }
OUT[1, i] <- sum(VALS[1,i,])
OUT[2, i] <- sum(VALS[2,i,]) }
#Give output
OUT }
Here is an example of using this function to produce a sample array containing a large number of correlated Bernoulli random variables. We can confirm that, for a large sample, the sampled values have sample means and sample correlation that is close to the specified parameters.
#Set parameters
n <- 10^6;
PROB1 <- 0.3;
PROB2 <- 0.8;
CORR <- 0.2;
#Generate sample of correlated Bernoulli random variables
set.seed(1);
SAMPLE <- rcorrbinom(n = n, prob1 = PROB1, prob2 = PROB2, corr = CORR);
#Check the properties of the sample
str(SAMPLE);
num [1:2, 1:10000] 0 1 0 1 1 1 0 0 0 1 ...
mean(SAMPLE[1,]);
[1] 0.300122
mean(SAMPLE[2,]);
[1] 0.800145
cor(SAMPLE[1,], SAMPLE[2,]);
[1] 0.20018
|
Generating correlated binomial random variables
Using the method described by whuber in his excellent answer, I have programmed a function that generates pairs of correlated binomial random variables using the standard syntax for distributions in R
|
8,470
|
Generating correlated binomial random variables
|
Here is another R implementation that uses the linear transformation mentioned in the original post.
set.seed(64378)
corr_binomial <- function(n, k, p, rho) {
z <- rbinom(n, k , p)
x_raw <- rbinom(n, k , p)
x <- z*rho + x_raw*(1 - rho^2)^0.5
observed_corr <- round(cor(x, z), 3)
scatter_z_x <- plot(z, x)
abline(lm(x ~ z))
return(list(observed_corr, summary(x)))
}
corr_binomial(1000, 50, .5, .6) # Correlated Binomial trials with a correlation of approximately r = .60
|
Generating correlated binomial random variables
|
Here is another R implementation that uses the linear transformation mentioned in the original post.
set.seed(64378)
corr_binomial <- function(n, k, p, rho) {
z <- rbinom(n, k , p)
x_raw <- rbinom(n,
|
Generating correlated binomial random variables
Here is another R implementation that uses the linear transformation mentioned in the original post.
set.seed(64378)
corr_binomial <- function(n, k, p, rho) {
z <- rbinom(n, k , p)
x_raw <- rbinom(n, k , p)
x <- z*rho + x_raw*(1 - rho^2)^0.5
observed_corr <- round(cor(x, z), 3)
scatter_z_x <- plot(z, x)
abline(lm(x ~ z))
return(list(observed_corr, summary(x)))
}
corr_binomial(1000, 50, .5, .6) # Correlated Binomial trials with a correlation of approximately r = .60
|
Generating correlated binomial random variables
Here is another R implementation that uses the linear transformation mentioned in the original post.
set.seed(64378)
corr_binomial <- function(n, k, p, rho) {
z <- rbinom(n, k , p)
x_raw <- rbinom(n,
|
8,471
|
Why use gradient descent with neural networks?
|
Because we can't. The optimization surface $S(\mathbf{w})$ as a function of the weights $\mathbf{w}$ is nonlinear and no closed form solution exists for $\frac{d S(\mathbf{w})}{d\mathbf{w}}=0$.
Gradient descent, by definition, descends. If you reach a stationary point after descending, it has to be a (local) minimum or a saddle point, but never a local maximum.
|
Why use gradient descent with neural networks?
|
Because we can't. The optimization surface $S(\mathbf{w})$ as a function of the weights $\mathbf{w}$ is nonlinear and no closed form solution exists for $\frac{d S(\mathbf{w})}{d\mathbf{w}}=0$.
Gradie
|
Why use gradient descent with neural networks?
Because we can't. The optimization surface $S(\mathbf{w})$ as a function of the weights $\mathbf{w}$ is nonlinear and no closed form solution exists for $\frac{d S(\mathbf{w})}{d\mathbf{w}}=0$.
Gradient descent, by definition, descends. If you reach a stationary point after descending, it has to be a (local) minimum or a saddle point, but never a local maximum.
|
Why use gradient descent with neural networks?
Because we can't. The optimization surface $S(\mathbf{w})$ as a function of the weights $\mathbf{w}$ is nonlinear and no closed form solution exists for $\frac{d S(\mathbf{w})}{d\mathbf{w}}=0$.
Gradie
|
8,472
|
Why use gradient descent with neural networks?
|
Regarding Marc Claesen's answer, I believe that gradient descent could stop at a local maximum in situations where you initialize to a local maximum or you just happen to end up there due to bad luck or a mistuned rate parameter. The local maximum would have zero gradient and the algorithm would think it had converged. This is why I often run multiple iterations from different starting points and keep track of the values along the way.
|
Why use gradient descent with neural networks?
|
Regarding Marc Claesen's answer, I believe that gradient descent could stop at a local maximum in situations where you initialize to a local maximum or you just happen to end up there due to bad luck
|
Why use gradient descent with neural networks?
Regarding Marc Claesen's answer, I believe that gradient descent could stop at a local maximum in situations where you initialize to a local maximum or you just happen to end up there due to bad luck or a mistuned rate parameter. The local maximum would have zero gradient and the algorithm would think it had converged. This is why I often run multiple iterations from different starting points and keep track of the values along the way.
|
Why use gradient descent with neural networks?
Regarding Marc Claesen's answer, I believe that gradient descent could stop at a local maximum in situations where you initialize to a local maximum or you just happen to end up there due to bad luck
|
8,473
|
Why use gradient descent with neural networks?
|
In Newton-type methods, at each step one solves $\frac{d(\text{error})}{dw}=0$ for a linearized or approximate version of the problem. Then the problem is linearized about the new point, and the process repeats until convergence. Some people have done it for neural nets, but it has the following drawbacks,
One needs to deal with second derivatives (the Hessian, specifically Hessian-vector products).
The "solve step" is very computationally expensive: in the time it takes to do a solve one could have done many gradient descent iterations.
If one uses a Krylov method for the Hessian solve, and one does not use a good preconditioner for the Hessian, then the costs roughly balance out - Newton iterations take much longer but make more progress, in such a way that the total time is roughly the same or slower than gradient descent. On the other hand, if one has a good Hessian preconditioner then Newton's method wins big-time.
That said, trust-region Newton-Krylov methods are the gold-standard in modern large-scale optimization, and I would only expect their use to increase in neural nets in the upcoming years as people want to solve larger and larger problems. (and also as more people in numerical optimization get interested in machine learning)
|
Why use gradient descent with neural networks?
|
In Newton-type methods, at each step one solves $\frac{d(\text{error})}{dw}=0$ for a linearized or approximate version of the problem. Then the problem is linearized about the new point, and the proce
|
Why use gradient descent with neural networks?
In Newton-type methods, at each step one solves $\frac{d(\text{error})}{dw}=0$ for a linearized or approximate version of the problem. Then the problem is linearized about the new point, and the process repeats until convergence. Some people have done it for neural nets, but it has the following drawbacks,
One needs to deal with second derivatives (the Hessian, specifically Hessian-vector products).
The "solve step" is very computationally expensive: in the time it takes to do a solve one could have done many gradient descent iterations.
If one uses a Krylov method for the Hessian solve, and one does not use a good preconditioner for the Hessian, then the costs roughly balance out - Newton iterations take much longer but make more progress, in such a way that the total time is roughly the same or slower than gradient descent. On the other hand, if one has a good Hessian preconditioner then Newton's method wins big-time.
That said, trust-region Newton-Krylov methods are the gold-standard in modern large-scale optimization, and I would only expect their use to increase in neural nets in the upcoming years as people want to solve larger and larger problems. (and also as more people in numerical optimization get interested in machine learning)
|
Why use gradient descent with neural networks?
In Newton-type methods, at each step one solves $\frac{d(\text{error})}{dw}=0$ for a linearized or approximate version of the problem. Then the problem is linearized about the new point, and the proce
|
8,474
|
Metrics for evaluating ranking algorithms
|
I am actually looking for the same answer, however I should be able to at least partially answer your question.
All of the metrics that you have mentioned have different traits and, unfortunately, the one you should pick depends on what you actually would like to measure. Here are some things that it would be worth to have in mind:
Spearman's rho metric penalises errors at the top of the list with the same weight as mismatches on the bottom, so in most cases this is not the metric to use for evaluating rankings
DCG & NDCG are one of the few metrics that take into account the non-binary utility function, so you can describe how useful is a record and not whether it's useful.
DCG & NDCG have fixed weighs for positions, so a document in a given position has always the same gain and discount independently of the documents shown above it
You usually would prefer NDCG over DCG, because it normalises the value by the number of relevant documents
MAP is supposed to be a classic and a 'go-to' metric for this problem and it seems to be a standard in the field.
(N)DCG should be always computed for a fixed amount of records (@k), because it has a long tail (lots of irrelevant records at the end of the ranking highly bias the metric). This doesn't apply to MAP.
Mean Reciprocal Rank only marks the position of the first relevant document, so if you care about as many relevant docs as possible to be high on the list, then this should not be your choice
Kendall's tau only handles binary utility function, it also should be computed @k (similar to NDCG)
Valuable resources:
Victor Lavrenko lecture on YouTube - it's only a link to the MAP vs NDCG episode, but the whole lecture includes much more (including Kendall's Tau). You should definitely check it out, great lecture!
ERR paper
Can't post more links, because of the fresh account :) If anybody has some more remarks or ideas, I would be happy to hear them as well!
|
Metrics for evaluating ranking algorithms
|
I am actually looking for the same answer, however I should be able to at least partially answer your question.
All of the metrics that you have mentioned have different traits and, unfortunately, the
|
Metrics for evaluating ranking algorithms
I am actually looking for the same answer, however I should be able to at least partially answer your question.
All of the metrics that you have mentioned have different traits and, unfortunately, the one you should pick depends on what you actually would like to measure. Here are some things that it would be worth to have in mind:
Spearman's rho metric penalises errors at the top of the list with the same weight as mismatches on the bottom, so in most cases this is not the metric to use for evaluating rankings
DCG & NDCG are one of the few metrics that take into account the non-binary utility function, so you can describe how useful is a record and not whether it's useful.
DCG & NDCG have fixed weighs for positions, so a document in a given position has always the same gain and discount independently of the documents shown above it
You usually would prefer NDCG over DCG, because it normalises the value by the number of relevant documents
MAP is supposed to be a classic and a 'go-to' metric for this problem and it seems to be a standard in the field.
(N)DCG should be always computed for a fixed amount of records (@k), because it has a long tail (lots of irrelevant records at the end of the ranking highly bias the metric). This doesn't apply to MAP.
Mean Reciprocal Rank only marks the position of the first relevant document, so if you care about as many relevant docs as possible to be high on the list, then this should not be your choice
Kendall's tau only handles binary utility function, it also should be computed @k (similar to NDCG)
Valuable resources:
Victor Lavrenko lecture on YouTube - it's only a link to the MAP vs NDCG episode, but the whole lecture includes much more (including Kendall's Tau). You should definitely check it out, great lecture!
ERR paper
Can't post more links, because of the fresh account :) If anybody has some more remarks or ideas, I would be happy to hear them as well!
|
Metrics for evaluating ranking algorithms
I am actually looking for the same answer, however I should be able to at least partially answer your question.
All of the metrics that you have mentioned have different traits and, unfortunately, the
|
8,475
|
Metrics for evaluating ranking algorithms
|
In many cases where you apply ranking algorithms (e.g. Google search, Amazon product recommendation) you have hundreds and thousands of results. The user only wants to watch at the top ~20 or so. So the rest is completely irrelevant.
To phrase it clearly: Only the top $k$ elements are relevant
If this is true for your application, then this has direct implications on the metric:
You only need to look at the top $k$ ranked items and the top $k$ items of the ground truth ranking.
The order of those potentially $2k$ items might be relevant or not - but for sure the order of all other items is irrelevant.
Three relevant metrics are top-k accuracy, precision@k and recall@k. The $k$ depends on your application. For all of them, for the ranking-queries you evaluate, the total number of relevant items should be above $k$.
Top-k classification accuracy for ranking
For the ground truth, it might be hard to define an order. And if you only distinguish relevant / not relevant, then you are actually in a classification case!
Top-n accuracy is a metric for classification. See What is the definition of Top-n accuracy?.
$$\text{top-k accuracy} = \frac{\text{how often was at least one relevant element within the top-k of a ranking query?}}{\text{ranking queries}}$$
So you let the ranking algorithm predict $k$ elements and see if it contains at least one relevant item.
I like this very much because it is so easy to interpret. $k$ comes from a business requirement (probably $k \in [5, 20]$), then you can say how often the users will be happy.
Downside of this: If you still care about the order within the $k$ items, you have to find another metric.
Precision@k
$$\text{Precision@k} = \frac{\text{number of relevant items within the top-k}}{k} \in [0, 1], \text{ higher is better}$$
What it tells you:
if it is high -> Much of what you show to the user is relevant to them
if it is low -> You waste your users time. Much of what you show them, is not relevant to them
Recall@k
$$\text{Recall@k} = \frac{\text{number of relevant items within the top-k}}{\text{total number of relevant items}} \in [0, 1], \text{ higher is better}$$
What it means:
If it is high: You show what you have! You give them all the relevant items.
If it is low: Compared with the total amount of relevant items, k is small / the relevant items within the top k is small. Due to this, recall@k alone might be not so meaningful. If it is combined with a high precision@k, then increasing k might make sense.
|
Metrics for evaluating ranking algorithms
|
In many cases where you apply ranking algorithms (e.g. Google search, Amazon product recommendation) you have hundreds and thousands of results. The user only wants to watch at the top ~20 or so. So t
|
Metrics for evaluating ranking algorithms
In many cases where you apply ranking algorithms (e.g. Google search, Amazon product recommendation) you have hundreds and thousands of results. The user only wants to watch at the top ~20 or so. So the rest is completely irrelevant.
To phrase it clearly: Only the top $k$ elements are relevant
If this is true for your application, then this has direct implications on the metric:
You only need to look at the top $k$ ranked items and the top $k$ items of the ground truth ranking.
The order of those potentially $2k$ items might be relevant or not - but for sure the order of all other items is irrelevant.
Three relevant metrics are top-k accuracy, precision@k and recall@k. The $k$ depends on your application. For all of them, for the ranking-queries you evaluate, the total number of relevant items should be above $k$.
Top-k classification accuracy for ranking
For the ground truth, it might be hard to define an order. And if you only distinguish relevant / not relevant, then you are actually in a classification case!
Top-n accuracy is a metric for classification. See What is the definition of Top-n accuracy?.
$$\text{top-k accuracy} = \frac{\text{how often was at least one relevant element within the top-k of a ranking query?}}{\text{ranking queries}}$$
So you let the ranking algorithm predict $k$ elements and see if it contains at least one relevant item.
I like this very much because it is so easy to interpret. $k$ comes from a business requirement (probably $k \in [5, 20]$), then you can say how often the users will be happy.
Downside of this: If you still care about the order within the $k$ items, you have to find another metric.
Precision@k
$$\text{Precision@k} = \frac{\text{number of relevant items within the top-k}}{k} \in [0, 1], \text{ higher is better}$$
What it tells you:
if it is high -> Much of what you show to the user is relevant to them
if it is low -> You waste your users time. Much of what you show them, is not relevant to them
Recall@k
$$\text{Recall@k} = \frac{\text{number of relevant items within the top-k}}{\text{total number of relevant items}} \in [0, 1], \text{ higher is better}$$
What it means:
If it is high: You show what you have! You give them all the relevant items.
If it is low: Compared with the total amount of relevant items, k is small / the relevant items within the top k is small. Due to this, recall@k alone might be not so meaningful. If it is combined with a high precision@k, then increasing k might make sense.
|
Metrics for evaluating ranking algorithms
In many cases where you apply ranking algorithms (e.g. Google search, Amazon product recommendation) you have hundreds and thousands of results. The user only wants to watch at the top ~20 or so. So t
|
8,476
|
Metrics for evaluating ranking algorithms
|
I recently had to choose a metric for evaluating multilabel ranking algorithms and got to this subject, which was really helpful. Here are some additions to stpk's answer, which were helpful for making a choice.
MAP can be adapted to multilabel problems, at the cost of an approximation
MAP does not need to be computed at k but the multilabel version might not be adapted when the negative class is preponderant
MAP and (N)DCG can both be rewritten as weigthed average of ranked relevance values
Details
Let us focus on average precision (AP) as mean average precision (MAP) is just an average of APs on several queries. AP is properly defined on binary data as the area under precision-recall curve, which can be rewritten as the average of the precisions at each positive items. (see the wikipedia article on MAP)
A possible approximation is to define it as the average of the precisions at each item. Sadly, we lose the nice property that the negative examples ranked at the end of the list have no impact on the value of AP. (This is particularly sad when it comes to evaluating a search engine, with far more negative examples than positive examples. A possible workaround is to subsample the negative examples, at the cost of other downsides, e.g. the queries with more positive items will become equally difficult to the queries with few positive examples.)
On the other hand, this approximation has the nice property that it generalizes well to the multilabel case. Indeed, in the binary case, the precision at position k can be also interpreted as the average relevance before position k, where the relevance of a positive example is 1, and the relevance of a negative example is 0. This definition extends quite naturally to the case where there are more than two different levels of relevance. In this case, AP can also be defined as the mean of the averages of the relevances at each position.
This expression is the one chosen by the speaker of the video cited by stpk in their answer. He shows in this video that the AP can be rewritten as a weighted mean of the relevances, the weight of the $k$-th element in the ranking being
$$w_k^{AP} = \frac{1}{K}\log(\frac{K}{k})$$
where $K$ is the number of items to rank. Now we have this expression, we can compare it to the DCG. Indeed, DCG is also a weighted average of the ranked relevances, the weights being:
$$w_k^{DCG} = \frac{1}{\log(k+1)}$$
From these two expressions, we can deduce that
- AP weighs the documents from 1 to 0.
- DCG weighs the documents independently from the total number of documents.
In both cases, if there are much more irrelevant examples than relevant examples, the total weight of the positive can be negligible. For AP, a workaround is to subsample the negative samples, but I'm not sure how to choose the proportion of subsampling, as well as whether to make it dependent on the query or on the number of positive documents. For DCG, we can cut it at k, but the same kind of questions arise.
I'd be happy to hear more about this, if anybody here worked on the subject.
|
Metrics for evaluating ranking algorithms
|
I recently had to choose a metric for evaluating multilabel ranking algorithms and got to this subject, which was really helpful. Here are some additions to stpk's answer, which were helpful for makin
|
Metrics for evaluating ranking algorithms
I recently had to choose a metric for evaluating multilabel ranking algorithms and got to this subject, which was really helpful. Here are some additions to stpk's answer, which were helpful for making a choice.
MAP can be adapted to multilabel problems, at the cost of an approximation
MAP does not need to be computed at k but the multilabel version might not be adapted when the negative class is preponderant
MAP and (N)DCG can both be rewritten as weigthed average of ranked relevance values
Details
Let us focus on average precision (AP) as mean average precision (MAP) is just an average of APs on several queries. AP is properly defined on binary data as the area under precision-recall curve, which can be rewritten as the average of the precisions at each positive items. (see the wikipedia article on MAP)
A possible approximation is to define it as the average of the precisions at each item. Sadly, we lose the nice property that the negative examples ranked at the end of the list have no impact on the value of AP. (This is particularly sad when it comes to evaluating a search engine, with far more negative examples than positive examples. A possible workaround is to subsample the negative examples, at the cost of other downsides, e.g. the queries with more positive items will become equally difficult to the queries with few positive examples.)
On the other hand, this approximation has the nice property that it generalizes well to the multilabel case. Indeed, in the binary case, the precision at position k can be also interpreted as the average relevance before position k, where the relevance of a positive example is 1, and the relevance of a negative example is 0. This definition extends quite naturally to the case where there are more than two different levels of relevance. In this case, AP can also be defined as the mean of the averages of the relevances at each position.
This expression is the one chosen by the speaker of the video cited by stpk in their answer. He shows in this video that the AP can be rewritten as a weighted mean of the relevances, the weight of the $k$-th element in the ranking being
$$w_k^{AP} = \frac{1}{K}\log(\frac{K}{k})$$
where $K$ is the number of items to rank. Now we have this expression, we can compare it to the DCG. Indeed, DCG is also a weighted average of the ranked relevances, the weights being:
$$w_k^{DCG} = \frac{1}{\log(k+1)}$$
From these two expressions, we can deduce that
- AP weighs the documents from 1 to 0.
- DCG weighs the documents independently from the total number of documents.
In both cases, if there are much more irrelevant examples than relevant examples, the total weight of the positive can be negligible. For AP, a workaround is to subsample the negative samples, but I'm not sure how to choose the proportion of subsampling, as well as whether to make it dependent on the query or on the number of positive documents. For DCG, we can cut it at k, but the same kind of questions arise.
I'd be happy to hear more about this, if anybody here worked on the subject.
|
Metrics for evaluating ranking algorithms
I recently had to choose a metric for evaluating multilabel ranking algorithms and got to this subject, which was really helpful. Here are some additions to stpk's answer, which were helpful for makin
|
8,477
|
White Noise in Statistics
|
TL;DR
The answer is NO, it doesn't have to be normal; YES, it can be other distributions.
Colors of the noise
Let's talk about colors of the noise.
The noise that an infant makes during the air travel is not white. It has color.
The noise that an airplane engine makes is also not white, but it's not as colored as the kid's noise. It's whiter.
The noise that an ocean or a forest produces is almost white.
If you use noise cancelling head phones, you know that #1 is impossible to cancel. It'll pierce through any head phone with ease. #2 will be cancelled very well.
As to #3, why would you cancel it?
Origin of a term "color"
What's the distinction between these three noises? It comes from spectral analysis. As you know from high school years you can send the white light through a prism and it will split the light into all different colors. That's what we call white: all colors in approximately the same proportion. No color dominates.
image is from https://www.haikudeck.com/waves-and-light-vocabulary-uncategorized-presentation-w5bmS88NC9
The color is the light of a certain frequency, or you could say electromagnetic waves of certain wavelength like shown below. The red color has low frequency relative to the blue, equivalently the red color has longer wavelength of almost 800nm compared to the blue wavelength of 450nm.
image is from here: https://hubpages.com/education/Teachers-Guide-for-Radiation-beyond-Visible-Spectrum
Spectral Analysis
If you take noise, whether acoustic, radio or other, and send it through the spectral analysis tool such as FFT, you get it spectral decomposition. You'll see how much of each frequency is in the noise, like shown in the next picture from Wikipedia. It's clear that this is not white noise: it has clear peaks at 50Hz, 40Hz etc.
If a narrow frequency band sticks out, then it's called colored, as in not white. So, white noise is just like white light, it has a wide range of frequencies in approximately same proportion like shown in the next figure from this site. The top chart shows the recording of the amplitude, and the bottom shows the spectral decomposition. No frequency sticks out. So the noise is white.
Perfect sine
Now, why does the sequence of independent identically distributed random numbers(iid) generates the white noise? Let's think of what makes a signal colored. It's the waves of certain frequency sticking out from others. They dominate the spectrum. Consider a perfect sign wave: $\sin(2\pi t)$. Let's see what is the covariance between any two points $\phi=1/2$ seconds apart:
$$E[\sin(2\pi t) \times \sin(2\pi (t+1/2)]=-E[\sin^2 (2\pi t)]=-\frac 1 2$$
So, in the presence of the sine wave we'll get autocorrelation in the time series: all oservations half a second apart will be perfectly negatively correlated! Now, saying that our data is i.i.d. implies that there is no any autocorrelation whatsoever. This means that there are no waves in the signal. The spectrum of the noise is flat.
Imperfect Example
Here's an example I created on my computer. I first recorded my tuning fork, then I recorded the noise from computer's fans. Then I ran the following MATLAB code to analyze the spectra:
[y,Fs] = audioread(filew);
data = y(1000:5000,1);
plot(data)
figure
periodogram(data,[],[],Fs);
[pxx,f] = periodogram(data,[],[],Fs);
[pm,i]=max(pxx);
f(i)
Here's the signal and the spectrum of the tuning fork. As expected it has a peak at around 440Hz. The tuning fork must produce a nearly ideal sine wave signal, like in my theoretical example earlier.
Next I did the same to the noise. As expected no frequency is sticking out. Obviously this is not the white noise, but it gets quite close to it. I think that there must be very high pitched frequency, it bother me a little bit. I need to change the fan soon. However, I don't see it in the spectrum. Maybe because my microphone is beyond crappy, or the sampling frequency is not high enough.
Distribution doesn't matter
The important part is that in the random sequence the numbers are not autocorrelated (or even stronger, independent). The exact distribution is not important. It could be Gaussian or gamma, but as long as the numbers do not correlate in the sequence the noise will be white.
|
White Noise in Statistics
|
TL;DR
The answer is NO, it doesn't have to be normal; YES, it can be other distributions.
Colors of the noise
Let's talk about colors of the noise.
The noise that an infant makes during the air trave
|
White Noise in Statistics
TL;DR
The answer is NO, it doesn't have to be normal; YES, it can be other distributions.
Colors of the noise
Let's talk about colors of the noise.
The noise that an infant makes during the air travel is not white. It has color.
The noise that an airplane engine makes is also not white, but it's not as colored as the kid's noise. It's whiter.
The noise that an ocean or a forest produces is almost white.
If you use noise cancelling head phones, you know that #1 is impossible to cancel. It'll pierce through any head phone with ease. #2 will be cancelled very well.
As to #3, why would you cancel it?
Origin of a term "color"
What's the distinction between these three noises? It comes from spectral analysis. As you know from high school years you can send the white light through a prism and it will split the light into all different colors. That's what we call white: all colors in approximately the same proportion. No color dominates.
image is from https://www.haikudeck.com/waves-and-light-vocabulary-uncategorized-presentation-w5bmS88NC9
The color is the light of a certain frequency, or you could say electromagnetic waves of certain wavelength like shown below. The red color has low frequency relative to the blue, equivalently the red color has longer wavelength of almost 800nm compared to the blue wavelength of 450nm.
image is from here: https://hubpages.com/education/Teachers-Guide-for-Radiation-beyond-Visible-Spectrum
Spectral Analysis
If you take noise, whether acoustic, radio or other, and send it through the spectral analysis tool such as FFT, you get it spectral decomposition. You'll see how much of each frequency is in the noise, like shown in the next picture from Wikipedia. It's clear that this is not white noise: it has clear peaks at 50Hz, 40Hz etc.
If a narrow frequency band sticks out, then it's called colored, as in not white. So, white noise is just like white light, it has a wide range of frequencies in approximately same proportion like shown in the next figure from this site. The top chart shows the recording of the amplitude, and the bottom shows the spectral decomposition. No frequency sticks out. So the noise is white.
Perfect sine
Now, why does the sequence of independent identically distributed random numbers(iid) generates the white noise? Let's think of what makes a signal colored. It's the waves of certain frequency sticking out from others. They dominate the spectrum. Consider a perfect sign wave: $\sin(2\pi t)$. Let's see what is the covariance between any two points $\phi=1/2$ seconds apart:
$$E[\sin(2\pi t) \times \sin(2\pi (t+1/2)]=-E[\sin^2 (2\pi t)]=-\frac 1 2$$
So, in the presence of the sine wave we'll get autocorrelation in the time series: all oservations half a second apart will be perfectly negatively correlated! Now, saying that our data is i.i.d. implies that there is no any autocorrelation whatsoever. This means that there are no waves in the signal. The spectrum of the noise is flat.
Imperfect Example
Here's an example I created on my computer. I first recorded my tuning fork, then I recorded the noise from computer's fans. Then I ran the following MATLAB code to analyze the spectra:
[y,Fs] = audioread(filew);
data = y(1000:5000,1);
plot(data)
figure
periodogram(data,[],[],Fs);
[pxx,f] = periodogram(data,[],[],Fs);
[pm,i]=max(pxx);
f(i)
Here's the signal and the spectrum of the tuning fork. As expected it has a peak at around 440Hz. The tuning fork must produce a nearly ideal sine wave signal, like in my theoretical example earlier.
Next I did the same to the noise. As expected no frequency is sticking out. Obviously this is not the white noise, but it gets quite close to it. I think that there must be very high pitched frequency, it bother me a little bit. I need to change the fan soon. However, I don't see it in the spectrum. Maybe because my microphone is beyond crappy, or the sampling frequency is not high enough.
Distribution doesn't matter
The important part is that in the random sequence the numbers are not autocorrelated (or even stronger, independent). The exact distribution is not important. It could be Gaussian or gamma, but as long as the numbers do not correlate in the sequence the noise will be white.
|
White Noise in Statistics
TL;DR
The answer is NO, it doesn't have to be normal; YES, it can be other distributions.
Colors of the noise
Let's talk about colors of the noise.
The noise that an infant makes during the air trave
|
8,478
|
White Noise in Statistics
|
White noise simply means that the sequence of samples are uncorrelated with zero mean and finite variance. There is no restriction on the distribution from which the samples are drawn. Now if the samples happen to be drawn from a Normal distribution, you have a special type of white noise called Gaussian white noise.
|
White Noise in Statistics
|
White noise simply means that the sequence of samples are uncorrelated with zero mean and finite variance. There is no restriction on the distribution from which the samples are drawn. Now if the samp
|
White Noise in Statistics
White noise simply means that the sequence of samples are uncorrelated with zero mean and finite variance. There is no restriction on the distribution from which the samples are drawn. Now if the samples happen to be drawn from a Normal distribution, you have a special type of white noise called Gaussian white noise.
|
White Noise in Statistics
White noise simply means that the sequence of samples are uncorrelated with zero mean and finite variance. There is no restriction on the distribution from which the samples are drawn. Now if the samp
|
8,479
|
Detecting significant predictors out of many independent variables
|
I would recommend trying a glm with lasso regularization. This adds a penalty to the model for number of variables, and as you increase the penalty, the number of variables in the model will decrease.
You should use cross-validation to select the value of the penalty parameter. If you have R, I suggest using the glmnet package. Use alpha=1 for lasso regression, and alpha=0 for ridge regression. Setting a value between 0 and 1 will use a combination of lasso and ridge penalties, also know as the elastic net.
|
Detecting significant predictors out of many independent variables
|
I would recommend trying a glm with lasso regularization. This adds a penalty to the model for number of variables, and as you increase the penalty, the number of variables in the model will decrease.
|
Detecting significant predictors out of many independent variables
I would recommend trying a glm with lasso regularization. This adds a penalty to the model for number of variables, and as you increase the penalty, the number of variables in the model will decrease.
You should use cross-validation to select the value of the penalty parameter. If you have R, I suggest using the glmnet package. Use alpha=1 for lasso regression, and alpha=0 for ridge regression. Setting a value between 0 and 1 will use a combination of lasso and ridge penalties, also know as the elastic net.
|
Detecting significant predictors out of many independent variables
I would recommend trying a glm with lasso regularization. This adds a penalty to the model for number of variables, and as you increase the penalty, the number of variables in the model will decrease.
|
8,480
|
Detecting significant predictors out of many independent variables
|
To expand on Zach's answer (+1), if you use the LASSO method in linear regression, you are trying to minimize the sum a quadratic function and an absolute value function, ie:
$$\min_{\beta} \; \; (Y-X\beta)^{T}(Y-X\beta) + \sum_i |\beta_i| $$
The first part is quadratic in $\beta$ (gold below), and the second is a square shaped curve (green below). The black line is the line of intersection.
The minimum lies on the curve of intersection, plotted here with the contour curves of the quadratic and square-shaped curve:
You can see the minimum is on one of the axes, hence it has eliminated that variable from the regression.
You can check out my blog post on using $L1$ penalties for regression and variable selection (otherwise known as Lasso regularization).
|
Detecting significant predictors out of many independent variables
|
To expand on Zach's answer (+1), if you use the LASSO method in linear regression, you are trying to minimize the sum a quadratic function and an absolute value function, ie:
$$\min_{\beta} \; \; (Y-X
|
Detecting significant predictors out of many independent variables
To expand on Zach's answer (+1), if you use the LASSO method in linear regression, you are trying to minimize the sum a quadratic function and an absolute value function, ie:
$$\min_{\beta} \; \; (Y-X\beta)^{T}(Y-X\beta) + \sum_i |\beta_i| $$
The first part is quadratic in $\beta$ (gold below), and the second is a square shaped curve (green below). The black line is the line of intersection.
The minimum lies on the curve of intersection, plotted here with the contour curves of the quadratic and square-shaped curve:
You can see the minimum is on one of the axes, hence it has eliminated that variable from the regression.
You can check out my blog post on using $L1$ penalties for regression and variable selection (otherwise known as Lasso regularization).
|
Detecting significant predictors out of many independent variables
To expand on Zach's answer (+1), if you use the LASSO method in linear regression, you are trying to minimize the sum a quadratic function and an absolute value function, ie:
$$\min_{\beta} \; \; (Y-X
|
8,481
|
Detecting significant predictors out of many independent variables
|
What is your prior belief on how many predictors are likely to be important? Is it likely that most of them have an exactly zero effect, or that everything affects the outcome, some variables only less than others?
And how is the health status related to the predictive task?
If you believe that only few variables are important, you may try the spike and slab prior (in the R's spikeSlabGAM package, for example), or L1. If you think all predictors affect the outcome, you may be out of luck.
And in general, all caveats related to causal inference from observational data apply.
|
Detecting significant predictors out of many independent variables
|
What is your prior belief on how many predictors are likely to be important? Is it likely that most of them have an exactly zero effect, or that everything affects the outcome, some variables only les
|
Detecting significant predictors out of many independent variables
What is your prior belief on how many predictors are likely to be important? Is it likely that most of them have an exactly zero effect, or that everything affects the outcome, some variables only less than others?
And how is the health status related to the predictive task?
If you believe that only few variables are important, you may try the spike and slab prior (in the R's spikeSlabGAM package, for example), or L1. If you think all predictors affect the outcome, you may be out of luck.
And in general, all caveats related to causal inference from observational data apply.
|
Detecting significant predictors out of many independent variables
What is your prior belief on how many predictors are likely to be important? Is it likely that most of them have an exactly zero effect, or that everything affects the outcome, some variables only les
|
8,482
|
Detecting significant predictors out of many independent variables
|
Whatever you do, it is worthwhile getting bootstrap confidence intervals on the ranks of importance of the predictors to show that you can really do this with your dataset. I am doubtful that any of the methods can reliably find the "true" predictors.
|
Detecting significant predictors out of many independent variables
|
Whatever you do, it is worthwhile getting bootstrap confidence intervals on the ranks of importance of the predictors to show that you can really do this with your dataset. I am doubtful that any of
|
Detecting significant predictors out of many independent variables
Whatever you do, it is worthwhile getting bootstrap confidence intervals on the ranks of importance of the predictors to show that you can really do this with your dataset. I am doubtful that any of the methods can reliably find the "true" predictors.
|
Detecting significant predictors out of many independent variables
Whatever you do, it is worthwhile getting bootstrap confidence intervals on the ranks of importance of the predictors to show that you can really do this with your dataset. I am doubtful that any of
|
8,483
|
Detecting significant predictors out of many independent variables
|
I remember Lasso regression doesn't perform very well when $n \leq p$, but I'm not sure. I think in this case Elastic Net is more appropriate for variable selection.
|
Detecting significant predictors out of many independent variables
|
I remember Lasso regression doesn't perform very well when $n \leq p$, but I'm not sure. I think in this case Elastic Net is more appropriate for variable selection.
|
Detecting significant predictors out of many independent variables
I remember Lasso regression doesn't perform very well when $n \leq p$, but I'm not sure. I think in this case Elastic Net is more appropriate for variable selection.
|
Detecting significant predictors out of many independent variables
I remember Lasso regression doesn't perform very well when $n \leq p$, but I'm not sure. I think in this case Elastic Net is more appropriate for variable selection.
|
8,484
|
How does quantile regression "work"?
|
I recommend Koenker & Hallock (2001, Journal of Economic Perspectives) and Koenker's textbook Quantile Regression.
The starting point is the observation that the median of a data set minimizes the sum of absolute errors. That is, the 50% quantile is a solution to a particular optimization problem (to find the value that minimizes the sum of absolute errors).
From this, it is easy to find that any $\tau$-quantile is the solution to a specific minimization problem, namely to minimize a sum of asymmetrically weighted absolute errors, with weights that depend on $\tau$.
Finally, to make the step to regression, we model the solution to this minimization problem as a linear combination of predictor variables, so now the problem is one of finding not a single value, but a set of regression parameters.
So your intuition is quite correct: all of the samples contribute to the $\beta$ estimates, with asymmetric weights depending on the quantile $\tau$ we aim for.
|
How does quantile regression "work"?
|
I recommend Koenker & Hallock (2001, Journal of Economic Perspectives) and Koenker's textbook Quantile Regression.
The starting point is the observation that the median of a data set minimizes the su
|
How does quantile regression "work"?
I recommend Koenker & Hallock (2001, Journal of Economic Perspectives) and Koenker's textbook Quantile Regression.
The starting point is the observation that the median of a data set minimizes the sum of absolute errors. That is, the 50% quantile is a solution to a particular optimization problem (to find the value that minimizes the sum of absolute errors).
From this, it is easy to find that any $\tau$-quantile is the solution to a specific minimization problem, namely to minimize a sum of asymmetrically weighted absolute errors, with weights that depend on $\tau$.
Finally, to make the step to regression, we model the solution to this minimization problem as a linear combination of predictor variables, so now the problem is one of finding not a single value, but a set of regression parameters.
So your intuition is quite correct: all of the samples contribute to the $\beta$ estimates, with asymmetric weights depending on the quantile $\tau$ we aim for.
|
How does quantile regression "work"?
I recommend Koenker & Hallock (2001, Journal of Economic Perspectives) and Koenker's textbook Quantile Regression.
The starting point is the observation that the median of a data set minimizes the su
|
8,485
|
How does quantile regression "work"?
|
The basic idea of quantile regression comes from the fact the the analyst is interested in distribution of data rather that just mean of data. Lets start with mean.
Mean regression fits a line of the form of $y=X\beta$ to the mean of data. In other words, $E(Y|X=x)=x\beta$. A general approach to estimate this line is using least square method, $\arg\min_\beta (y-x\beta)'(y-X\beta)$.
On the other hand median regression looks for a line that expect half of the data are on sides. In this case target function is $\arg\min_\beta |y-X\beta|$ where $|.|$ is the first norm.
Extending the idea of median to quantile results in Quantile regression. The idea behind is to find a line that $\alpha$-percent of data are beyond that.
Here you made a small mistake, Q-regression is not like finding a quantile of data then fit a line to that subset (or even the borders that is more challenging).
Q-regression looks for a line that split data into a qroup a $\alpha$ quantile and the rests. Target function, saying check function of Q-regression is
$$
\hat\beta_\alpha=\arg\min_\beta \bigg\{\alpha |y-X\beta| I(y>X\beta) + (1-\alpha) |y-X\beta|I(y<X\beta)\bigg\}.
$$
As you see this clever target function is nothing more that translating quantile to an optimization problem.
Moreover, as you see, Q-regression is defined for a certain quantie ($\beta_\alpha$) and then can be extended to find all quantiles. In other words, Q-regression can reproduce (conditional) distribution of response.
|
How does quantile regression "work"?
|
The basic idea of quantile regression comes from the fact the the analyst is interested in distribution of data rather that just mean of data. Lets start with mean.
Mean regression fits a line of the
|
How does quantile regression "work"?
The basic idea of quantile regression comes from the fact the the analyst is interested in distribution of data rather that just mean of data. Lets start with mean.
Mean regression fits a line of the form of $y=X\beta$ to the mean of data. In other words, $E(Y|X=x)=x\beta$. A general approach to estimate this line is using least square method, $\arg\min_\beta (y-x\beta)'(y-X\beta)$.
On the other hand median regression looks for a line that expect half of the data are on sides. In this case target function is $\arg\min_\beta |y-X\beta|$ where $|.|$ is the first norm.
Extending the idea of median to quantile results in Quantile regression. The idea behind is to find a line that $\alpha$-percent of data are beyond that.
Here you made a small mistake, Q-regression is not like finding a quantile of data then fit a line to that subset (or even the borders that is more challenging).
Q-regression looks for a line that split data into a qroup a $\alpha$ quantile and the rests. Target function, saying check function of Q-regression is
$$
\hat\beta_\alpha=\arg\min_\beta \bigg\{\alpha |y-X\beta| I(y>X\beta) + (1-\alpha) |y-X\beta|I(y<X\beta)\bigg\}.
$$
As you see this clever target function is nothing more that translating quantile to an optimization problem.
Moreover, as you see, Q-regression is defined for a certain quantie ($\beta_\alpha$) and then can be extended to find all quantiles. In other words, Q-regression can reproduce (conditional) distribution of response.
|
How does quantile regression "work"?
The basic idea of quantile regression comes from the fact the the analyst is interested in distribution of data rather that just mean of data. Lets start with mean.
Mean regression fits a line of the
|
8,486
|
Fit a sinusoidal term to data
|
If you just want a good estimate of $\omega$ and don't care much about
its standard error:
ssp <- spectrum(y)
per <- 1/ssp$freq[ssp$spec==max(ssp$spec)]
reslm <- lm(y ~ sin(2*pi/per*t)+cos(2*pi/per*t))
summary(reslm)
rg <- diff(range(y))
plot(y~t,ylim=c(min(y)-0.1*rg,max(y)+0.1*rg))
lines(fitted(reslm)~t,col=4,lty=2) # dashed blue line is sin fit
# including 2nd harmonic really improves the fit
reslm2 <- lm(y ~ sin(2*pi/per*t)+cos(2*pi/per*t)+sin(4*pi/per*t)+cos(4*pi/per*t))
summary(reslm2)
lines(fitted(reslm2)~t,col=3) # solid green line is periodic with second harmonic
(A better fit still would perhaps account for the outliers in that series in some way, reducing their influence.)
---
If you want some idea of the uncertainty in $\omega$, you could use profile likelihood (pdf1, pdf2 - references on getting approximate CIs or SEs from profile likelihood or its variants aren't hard to locate)
(Alternatively, you could feed these estimates into nls ... and start it already converged.)
|
Fit a sinusoidal term to data
|
If you just want a good estimate of $\omega$ and don't care much about
its standard error:
ssp <- spectrum(y)
per <- 1/ssp$freq[ssp$spec==max(ssp$spec)]
reslm <- lm(y ~ sin(2*pi/per*t)+cos(2*pi/per*
|
Fit a sinusoidal term to data
If you just want a good estimate of $\omega$ and don't care much about
its standard error:
ssp <- spectrum(y)
per <- 1/ssp$freq[ssp$spec==max(ssp$spec)]
reslm <- lm(y ~ sin(2*pi/per*t)+cos(2*pi/per*t))
summary(reslm)
rg <- diff(range(y))
plot(y~t,ylim=c(min(y)-0.1*rg,max(y)+0.1*rg))
lines(fitted(reslm)~t,col=4,lty=2) # dashed blue line is sin fit
# including 2nd harmonic really improves the fit
reslm2 <- lm(y ~ sin(2*pi/per*t)+cos(2*pi/per*t)+sin(4*pi/per*t)+cos(4*pi/per*t))
summary(reslm2)
lines(fitted(reslm2)~t,col=3) # solid green line is periodic with second harmonic
(A better fit still would perhaps account for the outliers in that series in some way, reducing their influence.)
---
If you want some idea of the uncertainty in $\omega$, you could use profile likelihood (pdf1, pdf2 - references on getting approximate CIs or SEs from profile likelihood or its variants aren't hard to locate)
(Alternatively, you could feed these estimates into nls ... and start it already converged.)
|
Fit a sinusoidal term to data
If you just want a good estimate of $\omega$ and don't care much about
its standard error:
ssp <- spectrum(y)
per <- 1/ssp$freq[ssp$spec==max(ssp$spec)]
reslm <- lm(y ~ sin(2*pi/per*t)+cos(2*pi/per*
|
8,487
|
Fit a sinusoidal term to data
|
As @Stefan suggested, different starting values do seem to improve the fit dramatically. I eyeballed the data to suggest that omega should be about $2 \pi / 20$, since the peaks looked like they were about 20 units apart.
When I put that into nls's start list, I got a curve that was much more reasonable, although it still has some systematic biases.
Depending on what your goal is with this data set, you could try to improve the fit by adding additional terms or using a nonparametric approach like a Gaussian process with a periodic kernel.
Choosing a starting value automatically
If you want to pick the dominant frequency, you can use a fast Fourier transform (FFT). This is way out of my area of expertise, so I'll let other folks fill in the details if they'd like (especially about steps 2 and 3), but the R code below should work.
# Step 1: do the FFT
raw.fft = fft(y)
# Step 2: drop anything past the N/2 - 1th element.
# This has something to do with the Nyquist-shannon limit, I believe
# (https://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem)
truncated.fft = raw.fft[seq(1, length(y)/2 - 1)]
# Step 3: drop the first element. It doesn't contain frequency information.
truncated.fft[1] = 0
# Step 4: the importance of each frequency corresponds to the absolute value of the FFT.
# The 2, pi, and length(y) ensure that omega is on the correct scale relative to t.
# Here, I set omega based on the largest value using which.max().
omega = which.max(abs(truncated.fft)) * 2 * pi / length(y)
You can also plot abs(truncated.fft) to see if there are other important frequencies, but you'll have to fiddle with the scaling of the x-axis a bit.
Also, I believe @Glen_b is correct that the problem is convex once you know omega (or maybe you need to know phi too? I'm not sure). In any case, knowing the starting values for the other parameters shouldn't be nearly as important as for omega if they're in the right ballpark. You could probably get decent estimates of the other parameters from the FFT, but I'm not certain how that would work.
|
Fit a sinusoidal term to data
|
As @Stefan suggested, different starting values do seem to improve the fit dramatically. I eyeballed the data to suggest that omega should be about $2 \pi / 20$, since the peaks looked like they were
|
Fit a sinusoidal term to data
As @Stefan suggested, different starting values do seem to improve the fit dramatically. I eyeballed the data to suggest that omega should be about $2 \pi / 20$, since the peaks looked like they were about 20 units apart.
When I put that into nls's start list, I got a curve that was much more reasonable, although it still has some systematic biases.
Depending on what your goal is with this data set, you could try to improve the fit by adding additional terms or using a nonparametric approach like a Gaussian process with a periodic kernel.
Choosing a starting value automatically
If you want to pick the dominant frequency, you can use a fast Fourier transform (FFT). This is way out of my area of expertise, so I'll let other folks fill in the details if they'd like (especially about steps 2 and 3), but the R code below should work.
# Step 1: do the FFT
raw.fft = fft(y)
# Step 2: drop anything past the N/2 - 1th element.
# This has something to do with the Nyquist-shannon limit, I believe
# (https://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem)
truncated.fft = raw.fft[seq(1, length(y)/2 - 1)]
# Step 3: drop the first element. It doesn't contain frequency information.
truncated.fft[1] = 0
# Step 4: the importance of each frequency corresponds to the absolute value of the FFT.
# The 2, pi, and length(y) ensure that omega is on the correct scale relative to t.
# Here, I set omega based on the largest value using which.max().
omega = which.max(abs(truncated.fft)) * 2 * pi / length(y)
You can also plot abs(truncated.fft) to see if there are other important frequencies, but you'll have to fiddle with the scaling of the x-axis a bit.
Also, I believe @Glen_b is correct that the problem is convex once you know omega (or maybe you need to know phi too? I'm not sure). In any case, knowing the starting values for the other parameters shouldn't be nearly as important as for omega if they're in the right ballpark. You could probably get decent estimates of the other parameters from the FFT, but I'm not certain how that would work.
|
Fit a sinusoidal term to data
As @Stefan suggested, different starting values do seem to improve the fit dramatically. I eyeballed the data to suggest that omega should be about $2 \pi / 20$, since the peaks looked like they were
|
8,488
|
Fit a sinusoidal term to data
|
As an alternative to what has already been said, it may be worth noting that an AR(2) model from the class of ARIMA models can be used to generate forecasts with a sine wave pattern.
An AR(2) model can be written as follows:
\begin{equation}
y_{t} = C + \phi_{1}y_{t-1} + \phi_{2}y_{t-2} + a_{t}
\end{equation}
where $C$ is a constant, $\phi_{1}$, $\phi_{2}$ are parameters to be estimated and $a_{t}$ is a random shock term.
Now, not all AR(2) models produce sine wave patterns (also known as stochastic cycles) in their forecasts, but it does happen when the following condition is satisfied:
\begin{equation}
\phi_{1}^{2} + 4 \phi_{2} < 0.
\end{equation}
Panratz(1991) tells us the following about stochastic cycles:
A stochastic cycle pattern can be thought of a distorted sine wave
pattern in the forecast pattern: It is a sine wave with a stochastic
(probabilistic) period, amplitude, and phase angle.
To see if such a model could be fitted to the data I used the auto.arima() function from the forecast package to find out if it would suggest an AR(2) model. It turns out that the auto.arima() function suggests an ARMA(2,2) model; not a pure AR(2) model, but this is OK. It's OK because an ARMA(2,2) model contains an AR(2) component, so the same rule (about stochastic cycles) applies. That is, we can still check the aforementioned condition to see if sine wave forecasts will be produced.
The results of auto.arima(y) are shown below.
Series: y
ARIMA(2,0,2) with non-zero mean
Coefficients:
ar1 ar2 ma1 ma2 intercept
1.7347 -0.8324 -1.2474 0.6918 10.2727
s.e. 0.1078 0.0981 0.1167 0.1911 0.5324
sigma^2 estimated as 0.6756: log likelihood=-60.14
AIC=132.27 AICc=134.32 BIC=143.5
Now let's check the condition:
\begin{equation}
\phi_{1}^{2} + 4 \phi_{2} < 0\\
1.7347^{2} + 4 (-0.8324) < 0 \\
-0.3202914 < 0
\end{equation}
and we find that the condition is, indeed, satisfied.
The plot below shows the original series, y, the fit of the ARMA(2,2) model, and 14 out-of-sample forecasts. As can be seen, the out-of-sample forecasts follow a sine-wave pattern.
Keep in mind two things. 1) This is just a very quick analysis (using an automated tool) and a proper treatment would involve following the Box-Jenkins methodology. 2) ARIMA forecasts are good at short-term forecasting, so you may find that long term forecasts from the models in the answers by @David J. Harris and @Glen_b to be more reliable.
Lastly, hopefully this is a nice addition to some already very informative answers.
Reference: Forecasting with dynamic regression models: Alan Pankratz, 1991, (John Wiley and Sons, New York), ISBN 0-471-61528-5
|
Fit a sinusoidal term to data
|
As an alternative to what has already been said, it may be worth noting that an AR(2) model from the class of ARIMA models can be used to generate forecasts with a sine wave pattern.
An AR(2) model c
|
Fit a sinusoidal term to data
As an alternative to what has already been said, it may be worth noting that an AR(2) model from the class of ARIMA models can be used to generate forecasts with a sine wave pattern.
An AR(2) model can be written as follows:
\begin{equation}
y_{t} = C + \phi_{1}y_{t-1} + \phi_{2}y_{t-2} + a_{t}
\end{equation}
where $C$ is a constant, $\phi_{1}$, $\phi_{2}$ are parameters to be estimated and $a_{t}$ is a random shock term.
Now, not all AR(2) models produce sine wave patterns (also known as stochastic cycles) in their forecasts, but it does happen when the following condition is satisfied:
\begin{equation}
\phi_{1}^{2} + 4 \phi_{2} < 0.
\end{equation}
Panratz(1991) tells us the following about stochastic cycles:
A stochastic cycle pattern can be thought of a distorted sine wave
pattern in the forecast pattern: It is a sine wave with a stochastic
(probabilistic) period, amplitude, and phase angle.
To see if such a model could be fitted to the data I used the auto.arima() function from the forecast package to find out if it would suggest an AR(2) model. It turns out that the auto.arima() function suggests an ARMA(2,2) model; not a pure AR(2) model, but this is OK. It's OK because an ARMA(2,2) model contains an AR(2) component, so the same rule (about stochastic cycles) applies. That is, we can still check the aforementioned condition to see if sine wave forecasts will be produced.
The results of auto.arima(y) are shown below.
Series: y
ARIMA(2,0,2) with non-zero mean
Coefficients:
ar1 ar2 ma1 ma2 intercept
1.7347 -0.8324 -1.2474 0.6918 10.2727
s.e. 0.1078 0.0981 0.1167 0.1911 0.5324
sigma^2 estimated as 0.6756: log likelihood=-60.14
AIC=132.27 AICc=134.32 BIC=143.5
Now let's check the condition:
\begin{equation}
\phi_{1}^{2} + 4 \phi_{2} < 0\\
1.7347^{2} + 4 (-0.8324) < 0 \\
-0.3202914 < 0
\end{equation}
and we find that the condition is, indeed, satisfied.
The plot below shows the original series, y, the fit of the ARMA(2,2) model, and 14 out-of-sample forecasts. As can be seen, the out-of-sample forecasts follow a sine-wave pattern.
Keep in mind two things. 1) This is just a very quick analysis (using an automated tool) and a proper treatment would involve following the Box-Jenkins methodology. 2) ARIMA forecasts are good at short-term forecasting, so you may find that long term forecasts from the models in the answers by @David J. Harris and @Glen_b to be more reliable.
Lastly, hopefully this is a nice addition to some already very informative answers.
Reference: Forecasting with dynamic regression models: Alan Pankratz, 1991, (John Wiley and Sons, New York), ISBN 0-471-61528-5
|
Fit a sinusoidal term to data
As an alternative to what has already been said, it may be worth noting that an AR(2) model from the class of ARIMA models can be used to generate forecasts with a sine wave pattern.
An AR(2) model c
|
8,489
|
Fit a sinusoidal term to data
|
This isn't so different than some of the other solutions but we can simplify the use of nls. y and t and the parameters are as defined in the question. We use:
the plinear algorithm of nls to avoid estimating A and C as plinear only requires initial values for parameters that do not enter linearly. In this case the RHS of the formula should be specified as a matrix with each column multiplying one of the parameters that enter linearly. The parameters themselves are implicit but we can name the columns so that the output is easier to read.
spec.ar to derive an initial value for omega as shown in the code below
0 for the initial value of phi.
This only uses base R -- no packages.
spec <- spec.ar(y, plot = FALSE, n.freq = 1000)
f <- spec$freq[which.max(spec$spec)]
fm <- nls(y ~ cbind(C = 1, A = cos(omega*t + phi)),
start = list(omega = 2*pi*f, phi = 0), algorithm = "plinear")
fm
## Nonlinear regression model
## model: y ~ cbind(C = 1, A = cos(omega * t + phi))
## data: parent.frame()
## omega phi .lin.C .lin.A
## 0.2636 0.3819 10.1501 2.5838
## residual sum-of-squares: 22.99
##
## Number of iterations to convergence: 5
## Achieved convergence tolerance: 2.346e-06
plot(y ~ t)
lines(fitted(fm) ~ t)
|
Fit a sinusoidal term to data
|
This isn't so different than some of the other solutions but we can simplify the use of nls. y and t and the parameters are as defined in the question. We use:
the plinear algorithm of nls to avoid
|
Fit a sinusoidal term to data
This isn't so different than some of the other solutions but we can simplify the use of nls. y and t and the parameters are as defined in the question. We use:
the plinear algorithm of nls to avoid estimating A and C as plinear only requires initial values for parameters that do not enter linearly. In this case the RHS of the formula should be specified as a matrix with each column multiplying one of the parameters that enter linearly. The parameters themselves are implicit but we can name the columns so that the output is easier to read.
spec.ar to derive an initial value for omega as shown in the code below
0 for the initial value of phi.
This only uses base R -- no packages.
spec <- spec.ar(y, plot = FALSE, n.freq = 1000)
f <- spec$freq[which.max(spec$spec)]
fm <- nls(y ~ cbind(C = 1, A = cos(omega*t + phi)),
start = list(omega = 2*pi*f, phi = 0), algorithm = "plinear")
fm
## Nonlinear regression model
## model: y ~ cbind(C = 1, A = cos(omega * t + phi))
## data: parent.frame()
## omega phi .lin.C .lin.A
## 0.2636 0.3819 10.1501 2.5838
## residual sum-of-squares: 22.99
##
## Number of iterations to convergence: 5
## Achieved convergence tolerance: 2.346e-06
plot(y ~ t)
lines(fitted(fm) ~ t)
|
Fit a sinusoidal term to data
This isn't so different than some of the other solutions but we can simplify the use of nls. y and t and the parameters are as defined in the question. We use:
the plinear algorithm of nls to avoid
|
8,490
|
Fit a sinusoidal term to data
|
The current methods to fit a sin curve to a given data set require a first guess of the parameters, followed by an interative process. This is a non-linear regression problem.
A different method consists in transforming the non-linear regression to a linear regression thanks to a convenient integral equation. Then, there is no need for initial guess and no need for iterative process : the fitting is directly obtained.
In case of the function y = a + r*sin(w*x+phi) or y=a+b*sin(w*x)+c*cos(w*x), see pages 35-36 of the paper "Régression sinusoidale" published on Scribd :
http://www.scribd.com/JJacquelin/documents
In case of the function y = a + p*x + r*sin(w*x+phi) : pages 49-51 of the chapter "Mixed linear and sinusoidal regressions".
In case of more complicated functions, the general process is explained in the chapter "Generalized sinusoidal regression" pages 54-61, followed by a numerical example y = r*sin(w*x+phi)+(b/x)+c*ln(x), pages 62-63
|
Fit a sinusoidal term to data
|
The current methods to fit a sin curve to a given data set require a first guess of the parameters, followed by an interative process. This is a non-linear regression problem.
A different method consi
|
Fit a sinusoidal term to data
The current methods to fit a sin curve to a given data set require a first guess of the parameters, followed by an interative process. This is a non-linear regression problem.
A different method consists in transforming the non-linear regression to a linear regression thanks to a convenient integral equation. Then, there is no need for initial guess and no need for iterative process : the fitting is directly obtained.
In case of the function y = a + r*sin(w*x+phi) or y=a+b*sin(w*x)+c*cos(w*x), see pages 35-36 of the paper "Régression sinusoidale" published on Scribd :
http://www.scribd.com/JJacquelin/documents
In case of the function y = a + p*x + r*sin(w*x+phi) : pages 49-51 of the chapter "Mixed linear and sinusoidal regressions".
In case of more complicated functions, the general process is explained in the chapter "Generalized sinusoidal regression" pages 54-61, followed by a numerical example y = r*sin(w*x+phi)+(b/x)+c*ln(x), pages 62-63
|
Fit a sinusoidal term to data
The current methods to fit a sin curve to a given data set require a first guess of the parameters, followed by an interative process. This is a non-linear regression problem.
A different method consi
|
8,491
|
Fit a sinusoidal term to data
|
Another option would be the functions sinusoid and mvrm from package BNSP.
data <- data.frame(y, t)
model <- y ~ sinusoid(t, harmonics = 2, amplitude = 1, period = 24)
m1 <- mvrm(formula = model, data = data, sweeps = 10000, burn = 5000, thin = 2, seed = 1, StorageDir = getwd())
plotOptionsM <- list(geom_point(data = data, aes(x = t, y = y)))
plot(x = m1, term = 1, plotOptions = plotOptionsM, intercept = TRUE, quantiles = c(0.025, 0.975), grid = 100)
The argument harmonics specifies the number of sins and cosines to be included. In this case, the model includes 2 pairs of sins and cosines: $\sin(2 \pi t /per)$, $\cos(2\pi t/per)$, and $\sin(4 \pi t per)$, $\cos(4 \pi t/per)$. The argument amplitude defines the model for the amplitude. Here amplitude = 1 signifies that the amplitude is constant over t (which I think is appropriate for this case).
|
Fit a sinusoidal term to data
|
Another option would be the functions sinusoid and mvrm from package BNSP.
data <- data.frame(y, t)
model <- y ~ sinusoid(t, harmonics = 2, amplitude = 1, period = 24)
m1 <- mvrm(formula = model, dat
|
Fit a sinusoidal term to data
Another option would be the functions sinusoid and mvrm from package BNSP.
data <- data.frame(y, t)
model <- y ~ sinusoid(t, harmonics = 2, amplitude = 1, period = 24)
m1 <- mvrm(formula = model, data = data, sweeps = 10000, burn = 5000, thin = 2, seed = 1, StorageDir = getwd())
plotOptionsM <- list(geom_point(data = data, aes(x = t, y = y)))
plot(x = m1, term = 1, plotOptions = plotOptionsM, intercept = TRUE, quantiles = c(0.025, 0.975), grid = 100)
The argument harmonics specifies the number of sins and cosines to be included. In this case, the model includes 2 pairs of sins and cosines: $\sin(2 \pi t /per)$, $\cos(2\pi t/per)$, and $\sin(4 \pi t per)$, $\cos(4 \pi t/per)$. The argument amplitude defines the model for the amplitude. Here amplitude = 1 signifies that the amplitude is constant over t (which I think is appropriate for this case).
|
Fit a sinusoidal term to data
Another option would be the functions sinusoid and mvrm from package BNSP.
data <- data.frame(y, t)
model <- y ~ sinusoid(t, harmonics = 2, amplitude = 1, period = 24)
m1 <- mvrm(formula = model, dat
|
8,492
|
Fit a sinusoidal term to data
|
If you know the lowest and highest point of your cosine-looking data, you can use this simple function to compute all cosine coefficients:
getMyCosine <- function(lowest_point=c(pi,-1), highest_point=c(0,1)){
cosine <- list(
T = pi / abs(highest_point[1] - lowest_point[1]),
b = - highest_point[1],
k = (highest_point[2] + lowest_point[2]) / 2,
A = (highest_point[2] - lowest_point[2]) / 2
)
return(cosine)
}
Below it is used to simulate the variation of temperature throughout the day with a cosine function, by entering the hours and temperature values for the lowest and warmest hour:
c <- getMyCosine(c(4,10),c(17,25))
# lowest temprature at 4:00 (10 degrees), highest at 17:00 (25 degrees)
x = seq(0,23,by=1); y = c$A*cos(c$T*(x +c$b))+c$k ;
library(ggplot2); qplot(x,y,geom="step")
The output is below:
|
Fit a sinusoidal term to data
|
If you know the lowest and highest point of your cosine-looking data, you can use this simple function to compute all cosine coefficients:
getMyCosine <- function(lowest_point=c(pi,-1), highest_point=
|
Fit a sinusoidal term to data
If you know the lowest and highest point of your cosine-looking data, you can use this simple function to compute all cosine coefficients:
getMyCosine <- function(lowest_point=c(pi,-1), highest_point=c(0,1)){
cosine <- list(
T = pi / abs(highest_point[1] - lowest_point[1]),
b = - highest_point[1],
k = (highest_point[2] + lowest_point[2]) / 2,
A = (highest_point[2] - lowest_point[2]) / 2
)
return(cosine)
}
Below it is used to simulate the variation of temperature throughout the day with a cosine function, by entering the hours and temperature values for the lowest and warmest hour:
c <- getMyCosine(c(4,10),c(17,25))
# lowest temprature at 4:00 (10 degrees), highest at 17:00 (25 degrees)
x = seq(0,23,by=1); y = c$A*cos(c$T*(x +c$b))+c$k ;
library(ggplot2); qplot(x,y,geom="step")
The output is below:
|
Fit a sinusoidal term to data
If you know the lowest and highest point of your cosine-looking data, you can use this simple function to compute all cosine coefficients:
getMyCosine <- function(lowest_point=c(pi,-1), highest_point=
|
8,493
|
Fit a sinusoidal term to data
|
Another option is using the generic function optim or nls. I've tried both none of them is completely robust
The following functions takes the data in y and calculates the parameters.
calc.period <- function(y,t)
{
fs <- 1/(t[2]-t[1])
ssp <- spectrum(y,plot=FALSE )
fN <- ssp$freq[which.max(ssp$spec)]
per <- 1/(fN*fs)
return(per)
}
fit.sine<- function(y, t)
{
data <- data.frame(x = as.vector(t), y=as.vector(y))
min.RSS <- function (data, par){
with(data, sum((par[1]*sin(2*pi*par[2]*x + par[3])+par[4]-y )^2))
}
amp = sd(data$y)*2.**0.5
offset = mean(data$y)
fest <- 1/calc.period(y,t)
guess = c( amp, fest, 0, offset)
#res <- optim(par=guess, fn = min.RSS, data=data )
r<-nls(y~offset+A*sin(2*pi*f*t+phi),
start=list(A=amp, f=fest, phi=0, offset=offset))
res <- list(par=as.vector(r$m$getPars()))
return(res)
}
genSine <- function(t, params)
return( params[1]*sin(2*pi*params[2]*t+ params[3])+params[4])
the use is the following:
t <- seq(0, 10, by = 0.01)
A <- 2
f <- 1.5
phase <- 0.2432
offset <- -2
y <- A*sin(2*pi*f*t +phase)+offset + rnorm(length(t), mean=0, sd=0.2)
reslm1 <- fit.sine(y = y, t= t)
The following code compares the data
ysin <- genSine(as.vector(t), params=reslm1$par)
ysin.cor <- genSine(as.vector(t), params=c(A, f, phase, offset))
plot(t, y)
lines(t, ysin, col=2)
lines(t, ysin.cor, col=3)
|
Fit a sinusoidal term to data
|
Another option is using the generic function optim or nls. I've tried both none of them is completely robust
The following functions takes the data in y and calculates the parameters.
calc.period <-
|
Fit a sinusoidal term to data
Another option is using the generic function optim or nls. I've tried both none of them is completely robust
The following functions takes the data in y and calculates the parameters.
calc.period <- function(y,t)
{
fs <- 1/(t[2]-t[1])
ssp <- spectrum(y,plot=FALSE )
fN <- ssp$freq[which.max(ssp$spec)]
per <- 1/(fN*fs)
return(per)
}
fit.sine<- function(y, t)
{
data <- data.frame(x = as.vector(t), y=as.vector(y))
min.RSS <- function (data, par){
with(data, sum((par[1]*sin(2*pi*par[2]*x + par[3])+par[4]-y )^2))
}
amp = sd(data$y)*2.**0.5
offset = mean(data$y)
fest <- 1/calc.period(y,t)
guess = c( amp, fest, 0, offset)
#res <- optim(par=guess, fn = min.RSS, data=data )
r<-nls(y~offset+A*sin(2*pi*f*t+phi),
start=list(A=amp, f=fest, phi=0, offset=offset))
res <- list(par=as.vector(r$m$getPars()))
return(res)
}
genSine <- function(t, params)
return( params[1]*sin(2*pi*params[2]*t+ params[3])+params[4])
the use is the following:
t <- seq(0, 10, by = 0.01)
A <- 2
f <- 1.5
phase <- 0.2432
offset <- -2
y <- A*sin(2*pi*f*t +phase)+offset + rnorm(length(t), mean=0, sd=0.2)
reslm1 <- fit.sine(y = y, t= t)
The following code compares the data
ysin <- genSine(as.vector(t), params=reslm1$par)
ysin.cor <- genSine(as.vector(t), params=c(A, f, phase, offset))
plot(t, y)
lines(t, ysin, col=2)
lines(t, ysin.cor, col=3)
|
Fit a sinusoidal term to data
Another option is using the generic function optim or nls. I've tried both none of them is completely robust
The following functions takes the data in y and calculates the parameters.
calc.period <-
|
8,494
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectations. Why is that?
|
I would like to offer a very simple, intuitive explanation. It amounts to looking at a picture: the rest of this post explains the picture and draws conclusions from it.
Here is what it comes down to: when there is a "probability mass" concentrated near $X=0$, there will be too much probability near $1/X\approx \pm \infty$, causing its expectation to be undefined.
Instead of being fully general, let's focus on random variables $X$ that have continuous densities $f_X$ in a neighborhood of $0$. Suppose $f_X(0)\ne 0$. Visually, these conditions mean the graph of $f$ lies above the axis around $0$:
The continuity of $f_X$ around $0$ implies that for any positive height $p$ less than $f_X(0)$ and sufficiently small $\epsilon$, we may carve out a rectangle beneath this graph which is centered around $x=0$, has width $2\epsilon$, and height $p$, as shown. This corresponds to expressing the original distribution as a mixture of a uniform distribution (with weight $p\times 2\epsilon=2p\epsilon$) and whatever remains.
In other words, we may think of $X$ as arising in the following way:
With probability $2p\epsilon$, draw a value from a Uniform$(-\epsilon,\epsilon)$ distribution.
Otherwise, draw a value from the distribution whose density is proportional to $f_X - p I_{(-\epsilon,\epsilon)}$. (This is the function drawn in yellow at the right.)
($I$ is the indicator function.)
Step $(1)$ shows that for any $0 \lt u \lt \epsilon$, the chance that $X$ is between $0$ and $u$ exceeds $p u / 2$. Equivalently, this is the chance that $1/X$ exceeds $1/u$. To put it another way: writing $S$ for the survivor function of $1/X$
$$S(x) = \Pr(1/X \gt x),$$
the picture shows $S(x) \gt p / (2x)$ for all $x \gt 1/\epsilon$.
We're done now, because this fact about $S$ implies the expectation is undefined. Compare the integrals involved in computing the expectation of the positive part of $1/X$, $(1/X)_{+} = \max(0, 1/X)$:
$$E[(1/X)_{+}] = \int_0^\infty S(x)dx \gt \int_{1/\epsilon}^x S(x)dx \gt \int_{1/\epsilon}^x \frac{p}{2x}dx = \frac{p}{2} \log(x\epsilon).$$
(This is a purely geometric argument: every integral represents an identifiable two-dimensional region and all the inequalities arise from strict inclusions within those regions. Indeed, we don't even need to know the final integral is a logarithm: there are simple geometric arguments showing this integral diverges.)
Since the right side diverges as $x\to\infty$, $E[(1/X)_{+}]$ diverges, too. The situation with the negative part of $1/X$ is the same (because the rectangle is centered around $0$), and the same argument shows the expectation of the negative part of $1/X$ diverges. Consequently the expectation of $1/X$ itself is undefined.
Incidentally, the same argument shows that when $X$ has probability concentrated on one side of $0$, such as any Exponential or Gamma distribution (with shape parameter less than $1$), then still the positive expectation diverges, but the negative expectation is zero. In this case the expectation is defined, but is infinite.
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectat
|
I would like to offer a very simple, intuitive explanation. It amounts to looking at a picture: the rest of this post explains the picture and draws conclusions from it.
Here is what it comes down to:
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectations. Why is that?
I would like to offer a very simple, intuitive explanation. It amounts to looking at a picture: the rest of this post explains the picture and draws conclusions from it.
Here is what it comes down to: when there is a "probability mass" concentrated near $X=0$, there will be too much probability near $1/X\approx \pm \infty$, causing its expectation to be undefined.
Instead of being fully general, let's focus on random variables $X$ that have continuous densities $f_X$ in a neighborhood of $0$. Suppose $f_X(0)\ne 0$. Visually, these conditions mean the graph of $f$ lies above the axis around $0$:
The continuity of $f_X$ around $0$ implies that for any positive height $p$ less than $f_X(0)$ and sufficiently small $\epsilon$, we may carve out a rectangle beneath this graph which is centered around $x=0$, has width $2\epsilon$, and height $p$, as shown. This corresponds to expressing the original distribution as a mixture of a uniform distribution (with weight $p\times 2\epsilon=2p\epsilon$) and whatever remains.
In other words, we may think of $X$ as arising in the following way:
With probability $2p\epsilon$, draw a value from a Uniform$(-\epsilon,\epsilon)$ distribution.
Otherwise, draw a value from the distribution whose density is proportional to $f_X - p I_{(-\epsilon,\epsilon)}$. (This is the function drawn in yellow at the right.)
($I$ is the indicator function.)
Step $(1)$ shows that for any $0 \lt u \lt \epsilon$, the chance that $X$ is between $0$ and $u$ exceeds $p u / 2$. Equivalently, this is the chance that $1/X$ exceeds $1/u$. To put it another way: writing $S$ for the survivor function of $1/X$
$$S(x) = \Pr(1/X \gt x),$$
the picture shows $S(x) \gt p / (2x)$ for all $x \gt 1/\epsilon$.
We're done now, because this fact about $S$ implies the expectation is undefined. Compare the integrals involved in computing the expectation of the positive part of $1/X$, $(1/X)_{+} = \max(0, 1/X)$:
$$E[(1/X)_{+}] = \int_0^\infty S(x)dx \gt \int_{1/\epsilon}^x S(x)dx \gt \int_{1/\epsilon}^x \frac{p}{2x}dx = \frac{p}{2} \log(x\epsilon).$$
(This is a purely geometric argument: every integral represents an identifiable two-dimensional region and all the inequalities arise from strict inclusions within those regions. Indeed, we don't even need to know the final integral is a logarithm: there are simple geometric arguments showing this integral diverges.)
Since the right side diverges as $x\to\infty$, $E[(1/X)_{+}]$ diverges, too. The situation with the negative part of $1/X$ is the same (because the rectangle is centered around $0$), and the same argument shows the expectation of the negative part of $1/X$ diverges. Consequently the expectation of $1/X$ itself is undefined.
Incidentally, the same argument shows that when $X$ has probability concentrated on one side of $0$, such as any Exponential or Gamma distribution (with shape parameter less than $1$), then still the positive expectation diverges, but the negative expectation is zero. In this case the expectation is defined, but is infinite.
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectat
I would like to offer a very simple, intuitive explanation. It amounts to looking at a picture: the rest of this post explains the picture and draws conclusions from it.
Here is what it comes down to:
|
8,495
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectations. Why is that?
|
Ratios and inverses are mostly meaningful with nonnegative random variables, so I will assume $X \ge 0$ almost surely. Then, if $X$ is a discrete variable which take on the value zero with positive probability, we will be dividing with zero with a positive probability, which explains why the expectation of $1/X$ will not exist.
Now look at the continuous distribution case, with $X \ge 0$ a random variable with density function $f(x)$. We will assume that $f(0)>0$ and that $f$ is continuous (at least at zero). Then there is an $\epsilon > 0$ such that $f(x) > \epsilon $ for $0 \le x < \epsilon$. The expected value of $1/X$ is given by
$$
\DeclareMathOperator{\E}{\mathbb{E}}
\E \frac1{X} = \int_0^\infty \frac1{x} f(x)\; dx
$$
Now let us change variable of integration to $u=1/x$, we have $du = -\frac1{x^2} \; dx$, obtaining
$$
\E \frac1{X} = -\int_{\infty}^0 u f(\frac1{u}) (\frac1{u})^2 \; du = \\
\int_0^\infty \frac1{u} f(\frac1{u}) \; du
$$
Now, by assumption $f(u) > \epsilon$ on $[0,\epsilon)$ so $f(\frac1{u}) > 1/\epsilon$ on $(1/\epsilon, \infty)$, using this we have
$$
\E \frac1{X} > \epsilon \int_{1/\epsilon}^\infty \frac1{u}\; du =\infty
$$
showing that the expectation does not exist. An example fulfilling this assumption is the exponential distribution with rate 1.
We have given an answer for inverses, what about ratios? Let $Z=Y/X$ be the ratio of two nonnegative random variables. If they are independent, we can write
$$
\E Z = \E\frac{Y}{X}=\E Y \cdot \E\frac1{x}
$$
so this pretty much reduces to the first case and there is not much new to say. What if they are dependent, with joint density factoring as
$$
f(x,y) = f(x \mid y) g(y)
$$
Then we get (using same substitution as above)
$$
\E \frac{Y}{X} = \int_0^\infty y \int_0^\infty \frac1{x} f(x\mid y) \; dx \;g(y)\; dy = \\
\int_0^\infty y \int_0^\infty \frac1{u} f(\frac1{u}\mid y) \; du \; g(y) \; dy
$$
and we can reason as above on the inner integral. The result will be that if the conditional density (given $y$) is positive and continuous at zero, for a set of $y$'s with positive marginal probability, the expectation will be infinite. I guess it will not be easy to find examples where the marginal expectation of $1/X$ is infinite, but the expectation of the ratio $Y/X$ is finite, unless there is a perfect correlation. It would be nice to see some such examples!
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectat
|
Ratios and inverses are mostly meaningful with nonnegative random variables, so I will assume $X \ge 0$ almost surely. Then, if $X$ is a discrete variable which take on the value zero with positive p
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectations. Why is that?
Ratios and inverses are mostly meaningful with nonnegative random variables, so I will assume $X \ge 0$ almost surely. Then, if $X$ is a discrete variable which take on the value zero with positive probability, we will be dividing with zero with a positive probability, which explains why the expectation of $1/X$ will not exist.
Now look at the continuous distribution case, with $X \ge 0$ a random variable with density function $f(x)$. We will assume that $f(0)>0$ and that $f$ is continuous (at least at zero). Then there is an $\epsilon > 0$ such that $f(x) > \epsilon $ for $0 \le x < \epsilon$. The expected value of $1/X$ is given by
$$
\DeclareMathOperator{\E}{\mathbb{E}}
\E \frac1{X} = \int_0^\infty \frac1{x} f(x)\; dx
$$
Now let us change variable of integration to $u=1/x$, we have $du = -\frac1{x^2} \; dx$, obtaining
$$
\E \frac1{X} = -\int_{\infty}^0 u f(\frac1{u}) (\frac1{u})^2 \; du = \\
\int_0^\infty \frac1{u} f(\frac1{u}) \; du
$$
Now, by assumption $f(u) > \epsilon$ on $[0,\epsilon)$ so $f(\frac1{u}) > 1/\epsilon$ on $(1/\epsilon, \infty)$, using this we have
$$
\E \frac1{X} > \epsilon \int_{1/\epsilon}^\infty \frac1{u}\; du =\infty
$$
showing that the expectation does not exist. An example fulfilling this assumption is the exponential distribution with rate 1.
We have given an answer for inverses, what about ratios? Let $Z=Y/X$ be the ratio of two nonnegative random variables. If they are independent, we can write
$$
\E Z = \E\frac{Y}{X}=\E Y \cdot \E\frac1{x}
$$
so this pretty much reduces to the first case and there is not much new to say. What if they are dependent, with joint density factoring as
$$
f(x,y) = f(x \mid y) g(y)
$$
Then we get (using same substitution as above)
$$
\E \frac{Y}{X} = \int_0^\infty y \int_0^\infty \frac1{x} f(x\mid y) \; dx \;g(y)\; dy = \\
\int_0^\infty y \int_0^\infty \frac1{u} f(\frac1{u}\mid y) \; du \; g(y) \; dy
$$
and we can reason as above on the inner integral. The result will be that if the conditional density (given $y$) is positive and continuous at zero, for a set of $y$'s with positive marginal probability, the expectation will be infinite. I guess it will not be easy to find examples where the marginal expectation of $1/X$ is infinite, but the expectation of the ratio $Y/X$ is finite, unless there is a perfect correlation. It would be nice to see some such examples!
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectat
Ratios and inverses are mostly meaningful with nonnegative random variables, so I will assume $X \ge 0$ almost surely. Then, if $X$ is a discrete variable which take on the value zero with positive p
|
8,496
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectations. Why is that?
|
Let's offer a "dissenting" view:
Ratios and inverses of random variables can be fine in the following sense:
It may be the case that in many cases they do not possess moments
But it is also the case that in many cases they result in recognizable, "named" and exhaustively studied distributions.
...and there is distribution-life beyond moments, like probabilities and quantiles
EXAMPLES for RATIOS
Student's t-distribution is the ratio of a Normal and a Chi distribution
F-distribution is the ratio of two Chi-squares
Ratio of two Normals is Cauchy
Ratio of two Exponentials is Lomax (shifted Pareto)
etc
On the contrary, it is products of random variables that appear to not lead to recognizable distributions that often.
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectat
|
Let's offer a "dissenting" view:
Ratios and inverses of random variables can be fine in the following sense:
It may be the case that in many cases they do not possess moments
But it is also the case
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectations. Why is that?
Let's offer a "dissenting" view:
Ratios and inverses of random variables can be fine in the following sense:
It may be the case that in many cases they do not possess moments
But it is also the case that in many cases they result in recognizable, "named" and exhaustively studied distributions.
...and there is distribution-life beyond moments, like probabilities and quantiles
EXAMPLES for RATIOS
Student's t-distribution is the ratio of a Normal and a Chi distribution
F-distribution is the ratio of two Chi-squares
Ratio of two Normals is Cauchy
Ratio of two Exponentials is Lomax (shifted Pareto)
etc
On the contrary, it is products of random variables that appear to not lead to recognizable distributions that often.
|
I've heard that ratios or inverses of random variables often are problematic, in not having expectat
Let's offer a "dissenting" view:
Ratios and inverses of random variables can be fine in the following sense:
It may be the case that in many cases they do not possess moments
But it is also the case
|
8,497
|
From uniform distribution to exponential distribution and vice-versa
|
It is not the case that exponentiating a uniform random variable gives an exponential, nor does taking the log of an exponential random variable yield a uniform.
Let $U$ be uniform on $(0,1)$ and let $X=\exp(U)$.
$F_X(x) = P(X \leq x) = P(\exp(U)\leq x) = P(U\leq \ln x) = \ln x\,,\quad 1<x<e$
So $f_x(x) = \frac{d}{dx} \ln x = \frac{1}{x}\,,\quad 1<x<e$.
This is not an exponential variate. A similar calculation shows that the log of an exponential is not uniform.
Let $Y$ be standard exponential, so $F_Y(y)=P(Y\leq y) = 1-e^{-y}\,,\quad y>0$.
Let $V=\ln Y$. Then $F_V(v) = P(V\leq v) = P(\ln Y\leq v) = P(Y\leq e^v) = 1-e^{-e^v}\,,\quad v<0$.
This is not a uniform. (Indeed $-V$ is a Gumbel-distributed random variable, so you might call the distribution of $V$ a 'flipped Gumbel'.)
However, in each case we can see it more quickly by simply considering the bounds on random variables. If $U$ is uniform(0,1) it lies between 0 and 1 so $X=\exp(U)$ lies between $1$ and $e$ ... so it's not exponential. Similarly, for $Y$ exponential, $\ln Y$ is on $(-\infty,\infty)$, so that can't be uniform(0,1), nor indeed any other uniform.
We could also simulate, and again see it right away:
First, exponentiating a uniform --
[the blue curve is the density (1/x on the indicated interval) we worked out above...]
Second, the log of a exponential:
Which we can see is far from uniform! (If we differentiate the cdf we worked out before, which would give the density, it matches the shape we see here.)
Indeed the inverse cdf method indicates that taking the negative of the log of a uniform(0,1) variate gives a standard exponential variate, and conversely, exponentiating the negative of a standard exponential gives a uniform. [Also see probability integral transform]
This method tells us that if $U=F_Y(Y)$, $Y = F^{-1}(U)$. If we apply the inverse of the cdf as a transformation on $U$, a standard uniform, the resulting random variable has distribution function $F_Y$.
If we let $U$ be uniform(0,1), then $P(U\leq u) = u$. Let $Y=-\ln (1-U)$. (Note that $1-U$ is also uniform on (0,1) so you could actually let $Y=-\ln U$, but we're following the inverse cdf method in full here)
Then $P(Y\leq y) = P(-\ln (1-U) \leq y) = P( 1-U \geq e^{-y}) = P( U \leq 1-e^{-y}) = 1-e^{-y}$, which is the cdf of a standard exponential.
[This property of the inverse cdf transform is why the $\log$ transform is actually required to obtain an exponential distribution, and the probability integral transform is why exponentiating the negative of a negative exponential gets back to a uniform.]
|
From uniform distribution to exponential distribution and vice-versa
|
It is not the case that exponentiating a uniform random variable gives an exponential, nor does taking the log of an exponential random variable yield a uniform.
Let $U$ be uniform on $(0,1)$ and let
|
From uniform distribution to exponential distribution and vice-versa
It is not the case that exponentiating a uniform random variable gives an exponential, nor does taking the log of an exponential random variable yield a uniform.
Let $U$ be uniform on $(0,1)$ and let $X=\exp(U)$.
$F_X(x) = P(X \leq x) = P(\exp(U)\leq x) = P(U\leq \ln x) = \ln x\,,\quad 1<x<e$
So $f_x(x) = \frac{d}{dx} \ln x = \frac{1}{x}\,,\quad 1<x<e$.
This is not an exponential variate. A similar calculation shows that the log of an exponential is not uniform.
Let $Y$ be standard exponential, so $F_Y(y)=P(Y\leq y) = 1-e^{-y}\,,\quad y>0$.
Let $V=\ln Y$. Then $F_V(v) = P(V\leq v) = P(\ln Y\leq v) = P(Y\leq e^v) = 1-e^{-e^v}\,,\quad v<0$.
This is not a uniform. (Indeed $-V$ is a Gumbel-distributed random variable, so you might call the distribution of $V$ a 'flipped Gumbel'.)
However, in each case we can see it more quickly by simply considering the bounds on random variables. If $U$ is uniform(0,1) it lies between 0 and 1 so $X=\exp(U)$ lies between $1$ and $e$ ... so it's not exponential. Similarly, for $Y$ exponential, $\ln Y$ is on $(-\infty,\infty)$, so that can't be uniform(0,1), nor indeed any other uniform.
We could also simulate, and again see it right away:
First, exponentiating a uniform --
[the blue curve is the density (1/x on the indicated interval) we worked out above...]
Second, the log of a exponential:
Which we can see is far from uniform! (If we differentiate the cdf we worked out before, which would give the density, it matches the shape we see here.)
Indeed the inverse cdf method indicates that taking the negative of the log of a uniform(0,1) variate gives a standard exponential variate, and conversely, exponentiating the negative of a standard exponential gives a uniform. [Also see probability integral transform]
This method tells us that if $U=F_Y(Y)$, $Y = F^{-1}(U)$. If we apply the inverse of the cdf as a transformation on $U$, a standard uniform, the resulting random variable has distribution function $F_Y$.
If we let $U$ be uniform(0,1), then $P(U\leq u) = u$. Let $Y=-\ln (1-U)$. (Note that $1-U$ is also uniform on (0,1) so you could actually let $Y=-\ln U$, but we're following the inverse cdf method in full here)
Then $P(Y\leq y) = P(-\ln (1-U) \leq y) = P( 1-U \geq e^{-y}) = P( U \leq 1-e^{-y}) = 1-e^{-y}$, which is the cdf of a standard exponential.
[This property of the inverse cdf transform is why the $\log$ transform is actually required to obtain an exponential distribution, and the probability integral transform is why exponentiating the negative of a negative exponential gets back to a uniform.]
|
From uniform distribution to exponential distribution and vice-versa
It is not the case that exponentiating a uniform random variable gives an exponential, nor does taking the log of an exponential random variable yield a uniform.
Let $U$ be uniform on $(0,1)$ and let
|
8,498
|
From uniform distribution to exponential distribution and vice-versa
|
You almost have it back to front. You asked:
"If $X$ has a uniform distribution, does it mean that $e^X$ follows an exponential distribution?"
"Similarly, if $Y$ follows an exponential distribution, does it mean $\ln(Y)$ follows a uniform distribution?"
In fact
if $X$ is uniform on $[0,1]$ then $-\log_e(X)$ follows an exponential distribution with parameter $1$
if $Y$ follows an exponential distribution with parameter $1$ then $e^{-Y}$ has a uniform distribution on $[0,1]$.
More generally you could say:
if $X$ is uniform on $[a,b]$ then $-\frac1k \log_e\left(\frac{X-a}{b-a}\right)$ follows an exponential distribution with rate parameter $k$
if $Y$ follows an exponential distribution with rate parameter $k$ then $e^{-kY}$ has a uniform distribution on $[0,1]$ while $a+(b-a)e^{-kY}$ has a uniform distribution on $[a,b]$
|
From uniform distribution to exponential distribution and vice-versa
|
You almost have it back to front. You asked:
"If $X$ has a uniform distribution, does it mean that $e^X$ follows an exponential distribution?"
"Similarly, if $Y$ follows an exponential distribution
|
From uniform distribution to exponential distribution and vice-versa
You almost have it back to front. You asked:
"If $X$ has a uniform distribution, does it mean that $e^X$ follows an exponential distribution?"
"Similarly, if $Y$ follows an exponential distribution, does it mean $\ln(Y)$ follows a uniform distribution?"
In fact
if $X$ is uniform on $[0,1]$ then $-\log_e(X)$ follows an exponential distribution with parameter $1$
if $Y$ follows an exponential distribution with parameter $1$ then $e^{-Y}$ has a uniform distribution on $[0,1]$.
More generally you could say:
if $X$ is uniform on $[a,b]$ then $-\frac1k \log_e\left(\frac{X-a}{b-a}\right)$ follows an exponential distribution with rate parameter $k$
if $Y$ follows an exponential distribution with rate parameter $k$ then $e^{-kY}$ has a uniform distribution on $[0,1]$ while $a+(b-a)e^{-kY}$ has a uniform distribution on $[a,b]$
|
From uniform distribution to exponential distribution and vice-versa
You almost have it back to front. You asked:
"If $X$ has a uniform distribution, does it mean that $e^X$ follows an exponential distribution?"
"Similarly, if $Y$ follows an exponential distribution
|
8,499
|
From uniform distribution to exponential distribution and vice-versa
|
Inspired by @Henry's fantastic answer:
If $X \sim \operatorname{Exp}(8), U \sim \operatorname{Unif}(0, 1)$
Then we know CDF of X is $F_X(x) = 1 - e^{-8x}$
Set $1 - e^{-8x} = u$, solve for $x$, we got $x = \frac{\ln(1-u)}{-8}$
Therefore, $X = \frac{\ln(1-U)}{-8} \sim \operatorname{Exp}(8)$
Since $1-U \sim \operatorname{Unif}(0,1)$ as well,
$X = \frac{\ln U}{-8} \sim \operatorname{Exp}(8)$ is also true.
|
From uniform distribution to exponential distribution and vice-versa
|
Inspired by @Henry's fantastic answer:
If $X \sim \operatorname{Exp}(8), U \sim \operatorname{Unif}(0, 1)$
Then we know CDF of X is $F_X(x) = 1 - e^{-8x}$
Set $1 - e^{-8x} = u$, solve for $x$, we got
|
From uniform distribution to exponential distribution and vice-versa
Inspired by @Henry's fantastic answer:
If $X \sim \operatorname{Exp}(8), U \sim \operatorname{Unif}(0, 1)$
Then we know CDF of X is $F_X(x) = 1 - e^{-8x}$
Set $1 - e^{-8x} = u$, solve for $x$, we got $x = \frac{\ln(1-u)}{-8}$
Therefore, $X = \frac{\ln(1-U)}{-8} \sim \operatorname{Exp}(8)$
Since $1-U \sim \operatorname{Unif}(0,1)$ as well,
$X = \frac{\ln U}{-8} \sim \operatorname{Exp}(8)$ is also true.
|
From uniform distribution to exponential distribution and vice-versa
Inspired by @Henry's fantastic answer:
If $X \sim \operatorname{Exp}(8), U \sim \operatorname{Unif}(0, 1)$
Then we know CDF of X is $F_X(x) = 1 - e^{-8x}$
Set $1 - e^{-8x} = u$, solve for $x$, we got
|
8,500
|
Why will ridge regression not shrink some coefficients to zero like lasso?
|
This is regarding the variance
OLS provides what is called the Best Linear Unbiased Estimator (BLUE). That means that if you take any other unbiased estimator, it is bound to have a higher variance then the OLS solution. So why on earth should we consider anything else than that?
Now the trick with regularization, such as the lasso or ridge, is to add some bias in turn to try to reduce the variance. Because when you estimate your prediction error, it is a combination of three things:
$$
\text{E}[(y-\hat{f}(x))^2]=\text{Bias}[\hat{f}(x))]^2
+\text{Var}[\hat{f}(x))]+\sigma^2
$$
The last part is the irreducible error, so we have no control over that. Using the OLS solution the bias term is zero. But it might be that the second term is large. It might be a good idea, (if we want good predictions), to add in some bias and hopefully reduce the variance.
So what is this $\text{Var}[\hat{f}(x))]$? It is the variance introduced in the estimates for the parameters in your model. The linear model has the form
$$
\mathbf{y}=\mathbf{X}\beta + \epsilon,\qquad \epsilon\sim\mathcal{N}(0,\sigma^2I)
$$
To obtain the OLS solution we solve the minimization problem
$$
\arg \min_\beta ||\mathbf{y}-\mathbf{X}\beta||^2
$$
This provides the solution
$$
\hat{\beta}_{\text{OLS}} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y}
$$
The minimization problem for ridge regression is similar:
$$
\arg \min_\beta ||\mathbf{y}-\mathbf{X}\beta||^2+\lambda||\beta||^2\qquad \lambda>0
$$
Now the solution becomes
$$
\hat{\beta}_{\text{Ridge}} = (\mathbf{X}^T\mathbf{X}+\lambda I)^{-1}\mathbf{X}^T\mathbf{y}
$$
So we are adding this $\lambda I$ (called the ridge) on the diagonal of the matrix that we invert. The effect this has on the matrix $\mathbf{X}^T\mathbf{X}$ is that it "pulls" the determinant of the matrix away from zero. Thus when you invert it, you do not get huge eigenvalues. But that leads to another interesting fact, namely that the variance of the parameter estimates becomes lower.
I am not sure if I can provide a more clear answer then this. What this all boils down to is the covariance matrix for the parameters in the model and the magnitude of the values in that covariance matrix.
I took ridge regression as an example, because that is much easier to treat. The lasso is much harder and there is still active ongoing research on that topic.
These slides provide some more information and this blog also has some relevant information.
EDIT: What do I mean that by adding the ridge the determinant is "pulled" away from zero?
Note that the matrix $\mathbf{X}^T\mathbf{X}$ is a positive definite symmetric matrix. Note that all symmetric matrices with real values have real eigenvalues. Also since it is positive definite, the eigenvalues are all greater than zero.
Ok so how do we calculate the eigenvalues? We solve the characteristic equation:
$$
\text{det}(\mathbf{X}^T\mathbf{X}-tI)=0
$$
This is a polynomial in $t$, and as stated above, the eigenvalues are real and positive. Now let's take a look at the equation for the ridge matrix we need to invert:
$$
\text{det}(\mathbf{X}^T\mathbf{X}+\lambda I-tI)=0
$$
We can change this a little bit and see:
$$
\text{det}(\mathbf{X}^T\mathbf{X}-(t-\lambda)I)=0
$$
So we can solve this for $(t-\lambda)$ and get the same eigenvalues as for the first problem. Let's assume that one eigenvalue is $t_i$. So the eigenvalue for the ridge problem becomes $t_i+\lambda$. It gets shifted by $\lambda$. This happens to all the eigenvalues, so they all move away from zero.
Here is some R code to illustrate this:
# Create random matrix
A <- matrix(sample(10,9,T),nrow=3,ncol=3)
# Make a symmetric matrix
B <- A+t(A)
# Calculate eigenvalues
eigen(B)
# Calculate eigenvalues of B with ridge
eigen(B+3*diag(3))
Which gives the results:
> eigen(B)
$values
[1] 37.368634 6.952718 -8.321352
> eigen(B+3*diag(3))
$values
[1] 40.368634 9.952718 -5.321352
So all the eigenvalues get shifted up by exactly 3.
You can also prove this in general by using the Gershgorin circle theorem. There the centers of the circles containing the eigenvalues are the diagonal elements. You can always add "enough" to the diagonal element to make all the circles in the positive real half-plane. That result is more general and not needed for this.
|
Why will ridge regression not shrink some coefficients to zero like lasso?
|
This is regarding the variance
OLS provides what is called the Best Linear Unbiased Estimator (BLUE). That means that if you take any other unbiased estimator, it is bound to have a higher variance th
|
Why will ridge regression not shrink some coefficients to zero like lasso?
This is regarding the variance
OLS provides what is called the Best Linear Unbiased Estimator (BLUE). That means that if you take any other unbiased estimator, it is bound to have a higher variance then the OLS solution. So why on earth should we consider anything else than that?
Now the trick with regularization, such as the lasso or ridge, is to add some bias in turn to try to reduce the variance. Because when you estimate your prediction error, it is a combination of three things:
$$
\text{E}[(y-\hat{f}(x))^2]=\text{Bias}[\hat{f}(x))]^2
+\text{Var}[\hat{f}(x))]+\sigma^2
$$
The last part is the irreducible error, so we have no control over that. Using the OLS solution the bias term is zero. But it might be that the second term is large. It might be a good idea, (if we want good predictions), to add in some bias and hopefully reduce the variance.
So what is this $\text{Var}[\hat{f}(x))]$? It is the variance introduced in the estimates for the parameters in your model. The linear model has the form
$$
\mathbf{y}=\mathbf{X}\beta + \epsilon,\qquad \epsilon\sim\mathcal{N}(0,\sigma^2I)
$$
To obtain the OLS solution we solve the minimization problem
$$
\arg \min_\beta ||\mathbf{y}-\mathbf{X}\beta||^2
$$
This provides the solution
$$
\hat{\beta}_{\text{OLS}} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y}
$$
The minimization problem for ridge regression is similar:
$$
\arg \min_\beta ||\mathbf{y}-\mathbf{X}\beta||^2+\lambda||\beta||^2\qquad \lambda>0
$$
Now the solution becomes
$$
\hat{\beta}_{\text{Ridge}} = (\mathbf{X}^T\mathbf{X}+\lambda I)^{-1}\mathbf{X}^T\mathbf{y}
$$
So we are adding this $\lambda I$ (called the ridge) on the diagonal of the matrix that we invert. The effect this has on the matrix $\mathbf{X}^T\mathbf{X}$ is that it "pulls" the determinant of the matrix away from zero. Thus when you invert it, you do not get huge eigenvalues. But that leads to another interesting fact, namely that the variance of the parameter estimates becomes lower.
I am not sure if I can provide a more clear answer then this. What this all boils down to is the covariance matrix for the parameters in the model and the magnitude of the values in that covariance matrix.
I took ridge regression as an example, because that is much easier to treat. The lasso is much harder and there is still active ongoing research on that topic.
These slides provide some more information and this blog also has some relevant information.
EDIT: What do I mean that by adding the ridge the determinant is "pulled" away from zero?
Note that the matrix $\mathbf{X}^T\mathbf{X}$ is a positive definite symmetric matrix. Note that all symmetric matrices with real values have real eigenvalues. Also since it is positive definite, the eigenvalues are all greater than zero.
Ok so how do we calculate the eigenvalues? We solve the characteristic equation:
$$
\text{det}(\mathbf{X}^T\mathbf{X}-tI)=0
$$
This is a polynomial in $t$, and as stated above, the eigenvalues are real and positive. Now let's take a look at the equation for the ridge matrix we need to invert:
$$
\text{det}(\mathbf{X}^T\mathbf{X}+\lambda I-tI)=0
$$
We can change this a little bit and see:
$$
\text{det}(\mathbf{X}^T\mathbf{X}-(t-\lambda)I)=0
$$
So we can solve this for $(t-\lambda)$ and get the same eigenvalues as for the first problem. Let's assume that one eigenvalue is $t_i$. So the eigenvalue for the ridge problem becomes $t_i+\lambda$. It gets shifted by $\lambda$. This happens to all the eigenvalues, so they all move away from zero.
Here is some R code to illustrate this:
# Create random matrix
A <- matrix(sample(10,9,T),nrow=3,ncol=3)
# Make a symmetric matrix
B <- A+t(A)
# Calculate eigenvalues
eigen(B)
# Calculate eigenvalues of B with ridge
eigen(B+3*diag(3))
Which gives the results:
> eigen(B)
$values
[1] 37.368634 6.952718 -8.321352
> eigen(B+3*diag(3))
$values
[1] 40.368634 9.952718 -5.321352
So all the eigenvalues get shifted up by exactly 3.
You can also prove this in general by using the Gershgorin circle theorem. There the centers of the circles containing the eigenvalues are the diagonal elements. You can always add "enough" to the diagonal element to make all the circles in the positive real half-plane. That result is more general and not needed for this.
|
Why will ridge regression not shrink some coefficients to zero like lasso?
This is regarding the variance
OLS provides what is called the Best Linear Unbiased Estimator (BLUE). That means that if you take any other unbiased estimator, it is bound to have a higher variance th
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.