idx int64 1 56k | question stringlengths 15 155 | answer stringlengths 2 29.2k ⌀ | question_cut stringlengths 15 100 | answer_cut stringlengths 2 200 ⌀ | conversation stringlengths 47 29.3k | conversation_cut stringlengths 47 301 |
|---|---|---|---|---|---|---|
25,301 | Is there any difference between Sensitivity and Recall? | It is not uncommon that statistical tools have different origins and names, but same meaning.
The name sensitivity comes from the statistics domain as a measure for the performance of a binary calssification, while recall is more related to the Information Engineering domain. | Is there any difference between Sensitivity and Recall? | It is not uncommon that statistical tools have different origins and names, but same meaning.
The name sensitivity comes from the statistics domain as a measure for the performance of a binary calssi | Is there any difference between Sensitivity and Recall?
It is not uncommon that statistical tools have different origins and names, but same meaning.
The name sensitivity comes from the statistics domain as a measure for the performance of a binary calssification, while recall is more related to the Information Engineering domain. | Is there any difference between Sensitivity and Recall?
It is not uncommon that statistical tools have different origins and names, but same meaning.
The name sensitivity comes from the statistics domain as a measure for the performance of a binary calssi |
25,302 | What is the point of having a dense layer in a neural network with no activation function? | One such scenario is the output layer of a network performing regression, which should be naturally linear. This tutorial demonstrates this case.
Another case that comes to my mind are deep linear networks which are often being used in neural networks literature as a toy model for studying some phenomena that would be too complex with usual non-linear networks. | What is the point of having a dense layer in a neural network with no activation function? | One such scenario is the output layer of a network performing regression, which should be naturally linear. This tutorial demonstrates this case.
Another case that comes to my mind are deep linear net | What is the point of having a dense layer in a neural network with no activation function?
One such scenario is the output layer of a network performing regression, which should be naturally linear. This tutorial demonstrates this case.
Another case that comes to my mind are deep linear networks which are often being used in neural networks literature as a toy model for studying some phenomena that would be too complex with usual non-linear networks. | What is the point of having a dense layer in a neural network with no activation function?
One such scenario is the output layer of a network performing regression, which should be naturally linear. This tutorial demonstrates this case.
Another case that comes to my mind are deep linear net |
25,303 | What is the point of having a dense layer in a neural network with no activation function? | Another purpose of using linear layers is to reduce dimensionality (and the number of parameters). For example the Skip-gram and CBOW model for word embeddings.
The training task is to predict context words of a given word $p(w_o|w_i)$. A naive way is to count the occurrences of context words for each word and put them in a matrix $M$, then the probability is just $p(w_o|w_i) = f(M_{w_i})_{w_o}$, where $f$ is a normalization function.
The problems is often the number of words $n$ is huge and we can't afford an $n$ by $n$ matrix. So we can first use an $n$ by $d$ matrix $A$ to reduce the dimension (to say 128) and use another $d$ by $n$ matrix $B$ to turn it back, then number of parameters can be reduced to $2*d*n$. It's kind of like matrix decomposition in the sense that we use $BA$ to approximate $M$.
The model can be implemented as two linear layers followed by a normalization function and can be trained using the cross-entropy loss $E[y_n\log f(BAw_i)]$, where for the Skip-gram model, $w_i$ is a one-hot vector, for the CBOW model, $w_i$ is a BOW vector. | What is the point of having a dense layer in a neural network with no activation function? | Another purpose of using linear layers is to reduce dimensionality (and the number of parameters). For example the Skip-gram and CBOW model for word embeddings.
The training task is to predict contex | What is the point of having a dense layer in a neural network with no activation function?
Another purpose of using linear layers is to reduce dimensionality (and the number of parameters). For example the Skip-gram and CBOW model for word embeddings.
The training task is to predict context words of a given word $p(w_o|w_i)$. A naive way is to count the occurrences of context words for each word and put them in a matrix $M$, then the probability is just $p(w_o|w_i) = f(M_{w_i})_{w_o}$, where $f$ is a normalization function.
The problems is often the number of words $n$ is huge and we can't afford an $n$ by $n$ matrix. So we can first use an $n$ by $d$ matrix $A$ to reduce the dimension (to say 128) and use another $d$ by $n$ matrix $B$ to turn it back, then number of parameters can be reduced to $2*d*n$. It's kind of like matrix decomposition in the sense that we use $BA$ to approximate $M$.
The model can be implemented as two linear layers followed by a normalization function and can be trained using the cross-entropy loss $E[y_n\log f(BAw_i)]$, where for the Skip-gram model, $w_i$ is a one-hot vector, for the CBOW model, $w_i$ is a BOW vector. | What is the point of having a dense layer in a neural network with no activation function?
Another purpose of using linear layers is to reduce dimensionality (and the number of parameters). For example the Skip-gram and CBOW model for word embeddings.
The training task is to predict contex |
25,304 | What is the point of having a dense layer in a neural network with no activation function? | Suppose you have a network for either a binary classification task. One way to implement this is using a final activation that yields predicted probabilities (non-negative, sum to 1). An inverse logistic function $f(x)=\frac{1}{1+\exp(-x)}$ is one way to do this in the binary case.
Using the standard binary cross-entropy loss $\mathcal{L}=-\sum_i y_i \log(\hat{y}_i)+(1-y_i)\log(1-\hat{y}_i)$ means that we're round-tripping exponential functions and logarithmic functions. This can cause a severe loss of precision due to accumulated numerical error.
On the other hand, working on the scale of $x$ instead of the probability scale eliminates the round-tripping. In other words, using an identity function the final layer, and a loss function that works on the scale of the linear predictor, achieves the same model without loss of precision.
We can extend the same reasoning to the case of a $k$-nary classification task with a softmax activation.
See: Numerical computation of cross entropy in practice | What is the point of having a dense layer in a neural network with no activation function? | Suppose you have a network for either a binary classification task. One way to implement this is using a final activation that yields predicted probabilities (non-negative, sum to 1). An inverse logis | What is the point of having a dense layer in a neural network with no activation function?
Suppose you have a network for either a binary classification task. One way to implement this is using a final activation that yields predicted probabilities (non-negative, sum to 1). An inverse logistic function $f(x)=\frac{1}{1+\exp(-x)}$ is one way to do this in the binary case.
Using the standard binary cross-entropy loss $\mathcal{L}=-\sum_i y_i \log(\hat{y}_i)+(1-y_i)\log(1-\hat{y}_i)$ means that we're round-tripping exponential functions and logarithmic functions. This can cause a severe loss of precision due to accumulated numerical error.
On the other hand, working on the scale of $x$ instead of the probability scale eliminates the round-tripping. In other words, using an identity function the final layer, and a loss function that works on the scale of the linear predictor, achieves the same model without loss of precision.
We can extend the same reasoning to the case of a $k$-nary classification task with a softmax activation.
See: Numerical computation of cross entropy in practice | What is the point of having a dense layer in a neural network with no activation function?
Suppose you have a network for either a binary classification task. One way to implement this is using a final activation that yields predicted probabilities (non-negative, sum to 1). An inverse logis |
25,305 | What is the point of having a dense layer in a neural network with no activation function? | If you choose to use activation=None, you for example add a BatchNormalization layer before you actually use the activation. This is used often in convolutional neural networks, but is good for dense neural networks as well.
z = tf.keras.layers.Dense(20, activation=None)(z)
z = tf.keras.layers.BatchNormalization()(z)
z = tf.keras.layers.Activation("relu")(z) | What is the point of having a dense layer in a neural network with no activation function? | If you choose to use activation=None, you for example add a BatchNormalization layer before you actually use the activation. This is used often in convolutional neural networks, but is good for dense | What is the point of having a dense layer in a neural network with no activation function?
If you choose to use activation=None, you for example add a BatchNormalization layer before you actually use the activation. This is used often in convolutional neural networks, but is good for dense neural networks as well.
z = tf.keras.layers.Dense(20, activation=None)(z)
z = tf.keras.layers.BatchNormalization()(z)
z = tf.keras.layers.Activation("relu")(z) | What is the point of having a dense layer in a neural network with no activation function?
If you choose to use activation=None, you for example add a BatchNormalization layer before you actually use the activation. This is used often in convolutional neural networks, but is good for dense |
25,306 | What is the point of having a dense layer in a neural network with no activation function? | You always want the most flexibility that is possible out of the library that you are using. For example, if you want to have a deep NN with skipped connections ( see this paper ) you need to apply your activation function after the operation F(x) + x is done. how can you implement that on a dense layer with the output F(x) that has no option to stop it from applying activation function before you can do the summation? | What is the point of having a dense layer in a neural network with no activation function? | You always want the most flexibility that is possible out of the library that you are using. For example, if you want to have a deep NN with skipped connections ( see this paper ) you need to apply yo | What is the point of having a dense layer in a neural network with no activation function?
You always want the most flexibility that is possible out of the library that you are using. For example, if you want to have a deep NN with skipped connections ( see this paper ) you need to apply your activation function after the operation F(x) + x is done. how can you implement that on a dense layer with the output F(x) that has no option to stop it from applying activation function before you can do the summation? | What is the point of having a dense layer in a neural network with no activation function?
You always want the most flexibility that is possible out of the library that you are using. For example, if you want to have a deep NN with skipped connections ( see this paper ) you need to apply yo |
25,307 | Expectation of square root of sum of independent squared uniform random variables | One approach is to first calculate the moment generating function (mgf) of $Y_n$ defined by $Y_n = U_1^2 + \dotsm + U_n^2$ where the $U_i, i=1,\dotsc, n$ is independent and identically distributed standard uniform random variables.
When we have that, we can see that
$$ \DeclareMathOperator{\E}{\mathbb{E}}
\E \sqrt{Y_n}
$$
is the fractional moment of $Y_n$ of order $\alpha=1/2$. Then we can use results from the paper Noel Cressie and Marinus Borkent: "The Moment Generating Function has its Moments", Journal of Statistical Planning and Inference 13 (1986) 337-344, which gives fractional moments via fractional differentiation of the moment generating function.
First the moment generating function of $U_1^2$, which we write $M_1(t)$.
$$
M_1(t) = \E e^{t U_1^2} = \int_0^1 \frac{e^{tx}}{2\sqrt{x}}\; dx
$$
and I evaluated that (with help of Maple and Wolphram Alpha) to give
$$ \DeclareMathOperator{\erf}{erf}
M_1(t)= \frac{\erf(\sqrt{-t})\sqrt{\pi}}{2\sqrt{-t}}
$$ where $i=\sqrt{-1}$ is the imaginary unit.
(Wolphram Alpha gives a similar answer, but in terms of the Dawson integral.) It turns out we will mostly need the case for $t<0$. Now it is easy to find the mgf of $Y_n$:
$$
M_n(t) = M_1(t)^n
$$
Then for the results from the cited paper. For $\mu>0$ they define the $\mu$th order integral of the function $f$ as
$$
I^\mu f(t) \equiv \Gamma(\mu)^{-1} \int_{-\infty}^t (t-z)^{\mu-1} f(z)\; dz
$$
Then, for $\alpha>0$ and nonintegral, $n$ a positive integer, and $0<\lambda<1$ such that $\alpha=n-\lambda$. Then the derivative of $f$ of order $\alpha$ is defined as
$$
D^\alpha f(t) \equiv \Gamma(\lambda)^{-1}\int_{-\infty}^t (t-z)^{\lambda-1} \frac{d^n f(z)}{d z^n}\; dz.
$$
Then they state (and prove) the following result, for a positive random variable $X$: Suppose $M_X$ (mgf) is defined. Then, for $\alpha>0$,
$$
D^\alpha M_X(0) = \E X^\alpha < \infty
$$
Now we can try to apply these results to $Y_n$. With $\alpha=1/2$ we find
$$
\E Y_n^{1/2} = D^{1/2} M_n (0) = \Gamma(1/2)^{-1}\int_{-\infty}^0 |z|^{-1/2} M_n'(z) \; dz
$$
where the prime denotes the derivative. Maple gives the following solution:
$$
\int_{-\infty}^0 \frac{n\cdot\left(\erf(\sqrt{-z})\sqrt{\pi}-2e^z\sqrt{-z} \right)e^{\frac{n(-2\ln 2 +2 \ln(\erf(\sqrt{-z}))-\ln(-z) +\ln(\pi))}{2}}}{2\pi(-z)^{3/2}\erf(\sqrt{-z})} \; dz
$$
I will show a plot of this expectation, made in maple using numerical integration, together with the approximate solution $A(n)=\sqrt{n/3-1/15}$ from some comment (and discussed in the answer by @Henry). They are remarkably close:
As a complement, a plot of the percentage error:
Above about $n=20$ the approximation is close to exact. Below the maple code used:
int( exp(t*x)/(2*sqrt(x)), x=0..1 ) assuming t>0;
int( exp(t*x)/(2*sqrt(x)), x=0..1 ) assuming t<0;
M := t -> erf(sqrt(-t))*sqrt(Pi)/(2*sqrt(-t))
Mn := (t, n) -> exp(n*log(M(t)))
A := n -> sqrt(n/3 - 1/15)
Ex := n -> int( diff(Mn(z, n), z)/(sqrt(abs(z))*GAMMA(1/2) ),
z=-infinity..0 , numeric=true)
plot([Ex(n), A(n)], n=1..100, color=[blue, red], legend=
[exact, approx], labels=[n, expectation],
title="expectation of sum of squared uniforms")
plot([((A(n)-Ex(n))/Ex(n))*100], n=1..100, color=
[blue], labels=[n, "% error"],
title="Percentage error of approximation") | Expectation of square root of sum of independent squared uniform random variables | One approach is to first calculate the moment generating function (mgf) of $Y_n$ defined by $Y_n = U_1^2 + \dotsm + U_n^2$ where the $U_i, i=1,\dotsc, n$ is independent and identically distributed sta | Expectation of square root of sum of independent squared uniform random variables
One approach is to first calculate the moment generating function (mgf) of $Y_n$ defined by $Y_n = U_1^2 + \dotsm + U_n^2$ where the $U_i, i=1,\dotsc, n$ is independent and identically distributed standard uniform random variables.
When we have that, we can see that
$$ \DeclareMathOperator{\E}{\mathbb{E}}
\E \sqrt{Y_n}
$$
is the fractional moment of $Y_n$ of order $\alpha=1/2$. Then we can use results from the paper Noel Cressie and Marinus Borkent: "The Moment Generating Function has its Moments", Journal of Statistical Planning and Inference 13 (1986) 337-344, which gives fractional moments via fractional differentiation of the moment generating function.
First the moment generating function of $U_1^2$, which we write $M_1(t)$.
$$
M_1(t) = \E e^{t U_1^2} = \int_0^1 \frac{e^{tx}}{2\sqrt{x}}\; dx
$$
and I evaluated that (with help of Maple and Wolphram Alpha) to give
$$ \DeclareMathOperator{\erf}{erf}
M_1(t)= \frac{\erf(\sqrt{-t})\sqrt{\pi}}{2\sqrt{-t}}
$$ where $i=\sqrt{-1}$ is the imaginary unit.
(Wolphram Alpha gives a similar answer, but in terms of the Dawson integral.) It turns out we will mostly need the case for $t<0$. Now it is easy to find the mgf of $Y_n$:
$$
M_n(t) = M_1(t)^n
$$
Then for the results from the cited paper. For $\mu>0$ they define the $\mu$th order integral of the function $f$ as
$$
I^\mu f(t) \equiv \Gamma(\mu)^{-1} \int_{-\infty}^t (t-z)^{\mu-1} f(z)\; dz
$$
Then, for $\alpha>0$ and nonintegral, $n$ a positive integer, and $0<\lambda<1$ such that $\alpha=n-\lambda$. Then the derivative of $f$ of order $\alpha$ is defined as
$$
D^\alpha f(t) \equiv \Gamma(\lambda)^{-1}\int_{-\infty}^t (t-z)^{\lambda-1} \frac{d^n f(z)}{d z^n}\; dz.
$$
Then they state (and prove) the following result, for a positive random variable $X$: Suppose $M_X$ (mgf) is defined. Then, for $\alpha>0$,
$$
D^\alpha M_X(0) = \E X^\alpha < \infty
$$
Now we can try to apply these results to $Y_n$. With $\alpha=1/2$ we find
$$
\E Y_n^{1/2} = D^{1/2} M_n (0) = \Gamma(1/2)^{-1}\int_{-\infty}^0 |z|^{-1/2} M_n'(z) \; dz
$$
where the prime denotes the derivative. Maple gives the following solution:
$$
\int_{-\infty}^0 \frac{n\cdot\left(\erf(\sqrt{-z})\sqrt{\pi}-2e^z\sqrt{-z} \right)e^{\frac{n(-2\ln 2 +2 \ln(\erf(\sqrt{-z}))-\ln(-z) +\ln(\pi))}{2}}}{2\pi(-z)^{3/2}\erf(\sqrt{-z})} \; dz
$$
I will show a plot of this expectation, made in maple using numerical integration, together with the approximate solution $A(n)=\sqrt{n/3-1/15}$ from some comment (and discussed in the answer by @Henry). They are remarkably close:
As a complement, a plot of the percentage error:
Above about $n=20$ the approximation is close to exact. Below the maple code used:
int( exp(t*x)/(2*sqrt(x)), x=0..1 ) assuming t>0;
int( exp(t*x)/(2*sqrt(x)), x=0..1 ) assuming t<0;
M := t -> erf(sqrt(-t))*sqrt(Pi)/(2*sqrt(-t))
Mn := (t, n) -> exp(n*log(M(t)))
A := n -> sqrt(n/3 - 1/15)
Ex := n -> int( diff(Mn(z, n), z)/(sqrt(abs(z))*GAMMA(1/2) ),
z=-infinity..0 , numeric=true)
plot([Ex(n), A(n)], n=1..100, color=[blue, red], legend=
[exact, approx], labels=[n, expectation],
title="expectation of sum of squared uniforms")
plot([((A(n)-Ex(n))/Ex(n))*100], n=1..100, color=
[blue], labels=[n, "% error"],
title="Percentage error of approximation") | Expectation of square root of sum of independent squared uniform random variables
One approach is to first calculate the moment generating function (mgf) of $Y_n$ defined by $Y_n = U_1^2 + \dotsm + U_n^2$ where the $U_i, i=1,\dotsc, n$ is independent and identically distributed sta |
25,308 | Expectation of square root of sum of independent squared uniform random variables | As an extended comment: it seems clear here that $E\left[\sqrt{Y_n}\right]= E\left[\sqrt{\sum_i X_i^2}\right]$ starts with $E\left[\sqrt{Y_n}\right] =\frac12=\sqrt{\frac{n}{3}-\frac{1}{12}}$ when $n=1$ and then approaches $\sqrt{\frac{n}{3}-\frac{1}{15}}$ as $n$ increases, related to the variance of $\sqrt{Y_n}$ falling from $\frac{1}{12}$ towards $\frac{1}{15}$. My linked question which S.Catterall answered provides a justification for the $\sqrt{\frac{n}{3}-\frac{1}{15}}$ asymptotic result based on each $X_i^2$ having mean $\frac13$ and variance $\frac{4}{45}$, and for the distribution being approximately and asymptotically normal.
This question is effectively about the distributions of distances from the origin of random points in an $n$-dimensional unit hypercube $[0,1]^n$. It is similar to a question on the distribution of distances between points in such a hypercube, so I can easily adapt what I did there to show the densities for various $n$ from $1$ to $16$ using numerical convolution. For $n=16$, the suggested normal approximation shown in red is a good fit, and from $n=4$ you can see a bell curve appearing.
For $n=2$ and $n=3$ you get a sharp peak at the mode of $1$ with what looks like the same density in both cases. Compare this with the distribution of $\sum_i X_i$, where the bell curve appears with $n=3$ and where the variance is proportional to $n$ | Expectation of square root of sum of independent squared uniform random variables | As an extended comment: it seems clear here that $E\left[\sqrt{Y_n}\right]= E\left[\sqrt{\sum_i X_i^2}\right]$ starts with $E\left[\sqrt{Y_n}\right] =\frac12=\sqrt{\frac{n}{3}-\frac{1}{12}}$ when $n=1 | Expectation of square root of sum of independent squared uniform random variables
As an extended comment: it seems clear here that $E\left[\sqrt{Y_n}\right]= E\left[\sqrt{\sum_i X_i^2}\right]$ starts with $E\left[\sqrt{Y_n}\right] =\frac12=\sqrt{\frac{n}{3}-\frac{1}{12}}$ when $n=1$ and then approaches $\sqrt{\frac{n}{3}-\frac{1}{15}}$ as $n$ increases, related to the variance of $\sqrt{Y_n}$ falling from $\frac{1}{12}$ towards $\frac{1}{15}$. My linked question which S.Catterall answered provides a justification for the $\sqrt{\frac{n}{3}-\frac{1}{15}}$ asymptotic result based on each $X_i^2$ having mean $\frac13$ and variance $\frac{4}{45}$, and for the distribution being approximately and asymptotically normal.
This question is effectively about the distributions of distances from the origin of random points in an $n$-dimensional unit hypercube $[0,1]^n$. It is similar to a question on the distribution of distances between points in such a hypercube, so I can easily adapt what I did there to show the densities for various $n$ from $1$ to $16$ using numerical convolution. For $n=16$, the suggested normal approximation shown in red is a good fit, and from $n=4$ you can see a bell curve appearing.
For $n=2$ and $n=3$ you get a sharp peak at the mode of $1$ with what looks like the same density in both cases. Compare this with the distribution of $\sum_i X_i$, where the bell curve appears with $n=3$ and where the variance is proportional to $n$ | Expectation of square root of sum of independent squared uniform random variables
As an extended comment: it seems clear here that $E\left[\sqrt{Y_n}\right]= E\left[\sqrt{\sum_i X_i^2}\right]$ starts with $E\left[\sqrt{Y_n}\right] =\frac12=\sqrt{\frac{n}{3}-\frac{1}{12}}$ when $n=1 |
25,309 | How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed] | I suposse that the Softmax function is applied when you request a probability prediction by calling the method mlp.predict_proba(X).
To support my supposition I have developed this small experiment:
from sklearn.neural_network import MLPClassifier
from sklearn.datasets import load_iris
import numpy as np
X,Y = load_iris().data, load_iris().target
mlp = MLPClassifier()
mlp.fit(X, Y)
print mlp.predict([3.1, 2.5, 8.4, 2.2])
print mlp.predict_proba([3.1, 2.5, 8.4, 2.2])
print "sum: %f"%np.sum(mlp.predict_proba([3.1, 2.5, 8.4, 2.2]))
Notice that no matter what values are plugged into predict_proba(), the output probability vector allways sums up to 1. This can only be achieved by the Softmax activation function (Using an activation other that Softmax there is no guaranty that the sum of the activations in the final layer will be exactly one, specially for an unseen sample).
If my guess is right, looking at the documentation I can not find any method to get the output of the network before Softmax... Maybe because this class is intended solely for classification (not regression or other fancy setups). | How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed] | I suposse that the Softmax function is applied when you request a probability prediction by calling the method mlp.predict_proba(X).
To support my supposition I have developed this small experiment:
| How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed]
I suposse that the Softmax function is applied when you request a probability prediction by calling the method mlp.predict_proba(X).
To support my supposition I have developed this small experiment:
from sklearn.neural_network import MLPClassifier
from sklearn.datasets import load_iris
import numpy as np
X,Y = load_iris().data, load_iris().target
mlp = MLPClassifier()
mlp.fit(X, Y)
print mlp.predict([3.1, 2.5, 8.4, 2.2])
print mlp.predict_proba([3.1, 2.5, 8.4, 2.2])
print "sum: %f"%np.sum(mlp.predict_proba([3.1, 2.5, 8.4, 2.2]))
Notice that no matter what values are plugged into predict_proba(), the output probability vector allways sums up to 1. This can only be achieved by the Softmax activation function (Using an activation other that Softmax there is no guaranty that the sum of the activations in the final layer will be exactly one, specially for an unseen sample).
If my guess is right, looking at the documentation I can not find any method to get the output of the network before Softmax... Maybe because this class is intended solely for classification (not regression or other fancy setups). | How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed]
I suposse that the Softmax function is applied when you request a probability prediction by calling the method mlp.predict_proba(X).
To support my supposition I have developed this small experiment:
|
25,310 | How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed] | The MLPClassifier can be used for "multiclass classification", "binary classification" and "multilabel classification". So the output layer is decided based on type of Y :
Multiclass: The outmost layer is the softmax layer
Multilabel or Binary-class: The outmost layer is the logistic/sigmoid.
Regression: The outmost layer is identity
Part of code from sklearn used in MLPClassifier which confirms it:
# Output for regression
if not is_classifier(self):
self.out_activation_ = 'identity'
# Output for multi class
elif self._label_binarizer.y_type_ == 'multiclass':
self.out_activation_ = 'softmax'
# Output for binary class and multi-label
else:
self.out_activation_ = 'logistic'
Multiclass classification: For a Feature X, there can only be one class. eg Sentiment Analysis Given a Text(X), is the output(Y) is positive, neutral or negative. Binary is a case of Multiclass where there are only 2 possible outputs.
Multilabel classification: For a Feature X, there can be multiple classes. | How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed] | The MLPClassifier can be used for "multiclass classification", "binary classification" and "multilabel classification". So the output layer is decided based on type of Y :
Multiclass: The outmost lay | How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed]
The MLPClassifier can be used for "multiclass classification", "binary classification" and "multilabel classification". So the output layer is decided based on type of Y :
Multiclass: The outmost layer is the softmax layer
Multilabel or Binary-class: The outmost layer is the logistic/sigmoid.
Regression: The outmost layer is identity
Part of code from sklearn used in MLPClassifier which confirms it:
# Output for regression
if not is_classifier(self):
self.out_activation_ = 'identity'
# Output for multi class
elif self._label_binarizer.y_type_ == 'multiclass':
self.out_activation_ = 'softmax'
# Output for binary class and multi-label
else:
self.out_activation_ = 'logistic'
Multiclass classification: For a Feature X, there can only be one class. eg Sentiment Analysis Given a Text(X), is the output(Y) is positive, neutral or negative. Binary is a case of Multiclass where there are only 2 possible outputs.
Multilabel classification: For a Feature X, there can be multiple classes. | How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed]
The MLPClassifier can be used for "multiclass classification", "binary classification" and "multilabel classification". So the output layer is decided based on type of Y :
Multiclass: The outmost lay |
25,311 | How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed] | Can't agree with the answer from Daniel Lopez. In my case answer predict_proba() doesn't return softmax results.
The answer from TrideepRath can easily solve this issue. To apply softmax define out_activation_:
your_model.out_activation_ = 'softmax' | How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed] | Can't agree with the answer from Daniel Lopez. In my case answer predict_proba() doesn't return softmax results.
The answer from TrideepRath can easily solve this issue. To apply softmax define out_a | How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed]
Can't agree with the answer from Daniel Lopez. In my case answer predict_proba() doesn't return softmax results.
The answer from TrideepRath can easily solve this issue. To apply softmax define out_activation_:
your_model.out_activation_ = 'softmax' | How to apply Softmax as Activation function in multi-layer Perceptron in scikit-learn? [closed]
Can't agree with the answer from Daniel Lopez. In my case answer predict_proba() doesn't return softmax results.
The answer from TrideepRath can easily solve this issue. To apply softmax define out_a |
25,312 | Can someone explain like I am 5 year-old about this problem from Hastie's ESL Book? | Let $r$ be distance from the origin, and let $V_0[p]$ be the volume of the unit hypersphere in $p$ dimensions. Then the volume contained in a hypersphere of radius $r$ is
$$V[r]=V_0[p]r^p$$
If we let $P=V[r]/V_0[p]$ denote the fraction of the volume contained within this hypersphere, and define $R=r^p$, then
$$P[R]=R$$
If the data points are uniformly distributed within the unit ball, then for $0\leq R\leq 1$ the above formula is a cumulative distribution function (CDF) for $R$. This is equivalent to a uniform probability density for $R$ over the unit interval, i.e. $p[R]= P'[R] =1$. So, as hinted by Mark Stone in the comments, we can reduce the $p$ dimensional case to an equivalent 1D problem.
Now if we have a single point $R$, then by definition of a CDF we have $\Pr[R\leq \rho]=P[\rho]$ and $\Pr[R\geq \rho]=1-P[\rho]$. If $R_{\min}$ is the smallest value out of $n$ points, and the points are all independent, then the CDF for is given by
$$\Pr[R_{\min}\geq \rho]=\Pr[R\geq \rho]^n=(1-\rho)^n$$
(this is a standard result of univariate extreme value theory).
By definition of the median, we have
$$\frac{1}{2}=\Pr[(R_{\min})_{\mathrm{med}}\geq R]=(1-R)^n$$
which we can rewrite as
$$(1-d^p)^n=\frac{1}{2}$$
which is equivalent to the desired result.
EDIT: Attempt at "ELI5"-style answer, in three parts.
For the 1D case with a single point, the distance is uniformly distributed over $[0,1]$, so the median will be $\frac{1}{2}$.
In 1D, the distribution for the minimum over $n$ points is the first case to the $n$-th power.
In $p$ dimensions, the distance $r$ is not uniformly distributed, but $r^p$ is. | Can someone explain like I am 5 year-old about this problem from Hastie's ESL Book? | Let $r$ be distance from the origin, and let $V_0[p]$ be the volume of the unit hypersphere in $p$ dimensions. Then the volume contained in a hypersphere of radius $r$ is
$$V[r]=V_0[p]r^p$$
If we let | Can someone explain like I am 5 year-old about this problem from Hastie's ESL Book?
Let $r$ be distance from the origin, and let $V_0[p]$ be the volume of the unit hypersphere in $p$ dimensions. Then the volume contained in a hypersphere of radius $r$ is
$$V[r]=V_0[p]r^p$$
If we let $P=V[r]/V_0[p]$ denote the fraction of the volume contained within this hypersphere, and define $R=r^p$, then
$$P[R]=R$$
If the data points are uniformly distributed within the unit ball, then for $0\leq R\leq 1$ the above formula is a cumulative distribution function (CDF) for $R$. This is equivalent to a uniform probability density for $R$ over the unit interval, i.e. $p[R]= P'[R] =1$. So, as hinted by Mark Stone in the comments, we can reduce the $p$ dimensional case to an equivalent 1D problem.
Now if we have a single point $R$, then by definition of a CDF we have $\Pr[R\leq \rho]=P[\rho]$ and $\Pr[R\geq \rho]=1-P[\rho]$. If $R_{\min}$ is the smallest value out of $n$ points, and the points are all independent, then the CDF for is given by
$$\Pr[R_{\min}\geq \rho]=\Pr[R\geq \rho]^n=(1-\rho)^n$$
(this is a standard result of univariate extreme value theory).
By definition of the median, we have
$$\frac{1}{2}=\Pr[(R_{\min})_{\mathrm{med}}\geq R]=(1-R)^n$$
which we can rewrite as
$$(1-d^p)^n=\frac{1}{2}$$
which is equivalent to the desired result.
EDIT: Attempt at "ELI5"-style answer, in three parts.
For the 1D case with a single point, the distance is uniformly distributed over $[0,1]$, so the median will be $\frac{1}{2}$.
In 1D, the distribution for the minimum over $n$ points is the first case to the $n$-th power.
In $p$ dimensions, the distance $r$ is not uniformly distributed, but $r^p$ is. | Can someone explain like I am 5 year-old about this problem from Hastie's ESL Book?
Let $r$ be distance from the origin, and let $V_0[p]$ be the volume of the unit hypersphere in $p$ dimensions. Then the volume contained in a hypersphere of radius $r$ is
$$V[r]=V_0[p]r^p$$
If we let |
25,313 | Why does $R^2$ grow when more predictor variables are added to a model? | Let's suppose that we've got two models:
$$
Y = \beta_0 + \beta_1 X_1 + \varepsilon \tag{M1}
$$
and
$$
Y = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \varepsilon \tag{M2}
$$
This means that we have
$$
RSS_1 = \sum_{i=1}^n (Y_i - \hat \beta_0 - \hat \beta_1^{(1)} X_1)^2
$$
and
$$
RSS_2 = \sum_{i=1}^n (Y_i - \hat \beta_0 - \hat \beta_1^{(2)} X_1 - \hat \beta_2 X_2)^2.
$$
Model $M2$ contains model $M1$ as a special case, so there is no way that $RSS_1 < RSS_2$: we can just set $\hat \beta_2 = 0$ and $\hat \beta_1^{(1)} = \hat \beta_1^{(2)}$ in order to get $RSS_1 = RSS_2$. Much more likely is that $RSS_2 < RSS_1$ because we have an extra parameter so we can fit the data more closely.
This reveals the big problem with the unadjusted $R^2$: there is no penalty for model complexity. A more complicated model will almost always fit the data better so $R^2$ will prefer this model, even if the extra complexity is just modeling noise. That's why other methods like the adjusted $R^2$ (as mentioned in Antoni Parellada's answer) and $AIC$ are popular, since these take into account both the fit of the model to the data while also penalizing model complexity. | Why does $R^2$ grow when more predictor variables are added to a model? | Let's suppose that we've got two models:
$$
Y = \beta_0 + \beta_1 X_1 + \varepsilon \tag{M1}
$$
and
$$
Y = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \varepsilon \tag{M2}
$$
This means that we have
$$
RSS_ | Why does $R^2$ grow when more predictor variables are added to a model?
Let's suppose that we've got two models:
$$
Y = \beta_0 + \beta_1 X_1 + \varepsilon \tag{M1}
$$
and
$$
Y = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \varepsilon \tag{M2}
$$
This means that we have
$$
RSS_1 = \sum_{i=1}^n (Y_i - \hat \beta_0 - \hat \beta_1^{(1)} X_1)^2
$$
and
$$
RSS_2 = \sum_{i=1}^n (Y_i - \hat \beta_0 - \hat \beta_1^{(2)} X_1 - \hat \beta_2 X_2)^2.
$$
Model $M2$ contains model $M1$ as a special case, so there is no way that $RSS_1 < RSS_2$: we can just set $\hat \beta_2 = 0$ and $\hat \beta_1^{(1)} = \hat \beta_1^{(2)}$ in order to get $RSS_1 = RSS_2$. Much more likely is that $RSS_2 < RSS_1$ because we have an extra parameter so we can fit the data more closely.
This reveals the big problem with the unadjusted $R^2$: there is no penalty for model complexity. A more complicated model will almost always fit the data better so $R^2$ will prefer this model, even if the extra complexity is just modeling noise. That's why other methods like the adjusted $R^2$ (as mentioned in Antoni Parellada's answer) and $AIC$ are popular, since these take into account both the fit of the model to the data while also penalizing model complexity. | Why does $R^2$ grow when more predictor variables are added to a model?
Let's suppose that we've got two models:
$$
Y = \beta_0 + \beta_1 X_1 + \varepsilon \tag{M1}
$$
and
$$
Y = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \varepsilon \tag{M2}
$$
This means that we have
$$
RSS_ |
25,314 | Why does $R^2$ grow when more predictor variables are added to a model? | It is the result of the fitting process that takes place in the OLS regression. Each variable is regressed against all others, and what is left unexplained (residuals) is carried over. In a way, the regression process looks for explanations in the variance in the data, but it doesn't really excel at telling what is signal and what is noise.
In fact, if you were to just include variables composed of random noise, you could still see how there would be progressive overfitting of this noise in a misleading attempt at explaining the variability in the "dependent" variable.
I did this test in here, and plotted the resulting effect on the $RSS$ as the number of non-sensical variables increased:
This is why it is advisable to use adjusted $R^2$ instead of $R^2$ to judge whether it is a good idea to include more variables in a model. | Why does $R^2$ grow when more predictor variables are added to a model? | It is the result of the fitting process that takes place in the OLS regression. Each variable is regressed against all others, and what is left unexplained (residuals) is carried over. In a way, the r | Why does $R^2$ grow when more predictor variables are added to a model?
It is the result of the fitting process that takes place in the OLS regression. Each variable is regressed against all others, and what is left unexplained (residuals) is carried over. In a way, the regression process looks for explanations in the variance in the data, but it doesn't really excel at telling what is signal and what is noise.
In fact, if you were to just include variables composed of random noise, you could still see how there would be progressive overfitting of this noise in a misleading attempt at explaining the variability in the "dependent" variable.
I did this test in here, and plotted the resulting effect on the $RSS$ as the number of non-sensical variables increased:
This is why it is advisable to use adjusted $R^2$ instead of $R^2$ to judge whether it is a good idea to include more variables in a model. | Why does $R^2$ grow when more predictor variables are added to a model?
It is the result of the fitting process that takes place in the OLS regression. Each variable is regressed against all others, and what is left unexplained (residuals) is carried over. In a way, the r |
25,315 | Optimization of stochastic computer models | (Expanding my comment to a proper answer.)
As I mentioned, it depends on your goal.
The expected value $\mathbb{E}[f(x)]$ is only one of many possible choices for the optimization target. For example, assuming that the $f(x)$ are normally distributed, you could do:
$$
x^\text{opt} = \arg \min_x \left\{ \mathbb{E}[f(x)] + \kappa \sqrt{\mathbb{Var}[f(x)]} \right\}
$$
for some $\kappa \in \mathbb{R}$ that manipulates risk-sensitivity. If $\kappa > 0$ you are looking for a robust solution that is likely to be best and discourages large positive fluctuations. Vice versa, a negative $\kappa$ would favour an "optimistic" optimization that looks for large negative fluctuations (negative is good since we are minimizing). You can choose $\kappa$ based on quantiles of the normal distribution (see reference 2 below).
In general, Bayesian optimization (BO, which is related to Gaussian processes and kriging) deals with costly and sometimes noisy function evaluations; although most of the focus of the literature has been on the former part. You can find reviews for Bayesian optimization at this question.
Several people have applied BO to noisy functions.
As an introdution to the topic, David Ginsbourger gave a nice talk titled "Variations on the Expected Improvement" at the Workshop on Gaussian Processes for Global Optimization (Sheffield, Sept 17, 2015). You can find his talk here, and all the talks are available on this page (I also recommend all the other talks as an excellent general introduction to BO.)
As references, I would start with the work done by Ginsbourger and colleagues, and Gramacy and colleagues:
Picheny, V. and Ginsbourger, D., 2014. "Noisy kriging-based optimization methods: a unified implementation within the DiceOptim package". Computational Statistics & Data Analysis, 71, pp.1035-1053. (link)
Picheny, V., Ginsbourger, D., Richet, Y. and Caplin, G., 2013. "Quantile-based optimization of noisy computer experiments with tunable precision". Technometrics, 55(1), pp.2-13. (link)
Gramacy, R.B. and Lee, H.K., 2012. "Bayesian treed Gaussian process models with an application to computer modeling". Journal of the American Statistical Association. (link)
Gramacy, R.B. and Apley, D.W., 2015. "Local Gaussian process approximation for large computer experiments". Journal of Computational and Graphical Statistics, 24(2), pp.561-578. (link)
Both Ginsburger and Gramacy have R packages that implement their BO methods, respectively DiceOptim and tgp. | Optimization of stochastic computer models | (Expanding my comment to a proper answer.)
As I mentioned, it depends on your goal.
The expected value $\mathbb{E}[f(x)]$ is only one of many possible choices for the optimization target. For example | Optimization of stochastic computer models
(Expanding my comment to a proper answer.)
As I mentioned, it depends on your goal.
The expected value $\mathbb{E}[f(x)]$ is only one of many possible choices for the optimization target. For example, assuming that the $f(x)$ are normally distributed, you could do:
$$
x^\text{opt} = \arg \min_x \left\{ \mathbb{E}[f(x)] + \kappa \sqrt{\mathbb{Var}[f(x)]} \right\}
$$
for some $\kappa \in \mathbb{R}$ that manipulates risk-sensitivity. If $\kappa > 0$ you are looking for a robust solution that is likely to be best and discourages large positive fluctuations. Vice versa, a negative $\kappa$ would favour an "optimistic" optimization that looks for large negative fluctuations (negative is good since we are minimizing). You can choose $\kappa$ based on quantiles of the normal distribution (see reference 2 below).
In general, Bayesian optimization (BO, which is related to Gaussian processes and kriging) deals with costly and sometimes noisy function evaluations; although most of the focus of the literature has been on the former part. You can find reviews for Bayesian optimization at this question.
Several people have applied BO to noisy functions.
As an introdution to the topic, David Ginsbourger gave a nice talk titled "Variations on the Expected Improvement" at the Workshop on Gaussian Processes for Global Optimization (Sheffield, Sept 17, 2015). You can find his talk here, and all the talks are available on this page (I also recommend all the other talks as an excellent general introduction to BO.)
As references, I would start with the work done by Ginsbourger and colleagues, and Gramacy and colleagues:
Picheny, V. and Ginsbourger, D., 2014. "Noisy kriging-based optimization methods: a unified implementation within the DiceOptim package". Computational Statistics & Data Analysis, 71, pp.1035-1053. (link)
Picheny, V., Ginsbourger, D., Richet, Y. and Caplin, G., 2013. "Quantile-based optimization of noisy computer experiments with tunable precision". Technometrics, 55(1), pp.2-13. (link)
Gramacy, R.B. and Lee, H.K., 2012. "Bayesian treed Gaussian process models with an application to computer modeling". Journal of the American Statistical Association. (link)
Gramacy, R.B. and Apley, D.W., 2015. "Local Gaussian process approximation for large computer experiments". Journal of Computational and Graphical Statistics, 24(2), pp.561-578. (link)
Both Ginsburger and Gramacy have R packages that implement their BO methods, respectively DiceOptim and tgp. | Optimization of stochastic computer models
(Expanding my comment to a proper answer.)
As I mentioned, it depends on your goal.
The expected value $\mathbb{E}[f(x)]$ is only one of many possible choices for the optimization target. For example |
25,316 | Optimization of stochastic computer models | The current answers focus on the proper (mathematical) definition of a stochastic optimization target - I want to provide a somewhat more applied perspective.
This problem occurs frequently when fitting stochastic models, e.g. using informal or synthetic likelihoods. Reference (1) provides you with a list of options that can be used to define the distance between a stochastic model and the data.
After having defined your target in this way, the issue that remains is finding the optimum of some mean of a noisy target. There are two routes to go, a) optimization, and b) MCMC sampling. You were asking specifically about optimization, but I want to bring in the MCMCs because they are often better behaved for this task.
a) If you stay with optimization, you need to make sure that you don't get stuck and that the optimizer can deal with a stochastic target. Chapter 4 in the PhD thesis of Matteo Fasiolo gives some hints, see (2).
b) As we note in (1), MCMCs are generally more robust against a stochastic target - under mild conditions regarding the distribution of the noise, the MCMC will average the noise away, and the sampled target will be indistinguishable from a non-noisy target with mean of the noisy target. However, MCMCs too can get stuck when encountering an evaluation that is particularly good. What you MUST NOT DO now is getting the following "obvious" idea: simply calculate both current and proposed value in each MCMC iteration. The keyword to look up here is "pseudo-marginal", see also here and here.
1) Hartig, F.; Calabrese, J. M.; Reineking, B.; Wiegand, T. & Huth, A. (2011) Statistical inference for stochastic simulation models - theory and application. Ecol. Lett., 14, 816-827.
2) Fasiolo, M. (2016) Statistical Methods for Complex Population Dynamics. University of Bath | Optimization of stochastic computer models | The current answers focus on the proper (mathematical) definition of a stochastic optimization target - I want to provide a somewhat more applied perspective.
This problem occurs frequently when fitti | Optimization of stochastic computer models
The current answers focus on the proper (mathematical) definition of a stochastic optimization target - I want to provide a somewhat more applied perspective.
This problem occurs frequently when fitting stochastic models, e.g. using informal or synthetic likelihoods. Reference (1) provides you with a list of options that can be used to define the distance between a stochastic model and the data.
After having defined your target in this way, the issue that remains is finding the optimum of some mean of a noisy target. There are two routes to go, a) optimization, and b) MCMC sampling. You were asking specifically about optimization, but I want to bring in the MCMCs because they are often better behaved for this task.
a) If you stay with optimization, you need to make sure that you don't get stuck and that the optimizer can deal with a stochastic target. Chapter 4 in the PhD thesis of Matteo Fasiolo gives some hints, see (2).
b) As we note in (1), MCMCs are generally more robust against a stochastic target - under mild conditions regarding the distribution of the noise, the MCMC will average the noise away, and the sampled target will be indistinguishable from a non-noisy target with mean of the noisy target. However, MCMCs too can get stuck when encountering an evaluation that is particularly good. What you MUST NOT DO now is getting the following "obvious" idea: simply calculate both current and proposed value in each MCMC iteration. The keyword to look up here is "pseudo-marginal", see also here and here.
1) Hartig, F.; Calabrese, J. M.; Reineking, B.; Wiegand, T. & Huth, A. (2011) Statistical inference for stochastic simulation models - theory and application. Ecol. Lett., 14, 816-827.
2) Fasiolo, M. (2016) Statistical Methods for Complex Population Dynamics. University of Bath | Optimization of stochastic computer models
The current answers focus on the proper (mathematical) definition of a stochastic optimization target - I want to provide a somewhat more applied perspective.
This problem occurs frequently when fitti |
25,317 | Optimization of stochastic computer models | Let's say we're in a discrete probability space so that $f(x) \in \mathcal{R}^n$. Intuitively, you need some function $U: \mathcal{R}^n \rightarrow \mathcal{R}$ so you can optimize $U(f(x))$. You can only optimize a single objective!
Optimizing a single objective function may sound quite constraining, but it is not! Rather a single objective can represent incredibly diverse preferences you may have over what is a better or worse solution.
Skipping ahead, a simple place to start may be choosing a random variable $\lambda$ then solving:
$$
\begin{array}{*2{>{\displaystyle}r}}
\mbox{minimize (over $x$)} & E\left[\lambda f(x) \right] \\
\mbox{subject to} & x \in X
\end{array}
$$
This is a simple linear re-weighting of $E[f(x)]$. Anyway, here's an argument for why collapsing multiple objectives to a single objective is typically ok.
Basic setup:
You have a choice variable $x$ and a feasible set $X$.
Your choice of $x$ leads a random outcome $\tilde{y} = f(x)$
You have rational preferences $\prec$ over the random outcome. (Basically, you can say whether you prefer one random outcome $\tilde{y}$ to another.)
Your problem is to choose $x^*\in X$ such that:
$$ \nexists_{x \in X} \quad f(x^*) \prec f(x) $$
In English, you wan to choose $x^*$ so that no feasible choice $x$ leads to an outcome preferred to $f(x^*)$.
Equivalence to maximizing utility (under certain technical conditions)
For technical simplicity, I'll say we're in a discrete probability space with $n$ outcomes so I can represent random outcome $\tilde{y}$ with a vector $\mathbf{y} \in \mathcal{R}^n$.
Under certain technical conditions (that aren't limiting in a practical sense), the above problem is equivalent to maximizing a utility function $U(\mathbf{y})$. (The utility function assigns more preferred outcomes a higher number.)
This logic would apply to any problem where your choice leads to multiple outcome variables.
$$
\begin{array}{*2{>{\displaystyle}r}}
\mbox{maximize (over $x$)} & U(f(x)) \\
\mbox{subject to} & x \in X
\end{array}
$$
Giving more structure to utility function $U$: Expected Utility hypothesis:
If we're in a probabilistic setting and we accept the Neumann-Morgernstern axioms, the overall utility function $U$ has to take a special form:
$$U(\mathbf{y}) = E[u(y_i)] = \sum_i p_i u(y_i) $$
Where $p_i$ is the probability of state $i$ and $u$ is a concave utility function. The curvature of $u$ measures risk aversion. Simply substituting this specialized form of $U$ you get:
$$
\begin{array}{*2{>{\displaystyle}r}}
\mbox{maximize (over $x$)} & \sum_i p_i u(y_i) \\
\mbox{subject to} & x \in X \\
& \mathbf{y} = f(x)
\end{array}
$$
Observe that the simple case $u(y_i) = y_i$ is maximizing the expected value (i.e. no risk aversion).
Another approach: $\lambda$ weights
Another thing to do is:
$$
\begin{array}{*2{>{\displaystyle}r}}
\mbox{maximize (over $x$)} & \sum_i \lambda_i y_i \\
\mbox{subject to} & x \in X \\
& \mathbf{y} = f(x)
\end{array}
$$
Intuitively, you can choose weights $\lambda_i$ that are larger or smaller than the probability $p_i$ of a state occurring, and this captures the importance of a state.
The deeper justification of this approach is that under certain technical conditions, there exists lambda weights $\boldsymbol{\lambda}$ such that the above problem and the earlier problems (eg. maximizing $U(f(x))$) have the same solution. | Optimization of stochastic computer models | Let's say we're in a discrete probability space so that $f(x) \in \mathcal{R}^n$. Intuitively, you need some function $U: \mathcal{R}^n \rightarrow \mathcal{R}$ so you can optimize $U(f(x))$. You can | Optimization of stochastic computer models
Let's say we're in a discrete probability space so that $f(x) \in \mathcal{R}^n$. Intuitively, you need some function $U: \mathcal{R}^n \rightarrow \mathcal{R}$ so you can optimize $U(f(x))$. You can only optimize a single objective!
Optimizing a single objective function may sound quite constraining, but it is not! Rather a single objective can represent incredibly diverse preferences you may have over what is a better or worse solution.
Skipping ahead, a simple place to start may be choosing a random variable $\lambda$ then solving:
$$
\begin{array}{*2{>{\displaystyle}r}}
\mbox{minimize (over $x$)} & E\left[\lambda f(x) \right] \\
\mbox{subject to} & x \in X
\end{array}
$$
This is a simple linear re-weighting of $E[f(x)]$. Anyway, here's an argument for why collapsing multiple objectives to a single objective is typically ok.
Basic setup:
You have a choice variable $x$ and a feasible set $X$.
Your choice of $x$ leads a random outcome $\tilde{y} = f(x)$
You have rational preferences $\prec$ over the random outcome. (Basically, you can say whether you prefer one random outcome $\tilde{y}$ to another.)
Your problem is to choose $x^*\in X$ such that:
$$ \nexists_{x \in X} \quad f(x^*) \prec f(x) $$
In English, you wan to choose $x^*$ so that no feasible choice $x$ leads to an outcome preferred to $f(x^*)$.
Equivalence to maximizing utility (under certain technical conditions)
For technical simplicity, I'll say we're in a discrete probability space with $n$ outcomes so I can represent random outcome $\tilde{y}$ with a vector $\mathbf{y} \in \mathcal{R}^n$.
Under certain technical conditions (that aren't limiting in a practical sense), the above problem is equivalent to maximizing a utility function $U(\mathbf{y})$. (The utility function assigns more preferred outcomes a higher number.)
This logic would apply to any problem where your choice leads to multiple outcome variables.
$$
\begin{array}{*2{>{\displaystyle}r}}
\mbox{maximize (over $x$)} & U(f(x)) \\
\mbox{subject to} & x \in X
\end{array}
$$
Giving more structure to utility function $U$: Expected Utility hypothesis:
If we're in a probabilistic setting and we accept the Neumann-Morgernstern axioms, the overall utility function $U$ has to take a special form:
$$U(\mathbf{y}) = E[u(y_i)] = \sum_i p_i u(y_i) $$
Where $p_i$ is the probability of state $i$ and $u$ is a concave utility function. The curvature of $u$ measures risk aversion. Simply substituting this specialized form of $U$ you get:
$$
\begin{array}{*2{>{\displaystyle}r}}
\mbox{maximize (over $x$)} & \sum_i p_i u(y_i) \\
\mbox{subject to} & x \in X \\
& \mathbf{y} = f(x)
\end{array}
$$
Observe that the simple case $u(y_i) = y_i$ is maximizing the expected value (i.e. no risk aversion).
Another approach: $\lambda$ weights
Another thing to do is:
$$
\begin{array}{*2{>{\displaystyle}r}}
\mbox{maximize (over $x$)} & \sum_i \lambda_i y_i \\
\mbox{subject to} & x \in X \\
& \mathbf{y} = f(x)
\end{array}
$$
Intuitively, you can choose weights $\lambda_i$ that are larger or smaller than the probability $p_i$ of a state occurring, and this captures the importance of a state.
The deeper justification of this approach is that under certain technical conditions, there exists lambda weights $\boldsymbol{\lambda}$ such that the above problem and the earlier problems (eg. maximizing $U(f(x))$) have the same solution. | Optimization of stochastic computer models
Let's say we're in a discrete probability space so that $f(x) \in \mathcal{R}^n$. Intuitively, you need some function $U: \mathcal{R}^n \rightarrow \mathcal{R}$ so you can optimize $U(f(x))$. You can |
25,318 | Why divide by $n-2$ for residual standard errors | You use the residuals to estimate the distribution of the error.
https://en.wikipedia.org/wiki/Errors_and_residuals , but these are different things.
Error's are what the 'true' model includes as randomness
Residuals are the differentiations that you 'observe' between a model fit and a measurement.
The residuals do not resemble the errors. When you fit a model then you will fit to the model plus the error terms. This means that the fitting has a tendency to fit a part of the error terms, in addition to the model, and this will in effect decrease the residuals in relation to the true errors (ie residuals < error, and in this particular case $residuals = error/(n-2)$).
The more parameters the model has (the more degrees of freedom the model has to fit, cover up, the partial error terms) the less the residuals will resemble the true distribution of the error.
So the expression $\frac{\sum r_i^2}{n-2}$ refers to $r_i$ as 'residiual' terms, but wishes to express some idea of variance in the 'error' terms and in order to do this it need to include the '$n-2$' instead of the '$n$' term because the residual terms have a slight bias. | Why divide by $n-2$ for residual standard errors | You use the residuals to estimate the distribution of the error.
https://en.wikipedia.org/wiki/Errors_and_residuals , but these are different things.
Error's are what the 'true' model includes as r | Why divide by $n-2$ for residual standard errors
You use the residuals to estimate the distribution of the error.
https://en.wikipedia.org/wiki/Errors_and_residuals , but these are different things.
Error's are what the 'true' model includes as randomness
Residuals are the differentiations that you 'observe' between a model fit and a measurement.
The residuals do not resemble the errors. When you fit a model then you will fit to the model plus the error terms. This means that the fitting has a tendency to fit a part of the error terms, in addition to the model, and this will in effect decrease the residuals in relation to the true errors (ie residuals < error, and in this particular case $residuals = error/(n-2)$).
The more parameters the model has (the more degrees of freedom the model has to fit, cover up, the partial error terms) the less the residuals will resemble the true distribution of the error.
So the expression $\frac{\sum r_i^2}{n-2}$ refers to $r_i$ as 'residiual' terms, but wishes to express some idea of variance in the 'error' terms and in order to do this it need to include the '$n-2$' instead of the '$n$' term because the residual terms have a slight bias. | Why divide by $n-2$ for residual standard errors
You use the residuals to estimate the distribution of the error.
https://en.wikipedia.org/wiki/Errors_and_residuals , but these are different things.
Error's are what the 'true' model includes as r |
25,319 | Why divide by $n-2$ for residual standard errors | The issue is that the $\beta$ coefficients are estimated so as to minimize $\sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ and so $n^{-1} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ tends underestimate $\sigma^2$. This is the same reason why we often divide by $n - 1$ when estimating variances of univariate distributions. The issue is not so bad in the simple linear regression case but when $p$ becomes large the shrinkage can be substantial. For this reason we generally prefer the unbiased estimate $(n - p)^{-1} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ because it doesn't suffer from this defect. | Why divide by $n-2$ for residual standard errors | The issue is that the $\beta$ coefficients are estimated so as to minimize $\sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ and so $n^{-1} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ tends underestimate $\sigma^2$. This | Why divide by $n-2$ for residual standard errors
The issue is that the $\beta$ coefficients are estimated so as to minimize $\sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ and so $n^{-1} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ tends underestimate $\sigma^2$. This is the same reason why we often divide by $n - 1$ when estimating variances of univariate distributions. The issue is not so bad in the simple linear regression case but when $p$ becomes large the shrinkage can be substantial. For this reason we generally prefer the unbiased estimate $(n - p)^{-1} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ because it doesn't suffer from this defect. | Why divide by $n-2$ for residual standard errors
The issue is that the $\beta$ coefficients are estimated so as to minimize $\sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ and so $n^{-1} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2$ tends underestimate $\sigma^2$. This |
25,320 | Why divide by $n-2$ for residual standard errors | the reason why we use n-2 df instead n-1 in estimating error variance is there are two parameters estimated in each equation, we deduct 2 from the number of observations to obtain the df. This assumption underlying the Chow test which explain unbiased estimators of the true variances in the two subperiods.So, for mathematical calculation, I refer to Chow test. | Why divide by $n-2$ for residual standard errors | the reason why we use n-2 df instead n-1 in estimating error variance is there are two parameters estimated in each equation, we deduct 2 from the number of observations to obtain the df. This assumpt | Why divide by $n-2$ for residual standard errors
the reason why we use n-2 df instead n-1 in estimating error variance is there are two parameters estimated in each equation, we deduct 2 from the number of observations to obtain the df. This assumption underlying the Chow test which explain unbiased estimators of the true variances in the two subperiods.So, for mathematical calculation, I refer to Chow test. | Why divide by $n-2$ for residual standard errors
the reason why we use n-2 df instead n-1 in estimating error variance is there are two parameters estimated in each equation, we deduct 2 from the number of observations to obtain the df. This assumpt |
25,321 | Why divide by $n-2$ for residual standard errors | Here's the intuitive answer.
Let's say that you need to make a regression line.
With $n=1$ data entry you can't make a line.
With $n=2$ data entries you can make exactly one line. Since you can make one and only one line you have $0=n-2$ degrees of freedom.
$\implies$With $n$ points you will have $n - 2$ degrees of freedom. | Why divide by $n-2$ for residual standard errors | Here's the intuitive answer.
Let's say that you need to make a regression line.
With $n=1$ data entry you can't make a line.
With $n=2$ data entries you can make exactly one line. Since you can make o | Why divide by $n-2$ for residual standard errors
Here's the intuitive answer.
Let's say that you need to make a regression line.
With $n=1$ data entry you can't make a line.
With $n=2$ data entries you can make exactly one line. Since you can make one and only one line you have $0=n-2$ degrees of freedom.
$\implies$With $n$ points you will have $n - 2$ degrees of freedom. | Why divide by $n-2$ for residual standard errors
Here's the intuitive answer.
Let's say that you need to make a regression line.
With $n=1$ data entry you can't make a line.
With $n=2$ data entries you can make exactly one line. Since you can make o |
25,322 | Precisely how does R's coxph() handle repeated measures? | Including cluster(ID) does not change the point estimates of the parameters. It does change the way that the standard errors are computed however.
More details can be found in Therneau & Grambsch's book Extending the Cox Model, chapter 8.2. Note that in their example, they use method = "breslow" as correction for ties, but also with the default (method = "efron") a similar calculation for the se's will be used, and appears in the summary as "robust se".
If cluster(ID) is used, a "robust" estimate of standard errors is imposed and possible dependence between subjects is measured (e.g. by standard errors and variance scores). Not using cluster(ID), on the other hand, imposes independence on each observation and more "information" is assumed in the data. In more technical terms, the score function for the parameters does not change, but the variance of this score does. A more intuitive argument is that 100 observations on 100 individuals provide more information than 100 observations on 10 individuals (or clusters).
Vague indeed. In short, +frailty(ID) in coxph() fits standard frailty models with gamma or log-normal random effects and with non-parametric baseline hazard / intensity. frailtypack uses parametric baseline (also flexible versions with splines or piecewise constant functions) and also fits more complicated models, such as correlated frailty, nested frailty, etc.
Finally, +cluster() is somewhat in the spirit of GEE, in that you take the score equations from a likelihood with independent observations, and use a different "robust" estimator for the standard errors.
edit: Thanks @Ivan for the suggestions regarding the clarity of the post. | Precisely how does R's coxph() handle repeated measures? | Including cluster(ID) does not change the point estimates of the parameters. It does change the way that the standard errors are computed however.
More details can be found in Therneau & Grambsch's bo | Precisely how does R's coxph() handle repeated measures?
Including cluster(ID) does not change the point estimates of the parameters. It does change the way that the standard errors are computed however.
More details can be found in Therneau & Grambsch's book Extending the Cox Model, chapter 8.2. Note that in their example, they use method = "breslow" as correction for ties, but also with the default (method = "efron") a similar calculation for the se's will be used, and appears in the summary as "robust se".
If cluster(ID) is used, a "robust" estimate of standard errors is imposed and possible dependence between subjects is measured (e.g. by standard errors and variance scores). Not using cluster(ID), on the other hand, imposes independence on each observation and more "information" is assumed in the data. In more technical terms, the score function for the parameters does not change, but the variance of this score does. A more intuitive argument is that 100 observations on 100 individuals provide more information than 100 observations on 10 individuals (or clusters).
Vague indeed. In short, +frailty(ID) in coxph() fits standard frailty models with gamma or log-normal random effects and with non-parametric baseline hazard / intensity. frailtypack uses parametric baseline (also flexible versions with splines or piecewise constant functions) and also fits more complicated models, such as correlated frailty, nested frailty, etc.
Finally, +cluster() is somewhat in the spirit of GEE, in that you take the score equations from a likelihood with independent observations, and use a different "robust" estimator for the standard errors.
edit: Thanks @Ivan for the suggestions regarding the clarity of the post. | Precisely how does R's coxph() handle repeated measures?
Including cluster(ID) does not change the point estimates of the parameters. It does change the way that the standard errors are computed however.
More details can be found in Therneau & Grambsch's bo |
25,323 | Precisely how does R's coxph() handle repeated measures? | Here's an answer from a survival package vignette I found helpful - it's linked in the first answer to the first question you linked to:
Best packages for Cox models with time varying covariates
They're referring to the long form data setup, or data with repeated entries for subjects.
One common question with this data setup is whether we need to worry about correlated data, since a given subject has multiple observations. The answer is no, we do not. The reason is that this representation is simply a programming trick. The likelihood equations at any time point use only one copy of any subject, the program picks out the correct row of data at each time. There two exceptions to this rule:
When subjects have multiple events, then the rows for the events are correlated within subject and a cluster variance is needed.
When a subject appears in overlapping intervals. This however is almost always a data error, since it corresponds to two copies of the subject being present in the same strata at the same time, e.g., she could meet herself at a party.
The example they give is
fit <- coxph(Surv(time1, time2, status) ~ age + creatinine, data=mydata)
suggesting that if you provide two times (start and end of period) to Surv instead of one, coxph() will figure out the rest. | Precisely how does R's coxph() handle repeated measures? | Here's an answer from a survival package vignette I found helpful - it's linked in the first answer to the first question you linked to:
Best packages for Cox models with time varying covariates
They' | Precisely how does R's coxph() handle repeated measures?
Here's an answer from a survival package vignette I found helpful - it's linked in the first answer to the first question you linked to:
Best packages for Cox models with time varying covariates
They're referring to the long form data setup, or data with repeated entries for subjects.
One common question with this data setup is whether we need to worry about correlated data, since a given subject has multiple observations. The answer is no, we do not. The reason is that this representation is simply a programming trick. The likelihood equations at any time point use only one copy of any subject, the program picks out the correct row of data at each time. There two exceptions to this rule:
When subjects have multiple events, then the rows for the events are correlated within subject and a cluster variance is needed.
When a subject appears in overlapping intervals. This however is almost always a data error, since it corresponds to two copies of the subject being present in the same strata at the same time, e.g., she could meet herself at a party.
The example they give is
fit <- coxph(Surv(time1, time2, status) ~ age + creatinine, data=mydata)
suggesting that if you provide two times (start and end of period) to Surv instead of one, coxph() will figure out the rest. | Precisely how does R's coxph() handle repeated measures?
Here's an answer from a survival package vignette I found helpful - it's linked in the first answer to the first question you linked to:
Best packages for Cox models with time varying covariates
They' |
25,324 | The role of variance in Central Limit Theorem | The classical statement of the Central Limit Theorem (CLT) considers a sequence of independent, identically distributed random variables $X_1, X_2, \ldots, X_n, \ldots$ with common distribution $F$. This sequence models the situation we confront when designing a sampling program or experiment: if we can obtain $n$ independent observations of the same underlying phenomenon, then the finite collection $X_1, X_2, \ldots, X_n$ models the anticipated data. Allowing the sequence to be infinite is a convenient way to contemplate arbitrarily large sample sizes.
Various laws of large numbers assert that the mean
$$m(X_1, X_2, \ldots, X_n) = \frac{1}{n}(X_1 + X_2 + \cdots + X_n)$$
will closely approach the expectation of $F$, $\mu(F)$, with high probability, provided $F$ actually has an expectation. (Not all distributions do.) This implies the deviation $m(X_1, X_2, \ldots, X_n) - \mu(F)$ (which, as a function of these $n$ random variables, is also a random variable) will tend to get smaller as $n$ increases. The CLT adds to this in a much more specific way: it states (under some conditions, which I will discuss below) that if we rescale this deviation by $\sqrt{n}$, it will have a distribution function $F_n$ that approaches some zero-mean Normal distribution function as $n$ grows large. (My answer at https://stats.stackexchange.com/a/3904 attempts to explain why this is and why the factor of $\sqrt{n}$ is the right one to use.)
This is not a standard statement of the CLT. Let's connect it with the usual one. That limiting zero-mean Normal distribution will be completely determined by a second parameter, which is usually chosen to be a measure of its spread (naturally!), such as its variance or standard deviation. Let $\sigma^2$ be its variance. Surely it must have some relationship to a similar property of $F$. To discover what this might be, let $F$ have a variance $\tau^2$--which might be infinite, by the way. Regardless, because the $X_i$ are independent, we easily compute the variance of the means:
$$\eqalign{
\text{Var}(m(X_1, X_2, \ldots, X_n)) &= \text{Var}(\frac{1}{n}(X_1 + X_2 + \cdots + X_n)) \\
&= \left(\frac{1}{n}\right)^2(\text{Var}(X_1) + \text{Var}(X_2) + \cdots + \text{Var}(X_n)) \\
&= \left(\frac{1}{n}\right)^2(\tau^2 + \tau^2 + \cdots + \tau^2) \\
&= \frac{\tau^2}{n}.
}$$
Consequently, the variance of the standardized residuals equals $\tau^2/n \times (\sqrt{n})^2 = \tau^2$: it is constant. The variance of the limiting Normal distribution, then, must be $\tau^2$ itself. (This immediately shows that the theorem can hold only when $\tau^2$ is finite: that is the additional assumption I glossed over earlier.)
(If we had chosen any other measure of spread of $F$ we could still succeed in connecting it to $\sigma^2$, but we would not have found that the corresponding measure of spread of the standardized mean deviation is constant for all $n$, which is a beautiful--albeit inessential--simplification.)
If we had wished, we could have standardized the mean deviations all along by dividing them by $\tau$ as well as multiplying them by $\sqrt{n}$. That would have ensured the limiting distribution is standard Normal, with unit variance. Whether you elect to standardize by $\tau$ in this way or not is really a matter of taste: it's the same theorem and the same conclusion in the end. What mattered was the multiplication by $\sqrt{n}$.
Note that you could multiply the deviations by some factor other than $\sqrt{n}$. You could use $\sqrt{n} + \exp(-n)$, or $n^{1/2 + 1/n}$, or anything else that asymptotically behaves just like $\sqrt{n}$. Any other asymptotic form would, in the limit, reduce $\sigma^2$ to $0$ or blow it up to $\infty$. This observation refines our appreciation of the CLT by showing the extent to which it is flexible concerning how the standardization is performed. We might want to state the CLT, then, in the following way.
Provided the deviation between the mean of a sequence of IID variables (with common distribution $F$) and the underlying expectation is scaled asymptotically by $\sqrt{n}$, this scaled deviation will have a zero-mean Normal limiting distribution whose variance is that of $F$.
Although variances are involved in the statement, they appear only because they are needed to characterize the limiting Normal distribution and relate its spread to that of $F$. This is only an incidental aspect. It has nothing to do with variance being "best" in any sense. The crux of the matter is the asymptotic rescaling by $\sqrt{n}$. | The role of variance in Central Limit Theorem | The classical statement of the Central Limit Theorem (CLT) considers a sequence of independent, identically distributed random variables $X_1, X_2, \ldots, X_n, \ldots$ with common distribution $F$. | The role of variance in Central Limit Theorem
The classical statement of the Central Limit Theorem (CLT) considers a sequence of independent, identically distributed random variables $X_1, X_2, \ldots, X_n, \ldots$ with common distribution $F$. This sequence models the situation we confront when designing a sampling program or experiment: if we can obtain $n$ independent observations of the same underlying phenomenon, then the finite collection $X_1, X_2, \ldots, X_n$ models the anticipated data. Allowing the sequence to be infinite is a convenient way to contemplate arbitrarily large sample sizes.
Various laws of large numbers assert that the mean
$$m(X_1, X_2, \ldots, X_n) = \frac{1}{n}(X_1 + X_2 + \cdots + X_n)$$
will closely approach the expectation of $F$, $\mu(F)$, with high probability, provided $F$ actually has an expectation. (Not all distributions do.) This implies the deviation $m(X_1, X_2, \ldots, X_n) - \mu(F)$ (which, as a function of these $n$ random variables, is also a random variable) will tend to get smaller as $n$ increases. The CLT adds to this in a much more specific way: it states (under some conditions, which I will discuss below) that if we rescale this deviation by $\sqrt{n}$, it will have a distribution function $F_n$ that approaches some zero-mean Normal distribution function as $n$ grows large. (My answer at https://stats.stackexchange.com/a/3904 attempts to explain why this is and why the factor of $\sqrt{n}$ is the right one to use.)
This is not a standard statement of the CLT. Let's connect it with the usual one. That limiting zero-mean Normal distribution will be completely determined by a second parameter, which is usually chosen to be a measure of its spread (naturally!), such as its variance or standard deviation. Let $\sigma^2$ be its variance. Surely it must have some relationship to a similar property of $F$. To discover what this might be, let $F$ have a variance $\tau^2$--which might be infinite, by the way. Regardless, because the $X_i$ are independent, we easily compute the variance of the means:
$$\eqalign{
\text{Var}(m(X_1, X_2, \ldots, X_n)) &= \text{Var}(\frac{1}{n}(X_1 + X_2 + \cdots + X_n)) \\
&= \left(\frac{1}{n}\right)^2(\text{Var}(X_1) + \text{Var}(X_2) + \cdots + \text{Var}(X_n)) \\
&= \left(\frac{1}{n}\right)^2(\tau^2 + \tau^2 + \cdots + \tau^2) \\
&= \frac{\tau^2}{n}.
}$$
Consequently, the variance of the standardized residuals equals $\tau^2/n \times (\sqrt{n})^2 = \tau^2$: it is constant. The variance of the limiting Normal distribution, then, must be $\tau^2$ itself. (This immediately shows that the theorem can hold only when $\tau^2$ is finite: that is the additional assumption I glossed over earlier.)
(If we had chosen any other measure of spread of $F$ we could still succeed in connecting it to $\sigma^2$, but we would not have found that the corresponding measure of spread of the standardized mean deviation is constant for all $n$, which is a beautiful--albeit inessential--simplification.)
If we had wished, we could have standardized the mean deviations all along by dividing them by $\tau$ as well as multiplying them by $\sqrt{n}$. That would have ensured the limiting distribution is standard Normal, with unit variance. Whether you elect to standardize by $\tau$ in this way or not is really a matter of taste: it's the same theorem and the same conclusion in the end. What mattered was the multiplication by $\sqrt{n}$.
Note that you could multiply the deviations by some factor other than $\sqrt{n}$. You could use $\sqrt{n} + \exp(-n)$, or $n^{1/2 + 1/n}$, or anything else that asymptotically behaves just like $\sqrt{n}$. Any other asymptotic form would, in the limit, reduce $\sigma^2$ to $0$ or blow it up to $\infty$. This observation refines our appreciation of the CLT by showing the extent to which it is flexible concerning how the standardization is performed. We might want to state the CLT, then, in the following way.
Provided the deviation between the mean of a sequence of IID variables (with common distribution $F$) and the underlying expectation is scaled asymptotically by $\sqrt{n}$, this scaled deviation will have a zero-mean Normal limiting distribution whose variance is that of $F$.
Although variances are involved in the statement, they appear only because they are needed to characterize the limiting Normal distribution and relate its spread to that of $F$. This is only an incidental aspect. It has nothing to do with variance being "best" in any sense. The crux of the matter is the asymptotic rescaling by $\sqrt{n}$. | The role of variance in Central Limit Theorem
The classical statement of the Central Limit Theorem (CLT) considers a sequence of independent, identically distributed random variables $X_1, X_2, \ldots, X_n, \ldots$ with common distribution $F$. |
25,325 | The role of variance in Central Limit Theorem | Variance is NOT essential to Central Limit Theorems. It is essential to the the garden variety beginner's i.i.d., Central Limit Theorem, the one most folks know and love, use and abuse.
There is not "the" Central Limit Theorem, there are many Central Limit Theorems:
The garden variety beginner's i.i.d. Central Limit Theorem. Even here, judicious choice of norming constant (so an advanced variant of the beginner's CLT) can allow Central Limit Theorems to be proved for certain random variables having infinite variance (see Feller Vol. II http://www.amazon.com/Introduction-Probability-Theory-Applications-Edition/dp/0471257095 p. 260).
The triangular array Lindeberg-Feller Central Limit Theorem.
http://sites.stat.psu.edu/~dhunter/asymp/lectures/p93to100.pdf
https://en.wikipedia.org/wiki/Central_limit_theorem .
The wild world of anything goes everything in sight dependent Central Limit Theorems for which variance need not even exist. I once proved a Central Limit Theorem for which not only variance didn't exist, but neither did the mean, and in fact not even a 1 - epsilon moment for epsilon arbitrarily small positive. That was a hairy proof, because it "barely" converged, and did so very slowly. Asymptotically it converged to a Normal, in reality, a sample size of millions of terms would be needed for the Normal to be a good approximation. | The role of variance in Central Limit Theorem | Variance is NOT essential to Central Limit Theorems. It is essential to the the garden variety beginner's i.i.d., Central Limit Theorem, the one most folks know and love, use and abuse.
There is not | The role of variance in Central Limit Theorem
Variance is NOT essential to Central Limit Theorems. It is essential to the the garden variety beginner's i.i.d., Central Limit Theorem, the one most folks know and love, use and abuse.
There is not "the" Central Limit Theorem, there are many Central Limit Theorems:
The garden variety beginner's i.i.d. Central Limit Theorem. Even here, judicious choice of norming constant (so an advanced variant of the beginner's CLT) can allow Central Limit Theorems to be proved for certain random variables having infinite variance (see Feller Vol. II http://www.amazon.com/Introduction-Probability-Theory-Applications-Edition/dp/0471257095 p. 260).
The triangular array Lindeberg-Feller Central Limit Theorem.
http://sites.stat.psu.edu/~dhunter/asymp/lectures/p93to100.pdf
https://en.wikipedia.org/wiki/Central_limit_theorem .
The wild world of anything goes everything in sight dependent Central Limit Theorems for which variance need not even exist. I once proved a Central Limit Theorem for which not only variance didn't exist, but neither did the mean, and in fact not even a 1 - epsilon moment for epsilon arbitrarily small positive. That was a hairy proof, because it "barely" converged, and did so very slowly. Asymptotically it converged to a Normal, in reality, a sample size of millions of terms would be needed for the Normal to be a good approximation. | The role of variance in Central Limit Theorem
Variance is NOT essential to Central Limit Theorems. It is essential to the the garden variety beginner's i.i.d., Central Limit Theorem, the one most folks know and love, use and abuse.
There is not |
25,326 | The role of variance in Central Limit Theorem | What is the best measure of spread depends on the situation. Variance is a measure of spread which is a parameter of the normal distribution. So if you models your data with a nornal distribition, the (arithmetic) mean and the empirical variance is the best estimators (they are "sufficient") of the parameters of that normal distribution. That also gives the link to the central limit theorem, since that is about a normal limit, that is, the limit is a normal distribution. So if yoy have enough observations that the central limit theorem is relevant, again you can use the normal distribution, and the empirical variance is the natural description of variability, because it is tied to the normal distribution.
Without this link to the normal distribution, there is no sense in which the varoiance is best or even a natual descriptor of variability. | The role of variance in Central Limit Theorem | What is the best measure of spread depends on the situation. Variance is a measure of spread which is a parameter of the normal distribution. So if you models your data with a nornal distribition, the | The role of variance in Central Limit Theorem
What is the best measure of spread depends on the situation. Variance is a measure of spread which is a parameter of the normal distribution. So if you models your data with a nornal distribition, the (arithmetic) mean and the empirical variance is the best estimators (they are "sufficient") of the parameters of that normal distribution. That also gives the link to the central limit theorem, since that is about a normal limit, that is, the limit is a normal distribution. So if yoy have enough observations that the central limit theorem is relevant, again you can use the normal distribution, and the empirical variance is the natural description of variability, because it is tied to the normal distribution.
Without this link to the normal distribution, there is no sense in which the varoiance is best or even a natual descriptor of variability. | The role of variance in Central Limit Theorem
What is the best measure of spread depends on the situation. Variance is a measure of spread which is a parameter of the normal distribution. So if you models your data with a nornal distribition, the |
25,327 | The role of variance in Central Limit Theorem | Addressing the second question only:
I guess that variance has been the dispersion measure of choice for most of the statistician mainly for historical reasons and then because of inertia for most of non statistician practitioners.
Although I cannot cite by heart a specific reference with some rigorous definition of spread, I can offer heuristic for its mathematical characterization: central moments (i.e., $ E[(X-\mu)^k]$) are very useful for weighing deviations from the distribution's center and their probabilities/frequencies, but only if $k$ is integer and even.
Why? Because that way deviations below the center (negative) will sum up with deviations above the center (positive), instead of partially canceling them, like average does, for instance. As you can think, absolute central moments (i.e., $E(|X-\mu|^k)$) can also do that job and, more, for any $k>0$ (ok, both moments are equal if $k$ is even).
So a large amount of small deviations (both positive and negative) with few large deviations are characteristics of little dispersion, which will yield a relatively small even central moment. Lots of large deviations will yield a relatively large even central moment.
Remember when I said about the historical reasons above? Before computational power became cheap and available, one needed to rely only on mathematical, analytical skills to deal with the development of statistical theories.
Problems involving central moments were easier to tackle than ones involving absolute central moments. For instance, optimization problems involving central moments (e.g., least squares) require only calculus, while optimization involving absolute central moments with $k$ odd (for $k=1$ you get a simplex problem), which cannot be solved with calculus alone. | The role of variance in Central Limit Theorem | Addressing the second question only:
I guess that variance has been the dispersion measure of choice for most of the statistician mainly for historical reasons and then because of inertia for most of | The role of variance in Central Limit Theorem
Addressing the second question only:
I guess that variance has been the dispersion measure of choice for most of the statistician mainly for historical reasons and then because of inertia for most of non statistician practitioners.
Although I cannot cite by heart a specific reference with some rigorous definition of spread, I can offer heuristic for its mathematical characterization: central moments (i.e., $ E[(X-\mu)^k]$) are very useful for weighing deviations from the distribution's center and their probabilities/frequencies, but only if $k$ is integer and even.
Why? Because that way deviations below the center (negative) will sum up with deviations above the center (positive), instead of partially canceling them, like average does, for instance. As you can think, absolute central moments (i.e., $E(|X-\mu|^k)$) can also do that job and, more, for any $k>0$ (ok, both moments are equal if $k$ is even).
So a large amount of small deviations (both positive and negative) with few large deviations are characteristics of little dispersion, which will yield a relatively small even central moment. Lots of large deviations will yield a relatively large even central moment.
Remember when I said about the historical reasons above? Before computational power became cheap and available, one needed to rely only on mathematical, analytical skills to deal with the development of statistical theories.
Problems involving central moments were easier to tackle than ones involving absolute central moments. For instance, optimization problems involving central moments (e.g., least squares) require only calculus, while optimization involving absolute central moments with $k$ odd (for $k=1$ you get a simplex problem), which cannot be solved with calculus alone. | The role of variance in Central Limit Theorem
Addressing the second question only:
I guess that variance has been the dispersion measure of choice for most of the statistician mainly for historical reasons and then because of inertia for most of |
25,328 | How to set custom contrasts with lmer in R | For the following steps, we need the data frame in the long format. The data frame dat contains the dependent variable result, the categorical predictor cond (levels: a, b, and c), and the random factor s.
library(tidyr)
dat <- gather(temp, cond, result, a, b, c)
In the following, I will illustrate two approaches to create a contrast matrix corresponding to the conditions you want to compare:
$a - \frac{b+c}{2}$
$b - c$
Custom contrasts
The matrix mat corresponds to the level differences.
mat <- rbind(c(1, -0.5, -0.5), # a vs. (b + c) / 2
c(0, 1, -1)) # b vs. c
To create the actual contrast matrix, we compute the generalized inverse with ginv (from MASS).
library(MASS)
cMat <- ginv(mat)
# [,1] [,2]
# [1,] 0.6666667 -7.130169e-17
# [2,] -0.3333333 5.000000e-01
# [3,] -0.3333333 -5.000000e-01
This contrast matrix cMat can be used in lmer.
library(lme4)
res <- lmer(result ~ cond + (1|s), data = dat,
contrasts = list(cond = cMat))
coef(summary(res))
# Estimate Std. Error t value
# (Intercept) -2.948115 0.0946025 -31.163182
# cond1 1.351517 0.2006822 6.734612
# cond2 1.153918 0.2317279 4.979625
As you can see, the fixed-effect estimates correspond to the differences specified above. Furthermore, the intercept represents the overall mean.
Helmert contrast with contr.helmert
You can also use the built-in contr.helmert function to create the contrast matrix.
cHelmert <- contr.helmert(3)
# [,1] [,2]
# 1 -1 -1
# 2 1 -1
# 3 0 2
However, the order does not correspond to the one you specified in the question.
Hence, we have to reverse the order of columns and rows. The first column corresponds to b vs. a and the second one corresponds to c vs. the mean of b and a.
cHelmert2 <- cHelmert[c(3:1), 2:1]
# [,1] [,2]
# 3 2 0
# 2 -1 1
# 1 -1 -1
Compare the contrast matrix cHelmert2 to cMat. You will notice that the columns are scaled versions of the other matrix.
The result of lmer is:
library(lme4)
res2 <- lmer(result ~ cond + (1|s), data = dat,
contrasts = list(cond = cHelmert2))
coef(summary(res2))
# Estimate Std. Error t value
# (Intercept) -2.9481150 0.09460250 -31.163182
# cond1 0.4505056 0.06689407 6.734612
# cond2 0.5769590 0.11586393 4.979625
This contrast matrix allows fo the same comparisons as the custom contrast matrix. However, since the values in the matrix are different, the fixed-effects coefficients are different too. Not suprisingly, the $t$-values are the same. | How to set custom contrasts with lmer in R | For the following steps, we need the data frame in the long format. The data frame dat contains the dependent variable result, the categorical predictor cond (levels: a, b, and c), and the random fact | How to set custom contrasts with lmer in R
For the following steps, we need the data frame in the long format. The data frame dat contains the dependent variable result, the categorical predictor cond (levels: a, b, and c), and the random factor s.
library(tidyr)
dat <- gather(temp, cond, result, a, b, c)
In the following, I will illustrate two approaches to create a contrast matrix corresponding to the conditions you want to compare:
$a - \frac{b+c}{2}$
$b - c$
Custom contrasts
The matrix mat corresponds to the level differences.
mat <- rbind(c(1, -0.5, -0.5), # a vs. (b + c) / 2
c(0, 1, -1)) # b vs. c
To create the actual contrast matrix, we compute the generalized inverse with ginv (from MASS).
library(MASS)
cMat <- ginv(mat)
# [,1] [,2]
# [1,] 0.6666667 -7.130169e-17
# [2,] -0.3333333 5.000000e-01
# [3,] -0.3333333 -5.000000e-01
This contrast matrix cMat can be used in lmer.
library(lme4)
res <- lmer(result ~ cond + (1|s), data = dat,
contrasts = list(cond = cMat))
coef(summary(res))
# Estimate Std. Error t value
# (Intercept) -2.948115 0.0946025 -31.163182
# cond1 1.351517 0.2006822 6.734612
# cond2 1.153918 0.2317279 4.979625
As you can see, the fixed-effect estimates correspond to the differences specified above. Furthermore, the intercept represents the overall mean.
Helmert contrast with contr.helmert
You can also use the built-in contr.helmert function to create the contrast matrix.
cHelmert <- contr.helmert(3)
# [,1] [,2]
# 1 -1 -1
# 2 1 -1
# 3 0 2
However, the order does not correspond to the one you specified in the question.
Hence, we have to reverse the order of columns and rows. The first column corresponds to b vs. a and the second one corresponds to c vs. the mean of b and a.
cHelmert2 <- cHelmert[c(3:1), 2:1]
# [,1] [,2]
# 3 2 0
# 2 -1 1
# 1 -1 -1
Compare the contrast matrix cHelmert2 to cMat. You will notice that the columns are scaled versions of the other matrix.
The result of lmer is:
library(lme4)
res2 <- lmer(result ~ cond + (1|s), data = dat,
contrasts = list(cond = cHelmert2))
coef(summary(res2))
# Estimate Std. Error t value
# (Intercept) -2.9481150 0.09460250 -31.163182
# cond1 0.4505056 0.06689407 6.734612
# cond2 0.5769590 0.11586393 4.979625
This contrast matrix allows fo the same comparisons as the custom contrast matrix. However, since the values in the matrix are different, the fixed-effects coefficients are different too. Not suprisingly, the $t$-values are the same. | How to set custom contrasts with lmer in R
For the following steps, we need the data frame in the long format. The data frame dat contains the dependent variable result, the categorical predictor cond (levels: a, b, and c), and the random fact |
25,329 | Is this interpretation of sparsity accurate? | Yes, although your confusion here is understandable, since the term "sparsity" is hard to define clearly in this context.
In the sense of the sparse argument to removeSparseTerms(), sparsity refers to the threshold of relative document frequency for a term, above which the term will be removed. Relative document frequency here means a proportion. As the help page for the command states (although not very clearly), sparsity is smaller as it approaches 1.0. (Note that sparsity cannot take values of 0 or 1.0, only values in between.)
So your interpretation is correct in that sparse = 0.99 will remove only terms that are more sparse than 0.99.
The exact interpretation for sparse = 0.99 is that for term $j$, you will retain all terms for which
$df_j > N * (1 - 0.99)$, where $N$ is the number of documents -- in this case probably all terms will be retained (see example below).
Near the other extreme, if sparse = .01, then only terms that appear in (nearly) every document will be retained. (Of course this depends on the number of terms and the number of documents, and in natural language, common words like "the" are likely to occur in every document and hence never be "sparse".)
An example of the sparsity threshold of 0.99, where a term that occurs at most in (first example) less than 0.01 documents, and (second example) just over 0.01 documents:
> # second term occurs in just 1 of 101 documents
> myTdm1 <- as.DocumentTermMatrix(slam::as.simple_triplet_matrix(matrix(c(rep(1, 101), rep(1,1), rep(0, 100)), ncol=2)),
+ weighting = weightTf)
> removeSparseTerms(myTdm1, .99)
<<DocumentTermMatrix (documents: 101, terms: 1)>>
Non-/sparse entries: 101/0
Sparsity : 0%
Maximal term length: 2
Weighting : term frequency (tf)
>
> # second term occurs in 2 of 101 documents
> myTdm2 <- as.DocumentTermMatrix(slam::as.simple_triplet_matrix(matrix(c(rep(1, 101), rep(1,2), rep(0, 99)), ncol=2)),
+ weighting = weightTf)
> removeSparseTerms(myTdm2, .99)
<<DocumentTermMatrix (documents: 101, terms: 2)>>
Non-/sparse entries: 103/99
Sparsity : 49%
Maximal term length: 2
Weighting : term frequency (tf)
Here are a few additional examples with actual text and terms:
> myText <- c("the quick brown furry fox jumped over a second furry brown fox",
"the sparse brown furry matrix",
"the quick matrix")
> require(tm)
> myVCorpus <- VCorpus(VectorSource(myText))
> myTdm <- DocumentTermMatrix(myVCorpus)
> as.matrix(myTdm)
Terms
Docs brown fox furry jumped matrix over quick second sparse the
1 2 2 2 1 0 1 1 1 0 1
2 1 0 1 0 1 0 0 0 1 1
3 0 0 0 0 1 0 1 0 0 1
> as.matrix(removeSparseTerms(myTdm, .01))
Terms
Docs the
1 1
2 1
3 1
> as.matrix(removeSparseTerms(myTdm, .99))
Terms
Docs brown fox furry jumped matrix over quick second sparse the
1 2 2 2 1 0 1 1 1 0 1
2 1 0 1 0 1 0 0 0 1 1
3 0 0 0 0 1 0 1 0 0 1
> as.matrix(removeSparseTerms(myTdm, .5))
Terms
Docs brown furry matrix quick the
1 2 2 0 1 1
2 1 1 1 0 1
3 0 0 1 1 1
In the last example with sparse = 0.34, only terms occurring in two-thirds of the documents were retained.
An alternative approach for trimming terms from document-term matrixes based on a document frequency is the text analysis package quanteda. The same functionality here refers not to sparsity but rather directly to the document frequency of terms (as in tf-idf).
> require(quanteda)
> myDfm <- dfm(myText, verbose = FALSE)
> docfreq(myDfm)
a brown fox furry jumped matrix over quick second sparse the
1 2 1 2 1 2 1 2 1 1 3
> trim(myDfm, minDoc = 2)
Features occurring in fewer than 2 documents: 6
Document-feature matrix of: 3 documents, 5 features.
3 x 5 sparse Matrix of class "dfmSparse"
features
docs brown furry the matrix quick
text1 2 2 1 0 1
text2 1 1 1 1 0
text3 0 0 1 1 1
This usage seems much more straightforward to me. | Is this interpretation of sparsity accurate? | Yes, although your confusion here is understandable, since the term "sparsity" is hard to define clearly in this context.
In the sense of the sparse argument to removeSparseTerms(), sparsity refers | Is this interpretation of sparsity accurate?
Yes, although your confusion here is understandable, since the term "sparsity" is hard to define clearly in this context.
In the sense of the sparse argument to removeSparseTerms(), sparsity refers to the threshold of relative document frequency for a term, above which the term will be removed. Relative document frequency here means a proportion. As the help page for the command states (although not very clearly), sparsity is smaller as it approaches 1.0. (Note that sparsity cannot take values of 0 or 1.0, only values in between.)
So your interpretation is correct in that sparse = 0.99 will remove only terms that are more sparse than 0.99.
The exact interpretation for sparse = 0.99 is that for term $j$, you will retain all terms for which
$df_j > N * (1 - 0.99)$, where $N$ is the number of documents -- in this case probably all terms will be retained (see example below).
Near the other extreme, if sparse = .01, then only terms that appear in (nearly) every document will be retained. (Of course this depends on the number of terms and the number of documents, and in natural language, common words like "the" are likely to occur in every document and hence never be "sparse".)
An example of the sparsity threshold of 0.99, where a term that occurs at most in (first example) less than 0.01 documents, and (second example) just over 0.01 documents:
> # second term occurs in just 1 of 101 documents
> myTdm1 <- as.DocumentTermMatrix(slam::as.simple_triplet_matrix(matrix(c(rep(1, 101), rep(1,1), rep(0, 100)), ncol=2)),
+ weighting = weightTf)
> removeSparseTerms(myTdm1, .99)
<<DocumentTermMatrix (documents: 101, terms: 1)>>
Non-/sparse entries: 101/0
Sparsity : 0%
Maximal term length: 2
Weighting : term frequency (tf)
>
> # second term occurs in 2 of 101 documents
> myTdm2 <- as.DocumentTermMatrix(slam::as.simple_triplet_matrix(matrix(c(rep(1, 101), rep(1,2), rep(0, 99)), ncol=2)),
+ weighting = weightTf)
> removeSparseTerms(myTdm2, .99)
<<DocumentTermMatrix (documents: 101, terms: 2)>>
Non-/sparse entries: 103/99
Sparsity : 49%
Maximal term length: 2
Weighting : term frequency (tf)
Here are a few additional examples with actual text and terms:
> myText <- c("the quick brown furry fox jumped over a second furry brown fox",
"the sparse brown furry matrix",
"the quick matrix")
> require(tm)
> myVCorpus <- VCorpus(VectorSource(myText))
> myTdm <- DocumentTermMatrix(myVCorpus)
> as.matrix(myTdm)
Terms
Docs brown fox furry jumped matrix over quick second sparse the
1 2 2 2 1 0 1 1 1 0 1
2 1 0 1 0 1 0 0 0 1 1
3 0 0 0 0 1 0 1 0 0 1
> as.matrix(removeSparseTerms(myTdm, .01))
Terms
Docs the
1 1
2 1
3 1
> as.matrix(removeSparseTerms(myTdm, .99))
Terms
Docs brown fox furry jumped matrix over quick second sparse the
1 2 2 2 1 0 1 1 1 0 1
2 1 0 1 0 1 0 0 0 1 1
3 0 0 0 0 1 0 1 0 0 1
> as.matrix(removeSparseTerms(myTdm, .5))
Terms
Docs brown furry matrix quick the
1 2 2 0 1 1
2 1 1 1 0 1
3 0 0 1 1 1
In the last example with sparse = 0.34, only terms occurring in two-thirds of the documents were retained.
An alternative approach for trimming terms from document-term matrixes based on a document frequency is the text analysis package quanteda. The same functionality here refers not to sparsity but rather directly to the document frequency of terms (as in tf-idf).
> require(quanteda)
> myDfm <- dfm(myText, verbose = FALSE)
> docfreq(myDfm)
a brown fox furry jumped matrix over quick second sparse the
1 2 1 2 1 2 1 2 1 1 3
> trim(myDfm, minDoc = 2)
Features occurring in fewer than 2 documents: 6
Document-feature matrix of: 3 documents, 5 features.
3 x 5 sparse Matrix of class "dfmSparse"
features
docs brown furry the matrix quick
text1 2 2 1 0 1
text2 1 1 1 1 0
text3 0 0 1 1 1
This usage seems much more straightforward to me. | Is this interpretation of sparsity accurate?
Yes, although your confusion here is understandable, since the term "sparsity" is hard to define clearly in this context.
In the sense of the sparse argument to removeSparseTerms(), sparsity refers |
25,330 | Why do people like smooth data? | "Natura non facit saltus" is an old principle in philosophy. Also, beauty and harmony are such principles. Another philosophical principle that has impact on statistics is qualitative thinking: Traditionally we don't think in effect sizes but whether an effect is there or not. This let to hypothesis testing. Estimators are too precise for your perception of nature. Take it as it is.
Statistics has to serve the human perception. So discontinuity points are disliked. One would immediately ask: Why is exactly at this a discontinuity? Especially in density estimation, these discontinuity points are mostly due to non asymptotical nature of real data. But you don't want to learn about your certain finite sample but about the underlying natural fact. If you believe this nature doesn't jump, then you need smooth estimators.
From a strict mathematical point of view, there is hardly a reason for it. Also, since Leibniz and Newton natural phenomena became known that are not smooth. Talk to the natural scientist you're working for. Challenge his view of smoothness/discontinuity and then do what you both decided to be most helpful for his understanding. | Why do people like smooth data? | "Natura non facit saltus" is an old principle in philosophy. Also, beauty and harmony are such principles. Another philosophical principle that has impact on statistics is qualitative thinking: Tradit | Why do people like smooth data?
"Natura non facit saltus" is an old principle in philosophy. Also, beauty and harmony are such principles. Another philosophical principle that has impact on statistics is qualitative thinking: Traditionally we don't think in effect sizes but whether an effect is there or not. This let to hypothesis testing. Estimators are too precise for your perception of nature. Take it as it is.
Statistics has to serve the human perception. So discontinuity points are disliked. One would immediately ask: Why is exactly at this a discontinuity? Especially in density estimation, these discontinuity points are mostly due to non asymptotical nature of real data. But you don't want to learn about your certain finite sample but about the underlying natural fact. If you believe this nature doesn't jump, then you need smooth estimators.
From a strict mathematical point of view, there is hardly a reason for it. Also, since Leibniz and Newton natural phenomena became known that are not smooth. Talk to the natural scientist you're working for. Challenge his view of smoothness/discontinuity and then do what you both decided to be most helpful for his understanding. | Why do people like smooth data?
"Natura non facit saltus" is an old principle in philosophy. Also, beauty and harmony are such principles. Another philosophical principle that has impact on statistics is qualitative thinking: Tradit |
25,331 | Why do people like smooth data? | There are two more reasons of practical matters. The first one is that analytical functions are much easier to work with mathematically, and therefore prove theorems about your algorithms and give them a stronger foundation.
The second is sensitivity. Say you have a machine learner $M$ whose output has a discontinuity at $x=x_0$. Then you would get very different results for $x_0 - \epsilon$ and $x_0 + \epsilon$, but that's OK because we made it discontinuous. Now, if you train your model with slightly different data ($\tilde M$), where the random noise is just a tiny bit different, the discontinuity will now be at $\tilde x_0$, probably very close to $x_0$, but not quite, and now, for some values of $\epsilon$, $x_0 + \epsilon$ has a very different value for $M$ and for $\tilde M$. | Why do people like smooth data? | There are two more reasons of practical matters. The first one is that analytical functions are much easier to work with mathematically, and therefore prove theorems about your algorithms and give the | Why do people like smooth data?
There are two more reasons of practical matters. The first one is that analytical functions are much easier to work with mathematically, and therefore prove theorems about your algorithms and give them a stronger foundation.
The second is sensitivity. Say you have a machine learner $M$ whose output has a discontinuity at $x=x_0$. Then you would get very different results for $x_0 - \epsilon$ and $x_0 + \epsilon$, but that's OK because we made it discontinuous. Now, if you train your model with slightly different data ($\tilde M$), where the random noise is just a tiny bit different, the discontinuity will now be at $\tilde x_0$, probably very close to $x_0$, but not quite, and now, for some values of $\epsilon$, $x_0 + \epsilon$ has a very different value for $M$ and for $\tilde M$. | Why do people like smooth data?
There are two more reasons of practical matters. The first one is that analytical functions are much easier to work with mathematically, and therefore prove theorems about your algorithms and give the |
25,332 | Why do people like smooth data? | There are many motivations, depending on the problem. But the idea is the same: add a priori knowledge about some problem to achieve a better solution and cope with complexity.
A more way to put it is: model selection. Here a nice example on model selection.
Another idea, deeply related to it is to find a similarity measure of data samples (there are different terms that relate to that idea: topographical mappings, distance metric, manifold learning,...).
Now, let us consider a practical example: optical character recognition. If you take the image of a character, you would expect the classifier to deal with invariances: if you rotate, displace or scale the image, it should be able to detect it. Also, if you apply some one modification slightly to the input, you would expect the answer/behaviour of your classifier to vary just slightly as well, because both samples (the original and the modified are very similar). This is where the enforcement of smoothness comes in.
There is a wealth of papers dealing with this idea, but this one (transformation invariance in pattern recognition, tangent distance and tangent propagation, Simard et. al) illustrates these ideas in great detail | Why do people like smooth data? | There are many motivations, depending on the problem. But the idea is the same: add a priori knowledge about some problem to achieve a better solution and cope with complexity.
A more way to put it is | Why do people like smooth data?
There are many motivations, depending on the problem. But the idea is the same: add a priori knowledge about some problem to achieve a better solution and cope with complexity.
A more way to put it is: model selection. Here a nice example on model selection.
Another idea, deeply related to it is to find a similarity measure of data samples (there are different terms that relate to that idea: topographical mappings, distance metric, manifold learning,...).
Now, let us consider a practical example: optical character recognition. If you take the image of a character, you would expect the classifier to deal with invariances: if you rotate, displace or scale the image, it should be able to detect it. Also, if you apply some one modification slightly to the input, you would expect the answer/behaviour of your classifier to vary just slightly as well, because both samples (the original and the modified are very similar). This is where the enforcement of smoothness comes in.
There is a wealth of papers dealing with this idea, but this one (transformation invariance in pattern recognition, tangent distance and tangent propagation, Simard et. al) illustrates these ideas in great detail | Why do people like smooth data?
There are many motivations, depending on the problem. But the idea is the same: add a priori knowledge about some problem to achieve a better solution and cope with complexity.
A more way to put it is |
25,333 | Approximation of logarithm of standard normal CDF for x<0 | Even a simple least squares cubic fit to $\log(\Phi(x))$ values for $x$ between -5 and 0 seems to be fairly adequate.
Just to get a quick sense of it I generated $x$ values every 0.01 between -5 and 0, and tried least squares cubic and quintic (5th degree) polynomial fits to $\log_2(\Phi(x))$. I presume you can do that as easily as I did, so I won't labor the point.
The maximum absolute error in $\log_2(\Phi(x))$ for the quintic is $5.2\times 10^{-4}$, which occurs at zero.
[It's not completely clear what you mean by "within 0.2 + 10% or so". If you could elaborate so as to make your criterion explicit, then I could address that in detail, and maybe adjust the weights to better optimize your criterion.]
When evaluating polynomials, if speed matters, you should keep Horner's method in mind.
As cardinal suggested, the plot is quite illustrative. Since I'd already generated one, I should have put it here:
Here's the (signed) error (absolute scale error in the logs):
it looks much as we might expect for a least squares fit. The lack of fit is pretty moderate; for many purposes that would be fine.
An alternative is you can flip the Karagiannidis & Lioumpas approximation (see here) for the upper tail around to the lower tail (by replacing $x$ by $-x$ in their formula) and taking logs:
$$Q(x)\approx\frac{\left( 1-e^{-1.4x}\right) e^{-\frac{x^{2}}{2}}}{1.135\sqrt{2\pi}x}, x >0 $$
So we get
$$\ln(\Phi(x))\approx \ln(1-e^{1.4x})-\ln(-x) -\frac{x^2}{2} - 1.04557$$
to get base 2 logs, you just multiply the result by $\log_2(e)$
This is less accurate than the quintic fit I mentioned, and likely slower to evaluate because of the logs and exponentiation. Still, it's nice and short, which has some advantages. Note that it wasn't designed for the log-scale.
The original paper has K&L's Equation 6 as:
$$\frac{(1-e^{-Ax}) e^{-x^2}}{B\sqrt{\pi}x}\approx\text{erfc}(x)$$
For $x$ values on the range [0,20] they suggest $A=1.98$ and $B=1.135$.
Dividing $x$ through by $\sqrt{2}$ to obtain $Q$, that suggests the formula on the Wikipedia page ($1.98/\sqrt{2}\approx 1.40007$)
Let's look at the quality of the approximation on the log-scale.
The purple dashed line is the K&L approximation. Now let's look at the error:
The size of the error gets quite a bit larger than our quintic. The fact that it's nearly linear in $x$ at the left half of the range suggests that we might improve the error by adding about $0.02x$ or $0.025x$ to the formula in the logs - but this would make the approximation a little worse for values near -1. Whether one would do that depends on what characteristics are desired. | Approximation of logarithm of standard normal CDF for x<0 | Even a simple least squares cubic fit to $\log(\Phi(x))$ values for $x$ between -5 and 0 seems to be fairly adequate.
Just to get a quick sense of it I generated $x$ values every 0.01 between -5 and | Approximation of logarithm of standard normal CDF for x<0
Even a simple least squares cubic fit to $\log(\Phi(x))$ values for $x$ between -5 and 0 seems to be fairly adequate.
Just to get a quick sense of it I generated $x$ values every 0.01 between -5 and 0, and tried least squares cubic and quintic (5th degree) polynomial fits to $\log_2(\Phi(x))$. I presume you can do that as easily as I did, so I won't labor the point.
The maximum absolute error in $\log_2(\Phi(x))$ for the quintic is $5.2\times 10^{-4}$, which occurs at zero.
[It's not completely clear what you mean by "within 0.2 + 10% or so". If you could elaborate so as to make your criterion explicit, then I could address that in detail, and maybe adjust the weights to better optimize your criterion.]
When evaluating polynomials, if speed matters, you should keep Horner's method in mind.
As cardinal suggested, the plot is quite illustrative. Since I'd already generated one, I should have put it here:
Here's the (signed) error (absolute scale error in the logs):
it looks much as we might expect for a least squares fit. The lack of fit is pretty moderate; for many purposes that would be fine.
An alternative is you can flip the Karagiannidis & Lioumpas approximation (see here) for the upper tail around to the lower tail (by replacing $x$ by $-x$ in their formula) and taking logs:
$$Q(x)\approx\frac{\left( 1-e^{-1.4x}\right) e^{-\frac{x^{2}}{2}}}{1.135\sqrt{2\pi}x}, x >0 $$
So we get
$$\ln(\Phi(x))\approx \ln(1-e^{1.4x})-\ln(-x) -\frac{x^2}{2} - 1.04557$$
to get base 2 logs, you just multiply the result by $\log_2(e)$
This is less accurate than the quintic fit I mentioned, and likely slower to evaluate because of the logs and exponentiation. Still, it's nice and short, which has some advantages. Note that it wasn't designed for the log-scale.
The original paper has K&L's Equation 6 as:
$$\frac{(1-e^{-Ax}) e^{-x^2}}{B\sqrt{\pi}x}\approx\text{erfc}(x)$$
For $x$ values on the range [0,20] they suggest $A=1.98$ and $B=1.135$.
Dividing $x$ through by $\sqrt{2}$ to obtain $Q$, that suggests the formula on the Wikipedia page ($1.98/\sqrt{2}\approx 1.40007$)
Let's look at the quality of the approximation on the log-scale.
The purple dashed line is the K&L approximation. Now let's look at the error:
The size of the error gets quite a bit larger than our quintic. The fact that it's nearly linear in $x$ at the left half of the range suggests that we might improve the error by adding about $0.02x$ or $0.025x$ to the formula in the logs - but this would make the approximation a little worse for values near -1. Whether one would do that depends on what characteristics are desired. | Approximation of logarithm of standard normal CDF for x<0
Even a simple least squares cubic fit to $\log(\Phi(x))$ values for $x$ between -5 and 0 seems to be fairly adequate.
Just to get a quick sense of it I generated $x$ values every 0.01 between -5 and |
25,334 | Approximation of logarithm of standard normal CDF for x<0 | Here is an alternate solution for neural network users:
You can approximate the CDF with 1 / (1 + 2*exp(-sqrt(2*pi)*x)) (extending this approximation).
And exploit the fact that most deep learning framework have a numerically stable implementation of log(1 + exp(x)) as the softplus activation function.
The resulting formula can be written in two lines of pytorch:
def log_standard_normal_cdf(x):
return -F.softplus(np.log(2) - x*np.sqrt(2*np.pi)) | Approximation of logarithm of standard normal CDF for x<0 | Here is an alternate solution for neural network users:
You can approximate the CDF with 1 / (1 + 2*exp(-sqrt(2*pi)*x)) (extending this approximation).
And exploit the fact that most deep learning fra | Approximation of logarithm of standard normal CDF for x<0
Here is an alternate solution for neural network users:
You can approximate the CDF with 1 / (1 + 2*exp(-sqrt(2*pi)*x)) (extending this approximation).
And exploit the fact that most deep learning framework have a numerically stable implementation of log(1 + exp(x)) as the softplus activation function.
The resulting formula can be written in two lines of pytorch:
def log_standard_normal_cdf(x):
return -F.softplus(np.log(2) - x*np.sqrt(2*np.pi)) | Approximation of logarithm of standard normal CDF for x<0
Here is an alternate solution for neural network users:
You can approximate the CDF with 1 / (1 + 2*exp(-sqrt(2*pi)*x)) (extending this approximation).
And exploit the fact that most deep learning fra |
25,335 | Approximation of logarithm of standard normal CDF for x<0 | To cover a wider range than originally requested, I eventually came up with this rational approximation
$$ \ln(\Phi(x<0)) \approx -\frac{1}{2}x^2 -4.8 + 2509\frac{x-13}{(x-40)^2(x-5)} $$
which has absolute error under 0.04 out to 20 standard deviations, after which the error may exceed that but remains under 0.04% of the value (as far as I can verify with numerical calculations). | Approximation of logarithm of standard normal CDF for x<0 | To cover a wider range than originally requested, I eventually came up with this rational approximation
$$ \ln(\Phi(x<0)) \approx -\frac{1}{2}x^2 -4.8 + 2509\frac{x-13}{(x-40)^2(x-5)} $$
which has abs | Approximation of logarithm of standard normal CDF for x<0
To cover a wider range than originally requested, I eventually came up with this rational approximation
$$ \ln(\Phi(x<0)) \approx -\frac{1}{2}x^2 -4.8 + 2509\frac{x-13}{(x-40)^2(x-5)} $$
which has absolute error under 0.04 out to 20 standard deviations, after which the error may exceed that but remains under 0.04% of the value (as far as I can verify with numerical calculations). | Approximation of logarithm of standard normal CDF for x<0
To cover a wider range than originally requested, I eventually came up with this rational approximation
$$ \ln(\Phi(x<0)) \approx -\frac{1}{2}x^2 -4.8 + 2509\frac{x-13}{(x-40)^2(x-5)} $$
which has abs |
25,336 | Approximation of logarithm of standard normal CDF for x<0 | I recently had the same problem and found what I think is a nicer solution. The Faddeeva package has a set of accurate functions for computing erf(z), erfc(z), etc. They all start by computing the Faddeeva function w(z):
\begin{equation}
w(z) = e^{-z^2} \text{erfc}(-iz)
\end{equation}
you can show that the log of the normal cdf is
\begin{eqnarray}
\log\Phi(z) &= \log\left[ \frac{1}{2}\left( 1 + \text{erf}\left( \frac{z}{\sqrt{2}} \right) \right) \right] \\
&= \log\left(\frac{1}{2}\right) + \log\left[ 1 + \text{erf}\left(\frac{z}{\sqrt{2}} \right) \right] \\
&= \log\left(\frac{1}{2}\right) + \log\left[e^{-z^2} w\left(\frac{-iz}{\sqrt{2}}\right) \right] \\
&= \log\left(\frac{1}{2}\right) - \frac{z^2}{2} + \log\left[ w\left(\frac{-iz}{\sqrt{2}}\right) \right]
\end{eqnarray}
So now we can compute three easy quantities that are all nicely behaved and get $\log\Phi(z)$ also nicely behaved for very small z. I verified that you get exactly the same values as a regular normcdf for the domain in which it is valid.
For very small z, I don't know the "right" answer, but for z=-100 you get -5005.5242 which normally would just give you -inf. And this method has the advantage of using existing packages for doing the tricky computations so you don't have to make up your own approximations and it is fast.
In python, $w(z)$ is available as scipy.special.wofz. | Approximation of logarithm of standard normal CDF for x<0 | I recently had the same problem and found what I think is a nicer solution. The Faddeeva package has a set of accurate functions for computing erf(z), erfc(z), etc. They all start by computing the F | Approximation of logarithm of standard normal CDF for x<0
I recently had the same problem and found what I think is a nicer solution. The Faddeeva package has a set of accurate functions for computing erf(z), erfc(z), etc. They all start by computing the Faddeeva function w(z):
\begin{equation}
w(z) = e^{-z^2} \text{erfc}(-iz)
\end{equation}
you can show that the log of the normal cdf is
\begin{eqnarray}
\log\Phi(z) &= \log\left[ \frac{1}{2}\left( 1 + \text{erf}\left( \frac{z}{\sqrt{2}} \right) \right) \right] \\
&= \log\left(\frac{1}{2}\right) + \log\left[ 1 + \text{erf}\left(\frac{z}{\sqrt{2}} \right) \right] \\
&= \log\left(\frac{1}{2}\right) + \log\left[e^{-z^2} w\left(\frac{-iz}{\sqrt{2}}\right) \right] \\
&= \log\left(\frac{1}{2}\right) - \frac{z^2}{2} + \log\left[ w\left(\frac{-iz}{\sqrt{2}}\right) \right]
\end{eqnarray}
So now we can compute three easy quantities that are all nicely behaved and get $\log\Phi(z)$ also nicely behaved for very small z. I verified that you get exactly the same values as a regular normcdf for the domain in which it is valid.
For very small z, I don't know the "right" answer, but for z=-100 you get -5005.5242 which normally would just give you -inf. And this method has the advantage of using existing packages for doing the tricky computations so you don't have to make up your own approximations and it is fast.
In python, $w(z)$ is available as scipy.special.wofz. | Approximation of logarithm of standard normal CDF for x<0
I recently had the same problem and found what I think is a nicer solution. The Faddeeva package has a set of accurate functions for computing erf(z), erfc(z), etc. They all start by computing the F |
25,337 | Approximation of logarithm of standard normal CDF for x<0 | We can use l'Hôpital's Rule:
$$
\lim_{x \rightarrow -\infty} \frac{\Phi(x)}{\phi(x)} = \frac{\phi(x)}{-x\phi(x)}=\frac{1}{-x}
$$
So:
$$
\lim_{x \rightarrow -\infty} \Phi(x) = \frac{\phi(x)}{-x}
$$
And then we get:
$$
\lim_{x \rightarrow -\infty} \log \Phi(x) = \log(\frac{1}{\sqrt{2\pi}}) -0.5 x^2 - \log(-x)
$$
This approximation should be accurate if x is small.
Also try this matlab code, it gives really good approximation: I found it in the GPML toolbox
% Safe computation of logphi(z) = log(normcdf(z)) and its derivatives
% dlogphi(z) = normpdf(x)/normcdf(x).
% The function is based on index 5725 in Hart et al. and gsl_sf_log_erfc_e.
%
% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2013-11-13.
function [lp,dlp,d2lp,d3lp] = logphi(z)
z = real(z); % support for real arguments only
lp = zeros(size(z)); % allocate memory
id1 = z.*z<0.0492; % first case: close to zero
lp0 = -z(id1)/sqrt(2*pi);
c = [ 0.00048204; -0.00142906; 0.0013200243174; 0.0009461589032;
-0.0045563339802; 0.00556964649138; 0.00125993961762116;
-0.01621575378835404; 0.02629651521057465; -0.001829764677455021;
2*(1-pi/3); (4-pi)/3; 1; 1];
f = 0; for i=1:14, f = lp0.*(c(i)+f); end, lp(id1) = -2*f-log(2);
id2 = z<-11.3137; % second case: very small
r = [ 1.2753666447299659525; 5.019049726784267463450;
6.1602098531096305441; 7.409740605964741794425;
2.9788656263939928886 ];
q = [ 2.260528520767326969592; 9.3960340162350541504;
12.048951927855129036034; 17.081440747466004316;
9.608965327192787870698; 3.3690752069827527677 ];
num = 0.5641895835477550741; for i=1:5, num = -z(id2).*num/sqrt(2) + r(i); end
den = 1.0; for i=1:6, den = -z(id2).*den/sqrt(2) + q(i); end
e = num./den; lp(id2) = log(e/2) - z(id2).^2/2;
id3 = ~id2 & ~id1; lp(id3) = log(erfc(-z(id3)/sqrt(2))/2); % third case: rest
if nargout>1 % compute first derivative
dlp = zeros(size(z)); % allocate memory
dlp( id2) = abs(den./num) * sqrt(2/pi); % strictly positive first derivative
dlp(~id2) = exp(-z(~id2).*z(~id2)/2-lp(~id2))/sqrt(2*pi); % safe computation
if nargout>2 % compute second derivative
d2lp = -dlp.*abs(z+dlp); % strictly negative second derivative
if nargout>3 % compute third derivative
d3lp = -d2lp.*abs(z+2*dlp)-dlp; % strictly positive third derivative
end
end
end
strong text
When x is very small,like x = -100, direct calculation of $\log\Phi(x)$ is impossible,but the approximation is still accurate | Approximation of logarithm of standard normal CDF for x<0 | We can use l'Hôpital's Rule:
$$
\lim_{x \rightarrow -\infty} \frac{\Phi(x)}{\phi(x)} = \frac{\phi(x)}{-x\phi(x)}=\frac{1}{-x}
$$
So:
$$
\lim_{x \rightarrow -\infty} \Phi(x) = \frac{\phi(x)}{-x}
$$
And | Approximation of logarithm of standard normal CDF for x<0
We can use l'Hôpital's Rule:
$$
\lim_{x \rightarrow -\infty} \frac{\Phi(x)}{\phi(x)} = \frac{\phi(x)}{-x\phi(x)}=\frac{1}{-x}
$$
So:
$$
\lim_{x \rightarrow -\infty} \Phi(x) = \frac{\phi(x)}{-x}
$$
And then we get:
$$
\lim_{x \rightarrow -\infty} \log \Phi(x) = \log(\frac{1}{\sqrt{2\pi}}) -0.5 x^2 - \log(-x)
$$
This approximation should be accurate if x is small.
Also try this matlab code, it gives really good approximation: I found it in the GPML toolbox
% Safe computation of logphi(z) = log(normcdf(z)) and its derivatives
% dlogphi(z) = normpdf(x)/normcdf(x).
% The function is based on index 5725 in Hart et al. and gsl_sf_log_erfc_e.
%
% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2013-11-13.
function [lp,dlp,d2lp,d3lp] = logphi(z)
z = real(z); % support for real arguments only
lp = zeros(size(z)); % allocate memory
id1 = z.*z<0.0492; % first case: close to zero
lp0 = -z(id1)/sqrt(2*pi);
c = [ 0.00048204; -0.00142906; 0.0013200243174; 0.0009461589032;
-0.0045563339802; 0.00556964649138; 0.00125993961762116;
-0.01621575378835404; 0.02629651521057465; -0.001829764677455021;
2*(1-pi/3); (4-pi)/3; 1; 1];
f = 0; for i=1:14, f = lp0.*(c(i)+f); end, lp(id1) = -2*f-log(2);
id2 = z<-11.3137; % second case: very small
r = [ 1.2753666447299659525; 5.019049726784267463450;
6.1602098531096305441; 7.409740605964741794425;
2.9788656263939928886 ];
q = [ 2.260528520767326969592; 9.3960340162350541504;
12.048951927855129036034; 17.081440747466004316;
9.608965327192787870698; 3.3690752069827527677 ];
num = 0.5641895835477550741; for i=1:5, num = -z(id2).*num/sqrt(2) + r(i); end
den = 1.0; for i=1:6, den = -z(id2).*den/sqrt(2) + q(i); end
e = num./den; lp(id2) = log(e/2) - z(id2).^2/2;
id3 = ~id2 & ~id1; lp(id3) = log(erfc(-z(id3)/sqrt(2))/2); % third case: rest
if nargout>1 % compute first derivative
dlp = zeros(size(z)); % allocate memory
dlp( id2) = abs(den./num) * sqrt(2/pi); % strictly positive first derivative
dlp(~id2) = exp(-z(~id2).*z(~id2)/2-lp(~id2))/sqrt(2*pi); % safe computation
if nargout>2 % compute second derivative
d2lp = -dlp.*abs(z+dlp); % strictly negative second derivative
if nargout>3 % compute third derivative
d3lp = -d2lp.*abs(z+2*dlp)-dlp; % strictly positive third derivative
end
end
end
strong text
When x is very small,like x = -100, direct calculation of $\log\Phi(x)$ is impossible,but the approximation is still accurate | Approximation of logarithm of standard normal CDF for x<0
We can use l'Hôpital's Rule:
$$
\lim_{x \rightarrow -\infty} \frac{\Phi(x)}{\phi(x)} = \frac{\phi(x)}{-x\phi(x)}=\frac{1}{-x}
$$
So:
$$
\lim_{x \rightarrow -\infty} \Phi(x) = \frac{\phi(x)}{-x}
$$
And |
25,338 | Approximation of logarithm of standard normal CDF for x<0 | Note that it's possible to avoid using expressions such as $\lim_{x\to-\infty}\Phi(x)=-\phi(x)/x$: Using L'Hopital's twice, we see that
$$
\lim_{x\to-\infty} -\frac{x\Phi(x)}{\phi(x)} =
\lim_{x\to-\infty} \frac{x\phi(x)+\Phi(x)} {x\phi(x)} =
1+ \lim_{x\to-\infty} \frac{\phi(x)}{\phi(x) - x^2\phi(x)} = 1,
$$
which means that
$$
\Phi(x) \approx -\frac{\phi(x)}{x}
$$
is a reasonable approximation for $x\ll0$. | Approximation of logarithm of standard normal CDF for x<0 | Note that it's possible to avoid using expressions such as $\lim_{x\to-\infty}\Phi(x)=-\phi(x)/x$: Using L'Hopital's twice, we see that
$$
\lim_{x\to-\infty} -\frac{x\Phi(x)}{\phi(x)} =
\lim_{x\to- | Approximation of logarithm of standard normal CDF for x<0
Note that it's possible to avoid using expressions such as $\lim_{x\to-\infty}\Phi(x)=-\phi(x)/x$: Using L'Hopital's twice, we see that
$$
\lim_{x\to-\infty} -\frac{x\Phi(x)}{\phi(x)} =
\lim_{x\to-\infty} \frac{x\phi(x)+\Phi(x)} {x\phi(x)} =
1+ \lim_{x\to-\infty} \frac{\phi(x)}{\phi(x) - x^2\phi(x)} = 1,
$$
which means that
$$
\Phi(x) \approx -\frac{\phi(x)}{x}
$$
is a reasonable approximation for $x\ll0$. | Approximation of logarithm of standard normal CDF for x<0
Note that it's possible to avoid using expressions such as $\lim_{x\to-\infty}\Phi(x)=-\phi(x)/x$: Using L'Hopital's twice, we see that
$$
\lim_{x\to-\infty} -\frac{x\Phi(x)}{\phi(x)} =
\lim_{x\to- |
25,339 | Approximation of logarithm of standard normal CDF for x<0 | You can also use monotone cubic interpolation using e.g. the Fritsch–Carlson method. This can give you a very precise solution and you can make an implementation like in this package. Here is an example with 300 knots:
# test values
us <- seq(-5, 0, length.out = 10000)
# create the spline function
n_points <- 300L
eps <- 1e-9
x <- seq(qnorm(eps), 1, length.out = n_points)
f <- splinefun(x = x, y = pnorm(x, log.p = TRUE), method = "monoH.FC")
max(abs(pnorm(us, log.p = TRUE) - f(us))) # largest abs error
#R> [1] 4.488093e-08
# plot x versus the error
xs <- seq(-5, 0, length.out = 1000)
plot(xs, pnorm(xs, log.p = TRUE) - f(xs), xlab = "x", ylab = "error",
type = "h")
This R version is not fast. However, you can make a fast implementation like in the package I linked to using that there is a fixed distance between all the knots. This allows you to quickly find the closets knot for a given value.
One though will need to an approximation to plug in for input values smaller than the smallest knot. | Approximation of logarithm of standard normal CDF for x<0 | You can also use monotone cubic interpolation using e.g. the Fritsch–Carlson method. This can give you a very precise solution and you can make an implementation like in this package. Here is an examp | Approximation of logarithm of standard normal CDF for x<0
You can also use monotone cubic interpolation using e.g. the Fritsch–Carlson method. This can give you a very precise solution and you can make an implementation like in this package. Here is an example with 300 knots:
# test values
us <- seq(-5, 0, length.out = 10000)
# create the spline function
n_points <- 300L
eps <- 1e-9
x <- seq(qnorm(eps), 1, length.out = n_points)
f <- splinefun(x = x, y = pnorm(x, log.p = TRUE), method = "monoH.FC")
max(abs(pnorm(us, log.p = TRUE) - f(us))) # largest abs error
#R> [1] 4.488093e-08
# plot x versus the error
xs <- seq(-5, 0, length.out = 1000)
plot(xs, pnorm(xs, log.p = TRUE) - f(xs), xlab = "x", ylab = "error",
type = "h")
This R version is not fast. However, you can make a fast implementation like in the package I linked to using that there is a fixed distance between all the knots. This allows you to quickly find the closets knot for a given value.
One though will need to an approximation to plug in for input values smaller than the smallest knot. | Approximation of logarithm of standard normal CDF for x<0
You can also use monotone cubic interpolation using e.g. the Fritsch–Carlson method. This can give you a very precise solution and you can make an implementation like in this package. Here is an examp |
25,340 | Approximation of logarithm of standard normal CDF for x<0 | I'm kinda late to the party but I would suggest to compute this quantity without approximations, I was using one of the approximations proposed in this post for academic reasons (code for my MSc thesis) and since I really need very high precision I ended up rewriting the function in pure C by using MPFR to avoid numerical problems
#include <gmp.h>
#include <mpfr.h>
double norm_logcdf(double x){
mpfr_t mpfr_x;
mpfr_init2(mpfr_x,64);
mpfr_set_d(mpfr_x,x,MPFR_RNDN);
mpfr_neg(mpfr_x,mpfr_x,MPFR_RNDN);
mpfr_mul_d(mpfr_x,mpfr_x, (double) M_SQRT1_2, MPFR_RNDN);
mpfr_erfc(mpfr_x,mpfr_x,MPFR_RNDN);
mpfr_mul_d(mpfr_x,mpfr_x,(double) 0.5, MPFR_RNDN);
mpfr_log(mpfr_x,mpfr_x,MPFR_RNDN);
double res = mpfr_get_d(mpfr_x,MPFR_RNDN);
mpfr_clear(mpfr_x);
return res;
}
``` | Approximation of logarithm of standard normal CDF for x<0 | I'm kinda late to the party but I would suggest to compute this quantity without approximations, I was using one of the approximations proposed in this post for academic reasons (code for my MSc thesi | Approximation of logarithm of standard normal CDF for x<0
I'm kinda late to the party but I would suggest to compute this quantity without approximations, I was using one of the approximations proposed in this post for academic reasons (code for my MSc thesis) and since I really need very high precision I ended up rewriting the function in pure C by using MPFR to avoid numerical problems
#include <gmp.h>
#include <mpfr.h>
double norm_logcdf(double x){
mpfr_t mpfr_x;
mpfr_init2(mpfr_x,64);
mpfr_set_d(mpfr_x,x,MPFR_RNDN);
mpfr_neg(mpfr_x,mpfr_x,MPFR_RNDN);
mpfr_mul_d(mpfr_x,mpfr_x, (double) M_SQRT1_2, MPFR_RNDN);
mpfr_erfc(mpfr_x,mpfr_x,MPFR_RNDN);
mpfr_mul_d(mpfr_x,mpfr_x,(double) 0.5, MPFR_RNDN);
mpfr_log(mpfr_x,mpfr_x,MPFR_RNDN);
double res = mpfr_get_d(mpfr_x,MPFR_RNDN);
mpfr_clear(mpfr_x);
return res;
}
``` | Approximation of logarithm of standard normal CDF for x<0
I'm kinda late to the party but I would suggest to compute this quantity without approximations, I was using one of the approximations proposed in this post for academic reasons (code for my MSc thesi |
25,341 | usefulness of k-means clustering on high dimensional data [duplicate] | Is k-means meaningful at all?
See for example my answer here: https://stats.stackexchange.com/a/35760/7828
k-means optimizes variances. Is the unweighted sum of variances meaningful on your data set? Probably not. How can then k-means be meaningful? In high-dimensional data, distance doesn't work. But variance = squared Euclidean distance; so is it meaningful to optimize something of which you know it doesn't work in high-dimensional data?
For the particular problems of high-dimensional data, I recommend the following study:
Zimek, A., Schubert, E. and Kriegel, H.-P. (2012), A survey on unsupervised outlier detection in high-dimensional numerical data. Statistical Analy Data Mining, 5: 363–387. doi: 10.1002/sam.11161
It's main focus is outlier detection, but the observations on the challenges of high-dimensional data apply to a much broader context. They show some simple experiments how high-dimensional data can be a problem. What I like about this study is they also show that high-dimensional data can be easy, too; it's not black and white, but you need to carefully study your data.
Useful is different. Often people use k-means not to actually discover clusters.
But to find representative objects. It's a clever way of semi-random sampling k objects that aren't too similar to be useful.
If you only need a clever way of sampling, k-means may be very useful. | usefulness of k-means clustering on high dimensional data [duplicate] | Is k-means meaningful at all?
See for example my answer here: https://stats.stackexchange.com/a/35760/7828
k-means optimizes variances. Is the unweighted sum of variances meaningful on your data set? | usefulness of k-means clustering on high dimensional data [duplicate]
Is k-means meaningful at all?
See for example my answer here: https://stats.stackexchange.com/a/35760/7828
k-means optimizes variances. Is the unweighted sum of variances meaningful on your data set? Probably not. How can then k-means be meaningful? In high-dimensional data, distance doesn't work. But variance = squared Euclidean distance; so is it meaningful to optimize something of which you know it doesn't work in high-dimensional data?
For the particular problems of high-dimensional data, I recommend the following study:
Zimek, A., Schubert, E. and Kriegel, H.-P. (2012), A survey on unsupervised outlier detection in high-dimensional numerical data. Statistical Analy Data Mining, 5: 363–387. doi: 10.1002/sam.11161
It's main focus is outlier detection, but the observations on the challenges of high-dimensional data apply to a much broader context. They show some simple experiments how high-dimensional data can be a problem. What I like about this study is they also show that high-dimensional data can be easy, too; it's not black and white, but you need to carefully study your data.
Useful is different. Often people use k-means not to actually discover clusters.
But to find representative objects. It's a clever way of semi-random sampling k objects that aren't too similar to be useful.
If you only need a clever way of sampling, k-means may be very useful. | usefulness of k-means clustering on high dimensional data [duplicate]
Is k-means meaningful at all?
See for example my answer here: https://stats.stackexchange.com/a/35760/7828
k-means optimizes variances. Is the unweighted sum of variances meaningful on your data set? |
25,342 | What is the ratio of uniform and normal distribution? | Let random variable $X \sim \text{Uniform}(a,b)$ with pdf $f(x)$:
where I have assumed $0<a<b$ (this nests the standard $\text{Uniform}(0,1)$ case). [ Different results will be obtained if say parameter $a<0$, but the procedure is exactly the same. ]
Further, let $Y \sim N(\mu, \sigma^2)$, and let $W=1/Y$ with pdf $g(w)$:
Then, we seek the pdf of the product $V = X*W$, say $h(v)$, which is given by:
where I am using mathStatica's TransformProduct function to automate the nitty-gritties, and where Erf denotes the Error function: http://reference.wolfram.com/language/ref/Erf.html
All done.
Plots
Here are two plots of the pdf:
Plot 1: $\mu = 0$, $\sigma = 1$, $b = 3$ ... and ... $a = 0, 1, 2$
Plot 2: $\mu = {0,\frac12,1}$, $\sigma = 1$, $a=0$, $b = 1$
Monte Carlo check
Here is a quick Monte Carlo check of the Plot 2 case, just to make sure no errors have crept in:
$\mu = \frac12$, $\sigma = 1$, $a=0$, $b = 1$
The blue line is the empirical Monte Carlo pdf, and the red dashed line is the theoretical pdf $h(v)$ above. Looks fine :) | What is the ratio of uniform and normal distribution? | Let random variable $X \sim \text{Uniform}(a,b)$ with pdf $f(x)$:
where I have assumed $0<a<b$ (this nests the standard $\text{Uniform}(0,1)$ case). [ Different results will be obtained if say parame | What is the ratio of uniform and normal distribution?
Let random variable $X \sim \text{Uniform}(a,b)$ with pdf $f(x)$:
where I have assumed $0<a<b$ (this nests the standard $\text{Uniform}(0,1)$ case). [ Different results will be obtained if say parameter $a<0$, but the procedure is exactly the same. ]
Further, let $Y \sim N(\mu, \sigma^2)$, and let $W=1/Y$ with pdf $g(w)$:
Then, we seek the pdf of the product $V = X*W$, say $h(v)$, which is given by:
where I am using mathStatica's TransformProduct function to automate the nitty-gritties, and where Erf denotes the Error function: http://reference.wolfram.com/language/ref/Erf.html
All done.
Plots
Here are two plots of the pdf:
Plot 1: $\mu = 0$, $\sigma = 1$, $b = 3$ ... and ... $a = 0, 1, 2$
Plot 2: $\mu = {0,\frac12,1}$, $\sigma = 1$, $a=0$, $b = 1$
Monte Carlo check
Here is a quick Monte Carlo check of the Plot 2 case, just to make sure no errors have crept in:
$\mu = \frac12$, $\sigma = 1$, $a=0$, $b = 1$
The blue line is the empirical Monte Carlo pdf, and the red dashed line is the theoretical pdf $h(v)$ above. Looks fine :) | What is the ratio of uniform and normal distribution?
Let random variable $X \sim \text{Uniform}(a,b)$ with pdf $f(x)$:
where I have assumed $0<a<b$ (this nests the standard $\text{Uniform}(0,1)$ case). [ Different results will be obtained if say parame |
25,343 | What is the ratio of uniform and normal distribution? | It is possible to find the distribution of $Z=\frac{X}{Y}$ from first principles, where $X\sim U[0,1]$ and $Y \sim N(\mu,\sigma^2)$. Consider the cumulative probability function of $Z$:
$$F_Z(z) = P(Z\le z) = P\left(\frac{X}{Y} \le z \right)$$
Consider the two cases $Y>0$ and $Y<0$. If $Y>0$, then $\frac{X}{Y}\le z\implies X \le zY $. Similarly if $Y<0$ then $\frac{X}{Y}\le z\implies X \ge zY $.
Now we know $-\infty<Z<\infty$. To find the above probability, consider the cases $z>0$ and $z<0$.
If $z>0$, then the probability can be expressed as an integration of the joint distribution of $(X,Y)$ over the below shown region. (using the inequalities)
So
$$F_Z(z) = \int_0^1 \int_{x/z}^\infty f_Y(y) dy dx + \int_0^1 \int_{-\infty}^0 f_Y(y) dy dx $$
where $f_Y(y)$ is the distribution function of $Y$.
Find the distribution function of $Z$ by differentiating the above.
$$\begin{align*} f_Z(z) &= \frac{d}{dz}\int_0^1 \left[ F_Y(\infty) - F_Y\left(\frac{x}{z}\right) \right] dx \\
&= \int_0^1 \frac{\partial}{\partial z} \left[ F_Y(\infty) - F_Y\left(\frac{x}{z}\right) \right] dx
\\
&= \int_0^1 \frac{x}{z^2} f_Y\left(\frac{x}{z}\right) dx \\
&= \int_0^1 \frac{x}{\sqrt{2\pi}\sigma z^2} \exp \left( - \frac{\left( \frac{x}{z}-\mu\right)^2}{2\sigma^2} \right) dx
\end{align*}$$
The integral above can be evaluated using the following sequence of transformations:
Let $u=\frac{x}{z}$
Let $v=u-\mu$
Separate the resulting integral into two integrals, one with $v$ only in the exponential, and one with $v$ multiplying with the exponential.
The resulting integrals can be simplified to yield
$$f_Z(z) = \frac{\sigma}{\sqrt{2\pi}}\left[ \exp\left(\frac{-\mu^2}{2\sigma^2}\right)-\exp\left(\frac{-\left(\frac{1}{z}-\mu\right)^2}{2\sigma^2}\right) \right] + \mu \left[ \Phi\left(\frac{\frac{1}{z}-\mu}{\sigma}\right)-\Phi\left(\frac{-\mu}{\sigma}\right) \right]$$
Here $\Phi(x)$ is the cumulative distribution function of the standard normal. An identical result is obtained for the case $z<0$.
This answer can be verified by simulation. The following script in R performs this task.
n <- 1e7
mu <- 2
sigma <- 4
X <- runif(n)
Y <- rnorm(n, mean=mu, sd=sigma)
Z <- X/Y
# Constrain range of Z to allow better visualization
Z <- Z[Z>-10]
Z <- Z[Z<10]
# The actual density
hist(Z, breaks=1000, xlim=c(-10,10), prob=TRUE)
# The theoretical density
r <- seq(from=-10, to=10, by=0.01)
p <- sigma/sqrt(2*pi)*( exp( -mu^2/(2*sigma^2)) - exp(-(1/r-mu)^2/(2*sigma^2)) ) + mu*( pnorm((1/r-mu)/sigma) - pnorm(-mu/sigma) )
lines(r,p, col="red")
Here are a few graphs for verification:
For $Y\sim N(0,1)$
For $Y\sim N(1,1)$
For $y\sim N(1,2)$
The undershooting of the theoretical answer seen in the graphs around $z=0$ is probably because of the constrained range. Otherwise the theoretical answer seems to follow the simulated density. | What is the ratio of uniform and normal distribution? | It is possible to find the distribution of $Z=\frac{X}{Y}$ from first principles, where $X\sim U[0,1]$ and $Y \sim N(\mu,\sigma^2)$. Consider the cumulative probability function of $Z$:
$$F_Z(z) = P(Z | What is the ratio of uniform and normal distribution?
It is possible to find the distribution of $Z=\frac{X}{Y}$ from first principles, where $X\sim U[0,1]$ and $Y \sim N(\mu,\sigma^2)$. Consider the cumulative probability function of $Z$:
$$F_Z(z) = P(Z\le z) = P\left(\frac{X}{Y} \le z \right)$$
Consider the two cases $Y>0$ and $Y<0$. If $Y>0$, then $\frac{X}{Y}\le z\implies X \le zY $. Similarly if $Y<0$ then $\frac{X}{Y}\le z\implies X \ge zY $.
Now we know $-\infty<Z<\infty$. To find the above probability, consider the cases $z>0$ and $z<0$.
If $z>0$, then the probability can be expressed as an integration of the joint distribution of $(X,Y)$ over the below shown region. (using the inequalities)
So
$$F_Z(z) = \int_0^1 \int_{x/z}^\infty f_Y(y) dy dx + \int_0^1 \int_{-\infty}^0 f_Y(y) dy dx $$
where $f_Y(y)$ is the distribution function of $Y$.
Find the distribution function of $Z$ by differentiating the above.
$$\begin{align*} f_Z(z) &= \frac{d}{dz}\int_0^1 \left[ F_Y(\infty) - F_Y\left(\frac{x}{z}\right) \right] dx \\
&= \int_0^1 \frac{\partial}{\partial z} \left[ F_Y(\infty) - F_Y\left(\frac{x}{z}\right) \right] dx
\\
&= \int_0^1 \frac{x}{z^2} f_Y\left(\frac{x}{z}\right) dx \\
&= \int_0^1 \frac{x}{\sqrt{2\pi}\sigma z^2} \exp \left( - \frac{\left( \frac{x}{z}-\mu\right)^2}{2\sigma^2} \right) dx
\end{align*}$$
The integral above can be evaluated using the following sequence of transformations:
Let $u=\frac{x}{z}$
Let $v=u-\mu$
Separate the resulting integral into two integrals, one with $v$ only in the exponential, and one with $v$ multiplying with the exponential.
The resulting integrals can be simplified to yield
$$f_Z(z) = \frac{\sigma}{\sqrt{2\pi}}\left[ \exp\left(\frac{-\mu^2}{2\sigma^2}\right)-\exp\left(\frac{-\left(\frac{1}{z}-\mu\right)^2}{2\sigma^2}\right) \right] + \mu \left[ \Phi\left(\frac{\frac{1}{z}-\mu}{\sigma}\right)-\Phi\left(\frac{-\mu}{\sigma}\right) \right]$$
Here $\Phi(x)$ is the cumulative distribution function of the standard normal. An identical result is obtained for the case $z<0$.
This answer can be verified by simulation. The following script in R performs this task.
n <- 1e7
mu <- 2
sigma <- 4
X <- runif(n)
Y <- rnorm(n, mean=mu, sd=sigma)
Z <- X/Y
# Constrain range of Z to allow better visualization
Z <- Z[Z>-10]
Z <- Z[Z<10]
# The actual density
hist(Z, breaks=1000, xlim=c(-10,10), prob=TRUE)
# The theoretical density
r <- seq(from=-10, to=10, by=0.01)
p <- sigma/sqrt(2*pi)*( exp( -mu^2/(2*sigma^2)) - exp(-(1/r-mu)^2/(2*sigma^2)) ) + mu*( pnorm((1/r-mu)/sigma) - pnorm(-mu/sigma) )
lines(r,p, col="red")
Here are a few graphs for verification:
For $Y\sim N(0,1)$
For $Y\sim N(1,1)$
For $y\sim N(1,2)$
The undershooting of the theoretical answer seen in the graphs around $z=0$ is probably because of the constrained range. Otherwise the theoretical answer seems to follow the simulated density. | What is the ratio of uniform and normal distribution?
It is possible to find the distribution of $Z=\frac{X}{Y}$ from first principles, where $X\sim U[0,1]$ and $Y \sim N(\mu,\sigma^2)$. Consider the cumulative probability function of $Z$:
$$F_Z(z) = P(Z |
25,344 | What is the ratio of uniform and normal distribution? | Besides the reciprocal of the slash distribution (or @Glen_b's "backslash distribution!"), a kind of ratio distribution, I don't know what to call it either, but I'll simulate one version in R.
Since you specify a positive mean of $Y$, I'll use $Y=\mathcal N(7,1)$ so that $\min(Y)>1$ in most samples of $N\le1\rm M$. Of course, other possibilities exist. For instance, any $Y<1$ would expand the range of $\frac X Y$ beyond 1, and any $Y<0$ would of course expand it into negative values. set.seed(1);x=rbeta(10000000,1,1)/rnorm(10000000,7);hist(x,n=length(x)/50000)
(Decrease size for slow computers! Or use runif if you know how!) | What is the ratio of uniform and normal distribution? | Besides the reciprocal of the slash distribution (or @Glen_b's "backslash distribution!"), a kind of ratio distribution, I don't know what to call it either, but I'll simulate one version in R.
Since | What is the ratio of uniform and normal distribution?
Besides the reciprocal of the slash distribution (or @Glen_b's "backslash distribution!"), a kind of ratio distribution, I don't know what to call it either, but I'll simulate one version in R.
Since you specify a positive mean of $Y$, I'll use $Y=\mathcal N(7,1)$ so that $\min(Y)>1$ in most samples of $N\le1\rm M$. Of course, other possibilities exist. For instance, any $Y<1$ would expand the range of $\frac X Y$ beyond 1, and any $Y<0$ would of course expand it into negative values. set.seed(1);x=rbeta(10000000,1,1)/rnorm(10000000,7);hist(x,n=length(x)/50000)
(Decrease size for slow computers! Or use runif if you know how!) | What is the ratio of uniform and normal distribution?
Besides the reciprocal of the slash distribution (or @Glen_b's "backslash distribution!"), a kind of ratio distribution, I don't know what to call it either, but I'll simulate one version in R.
Since |
25,345 | Similarity measure between multiple distributions | It's more common to measure discrepancy than similarity, but some of them can be converted easily to your way around.
Possible measures of discrepancy in distribution include (but are not limited to):
Kolmogorov-Smirnov distance. This distance between cdfs (or emprical cdfs), $D$, is small when the distributions are the same and close to 1 when they're very different, so $1-D$ should have the property you seek and doesn't require the same number of observations (indeed many of these measures don't).
Bhattacharyya distance. The Bhattacharyya coefficient, to which it is related (see the article) is a measure of similarity of distributions of the form you suggest.
Information-divergence. This is not symmetric (so D(x,y) is not D(y,x), and is not a metric), but it can be made symmetric (e.g. by looking at D(x,y)+D(y,x) for example) and there are some related metric distances to this divergence measure.
Chi-square distance: A variety of related measures get this name, used for discrete data (or discretized continuous data) -
$\quad$ I'll mention one: $d(x,y) = \frac{1}{2}\sum \frac{(x_i-y_i)^2 }{ x_i+y_i }$. This, as with the other chi-square distances, requires discretization into the same set of categories for both variables, and the x's and y's are proportions of their total category counts. This distance lies between 0 and 1, and is converted to a similarity by subtracting from 1. | Similarity measure between multiple distributions | It's more common to measure discrepancy than similarity, but some of them can be converted easily to your way around.
Possible measures of discrepancy in distribution include (but are not limited to) | Similarity measure between multiple distributions
It's more common to measure discrepancy than similarity, but some of them can be converted easily to your way around.
Possible measures of discrepancy in distribution include (but are not limited to):
Kolmogorov-Smirnov distance. This distance between cdfs (or emprical cdfs), $D$, is small when the distributions are the same and close to 1 when they're very different, so $1-D$ should have the property you seek and doesn't require the same number of observations (indeed many of these measures don't).
Bhattacharyya distance. The Bhattacharyya coefficient, to which it is related (see the article) is a measure of similarity of distributions of the form you suggest.
Information-divergence. This is not symmetric (so D(x,y) is not D(y,x), and is not a metric), but it can be made symmetric (e.g. by looking at D(x,y)+D(y,x) for example) and there are some related metric distances to this divergence measure.
Chi-square distance: A variety of related measures get this name, used for discrete data (or discretized continuous data) -
$\quad$ I'll mention one: $d(x,y) = \frac{1}{2}\sum \frac{(x_i-y_i)^2 }{ x_i+y_i }$. This, as with the other chi-square distances, requires discretization into the same set of categories for both variables, and the x's and y's are proportions of their total category counts. This distance lies between 0 and 1, and is converted to a similarity by subtracting from 1. | Similarity measure between multiple distributions
It's more common to measure discrepancy than similarity, but some of them can be converted easily to your way around.
Possible measures of discrepancy in distribution include (but are not limited to) |
25,346 | Similarity measure between multiple distributions | You say "have exactly the same characteristics". So, if you can enumerate these characteristics that are important for you and the application at hand, then you can deploy a test for each one of those. Probably you would need to specify some tolerance level for each metric. You can decide that two distributions are the same if they pass all the tests. From a pair of distributions you can easily generalise to a set.
If you are after a single metric for comparing distributions you can go for the standard Kullback–Leibler divergence. Pay attention that the simple measure is not symmetric - although there is a symmetric form discussed in the wikipedia article. | Similarity measure between multiple distributions | You say "have exactly the same characteristics". So, if you can enumerate these characteristics that are important for you and the application at hand, then you can deploy a test for each one of those | Similarity measure between multiple distributions
You say "have exactly the same characteristics". So, if you can enumerate these characteristics that are important for you and the application at hand, then you can deploy a test for each one of those. Probably you would need to specify some tolerance level for each metric. You can decide that two distributions are the same if they pass all the tests. From a pair of distributions you can easily generalise to a set.
If you are after a single metric for comparing distributions you can go for the standard Kullback–Leibler divergence. Pay attention that the simple measure is not symmetric - although there is a symmetric form discussed in the wikipedia article. | Similarity measure between multiple distributions
You say "have exactly the same characteristics". So, if you can enumerate these characteristics that are important for you and the application at hand, then you can deploy a test for each one of those |
25,347 | Does it make sense to compute confidence intervals and to test hypotheses when data from whole population is available? | The first question is one that has no generally agreed upon answer. My own view is like yours, but others have argued that a population can be viewed as a sample from a "super-population" where the exact nature of a super-population varies depending on context: E.g. a census of all the people living in a building could be viewed as a sample from all the people living in similar buildings; a census of the population of the USA (not that one could ever be truly complete) could be viewed as a sample from a super-population of Americans who might one day exist (or something like that). I think this is often an excuse to get to use p-values; many scientists in substantive fields aren't comfortable if they haven't got a p-value. (But that is my view).
The second question seems a bit odd to answer in a general way. When do you get a sample that is (say) even more than half of the population?
A bigger problem will be bias. Going back to the US Census, the problem isn't simply that it misses people, but that the people it misses are not a random sample of the total population; so, even if the census gets answers from (to pick a number) 95% of all people, if those 5% remaining are quite different, then results will be biased. | Does it make sense to compute confidence intervals and to test hypotheses when data from whole popul | The first question is one that has no generally agreed upon answer. My own view is like yours, but others have argued that a population can be viewed as a sample from a "super-population" where the ex | Does it make sense to compute confidence intervals and to test hypotheses when data from whole population is available?
The first question is one that has no generally agreed upon answer. My own view is like yours, but others have argued that a population can be viewed as a sample from a "super-population" where the exact nature of a super-population varies depending on context: E.g. a census of all the people living in a building could be viewed as a sample from all the people living in similar buildings; a census of the population of the USA (not that one could ever be truly complete) could be viewed as a sample from a super-population of Americans who might one day exist (or something like that). I think this is often an excuse to get to use p-values; many scientists in substantive fields aren't comfortable if they haven't got a p-value. (But that is my view).
The second question seems a bit odd to answer in a general way. When do you get a sample that is (say) even more than half of the population?
A bigger problem will be bias. Going back to the US Census, the problem isn't simply that it misses people, but that the people it misses are not a random sample of the total population; so, even if the census gets answers from (to pick a number) 95% of all people, if those 5% remaining are quite different, then results will be biased. | Does it make sense to compute confidence intervals and to test hypotheses when data from whole popul
The first question is one that has no generally agreed upon answer. My own view is like yours, but others have argued that a population can be viewed as a sample from a "super-population" where the ex |
25,348 | Does it make sense to compute confidence intervals and to test hypotheses when data from whole population is available? | Suppose only 2 out of 12 committee members are women.
The proportion $\frac{1}{6}$ can be taken as a statistic descriptive of the whole population (the committee). Perhaps something ought to be done to correct the imbalance, regardless of how it arose.
Or it can be taken as an estimate of the probability of a woman's being selected for the committee—a property of the selection process. You can put confidence intervals around it, test if it's significantly different from one-half (or another relevant null hypothesis), & so on. Perhaps the process needs to be changed to make it fair.
The two views, descriptive & inferential, are not contradictory, but quite distinct.
The answer to the second question is that it makes sense to calculate confidence intervals for & test hypotheses about a population parameter even if just a single individual is unsampled. Just note that CIs & tests have to take account of a considerable proportion of the population's being sampled: see finite population correction. | Does it make sense to compute confidence intervals and to test hypotheses when data from whole popul | Suppose only 2 out of 12 committee members are women.
The proportion $\frac{1}{6}$ can be taken as a statistic descriptive of the whole population (the committee). Perhaps something ought to be done t | Does it make sense to compute confidence intervals and to test hypotheses when data from whole population is available?
Suppose only 2 out of 12 committee members are women.
The proportion $\frac{1}{6}$ can be taken as a statistic descriptive of the whole population (the committee). Perhaps something ought to be done to correct the imbalance, regardless of how it arose.
Or it can be taken as an estimate of the probability of a woman's being selected for the committee—a property of the selection process. You can put confidence intervals around it, test if it's significantly different from one-half (or another relevant null hypothesis), & so on. Perhaps the process needs to be changed to make it fair.
The two views, descriptive & inferential, are not contradictory, but quite distinct.
The answer to the second question is that it makes sense to calculate confidence intervals for & test hypotheses about a population parameter even if just a single individual is unsampled. Just note that CIs & tests have to take account of a considerable proportion of the population's being sampled: see finite population correction. | Does it make sense to compute confidence intervals and to test hypotheses when data from whole popul
Suppose only 2 out of 12 committee members are women.
The proportion $\frac{1}{6}$ can be taken as a statistic descriptive of the whole population (the committee). Perhaps something ought to be done t |
25,349 | LDA vs. perceptron | As AdamO suggests in the above comment, you can't really do better than read Chapter 4 of The Elements of Statistical Learning (which I will call HTF) which compares LDA with other linear classification methods, giving many examples, and also discusses the use of LDA as a dimension-reduction technique in the vein of PCA which, as ttnphns points out, is rather popular.
From the point of view of classification, I think the key difference is this. Imagine that you have two classes and you want to separate them. Each class has a probability density function. The best possible situation would be if you knew these density functions, because then you could predict which class a point would belong to by evaluating the class-specific densities at that point.
Some kinds of classifier operate by finding an approximation to the density functions of the classes. LDA is one of these; it makes the assumption that the densities are multivariate normal with the same covariance matrix. This is a strong assumption, but if it is approximately correct, you get a good classifier. Many other classifiers also take this kind of approach, but try to be more flexible than assuming normality. For example, see page 108 of HTF.
On the other hand, on page 210, HTF warn:
If classification is the ultimate goal, then learning the separate
class densities well may be unnecessary, and can in fact be
misleading.
Another approach is simply to look for a boundary between the two classes, which is what the perceptron does. A more sophisticated version of this is the support vector machine. These methods can also be combined with adding features to the data using a technique called kernelization. This does not work with LDA because it does not preserve normality, but it is no problem for a classifier which is just looking for a separating hyperplane.
The difference between LDA and a classifier which looks for a separating hyperplane is like the difference between a t-test and some nonparamteric alternative in ordinary statistics. The latter is more robust (to outliers, for example) but the former is optimal if its assumptions are satisfied.
One more remark: it might be worth mentioning that some people might have cultural reasons for using methods like LDA or logistic regression, which may obligingly spew out ANOVA tables, hypothesis tests, and reassuring things like that. LDA was invented by Fisher; the perceptron was originally a model for a human or animal neuron and had no connection with statistics. It also works the other way; some people might prefer methods like support vector machines because they have the kind of cutting-edge hipster-cred which twentieth-century methods just can't match. It doesn't mean that they're better. (A good example of this is discussed in Machine Learning for Hackers, if I recall correctly.) | LDA vs. perceptron | As AdamO suggests in the above comment, you can't really do better than read Chapter 4 of The Elements of Statistical Learning (which I will call HTF) which compares LDA with other linear classificati | LDA vs. perceptron
As AdamO suggests in the above comment, you can't really do better than read Chapter 4 of The Elements of Statistical Learning (which I will call HTF) which compares LDA with other linear classification methods, giving many examples, and also discusses the use of LDA as a dimension-reduction technique in the vein of PCA which, as ttnphns points out, is rather popular.
From the point of view of classification, I think the key difference is this. Imagine that you have two classes and you want to separate them. Each class has a probability density function. The best possible situation would be if you knew these density functions, because then you could predict which class a point would belong to by evaluating the class-specific densities at that point.
Some kinds of classifier operate by finding an approximation to the density functions of the classes. LDA is one of these; it makes the assumption that the densities are multivariate normal with the same covariance matrix. This is a strong assumption, but if it is approximately correct, you get a good classifier. Many other classifiers also take this kind of approach, but try to be more flexible than assuming normality. For example, see page 108 of HTF.
On the other hand, on page 210, HTF warn:
If classification is the ultimate goal, then learning the separate
class densities well may be unnecessary, and can in fact be
misleading.
Another approach is simply to look for a boundary between the two classes, which is what the perceptron does. A more sophisticated version of this is the support vector machine. These methods can also be combined with adding features to the data using a technique called kernelization. This does not work with LDA because it does not preserve normality, but it is no problem for a classifier which is just looking for a separating hyperplane.
The difference between LDA and a classifier which looks for a separating hyperplane is like the difference between a t-test and some nonparamteric alternative in ordinary statistics. The latter is more robust (to outliers, for example) but the former is optimal if its assumptions are satisfied.
One more remark: it might be worth mentioning that some people might have cultural reasons for using methods like LDA or logistic regression, which may obligingly spew out ANOVA tables, hypothesis tests, and reassuring things like that. LDA was invented by Fisher; the perceptron was originally a model for a human or animal neuron and had no connection with statistics. It also works the other way; some people might prefer methods like support vector machines because they have the kind of cutting-edge hipster-cred which twentieth-century methods just can't match. It doesn't mean that they're better. (A good example of this is discussed in Machine Learning for Hackers, if I recall correctly.) | LDA vs. perceptron
As AdamO suggests in the above comment, you can't really do better than read Chapter 4 of The Elements of Statistical Learning (which I will call HTF) which compares LDA with other linear classificati |
25,350 | LDA vs. perceptron | For intuition, consider this case:
The line represents the "optimal boundary" between the two classes o and x.
LDA tries to find a hyperplane that minimizes the intercluster variance and maximize the intracluster variance, and then the takes the boundary to be orthogonal to that hyperplane. Here, this will probably not work because the clusters have large variance in the same direction.
A perceptron, on the other hand, may have a better chance of finding a good separating hyperplane.
In the case of classes that have a Gaussian distribution, though, the LDA will probably do better, since the perceptron only finds a separating hyperplane that is consistent with the data, without giving guarantees about which hyperplane it chooses (there could be an infinite number of consistent hyperplanes). However, more sophisticated versions of the perceptron can choose a hyperplane with some optimal properties, such as maximizing the margin between the classes (this is essentially what Support Vector Machines do).
Also note that both LDA and perceptron can be extended to non-linear decision boundaries via the kernel trick. | LDA vs. perceptron | For intuition, consider this case:
The line represents the "optimal boundary" between the two classes o and x.
LDA tries to find a hyperplane that minimizes the intercluster variance and maximize the | LDA vs. perceptron
For intuition, consider this case:
The line represents the "optimal boundary" between the two classes o and x.
LDA tries to find a hyperplane that minimizes the intercluster variance and maximize the intracluster variance, and then the takes the boundary to be orthogonal to that hyperplane. Here, this will probably not work because the clusters have large variance in the same direction.
A perceptron, on the other hand, may have a better chance of finding a good separating hyperplane.
In the case of classes that have a Gaussian distribution, though, the LDA will probably do better, since the perceptron only finds a separating hyperplane that is consistent with the data, without giving guarantees about which hyperplane it chooses (there could be an infinite number of consistent hyperplanes). However, more sophisticated versions of the perceptron can choose a hyperplane with some optimal properties, such as maximizing the margin between the classes (this is essentially what Support Vector Machines do).
Also note that both LDA and perceptron can be extended to non-linear decision boundaries via the kernel trick. | LDA vs. perceptron
For intuition, consider this case:
The line represents the "optimal boundary" between the two classes o and x.
LDA tries to find a hyperplane that minimizes the intercluster variance and maximize the |
25,351 | LDA vs. perceptron | One of the biggest differences between LDA and the other methods is that it's just a machine learning technique for data which are assumed to be normally distributed. That can be great under the case of missing data or truncation where you can use the EM algorithm to maximize likelihoods under very strange and/or interesting circumstances. Caveat emptor because model misspecifications, such as multimodal data, can lead to poor performing predictions where K-means clustering would have done better. Multimodal data can also be accounted for with EM to detect latent variables or clustering in LDA.
For instance, suppose you are looking to measure probability of developing a positive diagnosis of AIDS in 5 years based on CD4 count. Suppose further that you don't know the value of a specific biomarker that greatly impacts CD4 counts and is associated with further immunosuppression. CD4 counts under 400 are below lower limit of detection on most affordable assays. The EM algorithm allows us to iteratively calculate the LDA and biomarker assignment and the means and covariance for CD4 for the untruncated DF. | LDA vs. perceptron | One of the biggest differences between LDA and the other methods is that it's just a machine learning technique for data which are assumed to be normally distributed. That can be great under the case | LDA vs. perceptron
One of the biggest differences between LDA and the other methods is that it's just a machine learning technique for data which are assumed to be normally distributed. That can be great under the case of missing data or truncation where you can use the EM algorithm to maximize likelihoods under very strange and/or interesting circumstances. Caveat emptor because model misspecifications, such as multimodal data, can lead to poor performing predictions where K-means clustering would have done better. Multimodal data can also be accounted for with EM to detect latent variables or clustering in LDA.
For instance, suppose you are looking to measure probability of developing a positive diagnosis of AIDS in 5 years based on CD4 count. Suppose further that you don't know the value of a specific biomarker that greatly impacts CD4 counts and is associated with further immunosuppression. CD4 counts under 400 are below lower limit of detection on most affordable assays. The EM algorithm allows us to iteratively calculate the LDA and biomarker assignment and the means and covariance for CD4 for the untruncated DF. | LDA vs. perceptron
One of the biggest differences between LDA and the other methods is that it's just a machine learning technique for data which are assumed to be normally distributed. That can be great under the case |
25,352 | What are distances between variables making a covariance matrix? | Covariance (or correlation or cosine) can be easily and naturally converted into euclidean distance by means of the law of cosines, because it is a scalar product (= angular-based similarity) in euclidean space. Knowing covariance between two variables i and j as well as their variances automatically implies knowing d between the variables: $d_{ij}^2 = \sigma_i^2 + \sigma_j^2 −2cov_{ij}$. (That $d_{ij}^2$ is directly proportional to the usual squared Euclidean distance: you obtain the latter if you use the sums-of-squares and the sum-of-crossproducts in place of the variances and the covariance. Both variables should be of course centered initially: speaking of "covariances" is alias to thinking about data with removed means.)
Note, this formula means that a negative covariance is greater distance than positive covariance (and this is indeed the case from the geometrical point of view, i.e. when the variables are seen as vectors in the subject space ). If you don't want the sign of the covariance to play role, abolish negative sign. Ignoring negative sign isn't "patching by hand" operation and is warranted, when needed: if cov matrix is positive definite, abs(cov) matrix will be positive definite too; and hence the distances obtained by the above formula will be true euclidean distances (euclidean distance is a particular sort of metric distance).
Euclidean distances are universal in respect to hierarchical clustering: any method of such clustering is valid with either euclidean or squared euclidean d. But some methods, e.g. average linkage or complete linkage, can be used with any dissimilarity or similarity (not just metric distances). So you could use such methods directly with cov or abs(cov) matrix or - just for example - with max(abs(cov))-abs(cov) distance matrix. Of course, clustering results do potentially depend on the exact nature of the (dis)similarity used. | What are distances between variables making a covariance matrix? | Covariance (or correlation or cosine) can be easily and naturally converted into euclidean distance by means of the law of cosines, because it is a scalar product (= angular-based similarity) in eucli | What are distances between variables making a covariance matrix?
Covariance (or correlation or cosine) can be easily and naturally converted into euclidean distance by means of the law of cosines, because it is a scalar product (= angular-based similarity) in euclidean space. Knowing covariance between two variables i and j as well as their variances automatically implies knowing d between the variables: $d_{ij}^2 = \sigma_i^2 + \sigma_j^2 −2cov_{ij}$. (That $d_{ij}^2$ is directly proportional to the usual squared Euclidean distance: you obtain the latter if you use the sums-of-squares and the sum-of-crossproducts in place of the variances and the covariance. Both variables should be of course centered initially: speaking of "covariances" is alias to thinking about data with removed means.)
Note, this formula means that a negative covariance is greater distance than positive covariance (and this is indeed the case from the geometrical point of view, i.e. when the variables are seen as vectors in the subject space ). If you don't want the sign of the covariance to play role, abolish negative sign. Ignoring negative sign isn't "patching by hand" operation and is warranted, when needed: if cov matrix is positive definite, abs(cov) matrix will be positive definite too; and hence the distances obtained by the above formula will be true euclidean distances (euclidean distance is a particular sort of metric distance).
Euclidean distances are universal in respect to hierarchical clustering: any method of such clustering is valid with either euclidean or squared euclidean d. But some methods, e.g. average linkage or complete linkage, can be used with any dissimilarity or similarity (not just metric distances). So you could use such methods directly with cov or abs(cov) matrix or - just for example - with max(abs(cov))-abs(cov) distance matrix. Of course, clustering results do potentially depend on the exact nature of the (dis)similarity used. | What are distances between variables making a covariance matrix?
Covariance (or correlation or cosine) can be easily and naturally converted into euclidean distance by means of the law of cosines, because it is a scalar product (= angular-based similarity) in eucli |
25,353 | What are distances between variables making a covariance matrix? | Why not use the correlation matrix to do the clustering?
Assuming your random variables are centered, by calculating the correlation between variables you are calculating the cosine similarity distance. This distance is also mentioned in your link.
This distance can be used for hierarchical clustering. The smaller 1 - |cosine similarity|, the more similar your variables are. | What are distances between variables making a covariance matrix? | Why not use the correlation matrix to do the clustering?
Assuming your random variables are centered, by calculating the correlation between variables you are calculating the cosine similarity distanc | What are distances between variables making a covariance matrix?
Why not use the correlation matrix to do the clustering?
Assuming your random variables are centered, by calculating the correlation between variables you are calculating the cosine similarity distance. This distance is also mentioned in your link.
This distance can be used for hierarchical clustering. The smaller 1 - |cosine similarity|, the more similar your variables are. | What are distances between variables making a covariance matrix?
Why not use the correlation matrix to do the clustering?
Assuming your random variables are centered, by calculating the correlation between variables you are calculating the cosine similarity distanc |
25,354 | Fast approximation to inverse Beta CDF | whuber's comment is specially true if you want to compute beta inequalities (e.g. the probability that a beta distributed r.v. exceeds another beta distributed r.v.). See here for more details.
Another alternative, pointed out by J. Cook in his blog is to use the Kumaraswamy distribution to approximate the Beta distribution.
To adhere by the cross-validated rule, I'll briefly summarize the main elements here but go read that post. The CDF of a $K(a, b)$ variable is:
$$F(x|a,b)=1–(1–x^a)^b$$
This CDF is easy to inverse and to draw from so you can easily generate a draw from $K(a,b)$ by generating a $u$ uniform on $[0,1]$ and:
$$F^{-1}(u)=(1 – (1 – u)^{1/b})^{1/a}$$
The idea is that you can pick up the parameters $a$ and $b$ to match most $\text{beta}(\alpha,\beta)$ reasonably well: pick $a=\alpha$ and use a numerical approach to find the optimal $b|a$. Again, more details are given on the original post. Alternatively, you could use a pre-computed table of equivalent parameter sets for Beta and Kumaraswamy distributions (see here) or compute one yourself. | Fast approximation to inverse Beta CDF | whuber's comment is specially true if you want to compute beta inequalities (e.g. the probability that a beta distributed r.v. exceeds another beta distributed r.v.). See here for more details.
Anothe | Fast approximation to inverse Beta CDF
whuber's comment is specially true if you want to compute beta inequalities (e.g. the probability that a beta distributed r.v. exceeds another beta distributed r.v.). See here for more details.
Another alternative, pointed out by J. Cook in his blog is to use the Kumaraswamy distribution to approximate the Beta distribution.
To adhere by the cross-validated rule, I'll briefly summarize the main elements here but go read that post. The CDF of a $K(a, b)$ variable is:
$$F(x|a,b)=1–(1–x^a)^b$$
This CDF is easy to inverse and to draw from so you can easily generate a draw from $K(a,b)$ by generating a $u$ uniform on $[0,1]$ and:
$$F^{-1}(u)=(1 – (1 – u)^{1/b})^{1/a}$$
The idea is that you can pick up the parameters $a$ and $b$ to match most $\text{beta}(\alpha,\beta)$ reasonably well: pick $a=\alpha$ and use a numerical approach to find the optimal $b|a$. Again, more details are given on the original post. Alternatively, you could use a pre-computed table of equivalent parameter sets for Beta and Kumaraswamy distributions (see here) or compute one yourself. | Fast approximation to inverse Beta CDF
whuber's comment is specially true if you want to compute beta inequalities (e.g. the probability that a beta distributed r.v. exceeds another beta distributed r.v.). See here for more details.
Anothe |
25,355 | Fast approximation to inverse Beta CDF | For applications like this, you have to read the literature carefully, because somebody else's approximation might not reproduce the characteristic you are interested in.
There are simple solutions based on precomputing values within the range where a simple approximation (like a Normal approximation) might not do a good job. In this case, you would worry most about where skewness is high: that would be where the Beta parameters are very unequal and relatively small.
One solution is to create an interpolation function or lookup table based on this precomputation. To find the inverse CDF at $0.95$, first look up its value. If the value is found in the table, use that; otherwise, use the generic approximation. Given the ease with which millions of values could be precomputed and stored, this is the way to go for intensive simulations on a PC>
If RAM is really tight or, for some reason, you really want a formula, then the lookup table needs to be replaced by a formula. A good tool for fitting formulas for this purpose is Eureqa Formulize, a free download. This software identifies and fits functions to tabulated data (using a genetic algorithm). It is extremely fast, easy to learn, and fun to watch in action.
Using a table of the $0.95$ quantile of Beta distributions for integer values $(a,b)$ in the range $1\ldots 10$ and minimizing worst case error, I have found--by running the software while writing this paragraph--a large number of approximations. The base case is the normal approximation itself, $z = \text{mean} + \Phi^{-1}(0.95)\times\text{SD}$. Its worst case error is around $0.085$ (which is not terribly good). The formulas I searched for are in terms of $a$, $b$, $z$, the skewness (whose formula in terms of $a$ and $b$ you can look up on Wikipedia), and the central third moment$s_3$ (obtained by multiplying the skewness by the cube of the SD). Among the simpler formulas are
$$0.0012526 + z + 8.90369 s_3 + 0.0344753 z\times \text{skewness}$$
with a worst-case error of $0.011$--pretty good. This is recognizable as the Normal approximation $z$ plus corrections for (a) using the worst-case error as a criterion, which tends to introduce a small bias ($0.0013$) and (b) the skewness (as expected). This formula would be used whenever both $a$ and $b$ are $10$ or less; otherwise, you would revert to the Normal approximation ($z$ itself).
Here is a plot comparing my tabulated values (points) against the formula, taken directly from the software:
(The values jump around because this table of course is two-dimensional: it was originally organized by $a$ and $b$, but then flattened into a traditional spreadsheet format for this analysis.)
By applying this approach to a tabulated set of values you are most interested in, you will obtain different formulas. Pick one that best balances the desired accuracy against the complexity of the formula. | Fast approximation to inverse Beta CDF | For applications like this, you have to read the literature carefully, because somebody else's approximation might not reproduce the characteristic you are interested in.
There are simple solutions ba | Fast approximation to inverse Beta CDF
For applications like this, you have to read the literature carefully, because somebody else's approximation might not reproduce the characteristic you are interested in.
There are simple solutions based on precomputing values within the range where a simple approximation (like a Normal approximation) might not do a good job. In this case, you would worry most about where skewness is high: that would be where the Beta parameters are very unequal and relatively small.
One solution is to create an interpolation function or lookup table based on this precomputation. To find the inverse CDF at $0.95$, first look up its value. If the value is found in the table, use that; otherwise, use the generic approximation. Given the ease with which millions of values could be precomputed and stored, this is the way to go for intensive simulations on a PC>
If RAM is really tight or, for some reason, you really want a formula, then the lookup table needs to be replaced by a formula. A good tool for fitting formulas for this purpose is Eureqa Formulize, a free download. This software identifies and fits functions to tabulated data (using a genetic algorithm). It is extremely fast, easy to learn, and fun to watch in action.
Using a table of the $0.95$ quantile of Beta distributions for integer values $(a,b)$ in the range $1\ldots 10$ and minimizing worst case error, I have found--by running the software while writing this paragraph--a large number of approximations. The base case is the normal approximation itself, $z = \text{mean} + \Phi^{-1}(0.95)\times\text{SD}$. Its worst case error is around $0.085$ (which is not terribly good). The formulas I searched for are in terms of $a$, $b$, $z$, the skewness (whose formula in terms of $a$ and $b$ you can look up on Wikipedia), and the central third moment$s_3$ (obtained by multiplying the skewness by the cube of the SD). Among the simpler formulas are
$$0.0012526 + z + 8.90369 s_3 + 0.0344753 z\times \text{skewness}$$
with a worst-case error of $0.011$--pretty good. This is recognizable as the Normal approximation $z$ plus corrections for (a) using the worst-case error as a criterion, which tends to introduce a small bias ($0.0013$) and (b) the skewness (as expected). This formula would be used whenever both $a$ and $b$ are $10$ or less; otherwise, you would revert to the Normal approximation ($z$ itself).
Here is a plot comparing my tabulated values (points) against the formula, taken directly from the software:
(The values jump around because this table of course is two-dimensional: it was originally organized by $a$ and $b$, but then flattened into a traditional spreadsheet format for this analysis.)
By applying this approach to a tabulated set of values you are most interested in, you will obtain different formulas. Pick one that best balances the desired accuracy against the complexity of the formula. | Fast approximation to inverse Beta CDF
For applications like this, you have to read the literature carefully, because somebody else's approximation might not reproduce the characteristic you are interested in.
There are simple solutions ba |
25,356 | What's the name of this discrete distribution (recursive difference equation) I derived? | In a sense, what you have done is characterize all nonnegative
integer-valued distributions.
Let's set aside the description of the random process for a moment and
focus on the recursions in the question.
If $f_n = p_n (1 - F_{n-1})$, then certainly $F_n = p_n + (1-p_n)
F_{n-1}$. If we rewrite this second recursion in terms of the
survival function $S_n = 1 - F_n = \mathbb P(T > n)$ (where $T$ has
distribution $F$), we get something very suggestive
and easy to handle. Clearly,
$$
S_n = 1 - F_n = (1-p_n) S_{n-1} \>,
$$
and so
$$
S_n = \prod_{k=0}^n (1-p_k) \> .
$$
Thus, as long as our sequence $(p_n)$ takes values in $[0,1]$ and does
not converge too rapidly to zero, then we will obtain a valid survival
function (i.e., monotonically decreasing to zero as $n \to \infty$).
More specifically,
Proposition: A sequence $(p_n)$ taking values in $[0,1]$ determines a distribution on the nonnegative integers if and only
if $$
-\sum_{n=0}^\infty \log(1-p_n) = \infty \>, $$ and all such distributions have a corresponding sequence (though it may not be unique).
Thus, the recursion written in the question is fully general: Any
nonnegative integer valued distribution has a corresponding sequence
$(p_n)$ taking values is $[0,1]$.
However, the converse is not true; that is, there are sequences $(p_n)$ with values in $[0,1]$ that do not correspond to any valid distribution. (In particular, consider $0 < p_n <
1$ for all $n \leq N$ and $p_n = 0$ for $n > N$.)
But, wait, there's more!
We've hinted at a connection to survival analysis and it's worth
exploring this a little more deeply. In classical survival analysis
with an absolutely continuous distribution $F$ and corresponding density $f$, the
hazard function is defined as
$$
h(t) = \frac{f(t)}{S(t)} \>.
$$
The cumulative hazard is then $\Lambda(t) = \int_0^t h(s) \,\mathrm
d s$ and a simple analysis of derivatives shows that
$$
S(t) = \exp(-\Lambda(t)) = \exp\Big(-\int_0^t h(s) \,\mathrm d s\Big)\>.
$$
From this, we can immediately give a characterization of an admissible
hazard function: It is any measurable function $h$ such that $h(t) \geq 0$ for all $t$ and
$\int_0^t h(s) \,\mathrm d s \uparrow \infty$ as $t \to \infty$.
We get a similar recursion for the survival-function to the one above by noticing that for $t > t_0$
$$
S(t) = e^{-\int_{t_0}^t h(s) \,\mathrm d s} S(t_0) \>.
$$
Observe in particular that we could chose $h(t)$ to be piecewise
constant with each piece being of width 1 and such that the integral
converges to infinity. This would yield a survival function $S(t)$
that matches any desired discrete nonnegative integer valued one at
each positive integer.
Connecting back to the discrete case
To match a desired discrete $S(n)$ at each integer, we should choose a
hazard function that is piecewise constant such that
$$
h(t) = h_n = -\log(1-p_n)\>,
$$
on $(n-1,n]$. This provides a second proof of the necessary condition
for the sequence $(p_n)$ to define a valid distribution.
Note that, for small $p_n$, $-\log(1-p_n) \approx p_n = f_n / S_{n-1}$
which provides a heuristic connection between the hazard function of a
continuous distribution and the discrete distribution with matching
survival function on the integers.
Postscript: As a final note, the example $p_n = k n$ in the question does not
satisfy the necessary conditions without an appropriate modification to $f_n$
at $n = \lceil k^{-1} \rceil$ and setting $f_n = 0$ for all $n > \lceil k^{-1} \rceil$. | What's the name of this discrete distribution (recursive difference equation) I derived? | In a sense, what you have done is characterize all nonnegative
integer-valued distributions.
Let's set aside the description of the random process for a moment and
focus on the recursions in the que | What's the name of this discrete distribution (recursive difference equation) I derived?
In a sense, what you have done is characterize all nonnegative
integer-valued distributions.
Let's set aside the description of the random process for a moment and
focus on the recursions in the question.
If $f_n = p_n (1 - F_{n-1})$, then certainly $F_n = p_n + (1-p_n)
F_{n-1}$. If we rewrite this second recursion in terms of the
survival function $S_n = 1 - F_n = \mathbb P(T > n)$ (where $T$ has
distribution $F$), we get something very suggestive
and easy to handle. Clearly,
$$
S_n = 1 - F_n = (1-p_n) S_{n-1} \>,
$$
and so
$$
S_n = \prod_{k=0}^n (1-p_k) \> .
$$
Thus, as long as our sequence $(p_n)$ takes values in $[0,1]$ and does
not converge too rapidly to zero, then we will obtain a valid survival
function (i.e., monotonically decreasing to zero as $n \to \infty$).
More specifically,
Proposition: A sequence $(p_n)$ taking values in $[0,1]$ determines a distribution on the nonnegative integers if and only
if $$
-\sum_{n=0}^\infty \log(1-p_n) = \infty \>, $$ and all such distributions have a corresponding sequence (though it may not be unique).
Thus, the recursion written in the question is fully general: Any
nonnegative integer valued distribution has a corresponding sequence
$(p_n)$ taking values is $[0,1]$.
However, the converse is not true; that is, there are sequences $(p_n)$ with values in $[0,1]$ that do not correspond to any valid distribution. (In particular, consider $0 < p_n <
1$ for all $n \leq N$ and $p_n = 0$ for $n > N$.)
But, wait, there's more!
We've hinted at a connection to survival analysis and it's worth
exploring this a little more deeply. In classical survival analysis
with an absolutely continuous distribution $F$ and corresponding density $f$, the
hazard function is defined as
$$
h(t) = \frac{f(t)}{S(t)} \>.
$$
The cumulative hazard is then $\Lambda(t) = \int_0^t h(s) \,\mathrm
d s$ and a simple analysis of derivatives shows that
$$
S(t) = \exp(-\Lambda(t)) = \exp\Big(-\int_0^t h(s) \,\mathrm d s\Big)\>.
$$
From this, we can immediately give a characterization of an admissible
hazard function: It is any measurable function $h$ such that $h(t) \geq 0$ for all $t$ and
$\int_0^t h(s) \,\mathrm d s \uparrow \infty$ as $t \to \infty$.
We get a similar recursion for the survival-function to the one above by noticing that for $t > t_0$
$$
S(t) = e^{-\int_{t_0}^t h(s) \,\mathrm d s} S(t_0) \>.
$$
Observe in particular that we could chose $h(t)$ to be piecewise
constant with each piece being of width 1 and such that the integral
converges to infinity. This would yield a survival function $S(t)$
that matches any desired discrete nonnegative integer valued one at
each positive integer.
Connecting back to the discrete case
To match a desired discrete $S(n)$ at each integer, we should choose a
hazard function that is piecewise constant such that
$$
h(t) = h_n = -\log(1-p_n)\>,
$$
on $(n-1,n]$. This provides a second proof of the necessary condition
for the sequence $(p_n)$ to define a valid distribution.
Note that, for small $p_n$, $-\log(1-p_n) \approx p_n = f_n / S_{n-1}$
which provides a heuristic connection between the hazard function of a
continuous distribution and the discrete distribution with matching
survival function on the integers.
Postscript: As a final note, the example $p_n = k n$ in the question does not
satisfy the necessary conditions without an appropriate modification to $f_n$
at $n = \lceil k^{-1} \rceil$ and setting $f_n = 0$ for all $n > \lceil k^{-1} \rceil$. | What's the name of this discrete distribution (recursive difference equation) I derived?
In a sense, what you have done is characterize all nonnegative
integer-valued distributions.
Let's set aside the description of the random process for a moment and
focus on the recursions in the que |
25,357 | What's the name of this discrete distribution (recursive difference equation) I derived? | In the case $p(n) = p < 1$, we have some known properties. We can solve the recurrence relation
$$ F(n) = p + F(n-1)(1-p); \; F(0) = p $$
has the solution
$$ F(n) = P(N \le n) = 1- (1-p)^{n+1} $$
which is the geometric distribution. It is well studied.
The more general case of $p(n)$ can probably not be computed in closed form, and thus likely does not have a known distribution.
Other cases:
$p(n) = \frac{p}{n}; \; p<1; \;F(0) = p$ has solution
$$ F(n) = 1 - \frac{(1-p)\Gamma( n + 1 -p)}{\Gamma( 1-p)\Gamma(n+1)} $$
which is not a commonly known distribution.
Define $S(n) = 1-F(n)$ (known as the survival function in stats), the recurrence relation above reduces to the simpler form:
$$S(n) =\left(1 - p(n) \right) S(n-1)$$
From your example, it appears you want a function $p(n)$ that increases in $n$. Your choice $p(n) = kn$ isn't great analytically because of the break at $p>1$. Mathematicians and statisticians prefer smooth things. So I propose
$$p(n) = 1 - \frac{(1-p)}{n+1} \; p<1$$
which $p(0) = p$ and converges to 1. Solving the recurrence relation with this $p(n)$, has the nice analytical form:
$$ F(n) = 1 - \frac{ (1-p)^{n+1} }{ n! } $$
Consider $S(n) = 1 - F(n) = \frac{ (1-p)^{n+1} }{ n! }$. A known stat fact is that
$$\sum_{i=0}^{\infty} S(i) = E[N]$$
which, if you remember some calculus, looks a lot like the exponential's Taylor series, hence,
$$E[N] = (1-p)e^{(1-p) }$$ | What's the name of this discrete distribution (recursive difference equation) I derived? | In the case $p(n) = p < 1$, we have some known properties. We can solve the recurrence relation
$$ F(n) = p + F(n-1)(1-p); \; F(0) = p $$
has the solution
$$ F(n) = P(N \le n) = 1- (1-p)^{n+1} $$
whic | What's the name of this discrete distribution (recursive difference equation) I derived?
In the case $p(n) = p < 1$, we have some known properties. We can solve the recurrence relation
$$ F(n) = p + F(n-1)(1-p); \; F(0) = p $$
has the solution
$$ F(n) = P(N \le n) = 1- (1-p)^{n+1} $$
which is the geometric distribution. It is well studied.
The more general case of $p(n)$ can probably not be computed in closed form, and thus likely does not have a known distribution.
Other cases:
$p(n) = \frac{p}{n}; \; p<1; \;F(0) = p$ has solution
$$ F(n) = 1 - \frac{(1-p)\Gamma( n + 1 -p)}{\Gamma( 1-p)\Gamma(n+1)} $$
which is not a commonly known distribution.
Define $S(n) = 1-F(n)$ (known as the survival function in stats), the recurrence relation above reduces to the simpler form:
$$S(n) =\left(1 - p(n) \right) S(n-1)$$
From your example, it appears you want a function $p(n)$ that increases in $n$. Your choice $p(n) = kn$ isn't great analytically because of the break at $p>1$. Mathematicians and statisticians prefer smooth things. So I propose
$$p(n) = 1 - \frac{(1-p)}{n+1} \; p<1$$
which $p(0) = p$ and converges to 1. Solving the recurrence relation with this $p(n)$, has the nice analytical form:
$$ F(n) = 1 - \frac{ (1-p)^{n+1} }{ n! } $$
Consider $S(n) = 1 - F(n) = \frac{ (1-p)^{n+1} }{ n! }$. A known stat fact is that
$$\sum_{i=0}^{\infty} S(i) = E[N]$$
which, if you remember some calculus, looks a lot like the exponential's Taylor series, hence,
$$E[N] = (1-p)e^{(1-p) }$$ | What's the name of this discrete distribution (recursive difference equation) I derived?
In the case $p(n) = p < 1$, we have some known properties. We can solve the recurrence relation
$$ F(n) = p + F(n-1)(1-p); \; F(0) = p $$
has the solution
$$ F(n) = P(N \le n) = 1- (1-p)^{n+1} $$
whic |
25,358 | Graphs in regression discontinuity design in "Stata" or "R" | Is this much different from doing two local polynomials of degree 2, one for below the threshold and one for above with smooth at $K_i$ points? Here's an example with Stata:
use votex // the election-spending data that comes with rd
tw
(scatter lne d, mcolor(gs10) msize(tiny))
(lpolyci lne d if d<0, bw(0.05) deg(2) n(100) fcolor(none))
(lpolyci lne d if d>=0, bw(0.05) deg(2) n(100) fcolor(none)), xline(0) legend(off)
Alternatively, you can just save the lpoly smoothed values and standard errors as variables instead of using twoway. Below $x$ is the bin, $s$ is the smoothed mean, $se$ is the standard error, and $ul$ and $ll$ are the upper and lower limits of the 95% Confidence Interval for the smoothed outcome.
lpoly lne d if d<0, bw(0.05) deg(2) n(100) gen(x0 s0) ci se(se0)
lpoly lne d if d>=0, bw(0.05) deg(2) n(100) gen(x1 s1) ci se(se1)
/* Get the 95% CIs */
forvalues v=0/1 {
gen ul`v' = s`v' + 1.95*se`v'
gen ll`v' = s`v' - 1.95*se`v'
};
tw
(line ul0 ll0 s0 x0, lcolor(blue blue blue) lpattern(dash dash solid))
(line ul1 ll1 s1 x1, lcolor(red red red) lpattern(dash dash solid)), legend(off)
As you can see, the lines in the first plot are the same as in the second. | Graphs in regression discontinuity design in "Stata" or "R" | Is this much different from doing two local polynomials of degree 2, one for below the threshold and one for above with smooth at $K_i$ points? Here's an example with Stata:
use votex // the election- | Graphs in regression discontinuity design in "Stata" or "R"
Is this much different from doing two local polynomials of degree 2, one for below the threshold and one for above with smooth at $K_i$ points? Here's an example with Stata:
use votex // the election-spending data that comes with rd
tw
(scatter lne d, mcolor(gs10) msize(tiny))
(lpolyci lne d if d<0, bw(0.05) deg(2) n(100) fcolor(none))
(lpolyci lne d if d>=0, bw(0.05) deg(2) n(100) fcolor(none)), xline(0) legend(off)
Alternatively, you can just save the lpoly smoothed values and standard errors as variables instead of using twoway. Below $x$ is the bin, $s$ is the smoothed mean, $se$ is the standard error, and $ul$ and $ll$ are the upper and lower limits of the 95% Confidence Interval for the smoothed outcome.
lpoly lne d if d<0, bw(0.05) deg(2) n(100) gen(x0 s0) ci se(se0)
lpoly lne d if d>=0, bw(0.05) deg(2) n(100) gen(x1 s1) ci se(se1)
/* Get the 95% CIs */
forvalues v=0/1 {
gen ul`v' = s`v' + 1.95*se`v'
gen ll`v' = s`v' - 1.95*se`v'
};
tw
(line ul0 ll0 s0 x0, lcolor(blue blue blue) lpattern(dash dash solid))
(line ul1 ll1 s1 x1, lcolor(red red red) lpattern(dash dash solid)), legend(off)
As you can see, the lines in the first plot are the same as in the second. | Graphs in regression discontinuity design in "Stata" or "R"
Is this much different from doing two local polynomials of degree 2, one for below the threshold and one for above with smooth at $K_i$ points? Here's an example with Stata:
use votex // the election- |
25,359 | Graphs in regression discontinuity design in "Stata" or "R" | Here's a canned algorithm. Calonico, Cattaneo, and Titiunik recently proposed a procedure for robust bandwidth selection. They implemented their theoretical work for both Stata and R, and it also comes with a plot command. Here's an example in R:
# install.packages("rdrobust")
library(rdrobust)
set.seed(26950) # from random.org
x<-runif(1000,-1,1)
y<-5+3*x+2*(x>=0)+rnorm(1000)
rdplot(y,x)
That will give you this graph: | Graphs in regression discontinuity design in "Stata" or "R" | Here's a canned algorithm. Calonico, Cattaneo, and Titiunik recently proposed a procedure for robust bandwidth selection. They implemented their theoretical work for both Stata and R, and it also come | Graphs in regression discontinuity design in "Stata" or "R"
Here's a canned algorithm. Calonico, Cattaneo, and Titiunik recently proposed a procedure for robust bandwidth selection. They implemented their theoretical work for both Stata and R, and it also comes with a plot command. Here's an example in R:
# install.packages("rdrobust")
library(rdrobust)
set.seed(26950) # from random.org
x<-runif(1000,-1,1)
y<-5+3*x+2*(x>=0)+rnorm(1000)
rdplot(y,x)
That will give you this graph: | Graphs in regression discontinuity design in "Stata" or "R"
Here's a canned algorithm. Calonico, Cattaneo, and Titiunik recently proposed a procedure for robust bandwidth selection. They implemented their theoretical work for both Stata and R, and it also come |
25,360 | How do bookmakers select their opening odds? | I found an interview Pinnacle Sportsbook Behind the Scenes Part 2 - Opening Lines and Line Movements on Youtube. It's an interview with a trader working for a bookmaker. I think that some things said there support the claim from appleLover's answer that opening line need not be very sharp.
I tried to get some relevant parts below. As I am not a native English speaker, I might have missed some stuff.
Q: My first question for you is that your lines move much faster and much more precisely than any other book's lines out there.
How do the opening lines get set at Pinnacle?
And is it true that you are not too concerned with having sharp opening lines, since you move them so easily and so quickly?
A: Well, first of all you have to break it down into what we call sports with high liquidity and sports that are not as liquid.
There are lots of sports like futsal, badminton, handball.
These kinds of sports that we will throw up a line based on our best guess, whether other people in the market have it or whatever. Just our personal best guess.
We'll throw up a guess and let the public lead a way and teach us where the right price is and when we get to that right price we up limit a little bit and go from there. And public does a great job in teaching us and more often than not we might be losing in those kinds of situations. But that's part of the business.
In regards to the more major sports, again it depends. Usually, there's some good thought that goes into the opening line.
There's times when we put up an opener before the rest of the world and
obviously we'll be using our thought of where we think the line will end up in that calculation. There are times when
someone else might open before us but we might put a lean towards the number. Usually it's an individual dealer, who's in charge of that sport; he might consult one or two guys and we go with his opinion there.
Sometimes you see a game as a dealer, sometimes you just inevitably think that you're going to get a ton of money on one side or the other.
So you naturally try to encourage money on the other side as early possible.
But we do not have a roomful of savants or computer wizards generating opening lines.
The head dealer picks a line. And I think our model is really the magical thing here, not necessarily genius of some dealer behind the scenes.
It's amazing how quickly, if you just move your line, you get to a really solid number. | How do bookmakers select their opening odds? | I found an interview Pinnacle Sportsbook Behind the Scenes Part 2 - Opening Lines and Line Movements on Youtube. It's an interview with a trader working for a bookmaker. I think that some things said | How do bookmakers select their opening odds?
I found an interview Pinnacle Sportsbook Behind the Scenes Part 2 - Opening Lines and Line Movements on Youtube. It's an interview with a trader working for a bookmaker. I think that some things said there support the claim from appleLover's answer that opening line need not be very sharp.
I tried to get some relevant parts below. As I am not a native English speaker, I might have missed some stuff.
Q: My first question for you is that your lines move much faster and much more precisely than any other book's lines out there.
How do the opening lines get set at Pinnacle?
And is it true that you are not too concerned with having sharp opening lines, since you move them so easily and so quickly?
A: Well, first of all you have to break it down into what we call sports with high liquidity and sports that are not as liquid.
There are lots of sports like futsal, badminton, handball.
These kinds of sports that we will throw up a line based on our best guess, whether other people in the market have it or whatever. Just our personal best guess.
We'll throw up a guess and let the public lead a way and teach us where the right price is and when we get to that right price we up limit a little bit and go from there. And public does a great job in teaching us and more often than not we might be losing in those kinds of situations. But that's part of the business.
In regards to the more major sports, again it depends. Usually, there's some good thought that goes into the opening line.
There's times when we put up an opener before the rest of the world and
obviously we'll be using our thought of where we think the line will end up in that calculation. There are times when
someone else might open before us but we might put a lean towards the number. Usually it's an individual dealer, who's in charge of that sport; he might consult one or two guys and we go with his opinion there.
Sometimes you see a game as a dealer, sometimes you just inevitably think that you're going to get a ton of money on one side or the other.
So you naturally try to encourage money on the other side as early possible.
But we do not have a roomful of savants or computer wizards generating opening lines.
The head dealer picks a line. And I think our model is really the magical thing here, not necessarily genius of some dealer behind the scenes.
It's amazing how quickly, if you just move your line, you get to a really solid number. | How do bookmakers select their opening odds?
I found an interview Pinnacle Sportsbook Behind the Scenes Part 2 - Opening Lines and Line Movements on Youtube. It's an interview with a trader working for a bookmaker. I think that some things said |
25,361 | How do bookmakers select their opening odds? | books open with any crappy line. opening lines are generally not accurate. well, to be exact, a book's opening line is far more accurate than a line a sports fan who doesn't bet could come up with, but also far less accurate than a sports line that people who bets tens of thousands of dollars will come up with... only a couple of books open with lines, they have small limits, and when people start betting they adjust the line to be sharper. then as the line sharpens other books copy the line and raise limits. | How do bookmakers select their opening odds? | books open with any crappy line. opening lines are generally not accurate. well, to be exact, a book's opening line is far more accurate than a line a sports fan who doesn't bet could come up with, | How do bookmakers select their opening odds?
books open with any crappy line. opening lines are generally not accurate. well, to be exact, a book's opening line is far more accurate than a line a sports fan who doesn't bet could come up with, but also far less accurate than a sports line that people who bets tens of thousands of dollars will come up with... only a couple of books open with lines, they have small limits, and when people start betting they adjust the line to be sharper. then as the line sharpens other books copy the line and raise limits. | How do bookmakers select their opening odds?
books open with any crappy line. opening lines are generally not accurate. well, to be exact, a book's opening line is far more accurate than a line a sports fan who doesn't bet could come up with, |
25,362 | How do bookmakers select their opening odds? | In the UK for horse racing, form books would be the obvious source for the bookie to apply his judgement with. Similar statistics exist for most other sports and for many other topics. Otherwise, the bookie would probably acquaint him/herself with received opinion for the topic. | How do bookmakers select their opening odds? | In the UK for horse racing, form books would be the obvious source for the bookie to apply his judgement with. Similar statistics exist for most other sports and for many other topics. Otherwise, th | How do bookmakers select their opening odds?
In the UK for horse racing, form books would be the obvious source for the bookie to apply his judgement with. Similar statistics exist for most other sports and for many other topics. Otherwise, the bookie would probably acquaint him/herself with received opinion for the topic. | How do bookmakers select their opening odds?
In the UK for horse racing, form books would be the obvious source for the bookie to apply his judgement with. Similar statistics exist for most other sports and for many other topics. Otherwise, th |
25,363 | Should I use a binomial cdf or a normal cdf when flipping coins? | Here is an illustration of the answers of whuber and onestop.
In red the binomial distribution $\mathcal Bin(50,0.5)$, in black the density of the normal approximation $\mathcal N(25, 12.5)$, and in blue the surface corresponding to $\mathbb P(Y > 29.5)$ for $Y \sim \mathcal N(25, 12.5)$.
The height of a red bar corresponding to $\mathbb P(X=k)$ for $X\sim\mathcal Bin(50,0.5)$ is well approximated by $\mathbb P\left( k -{1\over 2} < Y < k + {1\over 2}\right)$. To get a good approximation of $\mathbb P(X \ge 30)$, you need to use $\mathbb P(Y>29.5)$.
(edit) This is
$$\mathbb P(Y>29.5) \simeq 0.1015459,$$
(obtained in R by 1-pnorm(29.5,25,sqrt(12.5))) whereas
$$\mathbb P(X \ge 30) \simeq 0.1013194:$$
the approximation is correct.
This is called continuity correction. It allows you to compute even "point probabilities" like $\mathbb P(X=22)$ :
$$\begin{align*}
\mathbb P(X=22) &= {50 \choose 22} 0.5^{22} \cdot 0.5^{28} \simeq 0.07882567, \\
\mathbb P(21.5 < Y < 22.5) & \simeq 0.2397501 - 0.1610994 \simeq 0.07865066.\end{align*}$$ | Should I use a binomial cdf or a normal cdf when flipping coins? | Here is an illustration of the answers of whuber and onestop.
In red the binomial distribution $\mathcal Bin(50,0.5)$, in black the density of the normal approximation $\mathcal N(25, 12.5)$, and in | Should I use a binomial cdf or a normal cdf when flipping coins?
Here is an illustration of the answers of whuber and onestop.
In red the binomial distribution $\mathcal Bin(50,0.5)$, in black the density of the normal approximation $\mathcal N(25, 12.5)$, and in blue the surface corresponding to $\mathbb P(Y > 29.5)$ for $Y \sim \mathcal N(25, 12.5)$.
The height of a red bar corresponding to $\mathbb P(X=k)$ for $X\sim\mathcal Bin(50,0.5)$ is well approximated by $\mathbb P\left( k -{1\over 2} < Y < k + {1\over 2}\right)$. To get a good approximation of $\mathbb P(X \ge 30)$, you need to use $\mathbb P(Y>29.5)$.
(edit) This is
$$\mathbb P(Y>29.5) \simeq 0.1015459,$$
(obtained in R by 1-pnorm(29.5,25,sqrt(12.5))) whereas
$$\mathbb P(X \ge 30) \simeq 0.1013194:$$
the approximation is correct.
This is called continuity correction. It allows you to compute even "point probabilities" like $\mathbb P(X=22)$ :
$$\begin{align*}
\mathbb P(X=22) &= {50 \choose 22} 0.5^{22} \cdot 0.5^{28} \simeq 0.07882567, \\
\mathbb P(21.5 < Y < 22.5) & \simeq 0.2397501 - 0.1610994 \simeq 0.07865066.\end{align*}$$ | Should I use a binomial cdf or a normal cdf when flipping coins?
Here is an illustration of the answers of whuber and onestop.
In red the binomial distribution $\mathcal Bin(50,0.5)$, in black the density of the normal approximation $\mathcal N(25, 12.5)$, and in |
25,364 | Should I use a binomial cdf or a normal cdf when flipping coins? | The normal distribution gives a closer approximation to the binomial if you use a continuity correction. Using this for your example, I get 0.1015. As this is homework, I'll leave it to you to fill in the details. | Should I use a binomial cdf or a normal cdf when flipping coins? | The normal distribution gives a closer approximation to the binomial if you use a continuity correction. Using this for your example, I get 0.1015. As this is homework, I'll leave it to you to fill in | Should I use a binomial cdf or a normal cdf when flipping coins?
The normal distribution gives a closer approximation to the binomial if you use a continuity correction. Using this for your example, I get 0.1015. As this is homework, I'll leave it to you to fill in the details. | Should I use a binomial cdf or a normal cdf when flipping coins?
The normal distribution gives a closer approximation to the binomial if you use a continuity correction. Using this for your example, I get 0.1015. As this is homework, I'll leave it to you to fill in |
25,365 | Should I use a binomial cdf or a normal cdf when flipping coins? | Consider this. In the discrete binomial distribution you have actual probabilities for individual numbers. In the continuous normal that isn't the case, you need a range of values. So... if you were going to approximate the probability of an individual value, let's say X, from the binomial with the normal how would you do that? Look at a probability histogram of the binomial distribution with the normal curve laid over it. You would need to actually select from X ± 0.5 to capture something similar to what the binomial probability of X is with the normal approximation.
Now extend that to when you're selecting a tail of the distribution. When you use the binomial method you're selecting your entire value's probability (30 in your case) plus everything higher. Therefore, when you do the continuous you have to make sure you capture that and select 0.5 less as well, so the cutoff on the continuous distribution is 29.5. | Should I use a binomial cdf or a normal cdf when flipping coins? | Consider this. In the discrete binomial distribution you have actual probabilities for individual numbers. In the continuous normal that isn't the case, you need a range of values. So... if you wer | Should I use a binomial cdf or a normal cdf when flipping coins?
Consider this. In the discrete binomial distribution you have actual probabilities for individual numbers. In the continuous normal that isn't the case, you need a range of values. So... if you were going to approximate the probability of an individual value, let's say X, from the binomial with the normal how would you do that? Look at a probability histogram of the binomial distribution with the normal curve laid over it. You would need to actually select from X ± 0.5 to capture something similar to what the binomial probability of X is with the normal approximation.
Now extend that to when you're selecting a tail of the distribution. When you use the binomial method you're selecting your entire value's probability (30 in your case) plus everything higher. Therefore, when you do the continuous you have to make sure you capture that and select 0.5 less as well, so the cutoff on the continuous distribution is 29.5. | Should I use a binomial cdf or a normal cdf when flipping coins?
Consider this. In the discrete binomial distribution you have actual probabilities for individual numbers. In the continuous normal that isn't the case, you need a range of values. So... if you wer |
25,366 | What are the predicted values returned by the predict() function in R when using original data as input? | The model you are working with takes the form
$y_{i} = \mu + \beta_{1} x_{1i} + \beta_{2} x_{2i} + \epsilon_{i}$ $\hspace{0.75cm}$ (1)
where $\epsilon_{i}$ is an error term assumed to come from a zero-mean normal distribution.
You have fitted the model and you have obtained estimates: $\hat{\mu}$, $\hat{\beta}_{1}$, and $\hat{\beta}_{2}$.
Now, if you fix covariate values within their range, say $x^{\star}_{1i}$ and $x^{\star}_{2i}$, a predicted value for $y_{i}$ can be obtained by computing
$y^{\star}_{i} = \hat{\mu} + \hat{\beta}_{1} x^{\star}_{1i} + \hat{\beta}_{2} x^{\star}_{2i}$ $\hspace{0.75cm}$ (2)
If your model fits perfectly your data, then predicted values are actual values. But, in general, $y$ values cannot be exactly obtained as a simple linear combination of $x$ values ("All models are wrong, but some are useful"). In other terms, the variance of the error term in (1) is not zero in general. But, basically, model (1) is a good approximation if the residuals $y_{i} - y_{i}^{\star}$ (or a scaled version of these) are "small".
Edit
In your comments, you asked what predict() actually does. Here is a simple illustrative example.
#generate a simple illustrative data set
> x <- runif(10)
> y <- 5 + 2.7 * x + rnorm(10, mean=0, sd=sqrt(0.15))
>
> #fit the model and store the coefficients
> regLin <- lm(y~x)
> coef <- coef(regLin)
>
> #use the predict() function
> y_star2 <- predict(regLin)
> #use equation (2)
> y_star1 <- coef[1] + coef[2] * x
> #compare
> cbind(y, y_star1, y_star2)
y y_star1 y_star2
1 7.100217 6.813616 6.813616
2 6.186333 5.785473 5.785473
3 7.141016 7.492979 7.492979
4 5.121265 5.282990 5.282990
5 4.681924 4.849776 4.849776
6 6.102339 6.106751 6.106751
7 7.223215 7.156512 7.156512
8 5.158546 5.253380 5.253380
9 7.160201 7.198074 7.198074
10 5.555289 5.490793 5.490793 | What are the predicted values returned by the predict() function in R when using original data as in | The model you are working with takes the form
$y_{i} = \mu + \beta_{1} x_{1i} + \beta_{2} x_{2i} + \epsilon_{i}$ $\hspace{0.75cm}$ (1)
where $\epsilon_{i}$ is an error term assumed to come from a z | What are the predicted values returned by the predict() function in R when using original data as input?
The model you are working with takes the form
$y_{i} = \mu + \beta_{1} x_{1i} + \beta_{2} x_{2i} + \epsilon_{i}$ $\hspace{0.75cm}$ (1)
where $\epsilon_{i}$ is an error term assumed to come from a zero-mean normal distribution.
You have fitted the model and you have obtained estimates: $\hat{\mu}$, $\hat{\beta}_{1}$, and $\hat{\beta}_{2}$.
Now, if you fix covariate values within their range, say $x^{\star}_{1i}$ and $x^{\star}_{2i}$, a predicted value for $y_{i}$ can be obtained by computing
$y^{\star}_{i} = \hat{\mu} + \hat{\beta}_{1} x^{\star}_{1i} + \hat{\beta}_{2} x^{\star}_{2i}$ $\hspace{0.75cm}$ (2)
If your model fits perfectly your data, then predicted values are actual values. But, in general, $y$ values cannot be exactly obtained as a simple linear combination of $x$ values ("All models are wrong, but some are useful"). In other terms, the variance of the error term in (1) is not zero in general. But, basically, model (1) is a good approximation if the residuals $y_{i} - y_{i}^{\star}$ (or a scaled version of these) are "small".
Edit
In your comments, you asked what predict() actually does. Here is a simple illustrative example.
#generate a simple illustrative data set
> x <- runif(10)
> y <- 5 + 2.7 * x + rnorm(10, mean=0, sd=sqrt(0.15))
>
> #fit the model and store the coefficients
> regLin <- lm(y~x)
> coef <- coef(regLin)
>
> #use the predict() function
> y_star2 <- predict(regLin)
> #use equation (2)
> y_star1 <- coef[1] + coef[2] * x
> #compare
> cbind(y, y_star1, y_star2)
y y_star1 y_star2
1 7.100217 6.813616 6.813616
2 6.186333 5.785473 5.785473
3 7.141016 7.492979 7.492979
4 5.121265 5.282990 5.282990
5 4.681924 4.849776 4.849776
6 6.102339 6.106751 6.106751
7 7.223215 7.156512 7.156512
8 5.158546 5.253380 5.253380
9 7.160201 7.198074 7.198074
10 5.555289 5.490793 5.490793 | What are the predicted values returned by the predict() function in R when using original data as in
The model you are working with takes the form
$y_{i} = \mu + \beta_{1} x_{1i} + \beta_{2} x_{2i} + \epsilon_{i}$ $\hspace{0.75cm}$ (1)
where $\epsilon_{i}$ is an error term assumed to come from a z |
25,367 | Algorithms and methods for attribute/feature selection? | My heart will be always with RF, but still you may take a look at Rough Sets. Especially LERS works quite good in case of massively disturbed data.
You may also try with importance obtained from other classifiers, like SVMs or Random Naive Bayes. | Algorithms and methods for attribute/feature selection? | My heart will be always with RF, but still you may take a look at Rough Sets. Especially LERS works quite good in case of massively disturbed data.
You may also try with importance obtained from other | Algorithms and methods for attribute/feature selection?
My heart will be always with RF, but still you may take a look at Rough Sets. Especially LERS works quite good in case of massively disturbed data.
You may also try with importance obtained from other classifiers, like SVMs or Random Naive Bayes. | Algorithms and methods for attribute/feature selection?
My heart will be always with RF, but still you may take a look at Rough Sets. Especially LERS works quite good in case of massively disturbed data.
You may also try with importance obtained from other |
25,368 | Algorithms and methods for attribute/feature selection? | The Task view on Machine Learning and Statistical Learning is a good starting point for question like this. | Algorithms and methods for attribute/feature selection? | The Task view on Machine Learning and Statistical Learning is a good starting point for question like this. | Algorithms and methods for attribute/feature selection?
The Task view on Machine Learning and Statistical Learning is a good starting point for question like this. | Algorithms and methods for attribute/feature selection?
The Task view on Machine Learning and Statistical Learning is a good starting point for question like this. |
25,369 | Algorithms and methods for attribute/feature selection? | Regularised regression with an L1 penatly term has worked well for me (c.f. LASSO and LARS). | Algorithms and methods for attribute/feature selection? | Regularised regression with an L1 penatly term has worked well for me (c.f. LASSO and LARS). | Algorithms and methods for attribute/feature selection?
Regularised regression with an L1 penatly term has worked well for me (c.f. LASSO and LARS). | Algorithms and methods for attribute/feature selection?
Regularised regression with an L1 penatly term has worked well for me (c.f. LASSO and LARS). |
25,370 | Algorithms and methods for attribute/feature selection? | I'm a big fan of the rfe function in the caret package. You can easily use it to cross-validate feature importance ratings from a random forest, a linear model, a bagged-tree model, a naive bayesian model, or any other algorithm that returns a measure of variable importance.
You can read more here. | Algorithms and methods for attribute/feature selection? | I'm a big fan of the rfe function in the caret package. You can easily use it to cross-validate feature importance ratings from a random forest, a linear model, a bagged-tree model, a naive bayesian | Algorithms and methods for attribute/feature selection?
I'm a big fan of the rfe function in the caret package. You can easily use it to cross-validate feature importance ratings from a random forest, a linear model, a bagged-tree model, a naive bayesian model, or any other algorithm that returns a measure of variable importance.
You can read more here. | Algorithms and methods for attribute/feature selection?
I'm a big fan of the rfe function in the caret package. You can easily use it to cross-validate feature importance ratings from a random forest, a linear model, a bagged-tree model, a naive bayesian |
25,371 | Algorithms and methods for attribute/feature selection? | I have had good results with ensemble feature selection procedures. For implementation you can take a look at the Java-ML library.
For references see for example here.
I believe that these procedures are also readily availiable in R. | Algorithms and methods for attribute/feature selection? | I have had good results with ensemble feature selection procedures. For implementation you can take a look at the Java-ML library.
For references see for example here.
I believe that these procedures | Algorithms and methods for attribute/feature selection?
I have had good results with ensemble feature selection procedures. For implementation you can take a look at the Java-ML library.
For references see for example here.
I believe that these procedures are also readily availiable in R. | Algorithms and methods for attribute/feature selection?
I have had good results with ensemble feature selection procedures. For implementation you can take a look at the Java-ML library.
For references see for example here.
I believe that these procedures |
25,372 | Algorithms and methods for attribute/feature selection? | Principal Component Analysis is a fairly common technique used to reduce the dimension of sampled data. You can find a very good implementation in R. | Algorithms and methods for attribute/feature selection? | Principal Component Analysis is a fairly common technique used to reduce the dimension of sampled data. You can find a very good implementation in R. | Algorithms and methods for attribute/feature selection?
Principal Component Analysis is a fairly common technique used to reduce the dimension of sampled data. You can find a very good implementation in R. | Algorithms and methods for attribute/feature selection?
Principal Component Analysis is a fairly common technique used to reduce the dimension of sampled data. You can find a very good implementation in R. |
25,373 | How to perform a 4 by 4 mixed ANOVA with between- and within-subjects contrasts using R? | A sketch of one solution (for another see below):
Data needs to be in the long format (i.e., on value per row) instead of in the wide format as in SPSS (i.e., one subject per row), see the reshape package, or ?reshape. That includes that there needs to be a variable indicating the subject identifier (i.e., subject id).
All factors (including the subject identifier) must be of class factor (run str on your data frame to check this). If you don't do this your results will be wrong.
If you want to obtain type-III sums of squares set the default contrasts to effect coding:
options(contrasts=c("contr.sum","contr.poly"))
Specify the desired model with lme from the nlme package (install and load the package beforehands via install.packages("nlme") and library(nlme)) using a compund symmetric correlation structure. See the answer and especially my comment to the accepted answer to this question. In your case that could be something like (if you would have provided sample data, which is strongly recommended, you would have received the correct code):
my.anova <- lme(dv ~ group*within, data = your.df, random = ~1|id, correlation = corCompSymm(form = ~1|id))
Use the generic anova function to obtain the anova table (see ?anova.lme):
anova(my.anova)
To obtain type-III sums of squares use the anova command with argument type set to "marginal" (this only works if contrasts are set to effects coding, see point 3):
anova(my.anova, type = "marginal")
The fitted object of type lme now allows diverse functions to perform contrasts. The most flexible solution (but a rather unhandy one) is the L argument in a call to anova.lme (see again ?anova.lme).
Other solutions also require a fitted lme object as an argument:
Also very flexible is the estimable function from the gmodels package. This package also offers the fit.contrasts function.
The multcomp package allows contrasts using alpha-error adjustment (but you can only perform contrasts using one of your factors), using the glht function.
A new and promising approach is the contrast package, however, so far it does not seem to privde all possible contrasts.
An alternative solution is to use standard ANOVA via the combination of afex and lsmeans as outlined in the afex-vignette. | How to perform a 4 by 4 mixed ANOVA with between- and within-subjects contrasts using R? | A sketch of one solution (for another see below):
Data needs to be in the long format (i.e., on value per row) instead of in the wide format as in SPSS (i.e., one subject per row), see the reshape pa | How to perform a 4 by 4 mixed ANOVA with between- and within-subjects contrasts using R?
A sketch of one solution (for another see below):
Data needs to be in the long format (i.e., on value per row) instead of in the wide format as in SPSS (i.e., one subject per row), see the reshape package, or ?reshape. That includes that there needs to be a variable indicating the subject identifier (i.e., subject id).
All factors (including the subject identifier) must be of class factor (run str on your data frame to check this). If you don't do this your results will be wrong.
If you want to obtain type-III sums of squares set the default contrasts to effect coding:
options(contrasts=c("contr.sum","contr.poly"))
Specify the desired model with lme from the nlme package (install and load the package beforehands via install.packages("nlme") and library(nlme)) using a compund symmetric correlation structure. See the answer and especially my comment to the accepted answer to this question. In your case that could be something like (if you would have provided sample data, which is strongly recommended, you would have received the correct code):
my.anova <- lme(dv ~ group*within, data = your.df, random = ~1|id, correlation = corCompSymm(form = ~1|id))
Use the generic anova function to obtain the anova table (see ?anova.lme):
anova(my.anova)
To obtain type-III sums of squares use the anova command with argument type set to "marginal" (this only works if contrasts are set to effects coding, see point 3):
anova(my.anova, type = "marginal")
The fitted object of type lme now allows diverse functions to perform contrasts. The most flexible solution (but a rather unhandy one) is the L argument in a call to anova.lme (see again ?anova.lme).
Other solutions also require a fitted lme object as an argument:
Also very flexible is the estimable function from the gmodels package. This package also offers the fit.contrasts function.
The multcomp package allows contrasts using alpha-error adjustment (but you can only perform contrasts using one of your factors), using the glht function.
A new and promising approach is the contrast package, however, so far it does not seem to privde all possible contrasts.
An alternative solution is to use standard ANOVA via the combination of afex and lsmeans as outlined in the afex-vignette. | How to perform a 4 by 4 mixed ANOVA with between- and within-subjects contrasts using R?
A sketch of one solution (for another see below):
Data needs to be in the long format (i.e., on value per row) instead of in the wide format as in SPSS (i.e., one subject per row), see the reshape pa |
25,374 | Compare R-squared from two different Random Forest models | Cross-validate! Use the train function in caret to fit your 2 models. Use one value of mtry (the same for both models). Caret will return a re-sampled estimate of RMSE and $R^2$.
See page 3 of the caret vignette (also in the full reference manual) | Compare R-squared from two different Random Forest models | Cross-validate! Use the train function in caret to fit your 2 models. Use one value of mtry (the same for both models). Caret will return a re-sampled estimate of RMSE and $R^2$.
See page 3 of the c | Compare R-squared from two different Random Forest models
Cross-validate! Use the train function in caret to fit your 2 models. Use one value of mtry (the same for both models). Caret will return a re-sampled estimate of RMSE and $R^2$.
See page 3 of the caret vignette (also in the full reference manual) | Compare R-squared from two different Random Forest models
Cross-validate! Use the train function in caret to fit your 2 models. Use one value of mtry (the same for both models). Caret will return a re-sampled estimate of RMSE and $R^2$.
See page 3 of the c |
25,375 | Compare R-squared from two different Random Forest models | I agree with Zach that the best idea is to cross-validate both models and then compare the $R^2$s, for instance by collecting values from each fold and comparing the resulting vectors with Wilcoxon test (paired for k-fold, unpaired for random CV).
The side option is to use all relevant feature selection, what would told you which attributes have a chance to be significantly useful for classification -- thus weather those expensive attributes are worth their price. It can be done for instance with a RF wrapper, Boruta. | Compare R-squared from two different Random Forest models | I agree with Zach that the best idea is to cross-validate both models and then compare the $R^2$s, for instance by collecting values from each fold and comparing the resulting vectors with Wilcoxon te | Compare R-squared from two different Random Forest models
I agree with Zach that the best idea is to cross-validate both models and then compare the $R^2$s, for instance by collecting values from each fold and comparing the resulting vectors with Wilcoxon test (paired for k-fold, unpaired for random CV).
The side option is to use all relevant feature selection, what would told you which attributes have a chance to be significantly useful for classification -- thus weather those expensive attributes are worth their price. It can be done for instance with a RF wrapper, Boruta. | Compare R-squared from two different Random Forest models
I agree with Zach that the best idea is to cross-validate both models and then compare the $R^2$s, for instance by collecting values from each fold and comparing the resulting vectors with Wilcoxon te |
25,376 | Compare R-squared from two different Random Forest models | You may want to think in terms of practical significance rather than statistical significance (or both). With enough data you can find things signifcant statistically that will have no real impact on your usage. I remember analyzing a model one time where the 5-way interactions were statistically significant, but when the predictions from the model including everything up to the 5-way interactions were compared to the predictions from a model including only 2-way interactions and main effects, the biggest difference was less than 1 person (the response was number of people and all interesting values were away from 0). So the added complexity was not worth it. So look at the differences in your predictions to see if the differences are enough to justify the extra cost, if not then why bother even looking for the statistical significance? If the differences are big enough to justify the cost if they are real, then I second the other sugestions of using cross validation. | Compare R-squared from two different Random Forest models | You may want to think in terms of practical significance rather than statistical significance (or both). With enough data you can find things signifcant statistically that will have no real impact on | Compare R-squared from two different Random Forest models
You may want to think in terms of practical significance rather than statistical significance (or both). With enough data you can find things signifcant statistically that will have no real impact on your usage. I remember analyzing a model one time where the 5-way interactions were statistically significant, but when the predictions from the model including everything up to the 5-way interactions were compared to the predictions from a model including only 2-way interactions and main effects, the biggest difference was less than 1 person (the response was number of people and all interesting values were away from 0). So the added complexity was not worth it. So look at the differences in your predictions to see if the differences are enough to justify the extra cost, if not then why bother even looking for the statistical significance? If the differences are big enough to justify the cost if they are real, then I second the other sugestions of using cross validation. | Compare R-squared from two different Random Forest models
You may want to think in terms of practical significance rather than statistical significance (or both). With enough data you can find things signifcant statistically that will have no real impact on |
25,377 | Compare R-squared from two different Random Forest models | One option would be to create a confidence interval for the mean squared error. I would use the mean squared error instead of $R^2$ since the denominator is the same for both models. The paper by Dudoit and van der Laan (article and working paper) provides a general theorem for the construction of a confidence interval for any risk estimator. Using the example from the iris data, here is some R code creating a 95% confidence interval using the method:
library(randomForest)
data(iris)
set.seed(42)
# split the data into training and testing sets
index <- 1:nrow(iris)
trainindex <- sample(index, trunc(length(index)/2))
trainset <- iris[trainindex, ]
testset <- iris[-trainindex, ]
# with species
model1 <- randomForest(Sepal.Length ~ Sepal.Width + Petal.Length +
Petal.Width + Species, data = trainset)
# without species
model2 <- randomForest(Sepal.Length ~ Sepal.Width + Petal.Length +
Petal.Width, data = trainset)
pred1 <- predict(model1, testset[, -1])
pred2 <- predict(model2, testset[, -1])
y <- testset[, 1]
n <- length(y)
# psi is the mean squared prediction error (MSPE) estimate
# sigma2 is the estimate of the variance of the MSPE
psi1 <- mean((y - pred1)^2)
sigma21 <- 1/n * var((y - pred1)^2)
# 95% CI:
c(psi1 - 1.96 * sqrt(sigma21), psi1, psi1 + 1.96 * sqrt(sigma21))
psi2 <- mean((y - pred2)^2)
sigma22 <- 1/n * var((y - pred2)^2)
# 95% CI:
c(psi2 - 1.96 * sqrt(sigma22), psi2, psi2 + 1.96 * sqrt(sigma22))
The method can also be extended to work within cross-validation (not just sample-split as shown above). | Compare R-squared from two different Random Forest models | One option would be to create a confidence interval for the mean squared error. I would use the mean squared error instead of $R^2$ since the denominator is the same for both models. The paper by Dudo | Compare R-squared from two different Random Forest models
One option would be to create a confidence interval for the mean squared error. I would use the mean squared error instead of $R^2$ since the denominator is the same for both models. The paper by Dudoit and van der Laan (article and working paper) provides a general theorem for the construction of a confidence interval for any risk estimator. Using the example from the iris data, here is some R code creating a 95% confidence interval using the method:
library(randomForest)
data(iris)
set.seed(42)
# split the data into training and testing sets
index <- 1:nrow(iris)
trainindex <- sample(index, trunc(length(index)/2))
trainset <- iris[trainindex, ]
testset <- iris[-trainindex, ]
# with species
model1 <- randomForest(Sepal.Length ~ Sepal.Width + Petal.Length +
Petal.Width + Species, data = trainset)
# without species
model2 <- randomForest(Sepal.Length ~ Sepal.Width + Petal.Length +
Petal.Width, data = trainset)
pred1 <- predict(model1, testset[, -1])
pred2 <- predict(model2, testset[, -1])
y <- testset[, 1]
n <- length(y)
# psi is the mean squared prediction error (MSPE) estimate
# sigma2 is the estimate of the variance of the MSPE
psi1 <- mean((y - pred1)^2)
sigma21 <- 1/n * var((y - pred1)^2)
# 95% CI:
c(psi1 - 1.96 * sqrt(sigma21), psi1, psi1 + 1.96 * sqrt(sigma21))
psi2 <- mean((y - pred2)^2)
sigma22 <- 1/n * var((y - pred2)^2)
# 95% CI:
c(psi2 - 1.96 * sqrt(sigma22), psi2, psi2 + 1.96 * sqrt(sigma22))
The method can also be extended to work within cross-validation (not just sample-split as shown above). | Compare R-squared from two different Random Forest models
One option would be to create a confidence interval for the mean squared error. I would use the mean squared error instead of $R^2$ since the denominator is the same for both models. The paper by Dudo |
25,378 | Compare R-squared from two different Random Forest models | Since you're already using randomForest after you cross-validate you might emit the chosen fit's computation of the predictor importance values.
> require(randomForest)
> rf.fit = randomForest(Species~.,data=iris,importance=TRUE)
> rf.fit$importance
setosa versicolor virginica MeanDecreaseAccuracy MeanDecreaseGini
Sepal.Length 0.036340893 0.021013369 0.032345037 0.030708732 9.444598
Sepal.Width 0.005399468 -0.002131412 0.007499143 0.003577089 2.046650
Petal.Length 0.319872296 0.297426025 0.290278930 0.299795555 42.494972
Petal.Width 0.343995456 0.309455331 0.277644128 0.307843300 45.286720 | Compare R-squared from two different Random Forest models | Since you're already using randomForest after you cross-validate you might emit the chosen fit's computation of the predictor importance values.
> require(randomForest)
> rf.fit = randomForest(Species | Compare R-squared from two different Random Forest models
Since you're already using randomForest after you cross-validate you might emit the chosen fit's computation of the predictor importance values.
> require(randomForest)
> rf.fit = randomForest(Species~.,data=iris,importance=TRUE)
> rf.fit$importance
setosa versicolor virginica MeanDecreaseAccuracy MeanDecreaseGini
Sepal.Length 0.036340893 0.021013369 0.032345037 0.030708732 9.444598
Sepal.Width 0.005399468 -0.002131412 0.007499143 0.003577089 2.046650
Petal.Length 0.319872296 0.297426025 0.290278930 0.299795555 42.494972
Petal.Width 0.343995456 0.309455331 0.277644128 0.307843300 45.286720 | Compare R-squared from two different Random Forest models
Since you're already using randomForest after you cross-validate you might emit the chosen fit's computation of the predictor importance values.
> require(randomForest)
> rf.fit = randomForest(Species |
25,379 | Compare R-squared from two different Random Forest models | I see this question has been asked long time ago; however, no answer points out to the significant shortcomings and misunderstandings in the question yet.
Please note:
You state that R^2 = ESS/TSS = 1 - RSS/TSS. This is only true in a linear context. The equality TSS = RSS + ESS holds true only in linear regression with intercept. Thus you can not use those definitions for random forests interchangeably. This is why RMSE and similar are more typical loss functions.
More importantly for statistical purposes: R^2 follows an unknown distribution (also in the linear setting). That means, testing a hypothesis with statistical significance using R^2 is not as straightforward. Cross-Validation, as mentioned by Zach, is a good choice.
As for user88 response: Cross validation with Wilcoxon test is a valid approach. A recent paper uses Wilcoxon signed ranks test and Friedman tests for comparison of different methods and algorithms. | Compare R-squared from two different Random Forest models | I see this question has been asked long time ago; however, no answer points out to the significant shortcomings and misunderstandings in the question yet.
Please note:
You state that R^2 = ESS/TSS = | Compare R-squared from two different Random Forest models
I see this question has been asked long time ago; however, no answer points out to the significant shortcomings and misunderstandings in the question yet.
Please note:
You state that R^2 = ESS/TSS = 1 - RSS/TSS. This is only true in a linear context. The equality TSS = RSS + ESS holds true only in linear regression with intercept. Thus you can not use those definitions for random forests interchangeably. This is why RMSE and similar are more typical loss functions.
More importantly for statistical purposes: R^2 follows an unknown distribution (also in the linear setting). That means, testing a hypothesis with statistical significance using R^2 is not as straightforward. Cross-Validation, as mentioned by Zach, is a good choice.
As for user88 response: Cross validation with Wilcoxon test is a valid approach. A recent paper uses Wilcoxon signed ranks test and Friedman tests for comparison of different methods and algorithms. | Compare R-squared from two different Random Forest models
I see this question has been asked long time ago; however, no answer points out to the significant shortcomings and misunderstandings in the question yet.
Please note:
You state that R^2 = ESS/TSS = |
25,380 | Are there cases where there is no optimal k in k-means? | In most situations, I would have thought that dsuch a plot basically means that there is no cluster structure in the data. However, clustering in very high dimensions such as this is tricky as for the Euclidean distance metric all distances tend to the same as the number of dimensions increases. See this Wikipedia page for references to some papers on this topic. In short, it may just be the high-dimensionality of the dataset that is the problem.
This is essentially "the curse of dimensionality", see this Wikipedia page as well.
A paper that may be of interest is Sanguinetti, G., "Dimensionality reduction of clustered datsets", IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 30 no. 3, pp. 535-540, March 2008 (www). Which is a bit like an unsupervised version of LDA that seeks out a low-dimensional space that emphasises the cluster structure. Perhaps you could use that as a feature extraction method before performing k-means? | Are there cases where there is no optimal k in k-means? | In most situations, I would have thought that dsuch a plot basically means that there is no cluster structure in the data. However, clustering in very high dimensions such as this is tricky as for th | Are there cases where there is no optimal k in k-means?
In most situations, I would have thought that dsuch a plot basically means that there is no cluster structure in the data. However, clustering in very high dimensions such as this is tricky as for the Euclidean distance metric all distances tend to the same as the number of dimensions increases. See this Wikipedia page for references to some papers on this topic. In short, it may just be the high-dimensionality of the dataset that is the problem.
This is essentially "the curse of dimensionality", see this Wikipedia page as well.
A paper that may be of interest is Sanguinetti, G., "Dimensionality reduction of clustered datsets", IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 30 no. 3, pp. 535-540, March 2008 (www). Which is a bit like an unsupervised version of LDA that seeks out a low-dimensional space that emphasises the cluster structure. Perhaps you could use that as a feature extraction method before performing k-means? | Are there cases where there is no optimal k in k-means?
In most situations, I would have thought that dsuch a plot basically means that there is no cluster structure in the data. However, clustering in very high dimensions such as this is tricky as for th |
25,381 | Are there cases where there is no optimal k in k-means? | How exactly do you use cosine similarity? Is this what is refered to as spherical K-means? Your data set is quite small, so I would try to visualise it as a network. For this it is natural to use a similarity (indeed, for example the cosine similarity or Pearson correlation), apply a cut-off (only consider relationships above a certain similarity), and view the result as a network in for example Cytoscape or BioLayout. This can be very helpful to get a feeling for the data.
Second, I would compute the singular values for your data matrix, or the eigenvalues of an appropriately transformed and normalised matrix (a document-document matrix obtained in some form). Cluster structure should (again) show up as a jump in the ordered list of eigenvalues or singular values. | Are there cases where there is no optimal k in k-means? | How exactly do you use cosine similarity? Is this what is refered to as spherical K-means? Your data set is quite small, so I would try to visualise it as a network. For this it is natural to use a si | Are there cases where there is no optimal k in k-means?
How exactly do you use cosine similarity? Is this what is refered to as spherical K-means? Your data set is quite small, so I would try to visualise it as a network. For this it is natural to use a similarity (indeed, for example the cosine similarity or Pearson correlation), apply a cut-off (only consider relationships above a certain similarity), and view the result as a network in for example Cytoscape or BioLayout. This can be very helpful to get a feeling for the data.
Second, I would compute the singular values for your data matrix, or the eigenvalues of an appropriately transformed and normalised matrix (a document-document matrix obtained in some form). Cluster structure should (again) show up as a jump in the ordered list of eigenvalues or singular values. | Are there cases where there is no optimal k in k-means?
How exactly do you use cosine similarity? Is this what is refered to as spherical K-means? Your data set is quite small, so I would try to visualise it as a network. For this it is natural to use a si |
25,382 | Are there cases where there is no optimal k in k-means? | Generally yes, k-means might converge to very distinct solutions that might be judged as unsuitable. This happens in particular for clusters with irregular shapes.
That get more intuition you could also try another visualization approach: For k-means you could visualize several runs with k-means using Graphgrams (see the WEKA graphgram package - best obtained by the package manager or here. An introduction and examples can also be found here. | Are there cases where there is no optimal k in k-means? | Generally yes, k-means might converge to very distinct solutions that might be judged as unsuitable. This happens in particular for clusters with irregular shapes.
That get more intuition you could al | Are there cases where there is no optimal k in k-means?
Generally yes, k-means might converge to very distinct solutions that might be judged as unsuitable. This happens in particular for clusters with irregular shapes.
That get more intuition you could also try another visualization approach: For k-means you could visualize several runs with k-means using Graphgrams (see the WEKA graphgram package - best obtained by the package manager or here. An introduction and examples can also be found here. | Are there cases where there is no optimal k in k-means?
Generally yes, k-means might converge to very distinct solutions that might be judged as unsuitable. This happens in particular for clusters with irregular shapes.
That get more intuition you could al |
25,383 | Are there cases where there is no optimal k in k-means? | If I understand the graph correctly it is a plot of the number of clusters, K on the x-axis and the within clusters distance on the y-axis?
Because your K-means objective function is to minimise the WCSS, this plot should always be monotonically decreasing. As you add more clusters, the distance between points in the cluster will always decrease. This is the fundamental problem of model selection, so you need to employ a bit more sophistication.
Perhaps try the Gap statistic: www-stat.stanford.edu/~tibs/ftp/gap.ps or others like it.
Furthermore, you may find that K-means isn't the right tool for the job. How many clusters do you expect to find? Using the variance rule for dimensionality reduction for clustering is not appropriate. See this paper for when projecting onto the first K-1 PCs is an appropriate preprocessing measure:
http://people.csail.mit.edu/gjw/papers/jcss.ps
You can quickly see if this is the right thing to do by plotting the projection onto the first two principal components. If there is a clear separation then K-means should be ok, if not you need to look into something else. Perhaps K-subspaces or other subspace clustering methods. Bare in mind these methods apply for Euclidean distance. I'm not sure how this changes for cosine. | Are there cases where there is no optimal k in k-means? | If I understand the graph correctly it is a plot of the number of clusters, K on the x-axis and the within clusters distance on the y-axis?
Because your K-means objective function is to minimise the W | Are there cases where there is no optimal k in k-means?
If I understand the graph correctly it is a plot of the number of clusters, K on the x-axis and the within clusters distance on the y-axis?
Because your K-means objective function is to minimise the WCSS, this plot should always be monotonically decreasing. As you add more clusters, the distance between points in the cluster will always decrease. This is the fundamental problem of model selection, so you need to employ a bit more sophistication.
Perhaps try the Gap statistic: www-stat.stanford.edu/~tibs/ftp/gap.ps or others like it.
Furthermore, you may find that K-means isn't the right tool for the job. How many clusters do you expect to find? Using the variance rule for dimensionality reduction for clustering is not appropriate. See this paper for when projecting onto the first K-1 PCs is an appropriate preprocessing measure:
http://people.csail.mit.edu/gjw/papers/jcss.ps
You can quickly see if this is the right thing to do by plotting the projection onto the first two principal components. If there is a clear separation then K-means should be ok, if not you need to look into something else. Perhaps K-subspaces or other subspace clustering methods. Bare in mind these methods apply for Euclidean distance. I'm not sure how this changes for cosine. | Are there cases where there is no optimal k in k-means?
If I understand the graph correctly it is a plot of the number of clusters, K on the x-axis and the within clusters distance on the y-axis?
Because your K-means objective function is to minimise the W |
25,384 | The use of median polish for feature selection | Tukey Median Polish, algorithm is used in the RMA normalization of microarrays. As you may be aware, microarray data is quite noisy, therefore they need a more robust way of estimating the probe intensities taking into account of observations for all the probes and microarrays. This is a typical model used for normalizing intensities of probes across arrays.
$$Y_{ij} = \mu_{i} + \alpha_{j} + \epsilon_{ij}$$
$$i=1,\ldots,I \qquad j=1,\ldots, J$$
Where $Y_{ij}$ is the $log$ transformed PM intensity for the $i^{th}$probe on the $j^{th}$ array. $\epsilon_{ij}$ are background noise and they can be assumed to correspond to noise in normal linear regression. However, a distributive assumption on $\epsilon$ may be restrictive, therefore we use Tukey Median Polish to get the estimates for $\hat{\mu_i}$ and $\hat{\alpha_j}$. This is a robust way of normalizing across arrays, as we want to separate signal, the intensity due to probe, from the array effect, $\alpha$. We can obtain the signal by normalizing for the array effect $\hat{\alpha_j}$ for all the arrays. Thus, we are only left with the probe effects plus some random noise.
The link that I have quoted before uses Tukey median polish to estimate the differentially expressed genes or "interesting" genes by ranking by the probe effect. However, the paper is pretty old, and probably at that time people were still trying to figure out how to analyze microarray data. Efron's non-parametric empirical Bayesian methods paper came in 2001, but probably may not have been widely used.
However, now we understand a lot about microarrays (statistically) and are pretty sure about their statistical analysis.
Microarray data is pretty noisy and RMA (which uses Median Polish) is one of the most popular normalization methods, may be because of its simplicity. Other popular and sophisticated methods are: GCRMA, VSN. It is important to normalize as the interest is probe effect and not array effect.
As you expect, the analysis could have benefited by some methods which take advantage of information borrowing across genes. These may include, Bayesian or empirical Bayesian methods. May be the paper that you are reading is old and these techniques weren't out until then.
Regarding your second point, yes they are probably modifying the experimental data. But, I think, this modification is for a better cause, hence justifiable. The reason being
a) Microarray data are pretty noisy. When the interest is probe effect, normalizing data by RMA, GCRMA, VSN, etc. is necessary and may be taking advantage of any special structure in the data is good. But I would avoid doing the second part. This is mainly because if we don't know the structure in advance, it is better not impose a lot of assumptions.
b) Most of the microarray experiments are exploratory in their nature, that is, the researchers are trying to narrow down to a few set of "interesting" genes for further analysis or experiments. If these genes have a strong signal, modifications like normalizations should not (substantially) effect the final results.
Therefore, the modifications may be justified. But I must remark, overdoing the normalizations may lead to wrong results. | The use of median polish for feature selection | Tukey Median Polish, algorithm is used in the RMA normalization of microarrays. As you may be aware, microarray data is quite noisy, therefore they need a more robust way of estimating the probe inten | The use of median polish for feature selection
Tukey Median Polish, algorithm is used in the RMA normalization of microarrays. As you may be aware, microarray data is quite noisy, therefore they need a more robust way of estimating the probe intensities taking into account of observations for all the probes and microarrays. This is a typical model used for normalizing intensities of probes across arrays.
$$Y_{ij} = \mu_{i} + \alpha_{j} + \epsilon_{ij}$$
$$i=1,\ldots,I \qquad j=1,\ldots, J$$
Where $Y_{ij}$ is the $log$ transformed PM intensity for the $i^{th}$probe on the $j^{th}$ array. $\epsilon_{ij}$ are background noise and they can be assumed to correspond to noise in normal linear regression. However, a distributive assumption on $\epsilon$ may be restrictive, therefore we use Tukey Median Polish to get the estimates for $\hat{\mu_i}$ and $\hat{\alpha_j}$. This is a robust way of normalizing across arrays, as we want to separate signal, the intensity due to probe, from the array effect, $\alpha$. We can obtain the signal by normalizing for the array effect $\hat{\alpha_j}$ for all the arrays. Thus, we are only left with the probe effects plus some random noise.
The link that I have quoted before uses Tukey median polish to estimate the differentially expressed genes or "interesting" genes by ranking by the probe effect. However, the paper is pretty old, and probably at that time people were still trying to figure out how to analyze microarray data. Efron's non-parametric empirical Bayesian methods paper came in 2001, but probably may not have been widely used.
However, now we understand a lot about microarrays (statistically) and are pretty sure about their statistical analysis.
Microarray data is pretty noisy and RMA (which uses Median Polish) is one of the most popular normalization methods, may be because of its simplicity. Other popular and sophisticated methods are: GCRMA, VSN. It is important to normalize as the interest is probe effect and not array effect.
As you expect, the analysis could have benefited by some methods which take advantage of information borrowing across genes. These may include, Bayesian or empirical Bayesian methods. May be the paper that you are reading is old and these techniques weren't out until then.
Regarding your second point, yes they are probably modifying the experimental data. But, I think, this modification is for a better cause, hence justifiable. The reason being
a) Microarray data are pretty noisy. When the interest is probe effect, normalizing data by RMA, GCRMA, VSN, etc. is necessary and may be taking advantage of any special structure in the data is good. But I would avoid doing the second part. This is mainly because if we don't know the structure in advance, it is better not impose a lot of assumptions.
b) Most of the microarray experiments are exploratory in their nature, that is, the researchers are trying to narrow down to a few set of "interesting" genes for further analysis or experiments. If these genes have a strong signal, modifications like normalizations should not (substantially) effect the final results.
Therefore, the modifications may be justified. But I must remark, overdoing the normalizations may lead to wrong results. | The use of median polish for feature selection
Tukey Median Polish, algorithm is used in the RMA normalization of microarrays. As you may be aware, microarray data is quite noisy, therefore they need a more robust way of estimating the probe inten |
25,385 | The use of median polish for feature selection | You may find some clues in pages 4 and 5 of this
It is a method of calculating residuals for the model
$$y_{i,j} = m + a_i + b_j + e_{i,j}$$
by calculating values for $m$, $a_i$ and $b_j$ so that if the $e_{i,j}$ are tabulated, the median of each row and of each column is 0.
The more conventional approach amounts to calculating values for $m$, $a_i$ and $b_j$ so that the mean (or sum) of each row and each column of residuals is 0.
The advantage of using the median is robustness to a small number of outliers; the disadvantage is that you are throwing away potentially useful information if there are no outliers. | The use of median polish for feature selection | You may find some clues in pages 4 and 5 of this
It is a method of calculating residuals for the model
$$y_{i,j} = m + a_i + b_j + e_{i,j}$$
by calculating values for $m$, $a_i$ and $b_j$ so that if | The use of median polish for feature selection
You may find some clues in pages 4 and 5 of this
It is a method of calculating residuals for the model
$$y_{i,j} = m + a_i + b_j + e_{i,j}$$
by calculating values for $m$, $a_i$ and $b_j$ so that if the $e_{i,j}$ are tabulated, the median of each row and of each column is 0.
The more conventional approach amounts to calculating values for $m$, $a_i$ and $b_j$ so that the mean (or sum) of each row and each column of residuals is 0.
The advantage of using the median is robustness to a small number of outliers; the disadvantage is that you are throwing away potentially useful information if there are no outliers. | The use of median polish for feature selection
You may find some clues in pages 4 and 5 of this
It is a method of calculating residuals for the model
$$y_{i,j} = m + a_i + b_j + e_{i,j}$$
by calculating values for $m$, $a_i$ and $b_j$ so that if |
25,386 | The use of median polish for feature selection | Looks like you are reading a paper that has some gene differential expression analysis. Having done some research involving microarray chips, I can share what little knowledge (hopefully correct) I have about using median polish.
Using median polish during the summarization step of microarray preprocessing is somewhat of a standard way to rid data of outliers with perfect match probe only chips (at least for RMA).
Median polish for microarray data is where you have the chip effect and probe effect as your rows and columns:
for each probe set (composed of n number of the same probe) on x chips:
chip1 chip2 chip3 ... chipx
probe1 iv iv iv ... iv
probe2 iv iv iv ... iv
probe3 iv iv iv ... iv
...
proben iv iv iv ... iv
where iv are intensity values
Because of the variability of the probe intensities, almost all analysis of microarray data is preprocessed using some sort of background correction and normalization before summarization.
here are some links to the bioC mailing list threads that talk about using median polish vs other methods:
https://stat.ethz.ch/pipermail/bioconductor/2004-May/004752.html
https://stat.ethz.ch/pipermail/bioconductor/2004-May/004734.html
Data from tissues and cell lines are usually analysed separately because when cells are cultured their expression profiles change dramatically from collected tissue samples. Without having more of the paper it is difficult to say whether or not processing the samples separately was appropriate.
Normalization, background correction, and summarization steps in the analysis pipeline are all modifications of experimental data, but in it's unprocessed state, the chip effects, batch effects, processing effects would overshadow any signal for analysis. These microarray experiments generate lists of genes that are candidates for follow up experiments (qPCR, etc) to confirm the results.
As far as being ad hoc, ask 5 people what fold difference is required for a gene to be considered differentially expressed and you will come up with at least 3 different answers. | The use of median polish for feature selection | Looks like you are reading a paper that has some gene differential expression analysis. Having done some research involving microarray chips, I can share what little knowledge (hopefully correct) I ha | The use of median polish for feature selection
Looks like you are reading a paper that has some gene differential expression analysis. Having done some research involving microarray chips, I can share what little knowledge (hopefully correct) I have about using median polish.
Using median polish during the summarization step of microarray preprocessing is somewhat of a standard way to rid data of outliers with perfect match probe only chips (at least for RMA).
Median polish for microarray data is where you have the chip effect and probe effect as your rows and columns:
for each probe set (composed of n number of the same probe) on x chips:
chip1 chip2 chip3 ... chipx
probe1 iv iv iv ... iv
probe2 iv iv iv ... iv
probe3 iv iv iv ... iv
...
proben iv iv iv ... iv
where iv are intensity values
Because of the variability of the probe intensities, almost all analysis of microarray data is preprocessed using some sort of background correction and normalization before summarization.
here are some links to the bioC mailing list threads that talk about using median polish vs other methods:
https://stat.ethz.ch/pipermail/bioconductor/2004-May/004752.html
https://stat.ethz.ch/pipermail/bioconductor/2004-May/004734.html
Data from tissues and cell lines are usually analysed separately because when cells are cultured their expression profiles change dramatically from collected tissue samples. Without having more of the paper it is difficult to say whether or not processing the samples separately was appropriate.
Normalization, background correction, and summarization steps in the analysis pipeline are all modifications of experimental data, but in it's unprocessed state, the chip effects, batch effects, processing effects would overshadow any signal for analysis. These microarray experiments generate lists of genes that are candidates for follow up experiments (qPCR, etc) to confirm the results.
As far as being ad hoc, ask 5 people what fold difference is required for a gene to be considered differentially expressed and you will come up with at least 3 different answers. | The use of median polish for feature selection
Looks like you are reading a paper that has some gene differential expression analysis. Having done some research involving microarray chips, I can share what little knowledge (hopefully correct) I ha |
25,387 | Testing statistical software | One useful technique is monte carlo testing. If there are two algorithms that do the same thing, implement both, feed them random data, and check that (to within a small tolerance for numerical fuzz) they produce the same answer. I've done this several times before:
I wrote an efficient but hard to implement $O(N\ log\ N)$ implementation of Kendall's Tau B. To test it I wrote a dead-simple 50-line implementation that ran in $O(N^2)$.
I wrote some code to do ridge regression. The best algorithm for doing this depends on whether you're in the $n > p$ or $p > n$ case, so I needed two algorithms anyhow.
In both of these cases I was implementing relatively well-known techniques in the D programming language (for which no implementation existed), so I also checked a few results against R. Nonetheless, the monte carlo testing caught bugs I never would have caught otherwise.
Another good test is asserts. You may not know exactly what the correct results of your computation should be, but that doesn't mean that you can't perform sanity checks at various stages of the computation. In practice if you have a lot of these in your code and they all pass, then the code is usually right.
Edit: A third method is to feed the algorithm data (synthetic or real) where you know at least approximately what the right answer is, even if you don't know exactly, and see by inspection if the answer is reasonable. For example, you may not know exactly what the estimates of your parameters are, but you may know which ones are supposed to be "big" and which ones are supposed to be "small". | Testing statistical software | One useful technique is monte carlo testing. If there are two algorithms that do the same thing, implement both, feed them random data, and check that (to within a small tolerance for numerical fuzz) | Testing statistical software
One useful technique is monte carlo testing. If there are two algorithms that do the same thing, implement both, feed them random data, and check that (to within a small tolerance for numerical fuzz) they produce the same answer. I've done this several times before:
I wrote an efficient but hard to implement $O(N\ log\ N)$ implementation of Kendall's Tau B. To test it I wrote a dead-simple 50-line implementation that ran in $O(N^2)$.
I wrote some code to do ridge regression. The best algorithm for doing this depends on whether you're in the $n > p$ or $p > n$ case, so I needed two algorithms anyhow.
In both of these cases I was implementing relatively well-known techniques in the D programming language (for which no implementation existed), so I also checked a few results against R. Nonetheless, the monte carlo testing caught bugs I never would have caught otherwise.
Another good test is asserts. You may not know exactly what the correct results of your computation should be, but that doesn't mean that you can't perform sanity checks at various stages of the computation. In practice if you have a lot of these in your code and they all pass, then the code is usually right.
Edit: A third method is to feed the algorithm data (synthetic or real) where you know at least approximately what the right answer is, even if you don't know exactly, and see by inspection if the answer is reasonable. For example, you may not know exactly what the estimates of your parameters are, but you may know which ones are supposed to be "big" and which ones are supposed to be "small". | Testing statistical software
One useful technique is monte carlo testing. If there are two algorithms that do the same thing, implement both, feed them random data, and check that (to within a small tolerance for numerical fuzz) |
25,388 | Testing statistical software | Not sure if this is really an answer to your question, but it is at least tangentially related.
I maintain the Statistics package in Maple. An interesting example of difficult to test code is random sample generation according to different distributions; it is easy to test that no errors are generated, but it is trickier to determine whether the samples that are generated conform to the requested distribution "well enough". Since Maple has both symbolic and numerical features, you can use some of the symbolic features to test the (purely numerical) sample generation:
We have implemented a few types of statistical hypothesis testing, one of which is the chi square suitable model test - a chi square test of the numbers of samples in bins determined from the inverse CDF of the given probability distribution. So for example, to test Cauchy distribution sample generation, I run something like
with(Statistics):
infolevel[Statistics] := 1:
distribution := CauchyDistribution(2, 3):
sample := Sample(distribution, 10^6):
ChiSquareSuitableModelTest(sample, distribution, 'bins' = 100, 'level' = 0.001);
Because I can generate as large a sample as I like, I can make $\alpha$ pretty small.
For distributions with finite moments, I compute on the one hand a number of sample moments, and on the other hand, I symbolically compute the corresponding distribution moments and their standard error. So for e.g. the beta distribution:
with(Statistics):
distribution := BetaDistribution(2, 3):
distributionMoments := Moment~(distribution, [seq(1 .. 10)]);
standardErrors := StandardError[10^6]~(Moment, distribution, [seq(1..10)]);
evalf(distributionMoments /~ standardErrors);
This shows a decreasing list of numbers, the last of which is 255.1085766. So for even the 10th moment, the value of the moment is more than 250 times the value of the standard error of the sample moment for a sample of size $10^6$. This means I can implement a test that runs more or less as follows:
with(Statistics):
sample := Sample(BetaDistribution(2, 3), 10^6):
sampleMoments := map2(Moment, sample, [seq(1 .. 10)]);
distributionMoments := [2/5, 1/5, 4/35, 1/14, 1/21, 1/30, 4/165, 1/55, 2/143, 1/91];
standardErrors :=
[1/5000, 1/70000*154^(1/2), 1/210000*894^(1/2), 1/770000*7755^(1/2),
1/54600*26^(1/2), 1/210000*266^(1/2), 7/5610000*2771^(1/2),
1/1567500*7809^(1/2), 3/5005000*6685^(1/2), 1/9209200*157366^(1/2)];
deviations := abs~(sampleMoments - distributionMoments) /~ standardErrors;
The numbers in distributionMoments and standardErrors come from the first run above. Now if the sample generation is correct, the numbers in deviations should be relatively small. I assume they are approximately normally distributed (which they aren't really, but it comes close enough - recall these are scaled versions of sample moments, not the samples themselves) and thus I can, for example, flag a case where a deviation is greater than 4 - corresponding to a sample moment that deviates more than four times the standard error from the distribution moment. This is very unlikely to occur at random if the sample generation is good. On the other hand, if the first 10 sample moments match the distribution moments to within less than half a percent, we have a fairly good approximation of the distribution.
The key to why both of these methods work is that the sample generation code and the symbolic code are almost completely disjoint. If there would be overlap between the two, then an error in that overlap could manifest itself both in the sample generation and in its verification, and thus not be caught. | Testing statistical software | Not sure if this is really an answer to your question, but it is at least tangentially related.
I maintain the Statistics package in Maple. An interesting example of difficult to test code is random s | Testing statistical software
Not sure if this is really an answer to your question, but it is at least tangentially related.
I maintain the Statistics package in Maple. An interesting example of difficult to test code is random sample generation according to different distributions; it is easy to test that no errors are generated, but it is trickier to determine whether the samples that are generated conform to the requested distribution "well enough". Since Maple has both symbolic and numerical features, you can use some of the symbolic features to test the (purely numerical) sample generation:
We have implemented a few types of statistical hypothesis testing, one of which is the chi square suitable model test - a chi square test of the numbers of samples in bins determined from the inverse CDF of the given probability distribution. So for example, to test Cauchy distribution sample generation, I run something like
with(Statistics):
infolevel[Statistics] := 1:
distribution := CauchyDistribution(2, 3):
sample := Sample(distribution, 10^6):
ChiSquareSuitableModelTest(sample, distribution, 'bins' = 100, 'level' = 0.001);
Because I can generate as large a sample as I like, I can make $\alpha$ pretty small.
For distributions with finite moments, I compute on the one hand a number of sample moments, and on the other hand, I symbolically compute the corresponding distribution moments and their standard error. So for e.g. the beta distribution:
with(Statistics):
distribution := BetaDistribution(2, 3):
distributionMoments := Moment~(distribution, [seq(1 .. 10)]);
standardErrors := StandardError[10^6]~(Moment, distribution, [seq(1..10)]);
evalf(distributionMoments /~ standardErrors);
This shows a decreasing list of numbers, the last of which is 255.1085766. So for even the 10th moment, the value of the moment is more than 250 times the value of the standard error of the sample moment for a sample of size $10^6$. This means I can implement a test that runs more or less as follows:
with(Statistics):
sample := Sample(BetaDistribution(2, 3), 10^6):
sampleMoments := map2(Moment, sample, [seq(1 .. 10)]);
distributionMoments := [2/5, 1/5, 4/35, 1/14, 1/21, 1/30, 4/165, 1/55, 2/143, 1/91];
standardErrors :=
[1/5000, 1/70000*154^(1/2), 1/210000*894^(1/2), 1/770000*7755^(1/2),
1/54600*26^(1/2), 1/210000*266^(1/2), 7/5610000*2771^(1/2),
1/1567500*7809^(1/2), 3/5005000*6685^(1/2), 1/9209200*157366^(1/2)];
deviations := abs~(sampleMoments - distributionMoments) /~ standardErrors;
The numbers in distributionMoments and standardErrors come from the first run above. Now if the sample generation is correct, the numbers in deviations should be relatively small. I assume they are approximately normally distributed (which they aren't really, but it comes close enough - recall these are scaled versions of sample moments, not the samples themselves) and thus I can, for example, flag a case where a deviation is greater than 4 - corresponding to a sample moment that deviates more than four times the standard error from the distribution moment. This is very unlikely to occur at random if the sample generation is good. On the other hand, if the first 10 sample moments match the distribution moments to within less than half a percent, we have a fairly good approximation of the distribution.
The key to why both of these methods work is that the sample generation code and the symbolic code are almost completely disjoint. If there would be overlap between the two, then an error in that overlap could manifest itself both in the sample generation and in its verification, and thus not be caught. | Testing statistical software
Not sure if this is really an answer to your question, but it is at least tangentially related.
I maintain the Statistics package in Maple. An interesting example of difficult to test code is random s |
25,389 | Testing statistical software | Bruce McCullough had a bit of a cottage industry in assessing statistical software (in the widest sense; he also tested Microsoft Excel. And found it wanting). Two papers that illustrate part of his approach are here and here. | Testing statistical software | Bruce McCullough had a bit of a cottage industry in assessing statistical software (in the widest sense; he also tested Microsoft Excel. And found it wanting). Two papers that illustrate part of his a | Testing statistical software
Bruce McCullough had a bit of a cottage industry in assessing statistical software (in the widest sense; he also tested Microsoft Excel. And found it wanting). Two papers that illustrate part of his approach are here and here. | Testing statistical software
Bruce McCullough had a bit of a cottage industry in assessing statistical software (in the widest sense; he also tested Microsoft Excel. And found it wanting). Two papers that illustrate part of his a |
25,390 | Testing statistical software | A lot of detail is given by the President of StataCorp, William Gould, in this Stata Journal article.1 It is a very interesting article about quality control of statistical software. | Testing statistical software | A lot of detail is given by the President of StataCorp, William Gould, in this Stata Journal article.1 It is a very interesting article about quality control of statistical software. | Testing statistical software
A lot of detail is given by the President of StataCorp, William Gould, in this Stata Journal article.1 It is a very interesting article about quality control of statistical software. | Testing statistical software
A lot of detail is given by the President of StataCorp, William Gould, in this Stata Journal article.1 It is a very interesting article about quality control of statistical software. |
25,391 | What are the assumptions for applying a Tobit regression model? | If we go for a simple answer, the excerpt from the Wooldridge book (page 533) is very appropriate:
... both heteroskedasticity and nonnormality result in the Tobit estimator $\hat{\beta}$ being inconsistent for $\beta$. This inconsistency occurs because the derived density of $y$ given $x$ hinges crucially on $y^*|x\sim\mathrm{Normal}(x\beta,\sigma^2)$. This nonrobustness of the Tobit estimator shows that data censoring can be very costly: in the absence of censoring ($y=y^*$) $\beta$ could be consistently estimated under $E(u|x)=0$ [or even $E(x'u)=0$].
The notations in this excerpt comes from Tobit model:
\begin{align}
y^{*}&=x\beta+u, \quad u|x\sim N(0,\sigma^2)\\
y^{*}&=\max(y^*,0)
\end{align}
where $y$ and $x$ are observed.
To sum up the difference between least squares and Tobit regression is the inherent assumption of normality in the latter.
Also I always thought that the original article of Amemyia was quite nice in laying out the theoretical foundations of the Tobit regression. | What are the assumptions for applying a Tobit regression model? | If we go for a simple answer, the excerpt from the Wooldridge book (page 533) is very appropriate:
... both heteroskedasticity and nonnormality result in the Tobit estimator $\hat{\beta}$ being incons | What are the assumptions for applying a Tobit regression model?
If we go for a simple answer, the excerpt from the Wooldridge book (page 533) is very appropriate:
... both heteroskedasticity and nonnormality result in the Tobit estimator $\hat{\beta}$ being inconsistent for $\beta$. This inconsistency occurs because the derived density of $y$ given $x$ hinges crucially on $y^*|x\sim\mathrm{Normal}(x\beta,\sigma^2)$. This nonrobustness of the Tobit estimator shows that data censoring can be very costly: in the absence of censoring ($y=y^*$) $\beta$ could be consistently estimated under $E(u|x)=0$ [or even $E(x'u)=0$].
The notations in this excerpt comes from Tobit model:
\begin{align}
y^{*}&=x\beta+u, \quad u|x\sim N(0,\sigma^2)\\
y^{*}&=\max(y^*,0)
\end{align}
where $y$ and $x$ are observed.
To sum up the difference between least squares and Tobit regression is the inherent assumption of normality in the latter.
Also I always thought that the original article of Amemyia was quite nice in laying out the theoretical foundations of the Tobit regression. | What are the assumptions for applying a Tobit regression model?
If we go for a simple answer, the excerpt from the Wooldridge book (page 533) is very appropriate:
... both heteroskedasticity and nonnormality result in the Tobit estimator $\hat{\beta}$ being incons |
25,392 | What are the assumptions for applying a Tobit regression model? | To echo Aniko's comment: The primary assumption is the existence of truncation. This is not the same assumption as the two other possibilities that your post suggests to me: boundedness and sample selection.
If you have a fundamentally bounded dependent variable rather than a truncated one you might want to move to a generalized linear model framework with one of the (less often chosen) distributions for Y e.g. log-normal, gamma, exponential, etc. which respect that lower bound.
Alternatively you might then ask yourself whether you think that the process that generates the zero observations in your model is the same as the one that generates the strictly positive values - prices in your application, I think. If this is not the case then something from the class of sample selection models, (e.g. Heckman models) might be appropriate. In that case you'd be in the situation of specifying one model of being willing to pay any price at all, and another model of what price your subjects would pay if they wanted to pay something.
In short, you probably want to review the difference between assuming truncated, censored, bounded, and sample selected dependent variables. Which one you want will come from the details of your application. Once that first most important assumption is made you can more easily determine whether you like the specific assumptions of any model in your chosen class. Some of the sample selection models have assumptions that are rather difficult to check... | What are the assumptions for applying a Tobit regression model? | To echo Aniko's comment: The primary assumption is the existence of truncation. This is not the same assumption as the two other possibilities that your post suggests to me: boundedness and sample se | What are the assumptions for applying a Tobit regression model?
To echo Aniko's comment: The primary assumption is the existence of truncation. This is not the same assumption as the two other possibilities that your post suggests to me: boundedness and sample selection.
If you have a fundamentally bounded dependent variable rather than a truncated one you might want to move to a generalized linear model framework with one of the (less often chosen) distributions for Y e.g. log-normal, gamma, exponential, etc. which respect that lower bound.
Alternatively you might then ask yourself whether you think that the process that generates the zero observations in your model is the same as the one that generates the strictly positive values - prices in your application, I think. If this is not the case then something from the class of sample selection models, (e.g. Heckman models) might be appropriate. In that case you'd be in the situation of specifying one model of being willing to pay any price at all, and another model of what price your subjects would pay if they wanted to pay something.
In short, you probably want to review the difference between assuming truncated, censored, bounded, and sample selected dependent variables. Which one you want will come from the details of your application. Once that first most important assumption is made you can more easily determine whether you like the specific assumptions of any model in your chosen class. Some of the sample selection models have assumptions that are rather difficult to check... | What are the assumptions for applying a Tobit regression model?
To echo Aniko's comment: The primary assumption is the existence of truncation. This is not the same assumption as the two other possibilities that your post suggests to me: boundedness and sample se |
25,393 | What are the assumptions for applying a Tobit regression model? | @Firefeather: Does your data contain (and can only really ever contain) only positive values? If so, model it using a generalized linear model with gamma error and log link. If it contains zeros then you could consider a two stage (logistic regression for probability of zero and gamma regression for the positive values). This latter scenario can also be modeled as a single regression using a zero inflated gamma. Some great explanations of this were given on a SAS list a few years ago. Start here if interested and search for follow-ups.
link text
Might help point you in another direction if the truncated regression turns out implausible. | What are the assumptions for applying a Tobit regression model? | @Firefeather: Does your data contain (and can only really ever contain) only positive values? If so, model it using a generalized linear model with gamma error and log link. If it contains zeros then | What are the assumptions for applying a Tobit regression model?
@Firefeather: Does your data contain (and can only really ever contain) only positive values? If so, model it using a generalized linear model with gamma error and log link. If it contains zeros then you could consider a two stage (logistic regression for probability of zero and gamma regression for the positive values). This latter scenario can also be modeled as a single regression using a zero inflated gamma. Some great explanations of this were given on a SAS list a few years ago. Start here if interested and search for follow-ups.
link text
Might help point you in another direction if the truncated regression turns out implausible. | What are the assumptions for applying a Tobit regression model?
@Firefeather: Does your data contain (and can only really ever contain) only positive values? If so, model it using a generalized linear model with gamma error and log link. If it contains zeros then |
25,394 | What are the assumptions for applying a Tobit regression model? | As others have mentioned here, the main application of tobit regression is where there is censoring of data. Tobit is widely used in conjunction with Data Envelopment Analysis (DEA) and by the economist. In DEA, efficiency score lies in between 0 and 1, which means that the dependent variable is censored at 0 from left and 1 from right. Therefore, application of linear regression (OLS) is not feasible.
Tobit is a combination of probit and truncated regression. Care must be taken while differentiating censoring and truncating:
Censoring: When the limit observations are in the sample. The dependent variable values hit a limit either to the left or right.
Truncation: Observation in which certain range of dependent values is not included in the study. For example, only positive values. Truncation has greater loss of information then censoring.
Tobit = Probit + Truncation Regression
Tobit model assumes normality as the probit model does.
Steps:
Probit model decides whether the dependent variable is 0 or 1.
$$
P(y>0) = Φ(x^{'} β) \tag{Discreet decision}
$$
If the dependent variable is 1 then by how much (assuming censoring at 0).
$E(y│y>0)= x^{'} β+ σλ\big(\frac{x^{'} β}{σ}\big) \tag{Continuous decision}$
Coefficient $β$ is same for both the decision model. $σλ\big(\frac{x^{'} β}{σ}\big)$ is the correction term to adjust the censored values (zeros).
Please also check Cragg's model where you can use different $β$ in each step. | What are the assumptions for applying a Tobit regression model? | As others have mentioned here, the main application of tobit regression is where there is censoring of data. Tobit is widely used in conjunction with Data Envelopment Analysis (DEA) and by the economi | What are the assumptions for applying a Tobit regression model?
As others have mentioned here, the main application of tobit regression is where there is censoring of data. Tobit is widely used in conjunction with Data Envelopment Analysis (DEA) and by the economist. In DEA, efficiency score lies in between 0 and 1, which means that the dependent variable is censored at 0 from left and 1 from right. Therefore, application of linear regression (OLS) is not feasible.
Tobit is a combination of probit and truncated regression. Care must be taken while differentiating censoring and truncating:
Censoring: When the limit observations are in the sample. The dependent variable values hit a limit either to the left or right.
Truncation: Observation in which certain range of dependent values is not included in the study. For example, only positive values. Truncation has greater loss of information then censoring.
Tobit = Probit + Truncation Regression
Tobit model assumes normality as the probit model does.
Steps:
Probit model decides whether the dependent variable is 0 or 1.
$$
P(y>0) = Φ(x^{'} β) \tag{Discreet decision}
$$
If the dependent variable is 1 then by how much (assuming censoring at 0).
$E(y│y>0)= x^{'} β+ σλ\big(\frac{x^{'} β}{σ}\big) \tag{Continuous decision}$
Coefficient $β$ is same for both the decision model. $σλ\big(\frac{x^{'} β}{σ}\big)$ is the correction term to adjust the censored values (zeros).
Please also check Cragg's model where you can use different $β$ in each step. | What are the assumptions for applying a Tobit regression model?
As others have mentioned here, the main application of tobit regression is where there is censoring of data. Tobit is widely used in conjunction with Data Envelopment Analysis (DEA) and by the economi |
25,395 | How do you test an implementation of k-means? | The k-means includes a stochastic component, so it is very unlikely you will get the same result unless you have exactly the same implementation and use the same starting configuration. However, you could see if your results are in agreement with well-known implementations (don't know about Matlab, but implementation of k-means algorithm in R is well explained, see Hartigan & Wong, 1979).
As for comparing two series of results, there still is an issue with label switching if it is to be run multiple times. Again, in the e1071 R package, there is a very handy function (;matchClasses()) that might be used to find the 'best' mapping between two categories in a two-way classification table. Basically, the idea is to rearrange the rows so as to maximise their agreement with columns, or use a greedy approach and permute rows and columns until the sum of on the diagonal (raw agreement) is maximal. Coefficient of agreement like the Kappa statistic are also provided.
Finally, about how to benchmark your implementation, there are a lot of freely available data, or you can simulate a dedicated data set (e.g., through a finite mixture model, see the MixSim package). | How do you test an implementation of k-means? | The k-means includes a stochastic component, so it is very unlikely you will get the same result unless you have exactly the same implementation and use the same starting configuration. However, you c | How do you test an implementation of k-means?
The k-means includes a stochastic component, so it is very unlikely you will get the same result unless you have exactly the same implementation and use the same starting configuration. However, you could see if your results are in agreement with well-known implementations (don't know about Matlab, but implementation of k-means algorithm in R is well explained, see Hartigan & Wong, 1979).
As for comparing two series of results, there still is an issue with label switching if it is to be run multiple times. Again, in the e1071 R package, there is a very handy function (;matchClasses()) that might be used to find the 'best' mapping between two categories in a two-way classification table. Basically, the idea is to rearrange the rows so as to maximise their agreement with columns, or use a greedy approach and permute rows and columns until the sum of on the diagonal (raw agreement) is maximal. Coefficient of agreement like the Kappa statistic are also provided.
Finally, about how to benchmark your implementation, there are a lot of freely available data, or you can simulate a dedicated data set (e.g., through a finite mixture model, see the MixSim package). | How do you test an implementation of k-means?
The k-means includes a stochastic component, so it is very unlikely you will get the same result unless you have exactly the same implementation and use the same starting configuration. However, you c |
25,396 | How do you test an implementation of k-means? | The mapping between two sets of results is easy to compute, because the information you obtain in a test can be represented as a set of three-tuples: the first component is a (multidimensional) point, the second is an (arbitrary) cluster label supplied by your algorithm, and the third is an (arbitrary) cluster label supplied by a reference algorithm. Construct the $k$ by $k$ classification table for the label pairs: if the results agree, it will be a multiple of a permutation matrix. That is, each row and each column must have exactly one nonzero cell. That's a simple check to program. It's also straightforward to track small deviations from this ideal back to individual data points so you can see precisely how the two answers differ if they differ at all. I wouldn't bother to compute statistical measures of agreement: either there is perfect agreement (up to permutation) or there is not, and in the latter case you need to track down all points of disagreement to understand how they occur. The results either agree or they do not; any amount of disagreement, even at just one point, needs checking.
You might want to use several kinds of datasets for testing: (1) published datasets with published k-means results; (2) synthetic datasets with obvious strong clusters; (3) synthetic datasets with no obvious clustering. (1) is a good discipline to use whenever you write any math or stats program. (2) is easy to do in many ways, such as by generating some random points to serve as centers of clusters and then generating point clouds by randomly displacing the cluster centers relatively small amounts. (3) provides some random checks that potentially uncover unexpected behaviors; again, that's a good general testing discipline.
In addition, consider creating datasets that stress the algorithm by lying just on the boundaries between extreme solutions. This will require creativity and a deep understanding of your algorithm (which presumably you have!). One example I would want to check in any event would be sets of vectors of the form $i \mathbb{v}$ where $\mathbb{v}$ is a vector with no zero components and $i$ takes on sequential integral values $0, 1, 2, \ldots, n-1$. I would also want to check the algorithm on sets of vectors that form equilateral polygons. In either situation, cases where $n$ is not a multiple of $k$ are particularly interesting, including where $n$ is less than $k$. What is common to these situations is that (a) they use all the dimensions of the problem, yet (b) the correct solutions are geometrically obvious, and (c) there are multiple correct solutions.
(Form random equilateral polygons in $d \ge 2$ dimensions by starting with two nonzero vectors $\mathbb{u}$ and $\mathbb{v}$ chosen at random. (A good way is to let their $2d$ components be independent standard normal variates.) Rescale them to have unit length; let's call these $\mathbb{x}$ and $\mathbb{z}$. Remove the $\mathbb{x}$ component from $\mathbb{z}$ by means of the formula
$$\mathbb{w} = \mathbb{z} - ( \mathbb{z} \cdot \mathbb{x} ) \mathbb{x}.$$
Obtain $\mathbb{y}$ by rescaling $\mathbb{w}$ to have unit length. If you like, uniformly rescale both $\mathbb{x}$ and $\mathbb{y}$ randomly. The vectors $\mathbb{x}$ and $\mathbb{y}$ form an orthogonal basis for a random 2D subspace in $d$ dimensions. An equilateral polygon of $n$ vertices is obtained as the set of $\cos(2 \pi k / n) \mathbb{x} + \sin(2 \pi k / n) \mathbb{y}$ as the integer $k$ ranges from $0$ through $n-1$.) | How do you test an implementation of k-means? | The mapping between two sets of results is easy to compute, because the information you obtain in a test can be represented as a set of three-tuples: the first component is a (multidimensional) point, | How do you test an implementation of k-means?
The mapping between two sets of results is easy to compute, because the information you obtain in a test can be represented as a set of three-tuples: the first component is a (multidimensional) point, the second is an (arbitrary) cluster label supplied by your algorithm, and the third is an (arbitrary) cluster label supplied by a reference algorithm. Construct the $k$ by $k$ classification table for the label pairs: if the results agree, it will be a multiple of a permutation matrix. That is, each row and each column must have exactly one nonzero cell. That's a simple check to program. It's also straightforward to track small deviations from this ideal back to individual data points so you can see precisely how the two answers differ if they differ at all. I wouldn't bother to compute statistical measures of agreement: either there is perfect agreement (up to permutation) or there is not, and in the latter case you need to track down all points of disagreement to understand how they occur. The results either agree or they do not; any amount of disagreement, even at just one point, needs checking.
You might want to use several kinds of datasets for testing: (1) published datasets with published k-means results; (2) synthetic datasets with obvious strong clusters; (3) synthetic datasets with no obvious clustering. (1) is a good discipline to use whenever you write any math or stats program. (2) is easy to do in many ways, such as by generating some random points to serve as centers of clusters and then generating point clouds by randomly displacing the cluster centers relatively small amounts. (3) provides some random checks that potentially uncover unexpected behaviors; again, that's a good general testing discipline.
In addition, consider creating datasets that stress the algorithm by lying just on the boundaries between extreme solutions. This will require creativity and a deep understanding of your algorithm (which presumably you have!). One example I would want to check in any event would be sets of vectors of the form $i \mathbb{v}$ where $\mathbb{v}$ is a vector with no zero components and $i$ takes on sequential integral values $0, 1, 2, \ldots, n-1$. I would also want to check the algorithm on sets of vectors that form equilateral polygons. In either situation, cases where $n$ is not a multiple of $k$ are particularly interesting, including where $n$ is less than $k$. What is common to these situations is that (a) they use all the dimensions of the problem, yet (b) the correct solutions are geometrically obvious, and (c) there are multiple correct solutions.
(Form random equilateral polygons in $d \ge 2$ dimensions by starting with two nonzero vectors $\mathbb{u}$ and $\mathbb{v}$ chosen at random. (A good way is to let their $2d$ components be independent standard normal variates.) Rescale them to have unit length; let's call these $\mathbb{x}$ and $\mathbb{z}$. Remove the $\mathbb{x}$ component from $\mathbb{z}$ by means of the formula
$$\mathbb{w} = \mathbb{z} - ( \mathbb{z} \cdot \mathbb{x} ) \mathbb{x}.$$
Obtain $\mathbb{y}$ by rescaling $\mathbb{w}$ to have unit length. If you like, uniformly rescale both $\mathbb{x}$ and $\mathbb{y}$ randomly. The vectors $\mathbb{x}$ and $\mathbb{y}$ form an orthogonal basis for a random 2D subspace in $d$ dimensions. An equilateral polygon of $n$ vertices is obtained as the set of $\cos(2 \pi k / n) \mathbb{x} + \sin(2 \pi k / n) \mathbb{y}$ as the integer $k$ ranges from $0$ through $n-1$.) | How do you test an implementation of k-means?
The mapping between two sets of results is easy to compute, because the information you obtain in a test can be represented as a set of three-tuples: the first component is a (multidimensional) point, |
25,397 | How do you test an implementation of k-means? | One very simple 'naive' approach would be to use simple synthetic data, for that every implementation should result in the same clusters.
Example in Python with import numpy as np:
test_data = np.zeros((40000, 4))
test_data[0:10000, :] = 30.0
test_data[10000:20000, :] = 60.0
test_data[20000:30000, :] = 90.0
test_data[30000:, :] = 120.0
For n_clusters = 4 it should give you a permutation of [30, 60, 90, 120] | How do you test an implementation of k-means? | One very simple 'naive' approach would be to use simple synthetic data, for that every implementation should result in the same clusters.
Example in Python with import numpy as np:
test_data = np.zero | How do you test an implementation of k-means?
One very simple 'naive' approach would be to use simple synthetic data, for that every implementation should result in the same clusters.
Example in Python with import numpy as np:
test_data = np.zeros((40000, 4))
test_data[0:10000, :] = 30.0
test_data[10000:20000, :] = 60.0
test_data[20000:30000, :] = 90.0
test_data[30000:, :] = 120.0
For n_clusters = 4 it should give you a permutation of [30, 60, 90, 120] | How do you test an implementation of k-means?
One very simple 'naive' approach would be to use simple synthetic data, for that every implementation should result in the same clusters.
Example in Python with import numpy as np:
test_data = np.zero |
25,398 | How do you test an implementation of k-means? | Since k-means contains decisions that are randomly chosen (the initialization part only), I think the best way to try your algorithm is to select the initial points and let them fixed in your algorithm first and then choose another source code of the algorithm and fix the points in the same way. Then you can compare for real the results. | How do you test an implementation of k-means? | Since k-means contains decisions that are randomly chosen (the initialization part only), I think the best way to try your algorithm is to select the initial points and let them fixed in your algorith | How do you test an implementation of k-means?
Since k-means contains decisions that are randomly chosen (the initialization part only), I think the best way to try your algorithm is to select the initial points and let them fixed in your algorithm first and then choose another source code of the algorithm and fix the points in the same way. Then you can compare for real the results. | How do you test an implementation of k-means?
Since k-means contains decisions that are randomly chosen (the initialization part only), I think the best way to try your algorithm is to select the initial points and let them fixed in your algorith |
25,399 | Why are residuals Normally distributed? | The connection is made through a specific procedure: namely, ordinary least squares. When you suppose a response $Y$ is a random variable related to other variables $X$ in the form
$$Y = X\beta + \varepsilon$$
where $\varepsilon$ is assumed to have a joint Normal distribution (plus some other assumptions that don't matter here), then the least squares solution is
$$\hat\beta = (X^\prime X)^{-}X^\prime Y = (X^\prime X)^{-}X^\prime (X\beta + \epsilon) = \beta + J\varepsilon$$
for a matrix $J = (X^\prime X)^{-}X^\prime $ that is computed only from $X.$ The residuals, or estimated errors, are the differences
$$\hat\varepsilon = Y - \hat Y = (X\beta + \varepsilon) - X\hat\beta = \varepsilon - XJ\varepsilon = (\mathbb I - H)\varepsilon$$
where $H = XJ = X(X^\prime X)^{-}X^\prime$ is the "hat matrix." This exhibits the residuals as linear combinations of $\varepsilon$ (with coefficients given by $\mathbb I - H$). Linear combinations of jointly Normal variables are Normal, QED. | Why are residuals Normally distributed? | The connection is made through a specific procedure: namely, ordinary least squares. When you suppose a response $Y$ is a random variable related to other variables $X$ in the form
$$Y = X\beta + \va | Why are residuals Normally distributed?
The connection is made through a specific procedure: namely, ordinary least squares. When you suppose a response $Y$ is a random variable related to other variables $X$ in the form
$$Y = X\beta + \varepsilon$$
where $\varepsilon$ is assumed to have a joint Normal distribution (plus some other assumptions that don't matter here), then the least squares solution is
$$\hat\beta = (X^\prime X)^{-}X^\prime Y = (X^\prime X)^{-}X^\prime (X\beta + \epsilon) = \beta + J\varepsilon$$
for a matrix $J = (X^\prime X)^{-}X^\prime $ that is computed only from $X.$ The residuals, or estimated errors, are the differences
$$\hat\varepsilon = Y - \hat Y = (X\beta + \varepsilon) - X\hat\beta = \varepsilon - XJ\varepsilon = (\mathbb I - H)\varepsilon$$
where $H = XJ = X(X^\prime X)^{-}X^\prime$ is the "hat matrix." This exhibits the residuals as linear combinations of $\varepsilon$ (with coefficients given by $\mathbb I - H$). Linear combinations of jointly Normal variables are Normal, QED. | Why are residuals Normally distributed?
The connection is made through a specific procedure: namely, ordinary least squares. When you suppose a response $Y$ is a random variable related to other variables $X$ in the form
$$Y = X\beta + \va |
25,400 | What are the pros and cons of using mahalanobis distance instead of propensity scores in matching | Mahalanobis distance matching (MDM) and propensity score matching (PSM) are methods of doing the same thing, which is to find a subset of control units similar to treated units to arrive at a balanced sample (i.e., where the distribution of covariates is the same in both groups).
MDM works by pairing units that are close based on a distance called the Mahalanobis distance, which you can think of like a scale-free Euclidean distance. For two units to have a Mahalanobis distance of 0, they must have identical covariate values. The more different the covariate values, the larger the Mahalanobis distance. The idea is that if you find control units close to the treated units on the Mahalanobis distance, each pair will have similar covariate values, and the distribution of the covariates in the treatment groups in the matched sample will be similar.
PSM works by pairing units that have similar propensity scores. Propensity scores reduce the entire covariate distribution into a single dimension; this means that two units with similar propensity scores will not necessarily have similar covariates values. However, because of the theoretical balancing properties of the propensity score, PSM can still yield balanced samples, even though any individual matched pair of units may not have similar covariate values.
This difference between the two methods, i.e., that MDM creates pairs close on covariate values while PSM does not (even though both may be effective at yielding balanced samples), is the focus of King & Nielsen's (2019) famous critique of PSM. See the chart below, taken from the 2019 paper:
Here, we have the same dataset of treated (red) and control (blue) units, with two covariates (X1, x-axis, and X2, y-axis) being matched on. On the left, MDM is used to pair the units (each gray link is a pair), and on the right, PSM is used. You can see that with MDM, paired units have much more similar covariate values than with PSM. PSM reduces the covariate space to a single dimension, which corresponds to the diagonal line pattern in the plot on the right. Units are paired with each other because they have similar propensity scores, even though they differ quite dramatically on the covariate values.
Why does this matter? King & Nielsen argue that PSM yields fragile and non-robust estimates that could vary wildly depending on the outcome model used. In particular, if you progressively discard units that are far apart from each other (i.e., by imposing a tighter and tighter caliper), eventually balance starts to get worse with PSM even though units close together on the PS remain. They call this the propensity score paradox, which is the motivation for recommending against the use of PSM in favor of potentially more robust methods like MDM that match directly on the covariate space.
So, should we avoid PSM and stick to MDM? No. Rippolone et al. (2018) investigated the impact of the propensity score paradox on real epidemiological data. They found that while the paradox did occur with some data, it was not troublesome until extreme caliper values were used, far beyond what would be recommended. PSM generally yielded good balance on the covariates. In contrast, MDM yielded poor balance in one dataset, sometimes even worse than no matching at all. See the plot below from Ripollone et al. (2018) comparing the balance results from MDM (blue) and PSM (red and green) on one dataset as more units are pruned:
The y-axis is a measure of covariate balance in the matched datasets (unrelated to the pairwise Mahalanobis distance used for matching), and the black dot is the pre-matching balance. We can see that as more units are pruned (moving right along the x-axis), balance gets worse for PSM and better for MDM, but at published recommendations for PSM calipers (vertical dashed lines), balance is excellent for PSM and poor for MDM.
How could we get such different conclusions from comparing the same methods? The answer is that it all depends on the dataset and its unique qualities, including its size, its initial balance, and the number and types of covariates to be matched on. It's worth noting that when analyzing a different dataset than the one depicted above, Ripollone et al. found MDM to yield better balance than PSM. Generally, MDM tends to work better with few covariates and covariates that are normally distributed, whereas PSM tends to work well as long as the propensity score is reasonably well estimated (because the matching is done on the propensity score, not the covariates themselves). The key, though, is that when MDM works, it really works, because it can give matched samples that are not only well-balanced overall, but also containing closely paired units, whereas PSM can only promise well-balanced samples but not close pairs.
What should you do? Normally I would say try both, but this time I will just say to use genetic matching (i.e., method = "genetic" in MatchIt), which combines PSM and MDM and uses optimization to find the distance measure that provides the best balance in the matched dataset. It's much slower than MDM and PSM, but the results will be uniformly better, as many simulation studies have shown. Genetic matching was another method recommended by King & Nielsen for not succumbing to the propensity score paradox. If you can't use genetic matching (e.g., because your dataset is too big or you don't have the time to wait), then you should try both MDM and PSM, and choose the one that yields the best balance measured broadly (i.e., on pairwise covariate distances and KS-statistics and polynomials and interactions of covariates and not just the means). It is straightforward to use MatchIt to quickly try and compare several matching methods before choosing one to move forward with for effect estimation.
There are ways of ensuring close pairs when using PSM, such as exact matching on some covariates, placing calipers on covariates directly, or doing MDM within propensity score calipers. All of these are possible in MatchIt and should be tried and compared.
King, G., & Nielsen, R. (2019). Why Propensity Scores Should Not Be Used for Matching. Political Analysis, 1–20. https://doi.org/10.1017/pan.2019.11
Ripollone, J. E., Huybrechts, K. F., Rothman, K. J., Ferguson, R. E., & Franklin, J. M. (2018). Implications of the Propensity Score Matching Paradox in Pharmacoepidemiology. American Journal of Epidemiology, 187(9), 1951–1961. https://doi.org/10.1093/aje/kwy078 | What are the pros and cons of using mahalanobis distance instead of propensity scores in matching | Mahalanobis distance matching (MDM) and propensity score matching (PSM) are methods of doing the same thing, which is to find a subset of control units similar to treated units to arrive at a balanced | What are the pros and cons of using mahalanobis distance instead of propensity scores in matching
Mahalanobis distance matching (MDM) and propensity score matching (PSM) are methods of doing the same thing, which is to find a subset of control units similar to treated units to arrive at a balanced sample (i.e., where the distribution of covariates is the same in both groups).
MDM works by pairing units that are close based on a distance called the Mahalanobis distance, which you can think of like a scale-free Euclidean distance. For two units to have a Mahalanobis distance of 0, they must have identical covariate values. The more different the covariate values, the larger the Mahalanobis distance. The idea is that if you find control units close to the treated units on the Mahalanobis distance, each pair will have similar covariate values, and the distribution of the covariates in the treatment groups in the matched sample will be similar.
PSM works by pairing units that have similar propensity scores. Propensity scores reduce the entire covariate distribution into a single dimension; this means that two units with similar propensity scores will not necessarily have similar covariates values. However, because of the theoretical balancing properties of the propensity score, PSM can still yield balanced samples, even though any individual matched pair of units may not have similar covariate values.
This difference between the two methods, i.e., that MDM creates pairs close on covariate values while PSM does not (even though both may be effective at yielding balanced samples), is the focus of King & Nielsen's (2019) famous critique of PSM. See the chart below, taken from the 2019 paper:
Here, we have the same dataset of treated (red) and control (blue) units, with two covariates (X1, x-axis, and X2, y-axis) being matched on. On the left, MDM is used to pair the units (each gray link is a pair), and on the right, PSM is used. You can see that with MDM, paired units have much more similar covariate values than with PSM. PSM reduces the covariate space to a single dimension, which corresponds to the diagonal line pattern in the plot on the right. Units are paired with each other because they have similar propensity scores, even though they differ quite dramatically on the covariate values.
Why does this matter? King & Nielsen argue that PSM yields fragile and non-robust estimates that could vary wildly depending on the outcome model used. In particular, if you progressively discard units that are far apart from each other (i.e., by imposing a tighter and tighter caliper), eventually balance starts to get worse with PSM even though units close together on the PS remain. They call this the propensity score paradox, which is the motivation for recommending against the use of PSM in favor of potentially more robust methods like MDM that match directly on the covariate space.
So, should we avoid PSM and stick to MDM? No. Rippolone et al. (2018) investigated the impact of the propensity score paradox on real epidemiological data. They found that while the paradox did occur with some data, it was not troublesome until extreme caliper values were used, far beyond what would be recommended. PSM generally yielded good balance on the covariates. In contrast, MDM yielded poor balance in one dataset, sometimes even worse than no matching at all. See the plot below from Ripollone et al. (2018) comparing the balance results from MDM (blue) and PSM (red and green) on one dataset as more units are pruned:
The y-axis is a measure of covariate balance in the matched datasets (unrelated to the pairwise Mahalanobis distance used for matching), and the black dot is the pre-matching balance. We can see that as more units are pruned (moving right along the x-axis), balance gets worse for PSM and better for MDM, but at published recommendations for PSM calipers (vertical dashed lines), balance is excellent for PSM and poor for MDM.
How could we get such different conclusions from comparing the same methods? The answer is that it all depends on the dataset and its unique qualities, including its size, its initial balance, and the number and types of covariates to be matched on. It's worth noting that when analyzing a different dataset than the one depicted above, Ripollone et al. found MDM to yield better balance than PSM. Generally, MDM tends to work better with few covariates and covariates that are normally distributed, whereas PSM tends to work well as long as the propensity score is reasonably well estimated (because the matching is done on the propensity score, not the covariates themselves). The key, though, is that when MDM works, it really works, because it can give matched samples that are not only well-balanced overall, but also containing closely paired units, whereas PSM can only promise well-balanced samples but not close pairs.
What should you do? Normally I would say try both, but this time I will just say to use genetic matching (i.e., method = "genetic" in MatchIt), which combines PSM and MDM and uses optimization to find the distance measure that provides the best balance in the matched dataset. It's much slower than MDM and PSM, but the results will be uniformly better, as many simulation studies have shown. Genetic matching was another method recommended by King & Nielsen for not succumbing to the propensity score paradox. If you can't use genetic matching (e.g., because your dataset is too big or you don't have the time to wait), then you should try both MDM and PSM, and choose the one that yields the best balance measured broadly (i.e., on pairwise covariate distances and KS-statistics and polynomials and interactions of covariates and not just the means). It is straightforward to use MatchIt to quickly try and compare several matching methods before choosing one to move forward with for effect estimation.
There are ways of ensuring close pairs when using PSM, such as exact matching on some covariates, placing calipers on covariates directly, or doing MDM within propensity score calipers. All of these are possible in MatchIt and should be tried and compared.
King, G., & Nielsen, R. (2019). Why Propensity Scores Should Not Be Used for Matching. Political Analysis, 1–20. https://doi.org/10.1017/pan.2019.11
Ripollone, J. E., Huybrechts, K. F., Rothman, K. J., Ferguson, R. E., & Franklin, J. M. (2018). Implications of the Propensity Score Matching Paradox in Pharmacoepidemiology. American Journal of Epidemiology, 187(9), 1951–1961. https://doi.org/10.1093/aje/kwy078 | What are the pros and cons of using mahalanobis distance instead of propensity scores in matching
Mahalanobis distance matching (MDM) and propensity score matching (PSM) are methods of doing the same thing, which is to find a subset of control units similar to treated units to arrive at a balanced |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.