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 |
|---|---|---|---|---|---|---|
31,401 | Stratification of the continuous y (target) variable in regression setting | You can try the verstack package to realize your requirement.
First, install it pip install verstack.
Then split the dataset based on the continuous label as:
from verstack.stratified_continuous_split import scsplit
train, valid = scsplit(df, df['continuous_column_name])
or
X_train, X_val, y_train, y_val = scsplit(X, y, stratify = y) | Stratification of the continuous y (target) variable in regression setting | You can try the verstack package to realize your requirement.
First, install it pip install verstack.
Then split the dataset based on the continuous label as:
from verstack.stratified_continuous_split | Stratification of the continuous y (target) variable in regression setting
You can try the verstack package to realize your requirement.
First, install it pip install verstack.
Then split the dataset based on the continuous label as:
from verstack.stratified_continuous_split import scsplit
train, valid = scsplit(df, df['continuous_column_name])
or
X_train, X_val, y_train, y_val = scsplit(X, y, stratify = y) | Stratification of the continuous y (target) variable in regression setting
You can try the verstack package to realize your requirement.
First, install it pip install verstack.
Then split the dataset based on the continuous label as:
from verstack.stratified_continuous_split |
31,402 | RMSE or MAPE? which one to choose for accuracy? | Use the RMSE.
Note that the (R)MSE and the MAPE will be minimized by quite different point forecasts (see my answer at Higher RMSE lower MAPE). You should first decide which functional of the unknown future distribution you want to elicit, then choose the corresponding error measure.
However, note that an ARIMA model will output a conditional expectation forecast, i.e., the functional that optimizes (R)MSE. It makes little sense to train a model to minimize the (R)MSE, then to assess its forecasts with a different error measure (Kolassa, 2020, IJF). If you truly want to find a MAPE-optimal forecast, you should also use the MAPE to fit your model. I am not aware of any off-the-shelf forecasting software that does this (if you use an ML pipeline, you may be able to specify any fitting criterion and choose the MAPE), and I have major doubts as to the usefulness of a MAPE-minimal forecast. | RMSE or MAPE? which one to choose for accuracy? | Use the RMSE.
Note that the (R)MSE and the MAPE will be minimized by quite different point forecasts (see my answer at Higher RMSE lower MAPE). You should first decide which functional of the unknown | RMSE or MAPE? which one to choose for accuracy?
Use the RMSE.
Note that the (R)MSE and the MAPE will be minimized by quite different point forecasts (see my answer at Higher RMSE lower MAPE). You should first decide which functional of the unknown future distribution you want to elicit, then choose the corresponding error measure.
However, note that an ARIMA model will output a conditional expectation forecast, i.e., the functional that optimizes (R)MSE. It makes little sense to train a model to minimize the (R)MSE, then to assess its forecasts with a different error measure (Kolassa, 2020, IJF). If you truly want to find a MAPE-optimal forecast, you should also use the MAPE to fit your model. I am not aware of any off-the-shelf forecasting software that does this (if you use an ML pipeline, you may be able to specify any fitting criterion and choose the MAPE), and I have major doubts as to the usefulness of a MAPE-minimal forecast. | RMSE or MAPE? which one to choose for accuracy?
Use the RMSE.
Note that the (R)MSE and the MAPE will be minimized by quite different point forecasts (see my answer at Higher RMSE lower MAPE). You should first decide which functional of the unknown |
31,403 | RMSE or MAPE? which one to choose for accuracy? | Based on visual inspection your time series might have a discernable wave every 1 to 3 months. If you include longer period terms in your model this will create an extrapolated mean estimate and prediction interval that is more "wiggly." It's not critical, but it might improve the point predictions. As you currently have it the vast majority of the observations in the test set fall within the prediction intervals.
MAPE stands for mean absolute percentage error. It is the average multiplicative effect between each estimated mean and the observed outcome. RMSE stands for root mean squared error, i.e. standard deviation. While they both summarize the variability of the observations around the mean, they are not in the same scale so don't expect the values to be similar. I suggest using RMSE as this is the basis for how the model is fit to the data. | RMSE or MAPE? which one to choose for accuracy? | Based on visual inspection your time series might have a discernable wave every 1 to 3 months. If you include longer period terms in your model this will create an extrapolated mean estimate and pred | RMSE or MAPE? which one to choose for accuracy?
Based on visual inspection your time series might have a discernable wave every 1 to 3 months. If you include longer period terms in your model this will create an extrapolated mean estimate and prediction interval that is more "wiggly." It's not critical, but it might improve the point predictions. As you currently have it the vast majority of the observations in the test set fall within the prediction intervals.
MAPE stands for mean absolute percentage error. It is the average multiplicative effect between each estimated mean and the observed outcome. RMSE stands for root mean squared error, i.e. standard deviation. While they both summarize the variability of the observations around the mean, they are not in the same scale so don't expect the values to be similar. I suggest using RMSE as this is the basis for how the model is fit to the data. | RMSE or MAPE? which one to choose for accuracy?
Based on visual inspection your time series might have a discernable wave every 1 to 3 months. If you include longer period terms in your model this will create an extrapolated mean estimate and pred |
31,404 | Is the ratio of two sums normally distributed? | Experiment. The ratio is Cauchy, as noted, if numerator and denominator are both normal distributions centered at zero (not illustrated here).
However, the ratio is also often
nowhere near normal if numerator and denominator are both centered several
standard deviations above zero. Using R:
set.seed(1234)
x1 = rnorm(100, 50, 7)
x2 = rnorm(100, 70, 8)
ratio = x1/x2
shapiro.test(ratio)
Shapiro-Wilk normality test
data: ratio
W = 0.94094, p-value = 0.0002201
qqnorm(ratio); qqline(ratio, col="blue")
hist(ratio, prob=T, col="skyblue2") | Is the ratio of two sums normally distributed? | Experiment. The ratio is Cauchy, as noted, if numerator and denominator are both normal distributions centered at zero (not illustrated here).
However, the ratio is also often
nowhere near normal if n | Is the ratio of two sums normally distributed?
Experiment. The ratio is Cauchy, as noted, if numerator and denominator are both normal distributions centered at zero (not illustrated here).
However, the ratio is also often
nowhere near normal if numerator and denominator are both centered several
standard deviations above zero. Using R:
set.seed(1234)
x1 = rnorm(100, 50, 7)
x2 = rnorm(100, 70, 8)
ratio = x1/x2
shapiro.test(ratio)
Shapiro-Wilk normality test
data: ratio
W = 0.94094, p-value = 0.0002201
qqnorm(ratio); qqline(ratio, col="blue")
hist(ratio, prob=T, col="skyblue2") | Is the ratio of two sums normally distributed?
Experiment. The ratio is Cauchy, as noted, if numerator and denominator are both normal distributions centered at zero (not illustrated here).
However, the ratio is also often
nowhere near normal if n |
31,405 | What is the difference between the Viterbi algorithm and beam search? | Yes, you're exactly right. If you set the beam size equal to the size of the HMM or CRF's state space (which is what I assume you meant by 'output space'), then you're guaranteed to find the optimal solution. This is because your search is now exhaustive.
The beam size is the number of candidates to expand in your search, as you move through the time series. If you expand all of them, then this is the Viterbi algorithm.
Recall that the time complexity of the Viterbi algorithm is $O(TN^2)$, where $T$ is the length of the time series, and $N$ is the size of the state space. The fact that this scales quadratically is what motivates beam search: reduce that $N^2$ to $K^2$ for some $K \ll N$, at the cost of exactness. If the state space is small, that's not a big improvement. But if thousands of states are possible (as with a WFSA language model), then this can make a big difference. | What is the difference between the Viterbi algorithm and beam search? | Yes, you're exactly right. If you set the beam size equal to the size of the HMM or CRF's state space (which is what I assume you meant by 'output space'), then you're guaranteed to find the optimal s | What is the difference between the Viterbi algorithm and beam search?
Yes, you're exactly right. If you set the beam size equal to the size of the HMM or CRF's state space (which is what I assume you meant by 'output space'), then you're guaranteed to find the optimal solution. This is because your search is now exhaustive.
The beam size is the number of candidates to expand in your search, as you move through the time series. If you expand all of them, then this is the Viterbi algorithm.
Recall that the time complexity of the Viterbi algorithm is $O(TN^2)$, where $T$ is the length of the time series, and $N$ is the size of the state space. The fact that this scales quadratically is what motivates beam search: reduce that $N^2$ to $K^2$ for some $K \ll N$, at the cost of exactness. If the state space is small, that's not a big improvement. But if thousands of states are possible (as with a WFSA language model), then this can make a big difference. | What is the difference between the Viterbi algorithm and beam search?
Yes, you're exactly right. If you set the beam size equal to the size of the HMM or CRF's state space (which is what I assume you meant by 'output space'), then you're guaranteed to find the optimal s |
31,406 | What is the difference between the Viterbi algorithm and beam search? | If we were to set the beam size to be equal to the number of possible states, wouldn't that mean the beam search algorithm is equivalent to the Viterbi algorithm?
Beam Search
Choose beam of B hypotheses
Do Viterbi algorithm, but keep only best B hypotheses at each step
Definiton of "step" depends on task:
Tagging: Same number of words tagged
Machine Translation: Same number of words translated
Speech Recognition: Same number of frames processed
Source: NLP Programming Tutorial 13 - Beam and A* Search by professor Graham Neubig
Then the reverse is the process of converting beam search into Viterbi.
if we set the beam size to be equivalent to the output space, then wouldn't we also eventually find an optimal solution?
The optimal path guarantee is due to the Generalized Distributive Law(or refer to this).
Because in Beam Search some unpromising parts of search space are pruned, and then we cannot apply the Generalized Distributive Law, and hence it can not guarantee an optimal path. Along the same line, if all the search space is considered the optimal path can be led to. | What is the difference between the Viterbi algorithm and beam search? | If we were to set the beam size to be equal to the number of possible states, wouldn't that mean the beam search algorithm is equivalent to the Viterbi algorithm?
Beam Search
Choose beam of B hypot | What is the difference between the Viterbi algorithm and beam search?
If we were to set the beam size to be equal to the number of possible states, wouldn't that mean the beam search algorithm is equivalent to the Viterbi algorithm?
Beam Search
Choose beam of B hypotheses
Do Viterbi algorithm, but keep only best B hypotheses at each step
Definiton of "step" depends on task:
Tagging: Same number of words tagged
Machine Translation: Same number of words translated
Speech Recognition: Same number of frames processed
Source: NLP Programming Tutorial 13 - Beam and A* Search by professor Graham Neubig
Then the reverse is the process of converting beam search into Viterbi.
if we set the beam size to be equivalent to the output space, then wouldn't we also eventually find an optimal solution?
The optimal path guarantee is due to the Generalized Distributive Law(or refer to this).
Because in Beam Search some unpromising parts of search space are pruned, and then we cannot apply the Generalized Distributive Law, and hence it can not guarantee an optimal path. Along the same line, if all the search space is considered the optimal path can be led to. | What is the difference between the Viterbi algorithm and beam search?
If we were to set the beam size to be equal to the number of possible states, wouldn't that mean the beam search algorithm is equivalent to the Viterbi algorithm?
Beam Search
Choose beam of B hypot |
31,407 | Loss functions in statistical decision theory vs. machine learning? | The loss that is of ultimate interest is the prediction loss (or decision loss). It represents real (financial/material/...) consequences of any given decision for the decision maker. It is this and only this loss that we want to minimize for its own sake rather than as an intermediate goal.
The training loss is an intermediate tool for building prediction models. It does not affect the welfare of the decision maker directly; its effects manifest themselves only via the prediction loss.
It may or may not be a good idea to match the training loss to the prediction loss.
For example, suppose you have a sample generated by a Normal random variable. You have to predict a new observation from the same population, and your prediction loss is quadratic. Absent additional information, your best guess is the mean of the random variable. The best* estimate of it is the sample mean. It so happens that the type of training loss that is minimized by the sample mean is quadratic. Thus, here the training loss coincides with the prediction loss.
Now suppose the situation is the same but your prediction loss is the absolute value of the prediction error. Absent additional information, your best guess is the median of the random variable. The best* estimate of it is the sample mean, not the sample median (because our sample is generated by a Normal random variable). As we already know, the training loss that yields the sample mean when minimized is quadratic. Thus, here the training loss does not coincide with the prediction loss.
*Best in the sense of minimizing the expected prediction loss. | Loss functions in statistical decision theory vs. machine learning? | The loss that is of ultimate interest is the prediction loss (or decision loss). It represents real (financial/material/...) consequences of any given decision for the decision maker. It is this and o | Loss functions in statistical decision theory vs. machine learning?
The loss that is of ultimate interest is the prediction loss (or decision loss). It represents real (financial/material/...) consequences of any given decision for the decision maker. It is this and only this loss that we want to minimize for its own sake rather than as an intermediate goal.
The training loss is an intermediate tool for building prediction models. It does not affect the welfare of the decision maker directly; its effects manifest themselves only via the prediction loss.
It may or may not be a good idea to match the training loss to the prediction loss.
For example, suppose you have a sample generated by a Normal random variable. You have to predict a new observation from the same population, and your prediction loss is quadratic. Absent additional information, your best guess is the mean of the random variable. The best* estimate of it is the sample mean. It so happens that the type of training loss that is minimized by the sample mean is quadratic. Thus, here the training loss coincides with the prediction loss.
Now suppose the situation is the same but your prediction loss is the absolute value of the prediction error. Absent additional information, your best guess is the median of the random variable. The best* estimate of it is the sample mean, not the sample median (because our sample is generated by a Normal random variable). As we already know, the training loss that yields the sample mean when minimized is quadratic. Thus, here the training loss does not coincide with the prediction loss.
*Best in the sense of minimizing the expected prediction loss. | Loss functions in statistical decision theory vs. machine learning?
The loss that is of ultimate interest is the prediction loss (or decision loss). It represents real (financial/material/...) consequences of any given decision for the decision maker. It is this and o |
31,408 | Loss functions in statistical decision theory vs. machine learning? | Let me give a slightly more ML-focused perspective on the accepted answer.
Don't conflate training loss and decision loss – they're separate concepts even though the functions can be the same. It's easier to see this distinction in classification than regression.
So, let's say we're doing binary classification using logistic regression. The training loss is cross entropy / log loss (maybe with regularization). After the model is trained, we don't care about the training loss anymore.
At prediction time, our logistic regression model tells us $P(y|x)$. We need to translate this distribution into a single class. Do we just pick the class with the highest probability? Do we want to be extra careful about false positives? We formally encode these preferences into a decision loss, which allows us to optimally choose a single class from $P(y|x)$.
For a more academic exposition, I found "Pattern Recognition and Machine Learning" to have a great disambiguation of these two.
Determination of $p(x, t)$ from a set of training data is an example of
inference and is typically a very difficult problem whose solution
forms the subject of much of this book. In a practical application,
however, we must often make a specific prediction for the value of $t$,
and this aspect is the subject of decision theory.... We shall see that the decision stage is generally very simple, even trivial, once we have solved the inference problem.
It is worth distinguishing between the squared loss function arising
from decision theory and the sum-of-squares error function that arose
in the maximum likelihood estimation of model parameters. We might
use more sophisticated techniques than least squares, for example
regularization or a fully Bayesian approach, to determine the
conditional distribution $p(t|x)$. These can all be combined with the
squared loss function for the purpose of making predictions. | Loss functions in statistical decision theory vs. machine learning? | Let me give a slightly more ML-focused perspective on the accepted answer.
Don't conflate training loss and decision loss – they're separate concepts even though the functions can be the same. It's ea | Loss functions in statistical decision theory vs. machine learning?
Let me give a slightly more ML-focused perspective on the accepted answer.
Don't conflate training loss and decision loss – they're separate concepts even though the functions can be the same. It's easier to see this distinction in classification than regression.
So, let's say we're doing binary classification using logistic regression. The training loss is cross entropy / log loss (maybe with regularization). After the model is trained, we don't care about the training loss anymore.
At prediction time, our logistic regression model tells us $P(y|x)$. We need to translate this distribution into a single class. Do we just pick the class with the highest probability? Do we want to be extra careful about false positives? We formally encode these preferences into a decision loss, which allows us to optimally choose a single class from $P(y|x)$.
For a more academic exposition, I found "Pattern Recognition and Machine Learning" to have a great disambiguation of these two.
Determination of $p(x, t)$ from a set of training data is an example of
inference and is typically a very difficult problem whose solution
forms the subject of much of this book. In a practical application,
however, we must often make a specific prediction for the value of $t$,
and this aspect is the subject of decision theory.... We shall see that the decision stage is generally very simple, even trivial, once we have solved the inference problem.
It is worth distinguishing between the squared loss function arising
from decision theory and the sum-of-squares error function that arose
in the maximum likelihood estimation of model parameters. We might
use more sophisticated techniques than least squares, for example
regularization or a fully Bayesian approach, to determine the
conditional distribution $p(t|x)$. These can all be combined with the
squared loss function for the purpose of making predictions. | Loss functions in statistical decision theory vs. machine learning?
Let me give a slightly more ML-focused perspective on the accepted answer.
Don't conflate training loss and decision loss – they're separate concepts even though the functions can be the same. It's ea |
31,409 | Loss functions in statistical decision theory vs. machine learning? | Actually this is not really a big difference between Statistics and Machine Learning. Machine Learning theory is concerned with how well predictions work outside the training sample in terms of the loss function as well. I think this is usually referred to as generalization risk or generalization error there, see for example
Bousquet & Elisseef: Stability and Generalization.
Obviously if you only have the training sample, you can only evaluate the loss function on the training data. But many methods are based on some kind of training loss minimization, which implies that the training error (because it is optimized on the training data) will not generalize well and loss on new observations can be expected to be higher. This depends on the specific method and situation, but considering at least theoretically (or on separate test data) applying the loss function to new to be predicted data is a key tool for investigating this, and both Statistics and Machine Learning are concerned with this. (And you can sometimes choose methods or parameters based on expected generalization loss rather than plain training loss, at least where theory exists.) | Loss functions in statistical decision theory vs. machine learning? | Actually this is not really a big difference between Statistics and Machine Learning. Machine Learning theory is concerned with how well predictions work outside the training sample in terms of the lo | Loss functions in statistical decision theory vs. machine learning?
Actually this is not really a big difference between Statistics and Machine Learning. Machine Learning theory is concerned with how well predictions work outside the training sample in terms of the loss function as well. I think this is usually referred to as generalization risk or generalization error there, see for example
Bousquet & Elisseef: Stability and Generalization.
Obviously if you only have the training sample, you can only evaluate the loss function on the training data. But many methods are based on some kind of training loss minimization, which implies that the training error (because it is optimized on the training data) will not generalize well and loss on new observations can be expected to be higher. This depends on the specific method and situation, but considering at least theoretically (or on separate test data) applying the loss function to new to be predicted data is a key tool for investigating this, and both Statistics and Machine Learning are concerned with this. (And you can sometimes choose methods or parameters based on expected generalization loss rather than plain training loss, at least where theory exists.) | Loss functions in statistical decision theory vs. machine learning?
Actually this is not really a big difference between Statistics and Machine Learning. Machine Learning theory is concerned with how well predictions work outside the training sample in terms of the lo |
31,410 | Loss functions in statistical decision theory vs. machine learning? | Theoretical approach: In first layer, define prediction error $\epsilon=y-E(y|x)$. Then, to estimate parameter, we define a loss or criterion function as $l(\epsilon)=\|\epsilon\|_p^p$.
Empricial approach: We define residual error $r=y-\hat{y}$, where $\hat{y}$ approximate the prediction function $E(y|x)$ from the given data under a suitable model structure with a suitable loss or criterion function $l(r)=\|r\|_p^p$. | Loss functions in statistical decision theory vs. machine learning? | Theoretical approach: In first layer, define prediction error $\epsilon=y-E(y|x)$. Then, to estimate parameter, we define a loss or criterion function as $l(\epsilon)=\|\epsilon\|_p^p$.
Empricial appr | Loss functions in statistical decision theory vs. machine learning?
Theoretical approach: In first layer, define prediction error $\epsilon=y-E(y|x)$. Then, to estimate parameter, we define a loss or criterion function as $l(\epsilon)=\|\epsilon\|_p^p$.
Empricial approach: We define residual error $r=y-\hat{y}$, where $\hat{y}$ approximate the prediction function $E(y|x)$ from the given data under a suitable model structure with a suitable loss or criterion function $l(r)=\|r\|_p^p$. | Loss functions in statistical decision theory vs. machine learning?
Theoretical approach: In first layer, define prediction error $\epsilon=y-E(y|x)$. Then, to estimate parameter, we define a loss or criterion function as $l(\epsilon)=\|\epsilon\|_p^p$.
Empricial appr |
31,411 | Machine Learning: Negative Log Likelihood vs Cross-Entropy | The Wikipedia page has left out a few steps. When they say "the likelihood of the training set", they just mean "the probability of the training set given some parameter values":
$$
L(\theta | x_1, ..., x_n) = p(x_1, ..., x_n | \theta)
$$
The data $x_k$ in the training set is assumed conditionally independent, so that
$$
p(x_1, ..., x_n | \theta) = \prod_{k=1}^n p(x_k | \theta)
$$
If the training set was $[2,2,1]$ then the likelihood would be $p(2|\theta) p(2|\theta) p(1|\theta) = p(2|\theta)^2 p(1|\theta)$. This suggests a simplification:
$$
\prod_{k=1}^n p(x_k | \theta) = \prod_i p(i | \theta)^{n_i}
$$
where $n_i$ is the number of times $i$ occurs in the training data.
The Wikipedia page defines $q_i = p(i | \theta)$ and $p_i = n_i/N$, so the likelihood is
$$
\prod_{k=1}^n q_{x_k} = \prod_i q_i^{n_i} = \prod_i q_i^{N p_i}
$$
At the end, they divide the logarithm by $N$ to get the cross-entropy. | Machine Learning: Negative Log Likelihood vs Cross-Entropy | The Wikipedia page has left out a few steps. When they say "the likelihood of the training set", they just mean "the probability of the training set given some parameter values":
$$
L(\theta | x_1, . | Machine Learning: Negative Log Likelihood vs Cross-Entropy
The Wikipedia page has left out a few steps. When they say "the likelihood of the training set", they just mean "the probability of the training set given some parameter values":
$$
L(\theta | x_1, ..., x_n) = p(x_1, ..., x_n | \theta)
$$
The data $x_k$ in the training set is assumed conditionally independent, so that
$$
p(x_1, ..., x_n | \theta) = \prod_{k=1}^n p(x_k | \theta)
$$
If the training set was $[2,2,1]$ then the likelihood would be $p(2|\theta) p(2|\theta) p(1|\theta) = p(2|\theta)^2 p(1|\theta)$. This suggests a simplification:
$$
\prod_{k=1}^n p(x_k | \theta) = \prod_i p(i | \theta)^{n_i}
$$
where $n_i$ is the number of times $i$ occurs in the training data.
The Wikipedia page defines $q_i = p(i | \theta)$ and $p_i = n_i/N$, so the likelihood is
$$
\prod_{k=1}^n q_{x_k} = \prod_i q_i^{n_i} = \prod_i q_i^{N p_i}
$$
At the end, they divide the logarithm by $N$ to get the cross-entropy. | Machine Learning: Negative Log Likelihood vs Cross-Entropy
The Wikipedia page has left out a few steps. When they say "the likelihood of the training set", they just mean "the probability of the training set given some parameter values":
$$
L(\theta | x_1, . |
31,412 | How does the bottleneck z dimension affect the reconstruction loss in VAEs | It seems to me that the link you are missing here is to the probabilistic / information theory interpretation of VAEs. When the capacity of your networks is large enough you will reach a point where the solution with a larger latent space does not keep more information than a smaller one. This is possible in VAEs because they produce a noisy representation inside.
To clarify things: First the bits/dim metric is per dimension of the input. You can read more about this metric in links collected here:
What is bits per dimension (bits/dim) exactly (in pixel CNN papers)?
Maybe the limit for infinitely big networks and infinite data is instructive here: VAEs optimize a variational bound on the evidence for the model. This is bounded from above by the true entropy of your data. At or near this point your bits/dim will converge and adding more complexity anywhere will no longer improve performance. With limited data this point will come earlier.
As you appear to think in terms of bottlenecks & auto-encoders: For VAEs the bottleneck is not really the number of dimensions in the latent space, but the noise. Without noise even a single continuous number has infinite capacity. As VAEs are allowed to adjust the noise on their representation they may very well represent the same amount of information in fewer dimensions with less noise. Thus, the number of latent dimensions much less informative about the capacity of the encoding than for classic autoencoders. Indeed VAEs regularly have latent space units who converge towards always being equal to the prior, i.e. not carrying any information about images.
In practice more latent units become harder to train and costly, such that you would avoid using too many latent units which "die", but from a theoretical viewpoint many dimensions does not equal an open bottleneck for VAEs.
Thus, overall I would say the dimensionality of z for VAEs is one of many knobs changing the expressiveness/complexity of the encoder/decoder and does not affect the reconstruction loss directly beyond this. | How does the bottleneck z dimension affect the reconstruction loss in VAEs | It seems to me that the link you are missing here is to the probabilistic / information theory interpretation of VAEs. When the capacity of your networks is large enough you will reach a point where t | How does the bottleneck z dimension affect the reconstruction loss in VAEs
It seems to me that the link you are missing here is to the probabilistic / information theory interpretation of VAEs. When the capacity of your networks is large enough you will reach a point where the solution with a larger latent space does not keep more information than a smaller one. This is possible in VAEs because they produce a noisy representation inside.
To clarify things: First the bits/dim metric is per dimension of the input. You can read more about this metric in links collected here:
What is bits per dimension (bits/dim) exactly (in pixel CNN papers)?
Maybe the limit for infinitely big networks and infinite data is instructive here: VAEs optimize a variational bound on the evidence for the model. This is bounded from above by the true entropy of your data. At or near this point your bits/dim will converge and adding more complexity anywhere will no longer improve performance. With limited data this point will come earlier.
As you appear to think in terms of bottlenecks & auto-encoders: For VAEs the bottleneck is not really the number of dimensions in the latent space, but the noise. Without noise even a single continuous number has infinite capacity. As VAEs are allowed to adjust the noise on their representation they may very well represent the same amount of information in fewer dimensions with less noise. Thus, the number of latent dimensions much less informative about the capacity of the encoding than for classic autoencoders. Indeed VAEs regularly have latent space units who converge towards always being equal to the prior, i.e. not carrying any information about images.
In practice more latent units become harder to train and costly, such that you would avoid using too many latent units which "die", but from a theoretical viewpoint many dimensions does not equal an open bottleneck for VAEs.
Thus, overall I would say the dimensionality of z for VAEs is one of many knobs changing the expressiveness/complexity of the encoder/decoder and does not affect the reconstruction loss directly beyond this. | How does the bottleneck z dimension affect the reconstruction loss in VAEs
It seems to me that the link you are missing here is to the probabilistic / information theory interpretation of VAEs. When the capacity of your networks is large enough you will reach a point where t |
31,413 | How does the bottleneck z dimension affect the reconstruction loss in VAEs | As mentioned in Variational Autoencoder − Dimension of the latent space, there is a heuristic upper-bound for the latent variable dimension: the size of the training data.
If you encoder is sufficiently powered (we assume it is anyways for VAEs), if your latent variable is $N$ dimensional and you have $N$ training samples, then your encoder can simply encode each sample in one dimension of the latent, severely overfitting your model.
In practice, however, that bound is probably tighter, since the encoder is non-linear it can fit the training data into a lower dimensional latent and yet overfit.
One possible test for this is to decode random latents and see what they look like (assuming you are modeling images). | How does the bottleneck z dimension affect the reconstruction loss in VAEs | As mentioned in Variational Autoencoder − Dimension of the latent space, there is a heuristic upper-bound for the latent variable dimension: the size of the training data.
If you encoder is sufficient | How does the bottleneck z dimension affect the reconstruction loss in VAEs
As mentioned in Variational Autoencoder − Dimension of the latent space, there is a heuristic upper-bound for the latent variable dimension: the size of the training data.
If you encoder is sufficiently powered (we assume it is anyways for VAEs), if your latent variable is $N$ dimensional and you have $N$ training samples, then your encoder can simply encode each sample in one dimension of the latent, severely overfitting your model.
In practice, however, that bound is probably tighter, since the encoder is non-linear it can fit the training data into a lower dimensional latent and yet overfit.
One possible test for this is to decode random latents and see what they look like (assuming you are modeling images). | How does the bottleneck z dimension affect the reconstruction loss in VAEs
As mentioned in Variational Autoencoder − Dimension of the latent space, there is a heuristic upper-bound for the latent variable dimension: the size of the training data.
If you encoder is sufficient |
31,414 | The Frog Problem (puzzle in YouTube video) | We will call $J_n$ the expected value for the jumps when there are $n$ leaves ahead. We set also $J_0 = 0$, which is consistent with the fact that if the frog has no leaf ahead it needs to do exactly $0$ jumps to arrive at destination.
We will name/number the leaves according to their distance from the destination. So the destination will be leaf $0$, the one immediately before $1$ and so on up to leaf $n-1$ that is the one in front of the frog. There are in total $n$ leaves and the probability to jump on any of them with one leap is $\frac{1}{n}$ according to the puzzle indications.
When the frog takes this first leap, it will land on leaf $k$, with $k \in \{0, ... n-1\}$ and, from that point, the expected value of remaining leaps will be $J_k$. Considering that these events are mutually exclusive, we get the following:
$$J_n = \sum_{k=0}^{n-1}\frac{1}{n}(1 + J_k)$$
where the $1$ represents the first leap to reach position $k$. As there are $n$ elements in the sum, it can be rearranged as:
$$J_n = 1 + \frac{1}{n} \sum_{k=0}^{n-1}J_k$$
which is indeed a bit too recursive. With simple arithmetics we can further rearrange it as follows:
$$n(J_n - 1) = \sum_{k=0}^{n-1}J_k$$
This relation is generic and can be also rewritten with $n-1$ instead of $n$:
$$(n-1)(J_{n-1} - 1) = \sum_{k=0}^{n-2}J_k$$
Subtracting the two relations we get:
$$n(J_n - 1) - (n-1)(J_{n-1} - 1) = \sum_{k=0}^{n-1}J_k - \sum_{k=0}^{n-2}J_k = J_{n-1}$$
that is:
$$n(J_n - 1) = (n-1)(J_{n-1} - 1) + J_{n-1} = nJ_{n-1} - (n-1)$$
$$J_n - 1 = J_{n-1} - \frac{n-1}{n}$$
$$J_n = J_{n-1} + \frac{1}{n}$$
Still recursive, but at least the $n$-th element is expressed in terms of $n-1$-th element only.
Now considering that $J_0 = 0$ the relation above can be collapsed to:
$$J_n = \sum_{k = 1}^{n}\frac{1}{k}$$
which is the answer to the puzzle. | The Frog Problem (puzzle in YouTube video) | We will call $J_n$ the expected value for the jumps when there are $n$ leaves ahead. We set also $J_0 = 0$, which is consistent with the fact that if the frog has no leaf ahead it needs to do exactly | The Frog Problem (puzzle in YouTube video)
We will call $J_n$ the expected value for the jumps when there are $n$ leaves ahead. We set also $J_0 = 0$, which is consistent with the fact that if the frog has no leaf ahead it needs to do exactly $0$ jumps to arrive at destination.
We will name/number the leaves according to their distance from the destination. So the destination will be leaf $0$, the one immediately before $1$ and so on up to leaf $n-1$ that is the one in front of the frog. There are in total $n$ leaves and the probability to jump on any of them with one leap is $\frac{1}{n}$ according to the puzzle indications.
When the frog takes this first leap, it will land on leaf $k$, with $k \in \{0, ... n-1\}$ and, from that point, the expected value of remaining leaps will be $J_k$. Considering that these events are mutually exclusive, we get the following:
$$J_n = \sum_{k=0}^{n-1}\frac{1}{n}(1 + J_k)$$
where the $1$ represents the first leap to reach position $k$. As there are $n$ elements in the sum, it can be rearranged as:
$$J_n = 1 + \frac{1}{n} \sum_{k=0}^{n-1}J_k$$
which is indeed a bit too recursive. With simple arithmetics we can further rearrange it as follows:
$$n(J_n - 1) = \sum_{k=0}^{n-1}J_k$$
This relation is generic and can be also rewritten with $n-1$ instead of $n$:
$$(n-1)(J_{n-1} - 1) = \sum_{k=0}^{n-2}J_k$$
Subtracting the two relations we get:
$$n(J_n - 1) - (n-1)(J_{n-1} - 1) = \sum_{k=0}^{n-1}J_k - \sum_{k=0}^{n-2}J_k = J_{n-1}$$
that is:
$$n(J_n - 1) = (n-1)(J_{n-1} - 1) + J_{n-1} = nJ_{n-1} - (n-1)$$
$$J_n - 1 = J_{n-1} - \frac{n-1}{n}$$
$$J_n = J_{n-1} + \frac{1}{n}$$
Still recursive, but at least the $n$-th element is expressed in terms of $n-1$-th element only.
Now considering that $J_0 = 0$ the relation above can be collapsed to:
$$J_n = \sum_{k = 1}^{n}\frac{1}{k}$$
which is the answer to the puzzle. | The Frog Problem (puzzle in YouTube video)
We will call $J_n$ the expected value for the jumps when there are $n$ leaves ahead. We set also $J_0 = 0$, which is consistent with the fact that if the frog has no leaf ahead it needs to do exactly |
31,415 | The Frog Problem (puzzle in YouTube video) | This is an interesting problem, and polettix gives the solution for the immediate problem of finding the expected number of jumps. I'm going to try looking at the broader issue of the distribution of the time it takes to get to the last lily-pad. This broader analysis allows us to find the probabilities of any state, and any of the moments of the distribution.
This analysis can be framed as a problem of finding the distribution of the "hitting time" for the absorbing state of a discrete Markov chain. It is relatively simple to program this Markov chain in statistical software and extract the resulting distribution of the hitting times, thus giving a complete solution to the Frog Problem.
Setting up the problem as a Markov chain: To set up the problem, we use states $x = 0,1,2,...,n$, where state $x=0$ is the frog on the river-bank, and the remaining states are for the frog being on lily-pads $1,...,n$ respectively. We let $\{ X_t | t =0,1,2,3,... \}$ be the random process in the problem, with the frog being at lily-pad $X_t$ immediately after jump $t$. The process is a strictly monotone discrete Markov chain with the $(n+1) \times (n+1)$ transition probability matrix:
$$\mathbf{P} = \begin{bmatrix}
0 & 1/n & 1/n & \cdots & 1/n & 1/n & 1/n \\
0 & 0 & 1/(n-1) & \cdots & 1/(n-1) & 1/(n-1) & 1/(n-1) \\
0 & 0 & 0 & \cdots & 1/(n-2) & 1/(n-2) & 1/(n-2) \\
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\
0 & 0 & 0 & \cdots & 0 & 1/2 & 1/2 \\
0 & 0 & 0 & \cdots & 0 & 0 & 1 \\
0 & 0 & 0 & \cdots & 0 & 0 & 1 \\
\end{bmatrix}.$$
The number of jumps to the last lily-pad is the hitting time for state $n$, which is:
$$T \equiv \min \{ t \in \mathbb{N} | X_t = n \}.$$
Our goal will be to find the probability mass function for the random variable $T$, which provides a full solution to the frog problem (i.e., it fully describes the behaviour of the number of jumps to the last lily-pad).
Finding the probability mass function: Since the frog progresses by at least one lily-pad at each jump, it takes at most $n$ jumps to reach the last lily-pad, so we must have $1 \leqslant T \leqslant n$. The cumulative distribution function for this time is:
$$F_T(t) = \mathbb{P}(T \leqslant t)
= \mathbb{P}(X_t = n)
= [\mathbf{P}^t]_{0,n}.$$
Thus, the probability mass function for the time is:
$$p_T(t) = \begin{cases}
1/n & & \text{for } t = 1, \\[6pt]
[\mathbf{P}^t]_{0,n} - [\mathbf{P}^{t-1}]_{0,n} & & \text{for } t > 1. \\[6pt]
\end{cases}$$
This mass function fully describes the distribution of the time taken for the frog to reach the last lily-pad, and so it can be considered to be a complete solution to the Frog problem. To facilitate computation, we can program this distribution in R as the dfrog function. This is a vectorised function that generates values from the probability mass function for an argument vector T and parameter n.
dfrog <- function(n, T = 1:n) {
#Create transition probability matrix
P <- matrix(0, nrow = n+1, ncol = n+1);
for (i in 1:n) {
for (j in i:n) {
P[i, j+1] <- 1/(n+1-i); } }
P[n+1, n+1] <- 1;
#Generate CDF and PMF vectors
PP <- P;
CDF <- rep(0, n);
for (t in 1:n) {
CDF[t] <- PP[1, n+1];
PP <- PP %*% P; }
PMF <- diff(c(0, CDF));
#Generate output vector
OUT <- rep(0, length(T));
for (i in 1:length(T)) { OUT[i] <- PMF[T[i]]; }
OUT; }
We can use this function to generate and plot the probability mass function. The plot below shows the distribution of the number of jumps when there are $n=20$ lily-pads. As can be seen, the frog will usually take 3-4 jumps to reach the last lily-pad in this case.
#Load ggplot and set theme
library(ggplot2);
THEME <- theme(plot.title = element_text(hjust = 0.5, size = 14, face = 'bold'),
plot.subtitle = element_text(hjust = 0.5, face = 'bold'));
#Plot the PMF
n <- 20;
DATA <- data.frame(Jumps = 1:n, Probability = dfrog(n));
ggplot(aes(x = Jumps, y = Probability), data = DATA) +
geom_bar(stat = 'identity', fill = 'darkgreen') +
THEME +
ggtitle('PMF of number of jumps to last lily-pad') +
labs(subtitle = paste0('(Frog problem with n = ', n, ' lily-pads)')); | The Frog Problem (puzzle in YouTube video) | This is an interesting problem, and polettix gives the solution for the immediate problem of finding the expected number of jumps. I'm going to try looking at the broader issue of the distribution of | The Frog Problem (puzzle in YouTube video)
This is an interesting problem, and polettix gives the solution for the immediate problem of finding the expected number of jumps. I'm going to try looking at the broader issue of the distribution of the time it takes to get to the last lily-pad. This broader analysis allows us to find the probabilities of any state, and any of the moments of the distribution.
This analysis can be framed as a problem of finding the distribution of the "hitting time" for the absorbing state of a discrete Markov chain. It is relatively simple to program this Markov chain in statistical software and extract the resulting distribution of the hitting times, thus giving a complete solution to the Frog Problem.
Setting up the problem as a Markov chain: To set up the problem, we use states $x = 0,1,2,...,n$, where state $x=0$ is the frog on the river-bank, and the remaining states are for the frog being on lily-pads $1,...,n$ respectively. We let $\{ X_t | t =0,1,2,3,... \}$ be the random process in the problem, with the frog being at lily-pad $X_t$ immediately after jump $t$. The process is a strictly monotone discrete Markov chain with the $(n+1) \times (n+1)$ transition probability matrix:
$$\mathbf{P} = \begin{bmatrix}
0 & 1/n & 1/n & \cdots & 1/n & 1/n & 1/n \\
0 & 0 & 1/(n-1) & \cdots & 1/(n-1) & 1/(n-1) & 1/(n-1) \\
0 & 0 & 0 & \cdots & 1/(n-2) & 1/(n-2) & 1/(n-2) \\
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \vdots \\
0 & 0 & 0 & \cdots & 0 & 1/2 & 1/2 \\
0 & 0 & 0 & \cdots & 0 & 0 & 1 \\
0 & 0 & 0 & \cdots & 0 & 0 & 1 \\
\end{bmatrix}.$$
The number of jumps to the last lily-pad is the hitting time for state $n$, which is:
$$T \equiv \min \{ t \in \mathbb{N} | X_t = n \}.$$
Our goal will be to find the probability mass function for the random variable $T$, which provides a full solution to the frog problem (i.e., it fully describes the behaviour of the number of jumps to the last lily-pad).
Finding the probability mass function: Since the frog progresses by at least one lily-pad at each jump, it takes at most $n$ jumps to reach the last lily-pad, so we must have $1 \leqslant T \leqslant n$. The cumulative distribution function for this time is:
$$F_T(t) = \mathbb{P}(T \leqslant t)
= \mathbb{P}(X_t = n)
= [\mathbf{P}^t]_{0,n}.$$
Thus, the probability mass function for the time is:
$$p_T(t) = \begin{cases}
1/n & & \text{for } t = 1, \\[6pt]
[\mathbf{P}^t]_{0,n} - [\mathbf{P}^{t-1}]_{0,n} & & \text{for } t > 1. \\[6pt]
\end{cases}$$
This mass function fully describes the distribution of the time taken for the frog to reach the last lily-pad, and so it can be considered to be a complete solution to the Frog problem. To facilitate computation, we can program this distribution in R as the dfrog function. This is a vectorised function that generates values from the probability mass function for an argument vector T and parameter n.
dfrog <- function(n, T = 1:n) {
#Create transition probability matrix
P <- matrix(0, nrow = n+1, ncol = n+1);
for (i in 1:n) {
for (j in i:n) {
P[i, j+1] <- 1/(n+1-i); } }
P[n+1, n+1] <- 1;
#Generate CDF and PMF vectors
PP <- P;
CDF <- rep(0, n);
for (t in 1:n) {
CDF[t] <- PP[1, n+1];
PP <- PP %*% P; }
PMF <- diff(c(0, CDF));
#Generate output vector
OUT <- rep(0, length(T));
for (i in 1:length(T)) { OUT[i] <- PMF[T[i]]; }
OUT; }
We can use this function to generate and plot the probability mass function. The plot below shows the distribution of the number of jumps when there are $n=20$ lily-pads. As can be seen, the frog will usually take 3-4 jumps to reach the last lily-pad in this case.
#Load ggplot and set theme
library(ggplot2);
THEME <- theme(plot.title = element_text(hjust = 0.5, size = 14, face = 'bold'),
plot.subtitle = element_text(hjust = 0.5, face = 'bold'));
#Plot the PMF
n <- 20;
DATA <- data.frame(Jumps = 1:n, Probability = dfrog(n));
ggplot(aes(x = Jumps, y = Probability), data = DATA) +
geom_bar(stat = 'identity', fill = 'darkgreen') +
THEME +
ggtitle('PMF of number of jumps to last lily-pad') +
labs(subtitle = paste0('(Frog problem with n = ', n, ' lily-pads)')); | The Frog Problem (puzzle in YouTube video)
This is an interesting problem, and polettix gives the solution for the immediate problem of finding the expected number of jumps. I'm going to try looking at the broader issue of the distribution of |
31,416 | The Frog Problem (puzzle in YouTube video) | Instead of using the recursive relation for the expected number $J_n = J_{n-1} + \frac{1}{n}$ we could also try a more mechanistic approach by computing every path that the frog can take and the distribution of the probability of the position of the frog after $k$ jumps.
This can be quickly computed using a Markov chain.
# stochastic Matrix
M <- pracma::Toeplitz(c(0,rep(1,10)),rep(0,11)) / c(1,1:10)
M[1,1] <- 1
# positions of frogs after k steps
V <- c(rep(0,10),1)
Vm <- sapply(0:10, FUN = function(k) V %*% (M %^% k))
# mean number of steps by computing 1-F(0)
sum(1-Vm[1,])
giving $2.928968$
The mass distribution, $p(x,k)$, for the probability to be at distance $x$ from the 'finish-leaf' in the $k$-th step would look like the following:
This method has one downside. It is not very easy to derive the final charming result that the expectation value for the number of steps is equal to the n-th harmonic number $\sum_{k=1}^n 1/k$.
In the comments I suggested that these distributions $p(x,k)$ would be like polynomial functions. However that is wrong. It is more complicated.
The distribution follows the relation:
$$p(x,k) = \sum_{y=x+1}^N \frac{p(y,k-1)}{j}$$
where $p(x,k)$ is a sum of the probabilities for the position of the frog in the $(k-1)$-th step, and $N$ is the number of leaves (generalizing from $N=10$). To start this relation we use $p(N,0)=1$.
This could be expanded as
$$p(x,k) = \frac{1}{N} \sum_{l_1=x+1}^{N-k} \sum_{l_2=l_1+1}^{N-k+1} ... \sum_{l_k=l_{k-1}+1}^{N-1} \frac{1}{l_1 \cdot l_2 \cdot ... l_k}$$
which is some sort of generalization of the Harmonic number.
You could describe it more compact as
$$p(x,k) = \frac{1}{N} \sum_{S \in S_{k,[x,...,N-1]}} \prod_{a \in S} \frac{1}{a}$$
where the sum is over all k-subsets $S$ in $S_{k,[x,...,N-1]}$, the set of all k-subset of $[x,...,N-1]$, and the product is over all the numbers $a$ in the subset $S$. For instance a subset $\lbrace 3,5,7 \rbrace$ would represent that the frog jumped from position 10 to 7 to 5 and to 3. The probability for the frog to follow this path is $\frac{1}{10 \cdot 7 \cdot 5 \cdot 3}$.
I am not sure yet how to continue from here to obtain the final result... I imagine you could use some recursive relation. | The Frog Problem (puzzle in YouTube video) | Instead of using the recursive relation for the expected number $J_n = J_{n-1} + \frac{1}{n}$ we could also try a more mechanistic approach by computing every path that the frog can take and the dist | The Frog Problem (puzzle in YouTube video)
Instead of using the recursive relation for the expected number $J_n = J_{n-1} + \frac{1}{n}$ we could also try a more mechanistic approach by computing every path that the frog can take and the distribution of the probability of the position of the frog after $k$ jumps.
This can be quickly computed using a Markov chain.
# stochastic Matrix
M <- pracma::Toeplitz(c(0,rep(1,10)),rep(0,11)) / c(1,1:10)
M[1,1] <- 1
# positions of frogs after k steps
V <- c(rep(0,10),1)
Vm <- sapply(0:10, FUN = function(k) V %*% (M %^% k))
# mean number of steps by computing 1-F(0)
sum(1-Vm[1,])
giving $2.928968$
The mass distribution, $p(x,k)$, for the probability to be at distance $x$ from the 'finish-leaf' in the $k$-th step would look like the following:
This method has one downside. It is not very easy to derive the final charming result that the expectation value for the number of steps is equal to the n-th harmonic number $\sum_{k=1}^n 1/k$.
In the comments I suggested that these distributions $p(x,k)$ would be like polynomial functions. However that is wrong. It is more complicated.
The distribution follows the relation:
$$p(x,k) = \sum_{y=x+1}^N \frac{p(y,k-1)}{j}$$
where $p(x,k)$ is a sum of the probabilities for the position of the frog in the $(k-1)$-th step, and $N$ is the number of leaves (generalizing from $N=10$). To start this relation we use $p(N,0)=1$.
This could be expanded as
$$p(x,k) = \frac{1}{N} \sum_{l_1=x+1}^{N-k} \sum_{l_2=l_1+1}^{N-k+1} ... \sum_{l_k=l_{k-1}+1}^{N-1} \frac{1}{l_1 \cdot l_2 \cdot ... l_k}$$
which is some sort of generalization of the Harmonic number.
You could describe it more compact as
$$p(x,k) = \frac{1}{N} \sum_{S \in S_{k,[x,...,N-1]}} \prod_{a \in S} \frac{1}{a}$$
where the sum is over all k-subsets $S$ in $S_{k,[x,...,N-1]}$, the set of all k-subset of $[x,...,N-1]$, and the product is over all the numbers $a$ in the subset $S$. For instance a subset $\lbrace 3,5,7 \rbrace$ would represent that the frog jumped from position 10 to 7 to 5 and to 3. The probability for the frog to follow this path is $\frac{1}{10 \cdot 7 \cdot 5 \cdot 3}$.
I am not sure yet how to continue from here to obtain the final result... I imagine you could use some recursive relation. | The Frog Problem (puzzle in YouTube video)
Instead of using the recursive relation for the expected number $J_n = J_{n-1} + \frac{1}{n}$ we could also try a more mechanistic approach by computing every path that the frog can take and the dist |
31,417 | The Frog Problem (puzzle in YouTube video) | Like Martijn Weterings, I tried the "compute all possibilities" approach.
At the start, the frog has $n$ choices each with $\frac{1}{n}$ probability. After that, the choices remaining depend on the initial choice. But the set of the probabilities of the remaining steps is easy enough to see: it's the reciprocals of the Power Set on $\{1,...,n-1\}$.
That is, for $n=3$, the probabilities of each step are (in reciprocal):
{ 3 } -- one jump of 3
{ 3, 1 } -- jump of 2 (with a 1/3 probability) then a jump of 1 (with 1/1 probability)
{ 3, 2 } -- 1 then 2
{ 3, 2, 1 } -- 1 then 1 then 1
The expected value of these is just the size of the set divided by the product of the elements of the set.
Since each set always starts with $n$, we move it out of the summation.
The expected number of jumps to get across to the nth leaf is:
$$ \frac{1}{n} \sum_{\textbf{x}\in{\mathbb{P}(\{1,...,n-1\})}} \frac{|\textbf{x}|+1}{\prod \textbf{x}} $$
I'm not sure what approach can be used to simply this form into the $$\sum_{k=1}^n \frac{1}{k}$$ form, but the equivalence of the two checks for the $n$ I've tried (2,3,10,20) | The Frog Problem (puzzle in YouTube video) | Like Martijn Weterings, I tried the "compute all possibilities" approach.
At the start, the frog has $n$ choices each with $\frac{1}{n}$ probability. After that, the choices remaining depend on the in | The Frog Problem (puzzle in YouTube video)
Like Martijn Weterings, I tried the "compute all possibilities" approach.
At the start, the frog has $n$ choices each with $\frac{1}{n}$ probability. After that, the choices remaining depend on the initial choice. But the set of the probabilities of the remaining steps is easy enough to see: it's the reciprocals of the Power Set on $\{1,...,n-1\}$.
That is, for $n=3$, the probabilities of each step are (in reciprocal):
{ 3 } -- one jump of 3
{ 3, 1 } -- jump of 2 (with a 1/3 probability) then a jump of 1 (with 1/1 probability)
{ 3, 2 } -- 1 then 2
{ 3, 2, 1 } -- 1 then 1 then 1
The expected value of these is just the size of the set divided by the product of the elements of the set.
Since each set always starts with $n$, we move it out of the summation.
The expected number of jumps to get across to the nth leaf is:
$$ \frac{1}{n} \sum_{\textbf{x}\in{\mathbb{P}(\{1,...,n-1\})}} \frac{|\textbf{x}|+1}{\prod \textbf{x}} $$
I'm not sure what approach can be used to simply this form into the $$\sum_{k=1}^n \frac{1}{k}$$ form, but the equivalence of the two checks for the $n$ I've tried (2,3,10,20) | The Frog Problem (puzzle in YouTube video)
Like Martijn Weterings, I tried the "compute all possibilities" approach.
At the start, the frog has $n$ choices each with $\frac{1}{n}$ probability. After that, the choices remaining depend on the in |
31,418 | Power calculation for two-sample Welch's t test | Comment: First, I would suggest you consider carefully whether you have a really good reason to use different sample sizes. Especially if the smaller sample size is used for the group with the larger population, this is not an efficient design.
Second, you can use simulation to get the power for various scenarios. For example, if you use $n_1 = 20,\,
\sigma_1 = 15,\,$ $n_2 = 50, \sigma_2 = 10,$ then you have about 75% power for detecting a difference $\delta = 10$ in population means with a Welch test at level 5%.
n1=20; n2=50; sg1=15; sg2=10; dlt=10
set.seed(619)
pv = replicate(10^6,
t.test(rnorm(n1,0,sg1),rnorm(n2,dlt,sg2))$p.val)
mean(pv <= .05)
[1] 0.753043
Because the P-value is taken directly from the procedure t.test in R, results should be accurate to 2 or 3 places, but this style of simulation runs slowly (maybe 2 or 3 min.) with
a million iterations.
You might want to use 10,000 iterations if you are doing repeated runs for various sample sizes, and then use a larger number of iterations to verify
the power of the final design.
Changing to $n_2 = 20$ gives power 67%, so the extra 30 observations in Group 2 are not 'buying' you as much as you might hope. By contrast, a balanced design with
$n_1 = n_2 = 35$ gives about 90% power (with everything else the same). | Power calculation for two-sample Welch's t test | Comment: First, I would suggest you consider carefully whether you have a really good reason to use different sample sizes. Especially if the smaller sample size is used for the group with the larger | Power calculation for two-sample Welch's t test
Comment: First, I would suggest you consider carefully whether you have a really good reason to use different sample sizes. Especially if the smaller sample size is used for the group with the larger population, this is not an efficient design.
Second, you can use simulation to get the power for various scenarios. For example, if you use $n_1 = 20,\,
\sigma_1 = 15,\,$ $n_2 = 50, \sigma_2 = 10,$ then you have about 75% power for detecting a difference $\delta = 10$ in population means with a Welch test at level 5%.
n1=20; n2=50; sg1=15; sg2=10; dlt=10
set.seed(619)
pv = replicate(10^6,
t.test(rnorm(n1,0,sg1),rnorm(n2,dlt,sg2))$p.val)
mean(pv <= .05)
[1] 0.753043
Because the P-value is taken directly from the procedure t.test in R, results should be accurate to 2 or 3 places, but this style of simulation runs slowly (maybe 2 or 3 min.) with
a million iterations.
You might want to use 10,000 iterations if you are doing repeated runs for various sample sizes, and then use a larger number of iterations to verify
the power of the final design.
Changing to $n_2 = 20$ gives power 67%, so the extra 30 observations in Group 2 are not 'buying' you as much as you might hope. By contrast, a balanced design with
$n_1 = n_2 = 35$ gives about 90% power (with everything else the same). | Power calculation for two-sample Welch's t test
Comment: First, I would suggest you consider carefully whether you have a really good reason to use different sample sizes. Especially if the smaller sample size is used for the group with the larger |
31,419 | Power calculation for two-sample Welch's t test | The article "Optimal sample sizes for Welch’s test under various allocation and cost considerations" from Show-Li Jan & Gwowen Shieh published in Behavior Research Methods in December 2011 has the following code in supplementary material A, slightly modified here for my own ergonomy.
ssize.welch = function(alpha=0.05, power=0.90, mu1, mu2, sigma1, sigma2, n2n1r, use_exact=FALSE)
{
mud<-mu1-mu2
sigsq1<-sigma1^2
sigsq2<-sigma2^2
numint<-1000
dd<-0.00001
coevec<-c(1,rep(c(4,2),numint/2-1),4,1)
intl<-(1-2*dd)/numint
bvec<-intl*seq(0,numint)+dd
#Z method
za<-qnorm(1-alpha/2)
zb<-qnorm(power)
n1<-ceiling(((sigsq1+sigsq2/n2n1r)*(za+zb)^2)/(mud^2))
n2<-ceiling(n1*n2n1r)
if(use_exact) #Exact method
{
n1 = n1-1
n2 = n2-1
powere<-0
while(powere<power)
{
n1<-n1+1
n2<-ceiling(n1*n2n1r)
sigsqt<-sigsq1/n1+sigsq2/n2
hsigsqt<-sqrt(sigsqt)
wpdf<-(intl/3)*coevec*dbeta(bvec,(n1-1)/2,(n2-1)/2)
dft<-n1+n2-2
p1<-(n1-1)/dft
p2<-1-p1
s1<-sigsq1/n1
s2<-sigsq2/n2
b12<-(s1/p1)*bvec+(s2/p2)*(1-bvec)
r1<-(s1/p1)*bvec/b12
r2<-1-r1
dfevec<-1/((r1^2)/(n1-1)+(r2^2)/(n2-1))
tdfea<-qt(1-alpha/2,dfevec)
powere<-sum(wpdf*pt(-tdfea*sqrt(b12/sigsqt),dft,mud/hsigsqt))+1-sum(wpdf*pt(tdfea*sqrt(b12/sigsqt),dft,mud/hsigsqt))
}
}
c(n1=n1,n2=n2)
}
ssize.welch(0.05,0.9,85,105,10,20,3)
ssize.welch(0.05,0.9,85,105,10,20,3,TRUE)
The Z method is also the one used in https://clincalc.com/stats/samplesize.aspx which cites Rosner B. Fundamentals of Biostatistics. 7th ed. Boston, MA: Brooks/Cole; 2011. Weirdly, it forces you to input only one variance but the formula it gives can use two (and is the same as the paper above). It is in the spirit of the usual way of computing sample sizes, but I'm not too sure about when the underlying approximations start to be false.
After some fiddling around, both methods give similar results unless you have very unbalanced groups (but in that case, at some point you might want to just approximate the super large group as a known population).
Hope this helps.
Edit : just realized this does not exactly answer your question about power rather than sample size, but you can easily flip the Z method formula to compute power (exact method seems more hairy ; worst case, numeric trial and error should work since the relationship is monotonous). | Power calculation for two-sample Welch's t test | The article "Optimal sample sizes for Welch’s test under various allocation and cost considerations" from Show-Li Jan & Gwowen Shieh published in Behavior Research Methods in December 2011 has the fol | Power calculation for two-sample Welch's t test
The article "Optimal sample sizes for Welch’s test under various allocation and cost considerations" from Show-Li Jan & Gwowen Shieh published in Behavior Research Methods in December 2011 has the following code in supplementary material A, slightly modified here for my own ergonomy.
ssize.welch = function(alpha=0.05, power=0.90, mu1, mu2, sigma1, sigma2, n2n1r, use_exact=FALSE)
{
mud<-mu1-mu2
sigsq1<-sigma1^2
sigsq2<-sigma2^2
numint<-1000
dd<-0.00001
coevec<-c(1,rep(c(4,2),numint/2-1),4,1)
intl<-(1-2*dd)/numint
bvec<-intl*seq(0,numint)+dd
#Z method
za<-qnorm(1-alpha/2)
zb<-qnorm(power)
n1<-ceiling(((sigsq1+sigsq2/n2n1r)*(za+zb)^2)/(mud^2))
n2<-ceiling(n1*n2n1r)
if(use_exact) #Exact method
{
n1 = n1-1
n2 = n2-1
powere<-0
while(powere<power)
{
n1<-n1+1
n2<-ceiling(n1*n2n1r)
sigsqt<-sigsq1/n1+sigsq2/n2
hsigsqt<-sqrt(sigsqt)
wpdf<-(intl/3)*coevec*dbeta(bvec,(n1-1)/2,(n2-1)/2)
dft<-n1+n2-2
p1<-(n1-1)/dft
p2<-1-p1
s1<-sigsq1/n1
s2<-sigsq2/n2
b12<-(s1/p1)*bvec+(s2/p2)*(1-bvec)
r1<-(s1/p1)*bvec/b12
r2<-1-r1
dfevec<-1/((r1^2)/(n1-1)+(r2^2)/(n2-1))
tdfea<-qt(1-alpha/2,dfevec)
powere<-sum(wpdf*pt(-tdfea*sqrt(b12/sigsqt),dft,mud/hsigsqt))+1-sum(wpdf*pt(tdfea*sqrt(b12/sigsqt),dft,mud/hsigsqt))
}
}
c(n1=n1,n2=n2)
}
ssize.welch(0.05,0.9,85,105,10,20,3)
ssize.welch(0.05,0.9,85,105,10,20,3,TRUE)
The Z method is also the one used in https://clincalc.com/stats/samplesize.aspx which cites Rosner B. Fundamentals of Biostatistics. 7th ed. Boston, MA: Brooks/Cole; 2011. Weirdly, it forces you to input only one variance but the formula it gives can use two (and is the same as the paper above). It is in the spirit of the usual way of computing sample sizes, but I'm not too sure about when the underlying approximations start to be false.
After some fiddling around, both methods give similar results unless you have very unbalanced groups (but in that case, at some point you might want to just approximate the super large group as a known population).
Hope this helps.
Edit : just realized this does not exactly answer your question about power rather than sample size, but you can easily flip the Z method formula to compute power (exact method seems more hairy ; worst case, numeric trial and error should work since the relationship is monotonous). | Power calculation for two-sample Welch's t test
The article "Optimal sample sizes for Welch’s test under various allocation and cost considerations" from Show-Li Jan & Gwowen Shieh published in Behavior Research Methods in December 2011 has the fol |
31,420 | Power calculation for two-sample Welch's t test | It seems to me the power calculation is pretty straight forward. Let's consider a 2 tailed alternative.
The null is rejected if $t<t_{\alpha/2}$ or $t>t_{1-\alpha/2}$. So Power = $P(T'<t_{t_\alpha/2})+P(T'>t_{1-\alpha/2})$
The true effect is $\eta=\frac{\mu_1-\mu_2}{\sqrt{s_1^2/n_1+s_2^2/n_2}}$
The true sampling distribution of $T'$ is a noncentral T distribution centered at $\eta$. Let $T = T'-\eta$ follow a t distribution centered at zero. So
$$\text{power} = P(T<t_{t_\alpha/2}-\eta)+P(T>t_{1-\alpha/2}-\eta)$$
I just figured this out on my own, so I may have made a mistake, but It seems to make sense to me. This formula cannot be reversed to give you the necessary sample size though, it would have to be solved by numerical means to get a pre-specified power given effect size (or given $\mu_1, \mu_2, \sigma_1, \sigma_2$. It would be easiest to solve it for $n_1=n_2=n$, but in theory you could specify (for example) $n_1$ and solve for $n_2$. | Power calculation for two-sample Welch's t test | It seems to me the power calculation is pretty straight forward. Let's consider a 2 tailed alternative.
The null is rejected if $t<t_{\alpha/2}$ or $t>t_{1-\alpha/2}$. So Power = $P(T'<t_{t_\alpha/2}) | Power calculation for two-sample Welch's t test
It seems to me the power calculation is pretty straight forward. Let's consider a 2 tailed alternative.
The null is rejected if $t<t_{\alpha/2}$ or $t>t_{1-\alpha/2}$. So Power = $P(T'<t_{t_\alpha/2})+P(T'>t_{1-\alpha/2})$
The true effect is $\eta=\frac{\mu_1-\mu_2}{\sqrt{s_1^2/n_1+s_2^2/n_2}}$
The true sampling distribution of $T'$ is a noncentral T distribution centered at $\eta$. Let $T = T'-\eta$ follow a t distribution centered at zero. So
$$\text{power} = P(T<t_{t_\alpha/2}-\eta)+P(T>t_{1-\alpha/2}-\eta)$$
I just figured this out on my own, so I may have made a mistake, but It seems to make sense to me. This formula cannot be reversed to give you the necessary sample size though, it would have to be solved by numerical means to get a pre-specified power given effect size (or given $\mu_1, \mu_2, \sigma_1, \sigma_2$. It would be easiest to solve it for $n_1=n_2=n$, but in theory you could specify (for example) $n_1$ and solve for $n_2$. | Power calculation for two-sample Welch's t test
It seems to me the power calculation is pretty straight forward. Let's consider a 2 tailed alternative.
The null is rejected if $t<t_{\alpha/2}$ or $t>t_{1-\alpha/2}$. So Power = $P(T'<t_{t_\alpha/2}) |
31,421 | Why is Permuted MNIST good for evaluating continual learning models? | Actually as stated in this paper https://arxiv.org/abs/1805.09733 the Permuted MNIST evaluation is not a good method to measure Continual Learning performance. This is because the permuted images differ too much from the original, which is not a good representation of real-world scenarios. Normally a new task with a new dataset could have similar images which could lead to the network making false positive predictions. | Why is Permuted MNIST good for evaluating continual learning models? | Actually as stated in this paper https://arxiv.org/abs/1805.09733 the Permuted MNIST evaluation is not a good method to measure Continual Learning performance. This is because the permuted images diff | Why is Permuted MNIST good for evaluating continual learning models?
Actually as stated in this paper https://arxiv.org/abs/1805.09733 the Permuted MNIST evaluation is not a good method to measure Continual Learning performance. This is because the permuted images differ too much from the original, which is not a good representation of real-world scenarios. Normally a new task with a new dataset could have similar images which could lead to the network making false positive predictions. | Why is Permuted MNIST good for evaluating continual learning models?
Actually as stated in this paper https://arxiv.org/abs/1805.09733 the Permuted MNIST evaluation is not a good method to measure Continual Learning performance. This is because the permuted images diff |
31,422 | Why is Permuted MNIST good for evaluating continual learning models? | Since the authors use an MLP which does not exploit the spatial relationship between the pixels as a CNN might, it is no more easy or difficult for their model to learn MNIST versus permuted MNIST.
the permutated images are very noisy which cannot be recognised even
by a human.
While the images look noisy, the amount of actual noise is close to 0, since again, they are just permuted versions of noise-free MNIST.
Applying blur, rotation, or some distortion are understandable but why
permuting the pixel?
Blur, rotation, or distortion would actually not work as well in this setting, since that would test the ability of the model to generalize to blur/rotation/distortion, whereas the actual goal is to test continual learning. | Why is Permuted MNIST good for evaluating continual learning models? | Since the authors use an MLP which does not exploit the spatial relationship between the pixels as a CNN might, it is no more easy or difficult for their model to learn MNIST versus permuted MNIST.
| Why is Permuted MNIST good for evaluating continual learning models?
Since the authors use an MLP which does not exploit the spatial relationship between the pixels as a CNN might, it is no more easy or difficult for their model to learn MNIST versus permuted MNIST.
the permutated images are very noisy which cannot be recognised even
by a human.
While the images look noisy, the amount of actual noise is close to 0, since again, they are just permuted versions of noise-free MNIST.
Applying blur, rotation, or some distortion are understandable but why
permuting the pixel?
Blur, rotation, or distortion would actually not work as well in this setting, since that would test the ability of the model to generalize to blur/rotation/distortion, whereas the actual goal is to test continual learning. | Why is Permuted MNIST good for evaluating continual learning models?
Since the authors use an MLP which does not exploit the spatial relationship between the pixels as a CNN might, it is no more easy or difficult for their model to learn MNIST versus permuted MNIST.
|
31,423 | Why is Permuted MNIST good for evaluating continual learning models? | I found a paper that could clearly answer my own question.
https://arxiv.org/abs/1708.02072
Data Permutation Experiment - The elements of every
feature vector are randomly permuted, with the permutation held constant within a session, but varying across sessions. The model is evaluated on its ability to recall data
learned in prior study sessions. Each session contains the
same number of examples. | Why is Permuted MNIST good for evaluating continual learning models? | I found a paper that could clearly answer my own question.
https://arxiv.org/abs/1708.02072
Data Permutation Experiment - The elements of every
feature vector are randomly permuted, with the permut | Why is Permuted MNIST good for evaluating continual learning models?
I found a paper that could clearly answer my own question.
https://arxiv.org/abs/1708.02072
Data Permutation Experiment - The elements of every
feature vector are randomly permuted, with the permutation held constant within a session, but varying across sessions. The model is evaluated on its ability to recall data
learned in prior study sessions. Each session contains the
same number of examples. | Why is Permuted MNIST good for evaluating continual learning models?
I found a paper that could clearly answer my own question.
https://arxiv.org/abs/1708.02072
Data Permutation Experiment - The elements of every
feature vector are randomly permuted, with the permut |
31,424 | Why is Permuted MNIST good for evaluating continual learning models? | Within Continual Learning, there are three main problem paradigms:
Task-Incremental Learning (where we want the model to solve multiple distinct tasks)
Class-Incremental Learning (where we want the model to solve a classification problem, while being presented with additional classes in each new task)
Domain-Incremental Learning (where we want the model to answer the same question, but the underlying distribution of the data changes with each task).
Permuted MNIST1 is designed to present an example of the latter problem, where the question (and output labels) are the same:
"Is this an image of a 0, 1, 2, 3, ... or 9?"
but the underlying distribution of the input data differs with each task.
Note however that Permuted NIST has been criticised2 for not providing a realistic example of an evaluation setting for a Continual Learning model (i.e. there is little to no similarity between the tasks). A more natural example may be, you have a model designed to classify images of cats and dogs based on headshot photos taken face on indoors. You receive new data for nominally the same task (classify pictures of cats and dogs), but the images are from a different distribution where a subset of learnable features are hypothesized to be shared (e.g. colour of animals, facial features etc), e.g:
photos of the animals in profile
photos of different species of cat and dog
photos in a different context (park vs indoors)
Permuted MNIST was originally proposed in An Empirical Investigation of Catastrophic Forgetting in Gradient-Based Neural Networks (2015), and has since been adopted as a common test of Domain-IL performance in Continual Learning (e.g. Three scenarios for continual learning):
To test this kind of learning problem, we designed a simple pair of tasks, where the tasks are the same, but with different ways of formatting the input. Specifically, we used MNIST classification, but with a different permutation of the pixels for the old task and the new task. Both tasks thus benefit from having concepts like penstroke detectors, or the concept of penstrokes being combined to form digits. However, the meaning of any individual pixel is different. The net must learn to associate new collections of pixels to penstrokes, without significantly disrupting the old higher level concepts, or erasing the old connections between pixels and penstrokes.
Towards Robust Evaluations of Continual Learning (2019):
Cross-task resemblances Input data from later tasks must resemble old tasks enough that they at least sometimes result in confident predictions of old classes, early in training. The widely used Permuted MNIST (see §4.2.1) which violates this... | Why is Permuted MNIST good for evaluating continual learning models? | Within Continual Learning, there are three main problem paradigms:
Task-Incremental Learning (where we want the model to solve multiple distinct tasks)
Class-Incremental Learning (where we want the m | Why is Permuted MNIST good for evaluating continual learning models?
Within Continual Learning, there are three main problem paradigms:
Task-Incremental Learning (where we want the model to solve multiple distinct tasks)
Class-Incremental Learning (where we want the model to solve a classification problem, while being presented with additional classes in each new task)
Domain-Incremental Learning (where we want the model to answer the same question, but the underlying distribution of the data changes with each task).
Permuted MNIST1 is designed to present an example of the latter problem, where the question (and output labels) are the same:
"Is this an image of a 0, 1, 2, 3, ... or 9?"
but the underlying distribution of the input data differs with each task.
Note however that Permuted NIST has been criticised2 for not providing a realistic example of an evaluation setting for a Continual Learning model (i.e. there is little to no similarity between the tasks). A more natural example may be, you have a model designed to classify images of cats and dogs based on headshot photos taken face on indoors. You receive new data for nominally the same task (classify pictures of cats and dogs), but the images are from a different distribution where a subset of learnable features are hypothesized to be shared (e.g. colour of animals, facial features etc), e.g:
photos of the animals in profile
photos of different species of cat and dog
photos in a different context (park vs indoors)
Permuted MNIST was originally proposed in An Empirical Investigation of Catastrophic Forgetting in Gradient-Based Neural Networks (2015), and has since been adopted as a common test of Domain-IL performance in Continual Learning (e.g. Three scenarios for continual learning):
To test this kind of learning problem, we designed a simple pair of tasks, where the tasks are the same, but with different ways of formatting the input. Specifically, we used MNIST classification, but with a different permutation of the pixels for the old task and the new task. Both tasks thus benefit from having concepts like penstroke detectors, or the concept of penstrokes being combined to form digits. However, the meaning of any individual pixel is different. The net must learn to associate new collections of pixels to penstrokes, without significantly disrupting the old higher level concepts, or erasing the old connections between pixels and penstrokes.
Towards Robust Evaluations of Continual Learning (2019):
Cross-task resemblances Input data from later tasks must resemble old tasks enough that they at least sometimes result in confident predictions of old classes, early in training. The widely used Permuted MNIST (see §4.2.1) which violates this... | Why is Permuted MNIST good for evaluating continual learning models?
Within Continual Learning, there are three main problem paradigms:
Task-Incremental Learning (where we want the model to solve multiple distinct tasks)
Class-Incremental Learning (where we want the m |
31,425 | Intuitively, how does the wild bootstrap work? | Let's say you have a training set $\mathcal{T}$ of $n$ example pairs $(y_i, \vec{x}_i)$.
A normal bootstrap is a set $\mathcal{B}$ of $n$ example pairs $(y_{r_i}, \vec{x}_{r_i})$, where $r_i$ is a sequence of $n$ random integers sampled uniformly from 1 to $n$. In particular, note that every example in $\mathcal{B}$ is exactly the same as one of the examples from $\mathcal{T}$, and some are repeated. But this is a little weird, especially when the response variable is continuous, because if we re-sampled the original population, we would almost surely not get even one exact duplicate, while a bootstrap is likely to have many.
To avoid duplicates, we need the examples of $\mathcal{B}$ not to be carbon copies of examples from $\mathcal{T}$, but rather synthetic examples that look more like what we would get it we sampled from the original population. This requires making an assumption about the distribution of the original population.
If we assume homoskedasticity and fit a linear model to $\mathcal{T}$ which has residuals $e_i$ then we can construct new, synthetic examples by replacing the fitted residual from each example with the residual from a different training example. If the residuals are truly i.i.d., there should be no problem swapping one for another. We do this replacement by subtracting the residual found for the training example $(y_i, \vec{x}_i)$ and adding the residual for some other example:
$$ y^*_i = y_{r_i} - e_{r_i} + e_{r'_i} \tag{1} $$
Where $r_i$ and $r'_i$ are two different and independent resamplings. We can then form the bootstrap in the usual way:
$$
\mathcal{B} = \{\, (y^*_i, \vec{x}_i)\, \}_{i=1}^n \tag{2}
$$
This is called the residual bootstrap and can be thought of as choosing new residuals from the empirical distribution function of residuals.
To relax the i.i.d. and homoskedasticity assumptions further, we can use a wild bootstrap, where we calculate the new response variable even more randomly by multiplying the randomly chosen residual by yet another random variable $v_i$.
$$ y^*_i = y_{r_i} - e_{r_i} + v_i e_{r'_i} \tag{3} $$
Often the standard normal distribution $ v_i \sim \mathcal{N}(0, 1) $ is used but other choices are possible. For example, sometimes $v_i$ is simply chosen with equal probability from $\{-1,1\}$, which simply randomly flips the sign half the time, forcing the residual distribution to be symmetric. The point is to get training examples which are closer to what we would have drawn from the original population without the artificial replication introduced by the bootstrap. | Intuitively, how does the wild bootstrap work? | Let's say you have a training set $\mathcal{T}$ of $n$ example pairs $(y_i, \vec{x}_i)$.
A normal bootstrap is a set $\mathcal{B}$ of $n$ example pairs $(y_{r_i}, \vec{x}_{r_i})$, where $r_i$ is a se | Intuitively, how does the wild bootstrap work?
Let's say you have a training set $\mathcal{T}$ of $n$ example pairs $(y_i, \vec{x}_i)$.
A normal bootstrap is a set $\mathcal{B}$ of $n$ example pairs $(y_{r_i}, \vec{x}_{r_i})$, where $r_i$ is a sequence of $n$ random integers sampled uniformly from 1 to $n$. In particular, note that every example in $\mathcal{B}$ is exactly the same as one of the examples from $\mathcal{T}$, and some are repeated. But this is a little weird, especially when the response variable is continuous, because if we re-sampled the original population, we would almost surely not get even one exact duplicate, while a bootstrap is likely to have many.
To avoid duplicates, we need the examples of $\mathcal{B}$ not to be carbon copies of examples from $\mathcal{T}$, but rather synthetic examples that look more like what we would get it we sampled from the original population. This requires making an assumption about the distribution of the original population.
If we assume homoskedasticity and fit a linear model to $\mathcal{T}$ which has residuals $e_i$ then we can construct new, synthetic examples by replacing the fitted residual from each example with the residual from a different training example. If the residuals are truly i.i.d., there should be no problem swapping one for another. We do this replacement by subtracting the residual found for the training example $(y_i, \vec{x}_i)$ and adding the residual for some other example:
$$ y^*_i = y_{r_i} - e_{r_i} + e_{r'_i} \tag{1} $$
Where $r_i$ and $r'_i$ are two different and independent resamplings. We can then form the bootstrap in the usual way:
$$
\mathcal{B} = \{\, (y^*_i, \vec{x}_i)\, \}_{i=1}^n \tag{2}
$$
This is called the residual bootstrap and can be thought of as choosing new residuals from the empirical distribution function of residuals.
To relax the i.i.d. and homoskedasticity assumptions further, we can use a wild bootstrap, where we calculate the new response variable even more randomly by multiplying the randomly chosen residual by yet another random variable $v_i$.
$$ y^*_i = y_{r_i} - e_{r_i} + v_i e_{r'_i} \tag{3} $$
Often the standard normal distribution $ v_i \sim \mathcal{N}(0, 1) $ is used but other choices are possible. For example, sometimes $v_i$ is simply chosen with equal probability from $\{-1,1\}$, which simply randomly flips the sign half the time, forcing the residual distribution to be symmetric. The point is to get training examples which are closer to what we would have drawn from the original population without the artificial replication introduced by the bootstrap. | Intuitively, how does the wild bootstrap work?
Let's say you have a training set $\mathcal{T}$ of $n$ example pairs $(y_i, \vec{x}_i)$.
A normal bootstrap is a set $\mathcal{B}$ of $n$ example pairs $(y_{r_i}, \vec{x}_{r_i})$, where $r_i$ is a se |
31,426 | Relationship between chi-squared and the normal distribution | Suppose we have a die that we think might not be fair.
We roll it 600 times and get the following table.
Face 1 2 3 4 5 6
Freq 44 97 102 99 105 153
So we have observed frequencies $X: 44,\, 97,\, 102,\, 99,\ 105,\ 153$ for
the respective faces. If the die is fair, we'd expect frequency
$E = 100$ for each face.
If the die is fair, then the statistic
$$Q - \sum_{i = 1}^6 \frac{(X_i - E)^2}{E} \stackrel{aprx}{\sim}
\mathsf{Chisq}(\text{DF} = 5).$$
Very roughly, the rationale for the approximate chi-squared distribution
is that we could look at the $X_i$ as being Poisson events each with mean
$\mu = \lambda = 100$ and variance $\sigma^2= \lambda = 100.$
Standarizing,
we have $Z_i = \frac{X_i - \mu}{\sigma} \stackrel{aprx}{\sim} \mathsf{Norm}(0,1).$ If the $Z_i$ were independent, then $Q = \sum_{i=1}^6 Z_i^2$ would be approximately chi-squared with $6$ degrees of freedom.
But the
$Z_i$ aren't independent because the $X_i$ are constrained to add to $600$ rolls of the die. With some hand-waving we 'correct' for this by reducing
the degrees of freedom for $Q$ from $6$ to $5.$ The language of the hand-waving is that we have 'lost' a degree of freedom due to a linear constraint.
[Hand-waving aside, many simulation experiments have shown that, for a fair die, such values $Q$ are very nearly distributed as chi-squared with 5 degrees of freedom, provided that $E > 5.$ Because our $E = 100$ the approximation is quite good. One such simulation is shown in the Addendum.]
For the data above, one can show that $Q = 59.84.$ However, if we actually have
$Q \sim \mathsf{Chisq}(5),$ then this observed value of $Q$ seems very unlikely, because only 5% of values from $\mathsf{Chisq}(5)$ should
exceed the critical value $c =11.07.$ Put another way the probability
that a value from this distribution exceeds $59.84$ is the P-value of
the chi-squared test, which is much smaller than $0.0001.$
x = c(44, 97, 102, 99, 105, 153)
q = sum((x-100)^2/1 0 0); q
[1] 59.84
qchisq(.95, 5)
[1] 11.0705 # critical value
1-pchisq(59.84, 5)
[1] 1.311595e-11 # P-value
The conclusion is that the data provide strong evidence that our die
is unfair. [In fact, the values $X_i$ were simulated using
probabilities $(\frac 1{12}, \frac 1 6, \frac 1 6, \frac 1 6,\frac 1 6,\frac 1 4),$ respectively, for
the faces, instead of $\frac 1 6$ for each face, as for a truly fair die.
So the chi-squared test has been able to detect that the die is unfair.]
Addendum: Shown below is a simulation of 100,000 values of $Q,$ each based on $600$ rolls of a fair die.
Their histogram is plotted along with the density of
$\mathsf{Chisq}(5)$ in order to illustrate that is the the approximate
distribution of such values of $Q.$
By way of explaining the code, one experiment with $600$ rolls of a
fair die is simulated and tallied using rle in the first three lines below.
set.seed(413)
rle(sort(sample(1:6, 600, rep=T)))$len
[1] 83 103 114 96 106 98
set.seed(2019); E = 100
q = replicate(10^5,
sum((rle(sort(sample(1:6,600,rep=T)))$len - E)^2/E))
hdr = "Simulated Values of Q with Density of CHISQ(5)"
hist(q, prob=T, br=30, col="skyblue2", main=hdr)
curve(dchisq(x, 5), add=T, lwd=2, col="red") | Relationship between chi-squared and the normal distribution | Suppose we have a die that we think might not be fair.
We roll it 600 times and get the following table.
Face 1 2 3 4 5 6
Freq 44 97 102 99 105 153
So we have observed frequencies $X | Relationship between chi-squared and the normal distribution
Suppose we have a die that we think might not be fair.
We roll it 600 times and get the following table.
Face 1 2 3 4 5 6
Freq 44 97 102 99 105 153
So we have observed frequencies $X: 44,\, 97,\, 102,\, 99,\ 105,\ 153$ for
the respective faces. If the die is fair, we'd expect frequency
$E = 100$ for each face.
If the die is fair, then the statistic
$$Q - \sum_{i = 1}^6 \frac{(X_i - E)^2}{E} \stackrel{aprx}{\sim}
\mathsf{Chisq}(\text{DF} = 5).$$
Very roughly, the rationale for the approximate chi-squared distribution
is that we could look at the $X_i$ as being Poisson events each with mean
$\mu = \lambda = 100$ and variance $\sigma^2= \lambda = 100.$
Standarizing,
we have $Z_i = \frac{X_i - \mu}{\sigma} \stackrel{aprx}{\sim} \mathsf{Norm}(0,1).$ If the $Z_i$ were independent, then $Q = \sum_{i=1}^6 Z_i^2$ would be approximately chi-squared with $6$ degrees of freedom.
But the
$Z_i$ aren't independent because the $X_i$ are constrained to add to $600$ rolls of the die. With some hand-waving we 'correct' for this by reducing
the degrees of freedom for $Q$ from $6$ to $5.$ The language of the hand-waving is that we have 'lost' a degree of freedom due to a linear constraint.
[Hand-waving aside, many simulation experiments have shown that, for a fair die, such values $Q$ are very nearly distributed as chi-squared with 5 degrees of freedom, provided that $E > 5.$ Because our $E = 100$ the approximation is quite good. One such simulation is shown in the Addendum.]
For the data above, one can show that $Q = 59.84.$ However, if we actually have
$Q \sim \mathsf{Chisq}(5),$ then this observed value of $Q$ seems very unlikely, because only 5% of values from $\mathsf{Chisq}(5)$ should
exceed the critical value $c =11.07.$ Put another way the probability
that a value from this distribution exceeds $59.84$ is the P-value of
the chi-squared test, which is much smaller than $0.0001.$
x = c(44, 97, 102, 99, 105, 153)
q = sum((x-100)^2/1 0 0); q
[1] 59.84
qchisq(.95, 5)
[1] 11.0705 # critical value
1-pchisq(59.84, 5)
[1] 1.311595e-11 # P-value
The conclusion is that the data provide strong evidence that our die
is unfair. [In fact, the values $X_i$ were simulated using
probabilities $(\frac 1{12}, \frac 1 6, \frac 1 6, \frac 1 6,\frac 1 6,\frac 1 4),$ respectively, for
the faces, instead of $\frac 1 6$ for each face, as for a truly fair die.
So the chi-squared test has been able to detect that the die is unfair.]
Addendum: Shown below is a simulation of 100,000 values of $Q,$ each based on $600$ rolls of a fair die.
Their histogram is plotted along with the density of
$\mathsf{Chisq}(5)$ in order to illustrate that is the the approximate
distribution of such values of $Q.$
By way of explaining the code, one experiment with $600$ rolls of a
fair die is simulated and tallied using rle in the first three lines below.
set.seed(413)
rle(sort(sample(1:6, 600, rep=T)))$len
[1] 83 103 114 96 106 98
set.seed(2019); E = 100
q = replicate(10^5,
sum((rle(sort(sample(1:6,600,rep=T)))$len - E)^2/E))
hdr = "Simulated Values of Q with Density of CHISQ(5)"
hist(q, prob=T, br=30, col="skyblue2", main=hdr)
curve(dchisq(x, 5), add=T, lwd=2, col="red") | Relationship between chi-squared and the normal distribution
Suppose we have a die that we think might not be fair.
We roll it 600 times and get the following table.
Face 1 2 3 4 5 6
Freq 44 97 102 99 105 153
So we have observed frequencies $X |
31,427 | Relationship between chi-squared and the normal distribution | Let $X_1,\ldots,X_k$ be independent standard normal random variables.
("Standard normal" means normal with expectation $0$ and variance $1.$)
Then $X_1^2 + \cdots + X_k^2$ has a chi-square distribution with $k$ degrees of freedom. | Relationship between chi-squared and the normal distribution | Let $X_1,\ldots,X_k$ be independent standard normal random variables.
("Standard normal" means normal with expectation $0$ and variance $1.$)
Then $X_1^2 + \cdots + X_k^2$ has a chi-square distributio | Relationship between chi-squared and the normal distribution
Let $X_1,\ldots,X_k$ be independent standard normal random variables.
("Standard normal" means normal with expectation $0$ and variance $1.$)
Then $X_1^2 + \cdots + X_k^2$ has a chi-square distribution with $k$ degrees of freedom. | Relationship between chi-squared and the normal distribution
Let $X_1,\ldots,X_k$ be independent standard normal random variables.
("Standard normal" means normal with expectation $0$ and variance $1.$)
Then $X_1^2 + \cdots + X_k^2$ has a chi-square distributio |
31,428 | How well should I expect Adam to work? | Actually, one of ADAM's key features is that it is slower and thus more careful. See section 2.1 of the paper.
In particular, there are pretty tight upper bounds on the step size. The paper lists 3 upper bounds, the simplest being that no individual parameter steps larger than $\alpha$ during any update, which is recommended to be 0.001.
With stochastic gradients, especially those with the potential for very large variations sample to sample, this is a very important feature. Your model may currently have near optimal parameter values at some point during optimization, but by bad luck, it hits an outlier shortly before the algorithm terminates, leading to an enormous jump to a very suboptimal set of parameter values. By using an extremely small trust region, as ADAM does, you can greatly reduce the probability of this occurring, as you would need to hit a very large number of outliers in a row to move a far distance away from your current solution.
This trust region aspect is important in the cases when you have a potentially very noisy approximation of the gradient (especially if there are rare cases of extremely inaccurate approximations) and if the second derivative is potentially very unstable. If these conditions do not exist, then the trust region aspect of ADAM are most likely to greatly slow down convergence without much benefit. | How well should I expect Adam to work? | Actually, one of ADAM's key features is that it is slower and thus more careful. See section 2.1 of the paper.
In particular, there are pretty tight upper bounds on the step size. The paper lists 3 up | How well should I expect Adam to work?
Actually, one of ADAM's key features is that it is slower and thus more careful. See section 2.1 of the paper.
In particular, there are pretty tight upper bounds on the step size. The paper lists 3 upper bounds, the simplest being that no individual parameter steps larger than $\alpha$ during any update, which is recommended to be 0.001.
With stochastic gradients, especially those with the potential for very large variations sample to sample, this is a very important feature. Your model may currently have near optimal parameter values at some point during optimization, but by bad luck, it hits an outlier shortly before the algorithm terminates, leading to an enormous jump to a very suboptimal set of parameter values. By using an extremely small trust region, as ADAM does, you can greatly reduce the probability of this occurring, as you would need to hit a very large number of outliers in a row to move a far distance away from your current solution.
This trust region aspect is important in the cases when you have a potentially very noisy approximation of the gradient (especially if there are rare cases of extremely inaccurate approximations) and if the second derivative is potentially very unstable. If these conditions do not exist, then the trust region aspect of ADAM are most likely to greatly slow down convergence without much benefit. | How well should I expect Adam to work?
Actually, one of ADAM's key features is that it is slower and thus more careful. See section 2.1 of the paper.
In particular, there are pretty tight upper bounds on the step size. The paper lists 3 up |
31,429 | How well should I expect Adam to work? | There might be several factors at play here:
The optimal learning rate for momentum based algorithms is usually lower than that for plain GD, because momentum increases the effective step size. I don't know what rate you tried, but between $10^{-5}$ and $10^{-3}$ usually works for me.
Adam and many other SGD w/ momentum variants were designed for optimizing noisy, very high dimensional non-convex functions, with many saddle points and other pathologies. Your test on $x^2+x^4$ is pretty much the opposite of this, so it might not reflect the strengths of Adam.
iirc with a proper learning rate and decay schedule, SGD will converge to results which are just as good or possibly better than Adam. As you noted, reduced sensitivity to hyperparameter settings is an advantage of Adam | How well should I expect Adam to work? | There might be several factors at play here:
The optimal learning rate for momentum based algorithms is usually lower than that for plain GD, because momentum increases the effective step size. I do | How well should I expect Adam to work?
There might be several factors at play here:
The optimal learning rate for momentum based algorithms is usually lower than that for plain GD, because momentum increases the effective step size. I don't know what rate you tried, but between $10^{-5}$ and $10^{-3}$ usually works for me.
Adam and many other SGD w/ momentum variants were designed for optimizing noisy, very high dimensional non-convex functions, with many saddle points and other pathologies. Your test on $x^2+x^4$ is pretty much the opposite of this, so it might not reflect the strengths of Adam.
iirc with a proper learning rate and decay schedule, SGD will converge to results which are just as good or possibly better than Adam. As you noted, reduced sensitivity to hyperparameter settings is an advantage of Adam | How well should I expect Adam to work?
There might be several factors at play here:
The optimal learning rate for momentum based algorithms is usually lower than that for plain GD, because momentum increases the effective step size. I do |
31,430 | Why with two classes, LDA gives only one dimension? | Like @amoeba, I don't understand your difference between Q1 and Q2: in any case, LDA obtains at most $k-1$ dimensions. For $k=2$ that's one dimension, for $k=8$ it would be 7. And of course, if the input space has lower dimensionality that that's the limiting factor.
One idea/heuristic behind LDA is that separating classes is easy if they are all spheres of the same size: all you then need is distance to the class means. Alternatively, you can say that the connection between class means are normal vectors for suitable separation planes.
In that narrative, you can look at LDA as a projection that in the first place does singular value decomposition (i.e. something very similar to PCA) of the pooled covariance matrix in order to get a space with such spherical classes. Let's call this our primary score space.
Depending on the customs of your field, this is either the PCA score space of the pooled covariance matrix = the PCA score space of the data matrix centered to the respective class means, or the PCA score space squeezed according to the eigenvalues/SVD diagonal matrix (some fields by default put this scaling for PCA into the loadings, others [mine] into the scores).
The primary score space still has the dimensionality corresponding to the rank of the pooled covariance matrix/data matrix centered to the respective class means. Pooled covariance matrix in this space is a unit sphere, i.e. each class is considered as a unit-sphere centered at the respective class mean, the means also projected into score space.
(At this point, we could derive other classification algorithms that use the SVD projection as heuristic but don't exploit/rely on the assumed unit-sized spherical shape of the classes.)
Now, as we have unit-spherical class shapes, the only thing remaining to care about are the class means. I.e., $k$ points. Even if our primary score space has higher dimensionality, the $k$ points will form a $k-1$ dimensional shape (simplex). Thus without loss of anything, we can further rotate our primary score space so that our $k-1$-simplex of class means lies in the first $k-1$ dimensions.
For the postulted spherical classes, all further dimensions cannot not help with the distinction: the classes have exactly the same size and position in these further dimensions. Thus, we throw them away.
(Again, you may derive another classifier that uses the first two projection steps but then keeps [some of] those further dimensions as the classes in practice may not be spherical.)
One classifer to look into when comparing LDA and PCA is SIMCA which can be seen as a one-class classifier analogous to LDA.
In SIMCA, you'll find the notion of in-model space and out-of-model space: in in-model space you detect changes of the same type of the usual variation within your class (but possibly of unusual magnitude). In out-of-model space you detect variation of a type that does not usually occur within any of the classes.
For our description of LDA, the $k-1$ dimensions we keep would be the in-model space, whereas the remaining dimensions are the out-of-model space. Interpretation will be slightly different compared to SIMCA, but you should have a start for your thoughts with this. | Why with two classes, LDA gives only one dimension? | Like @amoeba, I don't understand your difference between Q1 and Q2: in any case, LDA obtains at most $k-1$ dimensions. For $k=2$ that's one dimension, for $k=8$ it would be 7. And of course, if the in | Why with two classes, LDA gives only one dimension?
Like @amoeba, I don't understand your difference between Q1 and Q2: in any case, LDA obtains at most $k-1$ dimensions. For $k=2$ that's one dimension, for $k=8$ it would be 7. And of course, if the input space has lower dimensionality that that's the limiting factor.
One idea/heuristic behind LDA is that separating classes is easy if they are all spheres of the same size: all you then need is distance to the class means. Alternatively, you can say that the connection between class means are normal vectors for suitable separation planes.
In that narrative, you can look at LDA as a projection that in the first place does singular value decomposition (i.e. something very similar to PCA) of the pooled covariance matrix in order to get a space with such spherical classes. Let's call this our primary score space.
Depending on the customs of your field, this is either the PCA score space of the pooled covariance matrix = the PCA score space of the data matrix centered to the respective class means, or the PCA score space squeezed according to the eigenvalues/SVD diagonal matrix (some fields by default put this scaling for PCA into the loadings, others [mine] into the scores).
The primary score space still has the dimensionality corresponding to the rank of the pooled covariance matrix/data matrix centered to the respective class means. Pooled covariance matrix in this space is a unit sphere, i.e. each class is considered as a unit-sphere centered at the respective class mean, the means also projected into score space.
(At this point, we could derive other classification algorithms that use the SVD projection as heuristic but don't exploit/rely on the assumed unit-sized spherical shape of the classes.)
Now, as we have unit-spherical class shapes, the only thing remaining to care about are the class means. I.e., $k$ points. Even if our primary score space has higher dimensionality, the $k$ points will form a $k-1$ dimensional shape (simplex). Thus without loss of anything, we can further rotate our primary score space so that our $k-1$-simplex of class means lies in the first $k-1$ dimensions.
For the postulted spherical classes, all further dimensions cannot not help with the distinction: the classes have exactly the same size and position in these further dimensions. Thus, we throw them away.
(Again, you may derive another classifier that uses the first two projection steps but then keeps [some of] those further dimensions as the classes in practice may not be spherical.)
One classifer to look into when comparing LDA and PCA is SIMCA which can be seen as a one-class classifier analogous to LDA.
In SIMCA, you'll find the notion of in-model space and out-of-model space: in in-model space you detect changes of the same type of the usual variation within your class (but possibly of unusual magnitude). In out-of-model space you detect variation of a type that does not usually occur within any of the classes.
For our description of LDA, the $k-1$ dimensions we keep would be the in-model space, whereas the remaining dimensions are the out-of-model space. Interpretation will be slightly different compared to SIMCA, but you should have a start for your thoughts with this. | Why with two classes, LDA gives only one dimension?
Like @amoeba, I don't understand your difference between Q1 and Q2: in any case, LDA obtains at most $k-1$ dimensions. For $k=2$ that's one dimension, for $k=8$ it would be 7. And of course, if the in |
31,431 | Why with two classes, LDA gives only one dimension? | From the documentation:
discriminant_analysis.LinearDiscriminantAnalysis can be used to
perform supervised dimensionality reduction, by projecting the input
data to a linear subspace consisting of the directions which maximize
the separation between classes (in a precise sense discussed in the
mathematics section below). The dimension of the output is necessarily
less than the number of classes, so this is, in general, a rather
strong dimensionality reduction, and only makes sense in a multiclass
setting.
http://scikit-learn.org/stable/modules/lda_qda.html | Why with two classes, LDA gives only one dimension? | From the documentation:
discriminant_analysis.LinearDiscriminantAnalysis can be used to
perform supervised dimensionality reduction, by projecting the input
data to a linear subspace consisting o | Why with two classes, LDA gives only one dimension?
From the documentation:
discriminant_analysis.LinearDiscriminantAnalysis can be used to
perform supervised dimensionality reduction, by projecting the input
data to a linear subspace consisting of the directions which maximize
the separation between classes (in a precise sense discussed in the
mathematics section below). The dimension of the output is necessarily
less than the number of classes, so this is, in general, a rather
strong dimensionality reduction, and only makes sense in a multiclass
setting.
http://scikit-learn.org/stable/modules/lda_qda.html | Why with two classes, LDA gives only one dimension?
From the documentation:
discriminant_analysis.LinearDiscriminantAnalysis can be used to
perform supervised dimensionality reduction, by projecting the input
data to a linear subspace consisting o |
31,432 | Why with two classes, LDA gives only one dimension? | LDA is a supervised algorithm it searches for a lower-dimensional space, which is used to maximize the between-class variance, and minimize a within-class variance.
this is a simple algorithm from this paper Linear discriminant analysis: A detailed tutorial
the dimension of lower-dimensional space can be selected in the last step (= largest k eigenvalues) | Why with two classes, LDA gives only one dimension? | LDA is a supervised algorithm it searches for a lower-dimensional space, which is used to maximize the between-class variance, and minimize a within-class variance.
this is a simple algorithm from thi | Why with two classes, LDA gives only one dimension?
LDA is a supervised algorithm it searches for a lower-dimensional space, which is used to maximize the between-class variance, and minimize a within-class variance.
this is a simple algorithm from this paper Linear discriminant analysis: A detailed tutorial
the dimension of lower-dimensional space can be selected in the last step (= largest k eigenvalues) | Why with two classes, LDA gives only one dimension?
LDA is a supervised algorithm it searches for a lower-dimensional space, which is used to maximize the between-class variance, and minimize a within-class variance.
this is a simple algorithm from thi |
31,433 | Regression: Interaction Effects vs Random Effects | Welcome to CV.
In the usual terminology, an interaction is between two fixed effects. A random effect is usually part of a multi-level model, which is a way to deal with dependent errors. Often, the random effect is the subject (e.g. person) in the model.
So, for instance, one use of multilevel models is for longitudinal studies. Say you are studying the effect of diet on weight in 500 overweight adults. You measure weight at 5 time points for each person. You put 250 on one diet and 250 on another. You also measure their age, height and sex. The random effect is "person". But you could add an interaction between, say, age and sex. | Regression: Interaction Effects vs Random Effects | Welcome to CV.
In the usual terminology, an interaction is between two fixed effects. A random effect is usually part of a multi-level model, which is a way to deal with dependent errors. Often, the r | Regression: Interaction Effects vs Random Effects
Welcome to CV.
In the usual terminology, an interaction is between two fixed effects. A random effect is usually part of a multi-level model, which is a way to deal with dependent errors. Often, the random effect is the subject (e.g. person) in the model.
So, for instance, one use of multilevel models is for longitudinal studies. Say you are studying the effect of diet on weight in 500 overweight adults. You measure weight at 5 time points for each person. You put 250 on one diet and 250 on another. You also measure their age, height and sex. The random effect is "person". But you could add an interaction between, say, age and sex. | Regression: Interaction Effects vs Random Effects
Welcome to CV.
In the usual terminology, an interaction is between two fixed effects. A random effect is usually part of a multi-level model, which is a way to deal with dependent errors. Often, the r |
31,434 | Difference Between Rho and Decay Arguments in Keras RMSprop | Short explanation
rho is the "Gradient moving average [also exponentially weighted average] decay factor" and decay is the "Learning rate decay over each update".
Long explanation
RMSProp is defined as follows
source
So RMSProp uses "rho" to calculate an exponentially weighted average over the square of the gradients.
Note that "rho" is a direct parameter of the RMSProp optimizer (it is used in the RMSProp formula).
Decay on the other hand handles learning rate decay. Learning rate decay is a mechanism generally applied independently of the chosen optimizer. Keras simply builds this mechanism into the RMSProp optimizer for convenience (as does it with other optimizers like SGD and Adam which all have the same "decay" parameter). You may think of the "decay" parameter as "lr_decay".
It can be confusing at first that there are two decay parameters, but they are decaying different values.
"rho" is the decay factor or the exponentially weighted average over the square of the gradients.
"decay" decays the learning rate over time, so we can move even closer to the local minimum in the end of training. | Difference Between Rho and Decay Arguments in Keras RMSprop | Short explanation
rho is the "Gradient moving average [also exponentially weighted average] decay factor" and decay is the "Learning rate decay over each update".
Long explanation
RMSProp is defined a | Difference Between Rho and Decay Arguments in Keras RMSprop
Short explanation
rho is the "Gradient moving average [also exponentially weighted average] decay factor" and decay is the "Learning rate decay over each update".
Long explanation
RMSProp is defined as follows
source
So RMSProp uses "rho" to calculate an exponentially weighted average over the square of the gradients.
Note that "rho" is a direct parameter of the RMSProp optimizer (it is used in the RMSProp formula).
Decay on the other hand handles learning rate decay. Learning rate decay is a mechanism generally applied independently of the chosen optimizer. Keras simply builds this mechanism into the RMSProp optimizer for convenience (as does it with other optimizers like SGD and Adam which all have the same "decay" parameter). You may think of the "decay" parameter as "lr_decay".
It can be confusing at first that there are two decay parameters, but they are decaying different values.
"rho" is the decay factor or the exponentially weighted average over the square of the gradients.
"decay" decays the learning rate over time, so we can move even closer to the local minimum in the end of training. | Difference Between Rho and Decay Arguments in Keras RMSprop
Short explanation
rho is the "Gradient moving average [also exponentially weighted average] decay factor" and decay is the "Learning rate decay over each update".
Long explanation
RMSProp is defined a |
31,435 | Why would somebody use a hash function for creating a test/train split instead of random seed? | But can't the same thing be accomplished with a random.seed function?
...
What advantage does using a hash function have over using random seed?
Sampling is less straight forward when you can't fit the entire dataset in memory. In the context of a DBMS, this article suggests that using RAND() with a seed may not be reproducible when writing SQL. This is due to the multithreaded nature of the application, which does not guarantee the order of the returned items (unless you add the ORDER BY clause, which might be expensive). The author of the article proceeds by hashing one of the date fields in each row to get around this problem.
One other plausible use case would be when dealing with files. If I have a huge directory of images that I want to use for training/testing, it might be easier to work with a hash of the filename rather than trying to maintain a reproducible ordering of the files.
Moreover, using a hash function would mean we can no longer use the
field on which the hash was generated (which might be potentially
useful for a model) or it might be inserting some unknown bias into
the model?
Computing the hash of a field is not the same as computing the hash and then overwriting the original value. The hash would just be computed in some other memory block and used to assign the item to the train/test/validation set, the same way generating a random number does not overwrite any data.
With respect to introducing bias, I found this question on the cryptography site which attempts to address the statistical properties of SHA-1 mod n. | Why would somebody use a hash function for creating a test/train split instead of random seed? | But can't the same thing be accomplished with a random.seed function?
...
What advantage does using a hash function have over using random seed?
Sampling is less straight forward when you can't f | Why would somebody use a hash function for creating a test/train split instead of random seed?
But can't the same thing be accomplished with a random.seed function?
...
What advantage does using a hash function have over using random seed?
Sampling is less straight forward when you can't fit the entire dataset in memory. In the context of a DBMS, this article suggests that using RAND() with a seed may not be reproducible when writing SQL. This is due to the multithreaded nature of the application, which does not guarantee the order of the returned items (unless you add the ORDER BY clause, which might be expensive). The author of the article proceeds by hashing one of the date fields in each row to get around this problem.
One other plausible use case would be when dealing with files. If I have a huge directory of images that I want to use for training/testing, it might be easier to work with a hash of the filename rather than trying to maintain a reproducible ordering of the files.
Moreover, using a hash function would mean we can no longer use the
field on which the hash was generated (which might be potentially
useful for a model) or it might be inserting some unknown bias into
the model?
Computing the hash of a field is not the same as computing the hash and then overwriting the original value. The hash would just be computed in some other memory block and used to assign the item to the train/test/validation set, the same way generating a random number does not overwrite any data.
With respect to introducing bias, I found this question on the cryptography site which attempts to address the statistical properties of SHA-1 mod n. | Why would somebody use a hash function for creating a test/train split instead of random seed?
But can't the same thing be accomplished with a random.seed function?
...
What advantage does using a hash function have over using random seed?
Sampling is less straight forward when you can't f |
31,436 | Why would somebody use a hash function for creating a test/train split instead of random seed? | Adding to Joel's excellent answer, your MLops people will thank you for using a hash instead of a random seed. In many real world applications, you want to continue monitoring and retraining a model that is in production. Or you might want to try using a different programming language or data pipeline in the future. By using a hash function, you know that every observation (past, present, and future) will be reliably and reproducibly categorized, even as new data comes in and you move to a new system.
Here's a minimum reproducible example. Imagine I want to see if the mean of an important value has changed since we last updated our model. I don't want to use the holdout data in my analysis, which I'll define as an MD5 hash that starts with a, b, c, d, e, or f. I also don't feel like exporting all the data to my workstation just to look at some averages. I can write a quick SQL query to check the means over time without any holdout contamination.
SELECT date, AVG(value) FROM tbl WHERE LEFT(MD5(id),1) IN(0,1,2,3,4,5,6,7,8,9) GROUP BY 1
Now imagine I've downloaded some data into R. I can run the same analysis without having to worry about seeds being consistent between SQL and R.
tbl %>% mutate(group = str_sub(md5(id), 1, 1)) %>% group_by(date) %>% summarise(mean(value))
In addition to SQL and R, you could do the same thing with Python, Julia, Beam, BigQuery, etc.
My workplace is currently moving from one database system to another. Instead of having to worry about maintaining the same random seed across systems, I just have to Google "generate md5 in new system." | Why would somebody use a hash function for creating a test/train split instead of random seed? | Adding to Joel's excellent answer, your MLops people will thank you for using a hash instead of a random seed. In many real world applications, you want to continue monitoring and retraining a model t | Why would somebody use a hash function for creating a test/train split instead of random seed?
Adding to Joel's excellent answer, your MLops people will thank you for using a hash instead of a random seed. In many real world applications, you want to continue monitoring and retraining a model that is in production. Or you might want to try using a different programming language or data pipeline in the future. By using a hash function, you know that every observation (past, present, and future) will be reliably and reproducibly categorized, even as new data comes in and you move to a new system.
Here's a minimum reproducible example. Imagine I want to see if the mean of an important value has changed since we last updated our model. I don't want to use the holdout data in my analysis, which I'll define as an MD5 hash that starts with a, b, c, d, e, or f. I also don't feel like exporting all the data to my workstation just to look at some averages. I can write a quick SQL query to check the means over time without any holdout contamination.
SELECT date, AVG(value) FROM tbl WHERE LEFT(MD5(id),1) IN(0,1,2,3,4,5,6,7,8,9) GROUP BY 1
Now imagine I've downloaded some data into R. I can run the same analysis without having to worry about seeds being consistent between SQL and R.
tbl %>% mutate(group = str_sub(md5(id), 1, 1)) %>% group_by(date) %>% summarise(mean(value))
In addition to SQL and R, you could do the same thing with Python, Julia, Beam, BigQuery, etc.
My workplace is currently moving from one database system to another. Instead of having to worry about maintaining the same random seed across systems, I just have to Google "generate md5 in new system." | Why would somebody use a hash function for creating a test/train split instead of random seed?
Adding to Joel's excellent answer, your MLops people will thank you for using a hash instead of a random seed. In many real world applications, you want to continue monitoring and retraining a model t |
31,437 | How are random forest and extremely randomized trees split differently? | One iteration of Random Forest:
Select $m$ features randomly as a candidate set of splitting features
Within each of these features, find "best" cutpoint, where "best" is defined by Gini / Entropy / whatever measure
Now you have $m$ features paired with their optimal cutpoints. Choose as your splitting feature and cutpoint the pair that has the "best" performance with respect to Gini / Entropy / whatever measure
One iteration of Extremely Randomized Trees:
Select $m$ features randomly as a candidate set of splitting features
Within each of these features $F_i$, with $i \in {1, ...,m}$ draw a single random cutpoint uniformly from the interval $(min(F_i), max(F_i))$. Evaluate the performance of this feature with this cutpoint with respect to Gini / Entropy / whatever measure
Now you have $m$ features paired with their randomly selected cutpoints. Choose as your splitting feature and cutpoint the pair that has the "best" performance with respect to Gini / Entropy / whatever measure | How are random forest and extremely randomized trees split differently? | One iteration of Random Forest:
Select $m$ features randomly as a candidate set of splitting features
Within each of these features, find "best" cutpoint, where "best" is defined by Gini / Entropy / | How are random forest and extremely randomized trees split differently?
One iteration of Random Forest:
Select $m$ features randomly as a candidate set of splitting features
Within each of these features, find "best" cutpoint, where "best" is defined by Gini / Entropy / whatever measure
Now you have $m$ features paired with their optimal cutpoints. Choose as your splitting feature and cutpoint the pair that has the "best" performance with respect to Gini / Entropy / whatever measure
One iteration of Extremely Randomized Trees:
Select $m$ features randomly as a candidate set of splitting features
Within each of these features $F_i$, with $i \in {1, ...,m}$ draw a single random cutpoint uniformly from the interval $(min(F_i), max(F_i))$. Evaluate the performance of this feature with this cutpoint with respect to Gini / Entropy / whatever measure
Now you have $m$ features paired with their randomly selected cutpoints. Choose as your splitting feature and cutpoint the pair that has the "best" performance with respect to Gini / Entropy / whatever measure | How are random forest and extremely randomized trees split differently?
One iteration of Random Forest:
Select $m$ features randomly as a candidate set of splitting features
Within each of these features, find "best" cutpoint, where "best" is defined by Gini / Entropy / |
31,438 | Python - Test if my data follow a Poisson/Exponential distribution | One way to do what you're trying to do, is to compare your data with the hypothesized distribution (Exponential, Poisson, ..) and see if you can make any conclusions based on that comparison.
Here is one approach:
Figure out which distribution you want to compare against.
For that distribution, identify what the relevant parameters are that completely describe that distribution.
Usually it's the mean and variance. In the case of Poisson, the mean equals the variance so you only have 1 parameter to estimate, $\lambda$.
Use your own data to estimate that parameter.
For the Poisson, take the mean of your data. That will be the mean ($\lambda$) of the Poisson that you generate.
Compare the generated values of the Poisson distribution to the values of your actual data.
Usually compare means find the distance between the distribution. You can look up Kullback-Leiber divergence.
A potentially simpler method would be to compare the distance between each point generated by your data and the corresponding point on the Poisson distribution.
To see if the difference is large enough to be statistically significant (and therefore you can make some determination on the distribution of your data) you can run a significant test, as was mentioned in the comments. Look up KS-test for more information. This method has flaws so make sure you understand what it's doing.
If you don't understand significance testing, I recommend searching this forum for more information. There. Is. A lot.
Check out scipy.stats.kstest for implementation details in Python. | Python - Test if my data follow a Poisson/Exponential distribution | One way to do what you're trying to do, is to compare your data with the hypothesized distribution (Exponential, Poisson, ..) and see if you can make any conclusions based on that comparison.
Here is | Python - Test if my data follow a Poisson/Exponential distribution
One way to do what you're trying to do, is to compare your data with the hypothesized distribution (Exponential, Poisson, ..) and see if you can make any conclusions based on that comparison.
Here is one approach:
Figure out which distribution you want to compare against.
For that distribution, identify what the relevant parameters are that completely describe that distribution.
Usually it's the mean and variance. In the case of Poisson, the mean equals the variance so you only have 1 parameter to estimate, $\lambda$.
Use your own data to estimate that parameter.
For the Poisson, take the mean of your data. That will be the mean ($\lambda$) of the Poisson that you generate.
Compare the generated values of the Poisson distribution to the values of your actual data.
Usually compare means find the distance between the distribution. You can look up Kullback-Leiber divergence.
A potentially simpler method would be to compare the distance between each point generated by your data and the corresponding point on the Poisson distribution.
To see if the difference is large enough to be statistically significant (and therefore you can make some determination on the distribution of your data) you can run a significant test, as was mentioned in the comments. Look up KS-test for more information. This method has flaws so make sure you understand what it's doing.
If you don't understand significance testing, I recommend searching this forum for more information. There. Is. A lot.
Check out scipy.stats.kstest for implementation details in Python. | Python - Test if my data follow a Poisson/Exponential distribution
One way to do what you're trying to do, is to compare your data with the hypothesized distribution (Exponential, Poisson, ..) and see if you can make any conclusions based on that comparison.
Here is |
31,439 | Python - Test if my data follow a Poisson/Exponential distribution | seems like this is what you were looking for
https://nolanbconaway.github.io/blog/2019/poisson-etest
https://github.com/nolanbconaway/poisson-etest | Python - Test if my data follow a Poisson/Exponential distribution | seems like this is what you were looking for
https://nolanbconaway.github.io/blog/2019/poisson-etest
https://github.com/nolanbconaway/poisson-etest | Python - Test if my data follow a Poisson/Exponential distribution
seems like this is what you were looking for
https://nolanbconaway.github.io/blog/2019/poisson-etest
https://github.com/nolanbconaway/poisson-etest | Python - Test if my data follow a Poisson/Exponential distribution
seems like this is what you were looking for
https://nolanbconaway.github.io/blog/2019/poisson-etest
https://github.com/nolanbconaway/poisson-etest |
31,440 | Random Forest for regression--binary response | Try this with "prob" in predict(). It is done on mtcars predict vs column
library(randomForest)
mtcars$vs <- as.factor(mtcars$vs)
classifier <- randomForest( formula = vs~hp+drat, data=mtcars)
predict(classifier, type="prob")
I dont split to train and test sample but in reality you have to do this :)
You have to set factor to response variable in other case it will try to do Random Forest Regression :) | Random Forest for regression--binary response | Try this with "prob" in predict(). It is done on mtcars predict vs column
library(randomForest)
mtcars$vs <- as.factor(mtcars$vs)
classifier <- randomForest( formula = vs~hp+drat, data=mtcars)
predict | Random Forest for regression--binary response
Try this with "prob" in predict(). It is done on mtcars predict vs column
library(randomForest)
mtcars$vs <- as.factor(mtcars$vs)
classifier <- randomForest( formula = vs~hp+drat, data=mtcars)
predict(classifier, type="prob")
I dont split to train and test sample but in reality you have to do this :)
You have to set factor to response variable in other case it will try to do Random Forest Regression :) | Random Forest for regression--binary response
Try this with "prob" in predict(). It is done on mtcars predict vs column
library(randomForest)
mtcars$vs <- as.factor(mtcars$vs)
classifier <- randomForest( formula = vs~hp+drat, data=mtcars)
predict |
31,441 | Random Forest for regression--binary response | Let's start with something simpler, a decision tree, since random forests are forests of independent decision trees that are averaged. Decision tree is build by splitting your data into subsets conditionally on the features used. The splits are done by choosing the features, one at a time, and then choosing a split based on the values of the feature. In both cases we make our choices based on some loss function that is minimized. In regression case we minimize the variance, what is equivalent to minimizing squared loss. In classification case, we use entropy, or Gini impurity as a criterion. In the end your data gets packed into a number of subgroups and to make predictions, in classification case you predict the most frequent value within the subgroup, and in regression case you predict the mean of the subgroup. Obviously, if you calculate the mean of the binary values, you'd get the fraction, i.e. empirical probability. So basically in both cases you can calculate probabilities the same way, this problem reduces only to the criteria that is used for building the tree: mean squared error vs entropy (or Gini impurity). If you choose mean squared error, then you'd be minimizing the same loss as linear regression, while choosing entropy, leads to minimizing the same loss function as logistic regression. | Random Forest for regression--binary response | Let's start with something simpler, a decision tree, since random forests are forests of independent decision trees that are averaged. Decision tree is build by splitting your data into subsets condit | Random Forest for regression--binary response
Let's start with something simpler, a decision tree, since random forests are forests of independent decision trees that are averaged. Decision tree is build by splitting your data into subsets conditionally on the features used. The splits are done by choosing the features, one at a time, and then choosing a split based on the values of the feature. In both cases we make our choices based on some loss function that is minimized. In regression case we minimize the variance, what is equivalent to minimizing squared loss. In classification case, we use entropy, or Gini impurity as a criterion. In the end your data gets packed into a number of subgroups and to make predictions, in classification case you predict the most frequent value within the subgroup, and in regression case you predict the mean of the subgroup. Obviously, if you calculate the mean of the binary values, you'd get the fraction, i.e. empirical probability. So basically in both cases you can calculate probabilities the same way, this problem reduces only to the criteria that is used for building the tree: mean squared error vs entropy (or Gini impurity). If you choose mean squared error, then you'd be minimizing the same loss as linear regression, while choosing entropy, leads to minimizing the same loss function as logistic regression. | Random Forest for regression--binary response
Let's start with something simpler, a decision tree, since random forests are forests of independent decision trees that are averaged. Decision tree is build by splitting your data into subsets condit |
31,442 | How to calculate output shape in 3D convolution | The convolution formula is the same as in 2D and is well-described in CS231n tutorial:
$$Out = (W−F+2P)/S+1$$
... where $W$ is the input volume size, $F$ is the receptive field size, $S$ is the stride, and $P$ is the amount of zero padding used on the border. In particular, when $S=1$ and $P=0$, like in your question, it simplifies to
$$Out=W-F+1$$
So, if you input the tensor $(40,64,64,12)$, ignoring the batch size, and $F=3$, then the output tensor size will be $(38, 62, 62, 8)$.
Pooling layer normally halves each spatial dimension. This corresponds to the local receptive field size F=(2, 2, 2) and stride S=(2, 2, 2). Hence, the input tensor $(38, 62, 62, 8)$ will be transformed to $(19, 31, 31, 8)$.
But you set the stride S=(1, 1, 1), it'll reduce each spatial dimension by 1: $(37, 61, 61, 8)$.
The last dimension doesn't change. | How to calculate output shape in 3D convolution | The convolution formula is the same as in 2D and is well-described in CS231n tutorial:
$$Out = (W−F+2P)/S+1$$
... where $W$ is the input volume size, $F$ is the receptive field size, $S$ is the stride | How to calculate output shape in 3D convolution
The convolution formula is the same as in 2D and is well-described in CS231n tutorial:
$$Out = (W−F+2P)/S+1$$
... where $W$ is the input volume size, $F$ is the receptive field size, $S$ is the stride, and $P$ is the amount of zero padding used on the border. In particular, when $S=1$ and $P=0$, like in your question, it simplifies to
$$Out=W-F+1$$
So, if you input the tensor $(40,64,64,12)$, ignoring the batch size, and $F=3$, then the output tensor size will be $(38, 62, 62, 8)$.
Pooling layer normally halves each spatial dimension. This corresponds to the local receptive field size F=(2, 2, 2) and stride S=(2, 2, 2). Hence, the input tensor $(38, 62, 62, 8)$ will be transformed to $(19, 31, 31, 8)$.
But you set the stride S=(1, 1, 1), it'll reduce each spatial dimension by 1: $(37, 61, 61, 8)$.
The last dimension doesn't change. | How to calculate output shape in 3D convolution
The convolution formula is the same as in 2D and is well-described in CS231n tutorial:
$$Out = (W−F+2P)/S+1$$
... where $W$ is the input volume size, $F$ is the receptive field size, $S$ is the stride |
31,443 | How to calculate output shape in 3D convolution | It is explained in PyTorch's documentation about nn.Conv3d | How to calculate output shape in 3D convolution | It is explained in PyTorch's documentation about nn.Conv3d | How to calculate output shape in 3D convolution
It is explained in PyTorch's documentation about nn.Conv3d | How to calculate output shape in 3D convolution
It is explained in PyTorch's documentation about nn.Conv3d |
31,444 | Understanding and Interpreting letter value boxplots | The key term is letter-value (box)plots and the key reference is now
Hofmann, Heike, Wickham, Hadley and Kafadar, Karen.
2017.
Letter-value plots: Boxplots for large Data.
Journal of Computational and Graphical Statistics 10.1080/10618600.2017.1305277
http://dx.doi.org/10.1080/10618600.2017.1305277
Earlier versions of this paper can easily be found on-line.
As I understand it the width of each box just indicates how a box is defined. The fattest box is between letter values that are (approximate) quartiles, the next fattest boxes stretch between (approximate) quartiles and the (approximate) octiles beyond in either tail, and so on. Positively, this is just an extension of the common box plot convention that each box indicates that it is the interval between quartiles and the width is otherwise just a conventional choice. (Only occasionally are boxes shown that indicate the number of values in each.)
A little more negatively, people have to learn that the width of the box is otherwise arbitrary. It's not, for example, a boxy version of a density plot.
But the interpretation is otherwise similar to that of box plots, e.g. the central half of a sample is within these limits; the central three-quarters within these limits; and so on. Are groups or variables similar or different in distribution?
For a survey of letter values with different emphasis, see
Cox, N. J.
2016.
Speaking Stata: Letter values as selected quantiles
Stata Journal 16(4): 1058-1071.
http://www.stata-journal.com/article.html?article=st0465
I have to worry, on behalf of those who advocate this plot, that naive users are all too likely to interpret it as a blocky version of a violin plot, just as histograms are discretised density plots. The ideal of showing more detail than a box plot is admirable, and the practice usually helps, but there are many other ways to do that. Naturally, advice to read how it is defined and constructed should always be followed. | Understanding and Interpreting letter value boxplots | The key term is letter-value (box)plots and the key reference is now
Hofmann, Heike, Wickham, Hadley and Kafadar, Karen.
2017.
Letter-value plots: Boxplots for large Data.
Journal of Computational and | Understanding and Interpreting letter value boxplots
The key term is letter-value (box)plots and the key reference is now
Hofmann, Heike, Wickham, Hadley and Kafadar, Karen.
2017.
Letter-value plots: Boxplots for large Data.
Journal of Computational and Graphical Statistics 10.1080/10618600.2017.1305277
http://dx.doi.org/10.1080/10618600.2017.1305277
Earlier versions of this paper can easily be found on-line.
As I understand it the width of each box just indicates how a box is defined. The fattest box is between letter values that are (approximate) quartiles, the next fattest boxes stretch between (approximate) quartiles and the (approximate) octiles beyond in either tail, and so on. Positively, this is just an extension of the common box plot convention that each box indicates that it is the interval between quartiles and the width is otherwise just a conventional choice. (Only occasionally are boxes shown that indicate the number of values in each.)
A little more negatively, people have to learn that the width of the box is otherwise arbitrary. It's not, for example, a boxy version of a density plot.
But the interpretation is otherwise similar to that of box plots, e.g. the central half of a sample is within these limits; the central three-quarters within these limits; and so on. Are groups or variables similar or different in distribution?
For a survey of letter values with different emphasis, see
Cox, N. J.
2016.
Speaking Stata: Letter values as selected quantiles
Stata Journal 16(4): 1058-1071.
http://www.stata-journal.com/article.html?article=st0465
I have to worry, on behalf of those who advocate this plot, that naive users are all too likely to interpret it as a blocky version of a violin plot, just as histograms are discretised density plots. The ideal of showing more detail than a box plot is admirable, and the practice usually helps, but there are many other ways to do that. Naturally, advice to read how it is defined and constructed should always be followed. | Understanding and Interpreting letter value boxplots
The key term is letter-value (box)plots and the key reference is now
Hofmann, Heike, Wickham, Hadley and Kafadar, Karen.
2017.
Letter-value plots: Boxplots for large Data.
Journal of Computational and |
31,445 | Are most published correlations in social sciences untrustworthy and what is to be done about it? [closed] | Adding confidence intervals for the estimated true correlation coefficients $\rho$ would be a small (and very simple) first step in the right direction. Its width immediately gives you an impression on the precision of your sample correlation and, at the same time, allows the writer and also the audience to test useful hypotheses. What puzzled me always when talking to statisticians from social science that an absolute sample correlation coefficient above $L = 0.3$ (or some other limit) was considered to be meaningful. At the same time, they were testing the working hypothesis $\rho \ne 0$. This is inconsequencial. Why would a very small population correlation coefficient suddenly be considered as being meaningful? The "correct" working hypothesis would be $|\rho| > L$. Having a confidence interval for $\rho$ at hand, hypotheses like this can easily be tested: just check that the interval is located entirely above $L$ (or below $-L$) and you know whether you can claim a "substantial" statistical association even in the population.
Of course just adding a confidence interval and using meaningful tests won't solve too many problems (like bad sampling designs, omitted consideration of confounders etc.). But it is basically for free. I'd guess even SPSS is able to calculate them! | Are most published correlations in social sciences untrustworthy and what is to be done about it? [c | Adding confidence intervals for the estimated true correlation coefficients $\rho$ would be a small (and very simple) first step in the right direction. Its width immediately gives you an impression o | Are most published correlations in social sciences untrustworthy and what is to be done about it? [closed]
Adding confidence intervals for the estimated true correlation coefficients $\rho$ would be a small (and very simple) first step in the right direction. Its width immediately gives you an impression on the precision of your sample correlation and, at the same time, allows the writer and also the audience to test useful hypotheses. What puzzled me always when talking to statisticians from social science that an absolute sample correlation coefficient above $L = 0.3$ (or some other limit) was considered to be meaningful. At the same time, they were testing the working hypothesis $\rho \ne 0$. This is inconsequencial. Why would a very small population correlation coefficient suddenly be considered as being meaningful? The "correct" working hypothesis would be $|\rho| > L$. Having a confidence interval for $\rho$ at hand, hypotheses like this can easily be tested: just check that the interval is located entirely above $L$ (or below $-L$) and you know whether you can claim a "substantial" statistical association even in the population.
Of course just adding a confidence interval and using meaningful tests won't solve too many problems (like bad sampling designs, omitted consideration of confounders etc.). But it is basically for free. I'd guess even SPSS is able to calculate them! | Are most published correlations in social sciences untrustworthy and what is to be done about it? [c
Adding confidence intervals for the estimated true correlation coefficients $\rho$ would be a small (and very simple) first step in the right direction. Its width immediately gives you an impression o |
31,446 | Are most published correlations in social sciences untrustworthy and what is to be done about it? [closed] | As Michael M notes, the trustworthiness of reported correlations - or of any other estimate - can be assessed using confidence intervals. To a degree, that is. CIs will be too narrow if models were selected after data collection, which I estimate to happen about 95% of the time in the social sciences (which I'll honestly state is a complete guess of mine).
The remedy is twofold:
We are talking about a "replicability crisis". Thus, failed replications inform us that the original effect was probably just random noise. We need to do (and fund, and write up, and submit, and accept) more replications. Replication studies are slowly gaining respectability, and that is a good thing.
The second remedy is of course meta-analysis. If we have many reported correlations of similar data, even if every single one of them has low $n$, then we can pool the information and learn something. Ideally, we will even be able to detect publication-bias in the process. | Are most published correlations in social sciences untrustworthy and what is to be done about it? [c | As Michael M notes, the trustworthiness of reported correlations - or of any other estimate - can be assessed using confidence intervals. To a degree, that is. CIs will be too narrow if models were se | Are most published correlations in social sciences untrustworthy and what is to be done about it? [closed]
As Michael M notes, the trustworthiness of reported correlations - or of any other estimate - can be assessed using confidence intervals. To a degree, that is. CIs will be too narrow if models were selected after data collection, which I estimate to happen about 95% of the time in the social sciences (which I'll honestly state is a complete guess of mine).
The remedy is twofold:
We are talking about a "replicability crisis". Thus, failed replications inform us that the original effect was probably just random noise. We need to do (and fund, and write up, and submit, and accept) more replications. Replication studies are slowly gaining respectability, and that is a good thing.
The second remedy is of course meta-analysis. If we have many reported correlations of similar data, even if every single one of them has low $n$, then we can pool the information and learn something. Ideally, we will even be able to detect publication-bias in the process. | Are most published correlations in social sciences untrustworthy and what is to be done about it? [c
As Michael M notes, the trustworthiness of reported correlations - or of any other estimate - can be assessed using confidence intervals. To a degree, that is. CIs will be too narrow if models were se |
31,447 | Is manually tuning learning rate during training redundant with optimization methods like Adam? | Yes, it is good practice to tune the learning rate even with Adam.
Most variants of SGD which claim to be "adaptive", including optimizers like Adagrad and Adam, adjust the relative learning rates of parameters.
The update rules for many of these adaptive SGD variants involves an update very similar to the following:
$$\Delta w = \frac{1}{r} \frac{\partial{f}}{\partial w}$$
where $r$ usually is some sort of accumulating average of $\left| \frac{\partial{f}}{\partial w} \right|$ over time. (This is a very rough sketch of how it works!)
Since $r$ is different for every parameter, this means that even if one parameter has a really large gradient and another has a very small gradient, they are updated at the same rate.
However, if the gradient eventually becomes small, then $1/r$ will become large, which means the $\Delta w$ will stay roughly the same in size. Therefore, it is still necessary to lower the learning rate in order to achieve good results.
To summarize, the type of adaptivity provided by algorithms like Adam deal with adjusting the relative learning rates of different parameters, not decreasing the learning rate over time, so it's a different type of adaptive.
There are however other algorithms, such as YellowFin, which claim to not need tuning of any parameters at all. https://arxiv.org/abs/1706.03471 | Is manually tuning learning rate during training redundant with optimization methods like Adam? | Yes, it is good practice to tune the learning rate even with Adam.
Most variants of SGD which claim to be "adaptive", including optimizers like Adagrad and Adam, adjust the relative learning rates of | Is manually tuning learning rate during training redundant with optimization methods like Adam?
Yes, it is good practice to tune the learning rate even with Adam.
Most variants of SGD which claim to be "adaptive", including optimizers like Adagrad and Adam, adjust the relative learning rates of parameters.
The update rules for many of these adaptive SGD variants involves an update very similar to the following:
$$\Delta w = \frac{1}{r} \frac{\partial{f}}{\partial w}$$
where $r$ usually is some sort of accumulating average of $\left| \frac{\partial{f}}{\partial w} \right|$ over time. (This is a very rough sketch of how it works!)
Since $r$ is different for every parameter, this means that even if one parameter has a really large gradient and another has a very small gradient, they are updated at the same rate.
However, if the gradient eventually becomes small, then $1/r$ will become large, which means the $\Delta w$ will stay roughly the same in size. Therefore, it is still necessary to lower the learning rate in order to achieve good results.
To summarize, the type of adaptivity provided by algorithms like Adam deal with adjusting the relative learning rates of different parameters, not decreasing the learning rate over time, so it's a different type of adaptive.
There are however other algorithms, such as YellowFin, which claim to not need tuning of any parameters at all. https://arxiv.org/abs/1706.03471 | Is manually tuning learning rate during training redundant with optimization methods like Adam?
Yes, it is good practice to tune the learning rate even with Adam.
Most variants of SGD which claim to be "adaptive", including optimizers like Adagrad and Adam, adjust the relative learning rates of |
31,448 | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$ | There are a number of ways to obtain a first order Markov process with
gamma margins. A very good reference on this topic is the paper by
G.K. Grunwald, R.J. Hyndman and L.M. Tedesko:
A unified view of AR(1) models.
As you will see, the classical "innovation form" $y_t = \phi y_{t-1} +
\varepsilon_t$ is not the easiest way to specify the Markov
transition $p(y_t \, \vert \, y_{t-1})$, unless $\phi$ is taken as random.
Using well chosen distributions; Beta for $\phi$ and Gamma for
$\varepsilon_t$, one can obtain a gamma margin.
A famous continuous-time AR(1) process with Gamma margin is the
shot-noise process with exponential steps, widely used e.g. in hydrology
and relating to the Poisson process. This can be used with a
discrete-time sampling as well, it then appears as a random coefficient
AR(1) with mixed-type distribution for the innovation. | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$ | There are a number of ways to obtain a first order Markov process with
gamma margins. A very good reference on this topic is the paper by
G.K. Grunwald, R.J. Hyndman and L.M. Tedesko:
A unified view o | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$
There are a number of ways to obtain a first order Markov process with
gamma margins. A very good reference on this topic is the paper by
G.K. Grunwald, R.J. Hyndman and L.M. Tedesko:
A unified view of AR(1) models.
As you will see, the classical "innovation form" $y_t = \phi y_{t-1} +
\varepsilon_t$ is not the easiest way to specify the Markov
transition $p(y_t \, \vert \, y_{t-1})$, unless $\phi$ is taken as random.
Using well chosen distributions; Beta for $\phi$ and Gamma for
$\varepsilon_t$, one can obtain a gamma margin.
A famous continuous-time AR(1) process with Gamma margin is the
shot-noise process with exponential steps, widely used e.g. in hydrology
and relating to the Poisson process. This can be used with a
discrete-time sampling as well, it then appears as a random coefficient
AR(1) with mixed-type distribution for the innovation. | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$
There are a number of ways to obtain a first order Markov process with
gamma margins. A very good reference on this topic is the paper by
G.K. Grunwald, R.J. Hyndman and L.M. Tedesko:
A unified view o |
31,449 | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$ | One might guess (so did I initially) that yes, but that the AR(1) process will have new parameters. For shape $a$ and scale $s$, let $g_t\sim \Gamma(a,s)$. Write $\tilde{g}_t=g_t-E(g_t)$.
Then, an AR(1) proces in $g_t$, $y_t=\rho y_{t-1}+g_t$ may also be written as
$$
y_t=E(g_t)+\rho y_{t-1}+\tilde{g}_t
$$
Recall $E(g_t)=as$ and $Var(g_t)=as^2$. By properties of AR(1)-processes,
$$
E(y_t)=\frac{as}{1-\rho}
$$
and
$$
Var(y_t)=\frac{as^2}{1-\rho^2}
$$
Solving the system of equations of the first two moments of a gamma distribution for its two parameters yields new shape parameters of $y_t$, $a_y=E(y_t)^2/Var(y_t)$ and $s_y=Var(y_t)/E(y_t)$.
This argument is however incomplete as it does not show that $y_t$ is indeed $\Gamma$. Basically, write down the $MA(\infty)$ representation
$$
y_t=\frac{as}{1-\rho}+\sum_{j=0}^\infty\rho^j\tilde{g}_t,
$$
so that $y_t$ can be seen as a weighted series of demeaned gamma r.v.s. My reading of posts like this (see also the other more recent answers) suggests that this is not a gamma variate.
That said, a little simulation suggests that the approach does yield a fairly good approximation:
n <- 50000
shape.u <- 2
scale.u <- 1
u <- rgamma(n,shape=shape.u,scale=scale.u)
rho <- 0.75
y <- arima.sim(n=n, list(ar=rho), innov = u)
hist(y, col="lightblue", freq = F, breaks = 40)
(Theoretical.mean <- shape.u*scale.u/(1-rho))
mean(y)
(Theoretical.Variance <- shape.u*scale.u^2/(1-rho^2))
var(y)
shape.y <- Theoretical.mean^2/Theoretical.Variance
scale.y <- Theoretical.Variance/Theoretical.mean
grid <- seq(0,15,0.05)
lines(grid,dgamma(grid,shape=shape.y,scale=scale.y)) | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$ | One might guess (so did I initially) that yes, but that the AR(1) process will have new parameters. For shape $a$ and scale $s$, let $g_t\sim \Gamma(a,s)$. Write $\tilde{g}_t=g_t-E(g_t)$.
Then, an AR( | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$
One might guess (so did I initially) that yes, but that the AR(1) process will have new parameters. For shape $a$ and scale $s$, let $g_t\sim \Gamma(a,s)$. Write $\tilde{g}_t=g_t-E(g_t)$.
Then, an AR(1) proces in $g_t$, $y_t=\rho y_{t-1}+g_t$ may also be written as
$$
y_t=E(g_t)+\rho y_{t-1}+\tilde{g}_t
$$
Recall $E(g_t)=as$ and $Var(g_t)=as^2$. By properties of AR(1)-processes,
$$
E(y_t)=\frac{as}{1-\rho}
$$
and
$$
Var(y_t)=\frac{as^2}{1-\rho^2}
$$
Solving the system of equations of the first two moments of a gamma distribution for its two parameters yields new shape parameters of $y_t$, $a_y=E(y_t)^2/Var(y_t)$ and $s_y=Var(y_t)/E(y_t)$.
This argument is however incomplete as it does not show that $y_t$ is indeed $\Gamma$. Basically, write down the $MA(\infty)$ representation
$$
y_t=\frac{as}{1-\rho}+\sum_{j=0}^\infty\rho^j\tilde{g}_t,
$$
so that $y_t$ can be seen as a weighted series of demeaned gamma r.v.s. My reading of posts like this (see also the other more recent answers) suggests that this is not a gamma variate.
That said, a little simulation suggests that the approach does yield a fairly good approximation:
n <- 50000
shape.u <- 2
scale.u <- 1
u <- rgamma(n,shape=shape.u,scale=scale.u)
rho <- 0.75
y <- arima.sim(n=n, list(ar=rho), innov = u)
hist(y, col="lightblue", freq = F, breaks = 40)
(Theoretical.mean <- shape.u*scale.u/(1-rho))
mean(y)
(Theoretical.Variance <- shape.u*scale.u^2/(1-rho^2))
var(y)
shape.y <- Theoretical.mean^2/Theoretical.Variance
scale.y <- Theoretical.Variance/Theoretical.mean
grid <- seq(0,15,0.05)
lines(grid,dgamma(grid,shape=shape.y,scale=scale.y)) | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$
One might guess (so did I initially) that yes, but that the AR(1) process will have new parameters. For shape $a$ and scale $s$, let $g_t\sim \Gamma(a,s)$. Write $\tilde{g}_t=g_t-E(g_t)$.
Then, an AR( |
31,450 | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$ | I now have the answer to this question I posed, but it leads me to a further question.
So, first, the solution is as follows:
For a stationary Markov Chain with a $\Gamma[\alpha, p]$ marginal distribution, the probability density function of $P_t$ at $x$ is given by:
$f_{P_t}[x] = \frac{x^{p-1}\exp[-x/\alpha]}{\alpha^p\Gamma[p]} \quad x \geq 0$
then the conditional pdf of $P_{t+1}$ at $x$ given $P_t=u is:
$f_{P_{t+1}|P_t}[x|u]=\frac{1}{\alpha(1-\rho)\rho^{(p-1)/2}}\left[\frac{x}{u}\right]^{(p-1)/2}\exp\left[-\frac{x+\rho u}{\alpha(1-\rho)}\right]I_{p-1}\left[\frac{2\sqrt{\rho x u}}{\alpha(1-\rho)}\right]$
where $I_\nu$ denotes the modified Bessel function. This provides a Markov Chain with a gamma marginal distribution, and an AR correlation structure where $\rho(1)$ is $\rho$.
Further details of this are given in an excellent paper by David Warren, published in 1986 in the Journal of Hydrology, "Outflow Skewness in non-seasonal linear reservoirs with gamma-distributed inflows" (Volume 85, pp127-137; http://www.sciencedirect.com/science/article/pii/0022169486900806#).
This is great, because it answers my initial question, however, the systems I want to represent with this PDF require the generation of synthetic series. If the shape and scale parameters of the distribution are large, then this is straightforward. However, if I want the parameters to be small then I am unable to generate a series with the appropriate characteristics. I am using MATLAB to do this and the code is as follows:
% specify parameters for distribution
p = 0.05;
a = 0.5;
% generate first value
u = gamrnd(p,a);
$ keep a version of the margins pdf
x = 0.00001:0.00001:6;
f = (x.^(p-1)).*(exp(-x./a))./((a.^p).*gamma(p));
% specify the correlation structure
rho = 0.5;
% store the first value
input(1,1) = u;
% generate 999 other cvalues using the conditional distribution
for i = 2:1:999
i
z = (2./(a.*(1-rho))).*sqrt(rho.*x.*u);
PDF = (1./a).*(1./(1-rho)).*(rho.^(-(p-1)./2)).*((x./u).^((p-1)./2)).*...
exp(-(x+rho.*u)./(a.*(1-rho))).*besseli(p-1,z);
ycdf = cumsum(PDF,'omitnan')/sum(PDF,'omitnan');
rn = rand;
u = x(find(ycdf>rn,1));
input(i,1) = u;
end
If I use much larger numbers for the gamma distribution parameters then the marginal comes out spot on, but I need to use small values. Any thoughts on how I can do this? | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$ | I now have the answer to this question I posed, but it leads me to a further question.
So, first, the solution is as follows:
For a stationary Markov Chain with a $\Gamma[\alpha, p]$ marginal distribu | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$
I now have the answer to this question I posed, but it leads me to a further question.
So, first, the solution is as follows:
For a stationary Markov Chain with a $\Gamma[\alpha, p]$ marginal distribution, the probability density function of $P_t$ at $x$ is given by:
$f_{P_t}[x] = \frac{x^{p-1}\exp[-x/\alpha]}{\alpha^p\Gamma[p]} \quad x \geq 0$
then the conditional pdf of $P_{t+1}$ at $x$ given $P_t=u is:
$f_{P_{t+1}|P_t}[x|u]=\frac{1}{\alpha(1-\rho)\rho^{(p-1)/2}}\left[\frac{x}{u}\right]^{(p-1)/2}\exp\left[-\frac{x+\rho u}{\alpha(1-\rho)}\right]I_{p-1}\left[\frac{2\sqrt{\rho x u}}{\alpha(1-\rho)}\right]$
where $I_\nu$ denotes the modified Bessel function. This provides a Markov Chain with a gamma marginal distribution, and an AR correlation structure where $\rho(1)$ is $\rho$.
Further details of this are given in an excellent paper by David Warren, published in 1986 in the Journal of Hydrology, "Outflow Skewness in non-seasonal linear reservoirs with gamma-distributed inflows" (Volume 85, pp127-137; http://www.sciencedirect.com/science/article/pii/0022169486900806#).
This is great, because it answers my initial question, however, the systems I want to represent with this PDF require the generation of synthetic series. If the shape and scale parameters of the distribution are large, then this is straightforward. However, if I want the parameters to be small then I am unable to generate a series with the appropriate characteristics. I am using MATLAB to do this and the code is as follows:
% specify parameters for distribution
p = 0.05;
a = 0.5;
% generate first value
u = gamrnd(p,a);
$ keep a version of the margins pdf
x = 0.00001:0.00001:6;
f = (x.^(p-1)).*(exp(-x./a))./((a.^p).*gamma(p));
% specify the correlation structure
rho = 0.5;
% store the first value
input(1,1) = u;
% generate 999 other cvalues using the conditional distribution
for i = 2:1:999
i
z = (2./(a.*(1-rho))).*sqrt(rho.*x.*u);
PDF = (1./a).*(1./(1-rho)).*(rho.^(-(p-1)./2)).*((x./u).^((p-1)./2)).*...
exp(-(x+rho.*u)./(a.*(1-rho))).*besseli(p-1,z);
ycdf = cumsum(PDF,'omitnan')/sum(PDF,'omitnan');
rn = rand;
u = x(find(ycdf>rn,1));
input(i,1) = u;
end
If I use much larger numbers for the gamma distribution parameters then the marginal comes out spot on, but I need to use small values. Any thoughts on how I can do this? | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$
I now have the answer to this question I posed, but it leads me to a further question.
So, first, the solution is as follows:
For a stationary Markov Chain with a $\Gamma[\alpha, p]$ marginal distribu |
31,451 | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$ | A copula inspired idea would be to transform a Gaussian AR(1) process, say
$$
x_t = \phi_1 x_{t-1} + w_t
$$
where $w_t$ is $N(0,\sigma_w^2)$ where $\sigma_w^2=1-\phi^2$ such that the marginal distribution of $x_t\sim N(0,1)$ to a new process $y_t=F^{-1}(\Phi(x_t); a, s))$ where $F^{-1}$ is the quantile function of the gamma distribution and $\Phi$ is the cumulative standard normal density function.
While the resulting process $y_t$ would have the Markov property, is would not be AR(1), however, as its partial autocorrelation function do not cut off for lags greater than 1 as seen in the following simulation:
phi <- .5
x <- arima.sim(model=list(ar=phi),n=1e+6,sd=sqrt(1-phi^2))
y <- qgamma(pnorm(x), shape=.1)
par(mfrow=c(2,1))
acf(y)
pacf(y)
If instead letting $x_t$ be AR(p) with suitable coefficients, then perhaps $y_t$ can be made approximately AR(1), that is, choose the order $p$ and $\phi_1,\dots,\phi_p$ such that the pacf of $y_t$ becomes sufficiently small for all lags higher than 1. But now the process $y_t$ would no longer have the Markov property. | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$ | A copula inspired idea would be to transform a Gaussian AR(1) process, say
$$
x_t = \phi_1 x_{t-1} + w_t
$$
where $w_t$ is $N(0,\sigma_w^2)$ where $\sigma_w^2=1-\phi^2$ such that the marginal distribu | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$
A copula inspired idea would be to transform a Gaussian AR(1) process, say
$$
x_t = \phi_1 x_{t-1} + w_t
$$
where $w_t$ is $N(0,\sigma_w^2)$ where $\sigma_w^2=1-\phi^2$ such that the marginal distribution of $x_t\sim N(0,1)$ to a new process $y_t=F^{-1}(\Phi(x_t); a, s))$ where $F^{-1}$ is the quantile function of the gamma distribution and $\Phi$ is the cumulative standard normal density function.
While the resulting process $y_t$ would have the Markov property, is would not be AR(1), however, as its partial autocorrelation function do not cut off for lags greater than 1 as seen in the following simulation:
phi <- .5
x <- arima.sim(model=list(ar=phi),n=1e+6,sd=sqrt(1-phi^2))
y <- qgamma(pnorm(x), shape=.1)
par(mfrow=c(2,1))
acf(y)
pacf(y)
If instead letting $x_t$ be AR(p) with suitable coefficients, then perhaps $y_t$ can be made approximately AR(1), that is, choose the order $p$ and $\phi_1,\dots,\phi_p$ such that the pacf of $y_t$ becomes sufficiently small for all lags higher than 1. But now the process $y_t$ would no longer have the Markov property. | How to create a markov chain with gamma marginal distribution and AR(1) coefficient of $\rho$
A copula inspired idea would be to transform a Gaussian AR(1) process, say
$$
x_t = \phi_1 x_{t-1} + w_t
$$
where $w_t$ is $N(0,\sigma_w^2)$ where $\sigma_w^2=1-\phi^2$ such that the marginal distribu |
31,452 | What to do when count data does not fit a Poisson distribution | Let's consider, somewhat simplistically, the natural history of a conversation:
One person initiates a conversation by sending a message out into the ether.
People respond. Each new (unique) respondent adds one to the count.
Responses to any message are random: whether an individual responds depends on whether
They are aware of the message
Currently have an opportunity to respond
Are interested in responding.
Compared to the number of people who could receive messages, the number of messages initiated is relatively low. Thus
Almost all individuals will be responding to one, or a small manageable numbers, of messages at any time.
Characteristics (3) and (4) suggest a Poisson distribution could be a good model for the number of people responding to any message at any time: that is, the count minus one. What we do not know, and might not be safe assuming is whether all messages have approximately the same Poisson parameter or whether those parameters vary appreciably.
A good starting point, then, would be to test whether the counts minus one fit a Poisson distribution. Alternatively, they might fit some overdispersed distribution comprised of a mixture of Poissons.
The maximum likelihood estimate of the Poisson parameter $\lambda$ is the mean of the counts (minus one), equal to $1.20$. (It is important to use the ML estimate for this calculation rather than the "MinChisq" estimate computed by vcd::goodfit: see https://stats.stackexchange.com/a/17148/919.) Multiplying the Poisson probabilities by the total number of users gives the expected numbers of user counts. Here they are compared to the actual counts:
0 1 2 3 4 5
Expected 94 113 68 27 8 2
Actual 85 127 68 22 5 5
The fit looks close. It can be measured with the chi-squared statistic, $$\chi^2 = \frac{(85-94)^2}{94} + \frac{(127-113)^2}{113} + \cdots + \frac{(5-2)^2}{2} = 9.61.$$
The six terms in this sum measure the individual count discrepancies. They are
0 1 2 3 4 5
0.88 1.79 0.00 0.93 1.18 4.82
Values close to $1$ signify good agreement. Only the last value, $4.82$, is large. That is due to the small expected value of $2$ for a count of $5$. Typically, expected values less than $5$ are believed to lead to some unreliability in the traditional $\chi^2$ test: here, we should take the $\chi^2$ statistic to perhaps be a little inflated due to the small expected number of six-way conversations.
Nevertheless, this $\chi^2$ statistic is not terribly high: under the hypothesized unvarying Poisson distribution, this statistic would approximately follow a $\chi^2(5)$ distribution. That distribution tells us a value this high occurs almost nine percent of the time. We conclude there is little evidence of a departure from a constant Poisson distribution.
Incidentally, a plot of the data--in the sequence given--does hint at a variation in the counts. On average they increase a little from beginning to end, as the Lowess smooth on this plot suggests:
Thus, the chi-squared test of Poisson distribution should not be the last word: it should only be considered the beginning of a more detailed analysis.
Here is the R code used to perform the calculations and create the figure.
counts <- table(users-1)
mu <- mean(users-1)
expected <- dpois(as.numeric(names(counts)), mu) * length(users)
x <- (counts - expected)^2 / expected
print(round(x, 2)) # Terms in the chi-squared statistic
print(rbind(Expected = round(expected, 0), Actual=counts)) # Compare expected to actual
library(ggplot2)
X <- data.frame(Index=1:length(users), Count=users)
g <- ggplot(X, aes(Index, Count)) + geom_smooth(size=2) + geom_point(size=2, alpha=1/2)
print(g) | What to do when count data does not fit a Poisson distribution | Let's consider, somewhat simplistically, the natural history of a conversation:
One person initiates a conversation by sending a message out into the ether.
People respond. Each new (unique) respond | What to do when count data does not fit a Poisson distribution
Let's consider, somewhat simplistically, the natural history of a conversation:
One person initiates a conversation by sending a message out into the ether.
People respond. Each new (unique) respondent adds one to the count.
Responses to any message are random: whether an individual responds depends on whether
They are aware of the message
Currently have an opportunity to respond
Are interested in responding.
Compared to the number of people who could receive messages, the number of messages initiated is relatively low. Thus
Almost all individuals will be responding to one, or a small manageable numbers, of messages at any time.
Characteristics (3) and (4) suggest a Poisson distribution could be a good model for the number of people responding to any message at any time: that is, the count minus one. What we do not know, and might not be safe assuming is whether all messages have approximately the same Poisson parameter or whether those parameters vary appreciably.
A good starting point, then, would be to test whether the counts minus one fit a Poisson distribution. Alternatively, they might fit some overdispersed distribution comprised of a mixture of Poissons.
The maximum likelihood estimate of the Poisson parameter $\lambda$ is the mean of the counts (minus one), equal to $1.20$. (It is important to use the ML estimate for this calculation rather than the "MinChisq" estimate computed by vcd::goodfit: see https://stats.stackexchange.com/a/17148/919.) Multiplying the Poisson probabilities by the total number of users gives the expected numbers of user counts. Here they are compared to the actual counts:
0 1 2 3 4 5
Expected 94 113 68 27 8 2
Actual 85 127 68 22 5 5
The fit looks close. It can be measured with the chi-squared statistic, $$\chi^2 = \frac{(85-94)^2}{94} + \frac{(127-113)^2}{113} + \cdots + \frac{(5-2)^2}{2} = 9.61.$$
The six terms in this sum measure the individual count discrepancies. They are
0 1 2 3 4 5
0.88 1.79 0.00 0.93 1.18 4.82
Values close to $1$ signify good agreement. Only the last value, $4.82$, is large. That is due to the small expected value of $2$ for a count of $5$. Typically, expected values less than $5$ are believed to lead to some unreliability in the traditional $\chi^2$ test: here, we should take the $\chi^2$ statistic to perhaps be a little inflated due to the small expected number of six-way conversations.
Nevertheless, this $\chi^2$ statistic is not terribly high: under the hypothesized unvarying Poisson distribution, this statistic would approximately follow a $\chi^2(5)$ distribution. That distribution tells us a value this high occurs almost nine percent of the time. We conclude there is little evidence of a departure from a constant Poisson distribution.
Incidentally, a plot of the data--in the sequence given--does hint at a variation in the counts. On average they increase a little from beginning to end, as the Lowess smooth on this plot suggests:
Thus, the chi-squared test of Poisson distribution should not be the last word: it should only be considered the beginning of a more detailed analysis.
Here is the R code used to perform the calculations and create the figure.
counts <- table(users-1)
mu <- mean(users-1)
expected <- dpois(as.numeric(names(counts)), mu) * length(users)
x <- (counts - expected)^2 / expected
print(round(x, 2)) # Terms in the chi-squared statistic
print(rbind(Expected = round(expected, 0), Actual=counts)) # Compare expected to actual
library(ggplot2)
X <- data.frame(Index=1:length(users), Count=users)
g <- ggplot(X, aes(Index, Count)) + geom_smooth(size=2) + geom_point(size=2, alpha=1/2)
print(g) | What to do when count data does not fit a Poisson distribution
Let's consider, somewhat simplistically, the natural history of a conversation:
One person initiates a conversation by sending a message out into the ether.
People respond. Each new (unique) respond |
31,453 | Non-Convex Loss Function | We know "if a function is a non-convex loss function without plotting the graph" by using Calculus.
To quote Wikipedia's convex function article: "If the function is twice differentiable, and the second derivative is always greater than or equal to zero for its entire domain, then the function is convex." If the second derivative is always greater than zero then it is strictly convex.
Therefore if we can prove that the second derivatives of our selected cost function are always positive the function is convex.
We care about convexity because the minimum of a convex function is also a global minimum. If the function is strictly convex function then it will have at most one global minimum which is also convenient; we prove the global optimality of particular solution. Please see the thread here as why we generally want an objective function to be a convex function and here on whether gradient descent can be applied to non-convex functions, for some more information on the matter. | Non-Convex Loss Function | We know "if a function is a non-convex loss function without plotting the graph" by using Calculus.
To quote Wikipedia's convex function article: "If the function is twice differentiable, and the seco | Non-Convex Loss Function
We know "if a function is a non-convex loss function without plotting the graph" by using Calculus.
To quote Wikipedia's convex function article: "If the function is twice differentiable, and the second derivative is always greater than or equal to zero for its entire domain, then the function is convex." If the second derivative is always greater than zero then it is strictly convex.
Therefore if we can prove that the second derivatives of our selected cost function are always positive the function is convex.
We care about convexity because the minimum of a convex function is also a global minimum. If the function is strictly convex function then it will have at most one global minimum which is also convenient; we prove the global optimality of particular solution. Please see the thread here as why we generally want an objective function to be a convex function and here on whether gradient descent can be applied to non-convex functions, for some more information on the matter. | Non-Convex Loss Function
We know "if a function is a non-convex loss function without plotting the graph" by using Calculus.
To quote Wikipedia's convex function article: "If the function is twice differentiable, and the seco |
31,454 | Offset in Logistic regression: what are the typical use cases? | You include an offset when you know what the coefficient of that variable should be. Typically software fixes it at unity. As you point out in Poisson regression this is often used to include the effect of the denominator when we assume that if we multiplied the denominator by a factor we would also multiply the outcome by the same factor.
One case where an offset might be used outside the Poisson special case is when you have a hypothesised value for the coefficient from theory of previous studies. If you then include your predictor variable in the regression multiplied by the theoretical value and as an offset this will have the effect of including it with the theoretical value of the coefficient. If you also include the predictor as a standard regressor you will see from testing its coefficient against zero whether the offset is sufficient (so the theoretical value is supported) or whether you can reject that. | Offset in Logistic regression: what are the typical use cases? | You include an offset when you know what the coefficient of that variable should be. Typically software fixes it at unity. As you point out in Poisson regression this is often used to include the effe | Offset in Logistic regression: what are the typical use cases?
You include an offset when you know what the coefficient of that variable should be. Typically software fixes it at unity. As you point out in Poisson regression this is often used to include the effect of the denominator when we assume that if we multiplied the denominator by a factor we would also multiply the outcome by the same factor.
One case where an offset might be used outside the Poisson special case is when you have a hypothesised value for the coefficient from theory of previous studies. If you then include your predictor variable in the regression multiplied by the theoretical value and as an offset this will have the effect of including it with the theoretical value of the coefficient. If you also include the predictor as a standard regressor you will see from testing its coefficient against zero whether the offset is sufficient (so the theoretical value is supported) or whether you can reject that. | Offset in Logistic regression: what are the typical use cases?
You include an offset when you know what the coefficient of that variable should be. Typically software fixes it at unity. As you point out in Poisson regression this is often used to include the effe |
31,455 | Offset in Logistic regression: what are the typical use cases? | I sometimes use an offset in a logistic regression model. The use case is where I already have a complex model, which needs to be re-estimated to cover some new data outside the realm of the original data sample (in time, or in cross section), but where, for various reasons, it is practically infeasible to re-estimate the model on the entire, expanded data set. The goal is a new model that gives good predictions on some out-of-sample data, but which gives unchanged predictions on the in-sample data.
So I take the linear predictors from the original model, specify those as an offset, and then introduce additional variables aimed at fitting the new data, in such a way that it wouldn't change the predictions on the original data.
It's admittedly ad hoc, but an awfully useful trick in practice. I have no idea what the "legitimate" use of an offset in logistic regression is, but I'm glad statistical software packages allow for it. | Offset in Logistic regression: what are the typical use cases? | I sometimes use an offset in a logistic regression model. The use case is where I already have a complex model, which needs to be re-estimated to cover some new data outside the realm of the original | Offset in Logistic regression: what are the typical use cases?
I sometimes use an offset in a logistic regression model. The use case is where I already have a complex model, which needs to be re-estimated to cover some new data outside the realm of the original data sample (in time, or in cross section), but where, for various reasons, it is practically infeasible to re-estimate the model on the entire, expanded data set. The goal is a new model that gives good predictions on some out-of-sample data, but which gives unchanged predictions on the in-sample data.
So I take the linear predictors from the original model, specify those as an offset, and then introduce additional variables aimed at fitting the new data, in such a way that it wouldn't change the predictions on the original data.
It's admittedly ad hoc, but an awfully useful trick in practice. I have no idea what the "legitimate" use of an offset in logistic regression is, but I'm glad statistical software packages allow for it. | Offset in Logistic regression: what are the typical use cases?
I sometimes use an offset in a logistic regression model. The use case is where I already have a complex model, which needs to be re-estimated to cover some new data outside the realm of the original |
31,456 | Offset in Logistic regression: what are the typical use cases? | When the model is based on oversampled data, offset is used to correct the bias. An alternative is to use weights argument. Note however that offset produces correct probabilities by changing the intercept, usually a judgment based override. On the other hand, weights produces correct parameter estimates by countering the effect of oversampling, as if the model was based on correctly sampled data. | Offset in Logistic regression: what are the typical use cases? | When the model is based on oversampled data, offset is used to correct the bias. An alternative is to use weights argument. Note however that offset produces correct probabilities by changing the inte | Offset in Logistic regression: what are the typical use cases?
When the model is based on oversampled data, offset is used to correct the bias. An alternative is to use weights argument. Note however that offset produces correct probabilities by changing the intercept, usually a judgment based override. On the other hand, weights produces correct parameter estimates by countering the effect of oversampling, as if the model was based on correctly sampled data. | Offset in Logistic regression: what are the typical use cases?
When the model is based on oversampled data, offset is used to correct the bias. An alternative is to use weights argument. Note however that offset produces correct probabilities by changing the inte |
31,457 | Offset in Logistic regression: what are the typical use cases? | There are a variety of uses for offsets in logistic regression, whether for specific factors or the outputs of other models.
For specific factors, they may be included or excluded from the final implementation. Included, if the goal is fix them in the final model, whether to force assumptions (based upon past experience) or restrict influence. Excluded, if the goal is to control for those factors {maturity effect, disparate impact}.
For model outputs they can be i) part of a full development process to stage in groups of variables; ii) to incorporate new data sources in new samples without affecting the original model; iii) to validate a model's ranking abilitys pre- or post-implementation. | Offset in Logistic regression: what are the typical use cases? | There are a variety of uses for offsets in logistic regression, whether for specific factors or the outputs of other models.
For specific factors, they may be included or excluded from the final imple | Offset in Logistic regression: what are the typical use cases?
There are a variety of uses for offsets in logistic regression, whether for specific factors or the outputs of other models.
For specific factors, they may be included or excluded from the final implementation. Included, if the goal is fix them in the final model, whether to force assumptions (based upon past experience) or restrict influence. Excluded, if the goal is to control for those factors {maturity effect, disparate impact}.
For model outputs they can be i) part of a full development process to stage in groups of variables; ii) to incorporate new data sources in new samples without affecting the original model; iii) to validate a model's ranking abilitys pre- or post-implementation. | Offset in Logistic regression: what are the typical use cases?
There are a variety of uses for offsets in logistic regression, whether for specific factors or the outputs of other models.
For specific factors, they may be included or excluded from the final imple |
31,458 | Do boosting techniques use voting like any other ensemble method? | Boosting can generally be understood as (weighted) voting
In the case of boosting, one of its inventors gives an affirmative answer in this introduction to AdaBoost (emphasis mine):
The final or combined hypothesis $H$ computes the sign of a weighted
combination of weak hypotheses
$$F(x) = \sum_{t=1}^T\alpha_th_t(x)$$
This is equivalent to saying that $H$ is computed as a weighted majority vote of the weak hypotheses $h_t$ where each is assigned weight $\alpha_t$. (In this chapter, we use the terms “hypothesis” and “classifier” interchangeably.)
So yes, the final model returned is a weighted vote of all the weak learners trained to that iteration. Likewise, you'll find this snippet on Wikipedia about boosting in general:
While boosting is not algorithmically constrained, most boosting algorithms consist of iteratively learning weak classifiers with respect to a distribution and adding them to a final strong classifier. When they are added, they are typically weighted in some way that is usually related to the weak learners' accuracy.
Also note the mention therein that the original boosting algorithms used a "majority." The notion of voting is pretty firmly baked into boosting: Its guiding principle is to improve an ensemble at each iteration by adding a new voter, then deciding how much weight to give each vote.
This same intuition carries for the example of gradient boosting: At each iteration $m$ we find a new learner $h_m$ fitted to pseudo-residuals, then optimize $\gamma_m$ to decide how much weight to give $h_m$'s "vote."
Extending to all ensemble methods runs into counterexamples
As it is, some would find that even the notion of weighting stretches the voting metaphor. When considering whether to extend this intuition to all ensemble learning methods, consider this snippet:
Ensembles combine multiple hypotheses to form a (hopefully) better hypothesis. The term ensemble is usually reserved for methods that generate multiple hypotheses using the same base learner.
And this one on the example ensemble method of stacking:
Stacking (sometimes called stacked generalization) involves training a learning algorithm to combine the predictions of several other learning algorithms. First, all of the other algorithms are trained using the available data, then a combiner algorithm is trained to make a final prediction using all the predictions of the other algorithms as additional inputs. If an arbitrary combiner algorithm is used, then stacking can theoretically represent any of the ensemble techniques described in this article, although in practice, a single-layer logistic regression model is often used as the combiner.
If you're defining ensemble methods to include stacking methods with an arbitrary combiner, you can construct methods that, in my view, stretch the notion of voting beyond its limit. It's difficult to see how a collection of weak learners combined via a decision tree or neural network can be viewed as "voting." (Leaving aside the also difficult question of when that method might prove practically useful.)
Some introductions describe ensembles and voting as synonymous; I'm not familiar enough with recent literature on these methods to say how these terms are generally applied recently, but I hope this answer gives an idea of how far the notion of voting extends. | Do boosting techniques use voting like any other ensemble method? | Boosting can generally be understood as (weighted) voting
In the case of boosting, one of its inventors gives an affirmative answer in this introduction to AdaBoost (emphasis mine):
The final or comb | Do boosting techniques use voting like any other ensemble method?
Boosting can generally be understood as (weighted) voting
In the case of boosting, one of its inventors gives an affirmative answer in this introduction to AdaBoost (emphasis mine):
The final or combined hypothesis $H$ computes the sign of a weighted
combination of weak hypotheses
$$F(x) = \sum_{t=1}^T\alpha_th_t(x)$$
This is equivalent to saying that $H$ is computed as a weighted majority vote of the weak hypotheses $h_t$ where each is assigned weight $\alpha_t$. (In this chapter, we use the terms “hypothesis” and “classifier” interchangeably.)
So yes, the final model returned is a weighted vote of all the weak learners trained to that iteration. Likewise, you'll find this snippet on Wikipedia about boosting in general:
While boosting is not algorithmically constrained, most boosting algorithms consist of iteratively learning weak classifiers with respect to a distribution and adding them to a final strong classifier. When they are added, they are typically weighted in some way that is usually related to the weak learners' accuracy.
Also note the mention therein that the original boosting algorithms used a "majority." The notion of voting is pretty firmly baked into boosting: Its guiding principle is to improve an ensemble at each iteration by adding a new voter, then deciding how much weight to give each vote.
This same intuition carries for the example of gradient boosting: At each iteration $m$ we find a new learner $h_m$ fitted to pseudo-residuals, then optimize $\gamma_m$ to decide how much weight to give $h_m$'s "vote."
Extending to all ensemble methods runs into counterexamples
As it is, some would find that even the notion of weighting stretches the voting metaphor. When considering whether to extend this intuition to all ensemble learning methods, consider this snippet:
Ensembles combine multiple hypotheses to form a (hopefully) better hypothesis. The term ensemble is usually reserved for methods that generate multiple hypotheses using the same base learner.
And this one on the example ensemble method of stacking:
Stacking (sometimes called stacked generalization) involves training a learning algorithm to combine the predictions of several other learning algorithms. First, all of the other algorithms are trained using the available data, then a combiner algorithm is trained to make a final prediction using all the predictions of the other algorithms as additional inputs. If an arbitrary combiner algorithm is used, then stacking can theoretically represent any of the ensemble techniques described in this article, although in practice, a single-layer logistic regression model is often used as the combiner.
If you're defining ensemble methods to include stacking methods with an arbitrary combiner, you can construct methods that, in my view, stretch the notion of voting beyond its limit. It's difficult to see how a collection of weak learners combined via a decision tree or neural network can be viewed as "voting." (Leaving aside the also difficult question of when that method might prove practically useful.)
Some introductions describe ensembles and voting as synonymous; I'm not familiar enough with recent literature on these methods to say how these terms are generally applied recently, but I hope this answer gives an idea of how far the notion of voting extends. | Do boosting techniques use voting like any other ensemble method?
Boosting can generally be understood as (weighted) voting
In the case of boosting, one of its inventors gives an affirmative answer in this introduction to AdaBoost (emphasis mine):
The final or comb |
31,459 | Do boosting techniques use voting like any other ensemble method? | Boosting is different from bagging (voting). I do not see a way to interpret boosting as "voting" (see my edit for additional details).
Voting (especially majority vote) usually means combined decision from "separate / less correlated" week classifiers.
In boosting, we are building one classifier upon another. So, they are not "separate peers" but one is "less weaker than another".
My answers here gives boosting break down by iterations.
How does linear base leaner works in boosting? And how it works in xgboost library?
The example is trying to approximate a quadratic function by by boosting on decision stump.
First two plots are ground truth and boosting model after many iterations. They are contour plots. X and Y axis are two features and function value is represented by color.
Then I am showing first 4 iterations. You can see we are not averaging/voting 4 models, but enhance the model over each iterations.
After seeing another answer, I feel the answer to this question depends on how we define "voting". Do we consider weighted sum as voting ? If yes, then I think we still can say boosting can be generalized with voting. | Do boosting techniques use voting like any other ensemble method? | Boosting is different from bagging (voting). I do not see a way to interpret boosting as "voting" (see my edit for additional details).
Voting (especially majority vote) usually means combined decis | Do boosting techniques use voting like any other ensemble method?
Boosting is different from bagging (voting). I do not see a way to interpret boosting as "voting" (see my edit for additional details).
Voting (especially majority vote) usually means combined decision from "separate / less correlated" week classifiers.
In boosting, we are building one classifier upon another. So, they are not "separate peers" but one is "less weaker than another".
My answers here gives boosting break down by iterations.
How does linear base leaner works in boosting? And how it works in xgboost library?
The example is trying to approximate a quadratic function by by boosting on decision stump.
First two plots are ground truth and boosting model after many iterations. They are contour plots. X and Y axis are two features and function value is represented by color.
Then I am showing first 4 iterations. You can see we are not averaging/voting 4 models, but enhance the model over each iterations.
After seeing another answer, I feel the answer to this question depends on how we define "voting". Do we consider weighted sum as voting ? If yes, then I think we still can say boosting can be generalized with voting. | Do boosting techniques use voting like any other ensemble method?
Boosting is different from bagging (voting). I do not see a way to interpret boosting as "voting" (see my edit for additional details).
Voting (especially majority vote) usually means combined decis |
31,460 | How can I highlight noisy patches in a time series? | For simplicity, I would suggest analyzing the sizes (absolute values) of the residuals relative to a robust smooth of the data. For automated detection, consider replacing those sizes by an indicator: 1 when they exceed some high quantile, say at level $1-\alpha$, and 0 otherwise. Smooth this indicator and highlight any smoothed values that exceed $\alpha$.
The graphic at left plots $1201$ data points in blue along with a robust, local smooth in black. The graphic at right shows the sizes of the residuals of that smooth. The black dotted line is their 80th percentile (corresponding to $\alpha=0.2$). The red curve is constructed as described above, but has been scaled (from values of $0$ and $1$) to the midrange of the absolute residuals for plotting.
Varying $\alpha$ allows control over the precision. In this instance, setting $\alpha$ less than $0.20$ identifies a short gap in the noise around 22 hours, while setting $\alpha$ greater than $0.20$ also picks up the rapid change near 0 hours.
The details of the smooth don't matter much. In this example a loess smooth (implemented in R as loess with span=0.05 to localize it) was used, but even a windowed mean would have done fine. To smooth the absolute residuals I ran a windowed mean of width 17 (about 24 minutes) followed by a windowed median. These windowed smooths are relatively easy to implement in Excel. An efficient VBA implementation (for older versions of Excel, but the source code ought to work even in new versions) is available at http://www.quantdec.com/Excel/smoothing.htm.
R Code
#
# Emulate the data in the plot.
#
xy <- matrix(c(0, 96.35, 0.3, 96.6, 0.7, 96.7, 1, 96.73, 1.5, 96.74, 2.5, 96.75,
4, 96.9, 5, 97.05, 7, 97.5, 10, 98.5, 12, 99.3, 12.5, 99.35,
13, 99.355, 13.5, 99.36, 14.5, 99.365, 15, 99.37, 15.5, 99.375,
15.6, 99.4, 15.7, 99.41, 20, 99.5, 25, 99.4, 27, 99.37),
ncol=2, byrow=TRUE)
n <- 401
set.seed(17)
noise.x <- cumsum(rexp(n, n/max(xy[,1])))
noise.y <- rep(c(-1,1), ceiling(n/2))[1:n]
noise.amp <- runif(n, 0.8, 1.2) * 0.04
noise.amp <- noise.amp * ifelse(noise.x < 16 | noise.x > 24.5, 0.05, 1)
noise.y <- noise.y * noise.amp
g <- approxfun(noise.x, noise.y)
f <- splinefun(xy[,1], xy[,2])
x <- seq(0, max(xy[,1]), length.out=1201)
y <- f(x) + g(x)
#
# Plot the data and a smooth.
#
par(mfrow=c(1,2))
plot(range(xy[,1]), range(xy[,2]), type="n", main="Data", sub="With Smooth",
xlab="Time (hours)", ylab="Water Level")
abline(h=seq(96, 100, by=0.5), col="#e0e0e0")
abline(v=seq(0, 30, by=5), col="#e0e0e0")
#curve(f(x) + g(x), xlim=range(xy[,1]), col="#2070c0", lwd=2, add=TRUE, n=1201)
lines(x,y, type="l", col="#2070c0", lwd=2)
span <- 0.05
fit <- loess(y ~ x, span=span)
y.hat <- predict(fit)
lines(fit$x, y.hat)
#
# Plot the absolute residuals to the smooth.
#
r <- abs(resid(fit))
plot(fit$x, r, type="l", col="#808080",
main="Absolute Residuals", sub="With Smooth and a Threshold",
xlab="Time hours", ylab="Residual Water Level")
#
# Smooth plot an indicator of the smoothed residuals.
#
library(zoo)
smooth <- function(x, window=17) {
x.1 <- rollapply(ts(x), window, mean)
x.2 <- rollapply(x.1, window, median)
return(as.vector(x.2))
}
alpha <- 0.2
threshold <- quantile(r, 1-alpha)
abline(h=threshold, lwd=2, lty=3)
r.hat <- smooth(r >threshold)
x.hat <- smooth(fit$x)
z <- max(r)/2 * (r.hat > alpha)
lines(x.hat, z, lwd=2, col="#c02020")
par(mfrow=c(1,1)) | How can I highlight noisy patches in a time series? | For simplicity, I would suggest analyzing the sizes (absolute values) of the residuals relative to a robust smooth of the data. For automated detection, consider replacing those sizes by an indicator | How can I highlight noisy patches in a time series?
For simplicity, I would suggest analyzing the sizes (absolute values) of the residuals relative to a robust smooth of the data. For automated detection, consider replacing those sizes by an indicator: 1 when they exceed some high quantile, say at level $1-\alpha$, and 0 otherwise. Smooth this indicator and highlight any smoothed values that exceed $\alpha$.
The graphic at left plots $1201$ data points in blue along with a robust, local smooth in black. The graphic at right shows the sizes of the residuals of that smooth. The black dotted line is their 80th percentile (corresponding to $\alpha=0.2$). The red curve is constructed as described above, but has been scaled (from values of $0$ and $1$) to the midrange of the absolute residuals for plotting.
Varying $\alpha$ allows control over the precision. In this instance, setting $\alpha$ less than $0.20$ identifies a short gap in the noise around 22 hours, while setting $\alpha$ greater than $0.20$ also picks up the rapid change near 0 hours.
The details of the smooth don't matter much. In this example a loess smooth (implemented in R as loess with span=0.05 to localize it) was used, but even a windowed mean would have done fine. To smooth the absolute residuals I ran a windowed mean of width 17 (about 24 minutes) followed by a windowed median. These windowed smooths are relatively easy to implement in Excel. An efficient VBA implementation (for older versions of Excel, but the source code ought to work even in new versions) is available at http://www.quantdec.com/Excel/smoothing.htm.
R Code
#
# Emulate the data in the plot.
#
xy <- matrix(c(0, 96.35, 0.3, 96.6, 0.7, 96.7, 1, 96.73, 1.5, 96.74, 2.5, 96.75,
4, 96.9, 5, 97.05, 7, 97.5, 10, 98.5, 12, 99.3, 12.5, 99.35,
13, 99.355, 13.5, 99.36, 14.5, 99.365, 15, 99.37, 15.5, 99.375,
15.6, 99.4, 15.7, 99.41, 20, 99.5, 25, 99.4, 27, 99.37),
ncol=2, byrow=TRUE)
n <- 401
set.seed(17)
noise.x <- cumsum(rexp(n, n/max(xy[,1])))
noise.y <- rep(c(-1,1), ceiling(n/2))[1:n]
noise.amp <- runif(n, 0.8, 1.2) * 0.04
noise.amp <- noise.amp * ifelse(noise.x < 16 | noise.x > 24.5, 0.05, 1)
noise.y <- noise.y * noise.amp
g <- approxfun(noise.x, noise.y)
f <- splinefun(xy[,1], xy[,2])
x <- seq(0, max(xy[,1]), length.out=1201)
y <- f(x) + g(x)
#
# Plot the data and a smooth.
#
par(mfrow=c(1,2))
plot(range(xy[,1]), range(xy[,2]), type="n", main="Data", sub="With Smooth",
xlab="Time (hours)", ylab="Water Level")
abline(h=seq(96, 100, by=0.5), col="#e0e0e0")
abline(v=seq(0, 30, by=5), col="#e0e0e0")
#curve(f(x) + g(x), xlim=range(xy[,1]), col="#2070c0", lwd=2, add=TRUE, n=1201)
lines(x,y, type="l", col="#2070c0", lwd=2)
span <- 0.05
fit <- loess(y ~ x, span=span)
y.hat <- predict(fit)
lines(fit$x, y.hat)
#
# Plot the absolute residuals to the smooth.
#
r <- abs(resid(fit))
plot(fit$x, r, type="l", col="#808080",
main="Absolute Residuals", sub="With Smooth and a Threshold",
xlab="Time hours", ylab="Residual Water Level")
#
# Smooth plot an indicator of the smoothed residuals.
#
library(zoo)
smooth <- function(x, window=17) {
x.1 <- rollapply(ts(x), window, mean)
x.2 <- rollapply(x.1, window, median)
return(as.vector(x.2))
}
alpha <- 0.2
threshold <- quantile(r, 1-alpha)
abline(h=threshold, lwd=2, lty=3)
r.hat <- smooth(r >threshold)
x.hat <- smooth(fit$x)
z <- max(r)/2 * (r.hat > alpha)
lines(x.hat, z, lwd=2, col="#c02020")
par(mfrow=c(1,1)) | How can I highlight noisy patches in a time series?
For simplicity, I would suggest analyzing the sizes (absolute values) of the residuals relative to a robust smooth of the data. For automated detection, consider replacing those sizes by an indicator |
31,461 | Is $E[E(X|Y)|Z] =E[X|Y,Z]$ If so, how to prove? | Those two conditional expectations differ in
general:$$\mathbb{E}[\mathbb{E}(X|Y)|Z] \ne\mathbb{E}[X|Y,Z]$$
As a matter of fact, strictly speaking, they do not even live in the same functional space as the first one is a function of $Z$, measurable wrt $\sigma(Z)$, the $\sigma$ algebra induced by $Z$, while the second one is a function of $(Y,Z)$, hence measurable wrt $\sigma(Y,Z)$, the $\sigma$ algebra induced by $(Y,Z)$,
As a counter-example, consider the setting when
$X$ and $Y$ are independent
$X$ and $Z$ are dependent, with $\mathbb{E}[X|Z]\ne \mathbb{E}[X]$
Then, because of the independence between $X$ and $Y$, $\mathbb{E}(X|Y)=\mathbb{E}[X]$ and therefore$$\mathbb{E}[\mathbb{E}(X|Y)|Z]= \mathbb{E}[X]\ne\mathbb{E}[X|Y,Z]$$
A valid equality is instead$$\mathbb{E}[\mathbb{E}(X|Y,Z)|Z]=\mathbb{E}[X|Z]$$that holds for all dependence relations between the three random variables.
Notations: The difference between the notations $\mathbb{E}[\mathbb{E}(X|Y)|Z]$ and $\mathbb{E}[\mathbb{E}(X|Y=y)|Z=z]$ is that
$\mathbb{E}[\mathbb{E}(X|Y)|Z]$ is a random variable, transform of the random variable $Z$ (and not of the random variable $Y$ since $Y$Y is also conditioned on $Z$);
$\mathbb{E}[\mathbb{E}(X|Y=y)|Z=z]$ is a function of apparently both $y$ and $z$, but in fact only of $y$ (as explained below) which has no clear meaning from a probabilistic point of view. Indeed, for a given value $y$, $\mathbb{E}(X|Y=y)$ is a constant for which taking a conditional expectation conditional on the realisation $Z=z$ makes little sense as it also returns $\mathbb{E}(X|Y=y)$. For instance, if $X$ depends on both $Y$ and $X$ as a random variable, for a given realisation $y$ of $Y$ and $Z$ of $z$, $\mathbb{E}(X|Y=y)$ is a constant that generally differs from $\mathbb{E}(X)$ and from $\mathbb{E}(X|Y=y,Z=z)$. But $\mathbb{E}[\mathbb{E}(X|Y=y)|Z=z]$ is not a realisation of the random variable $\mathbb{E}[\mathbb{E}(X|Y)|Z]$. The correct realisation is $\mathbb{E}[\mathbb{E}(X|Y)|Z=z]$ | Is $E[E(X|Y)|Z] =E[X|Y,Z]$ If so, how to prove? | Those two conditional expectations differ in
general:$$\mathbb{E}[\mathbb{E}(X|Y)|Z] \ne\mathbb{E}[X|Y,Z]$$
As a matter of fact, strictly speaking, they do not even live in the same functional spac | Is $E[E(X|Y)|Z] =E[X|Y,Z]$ If so, how to prove?
Those two conditional expectations differ in
general:$$\mathbb{E}[\mathbb{E}(X|Y)|Z] \ne\mathbb{E}[X|Y,Z]$$
As a matter of fact, strictly speaking, they do not even live in the same functional space as the first one is a function of $Z$, measurable wrt $\sigma(Z)$, the $\sigma$ algebra induced by $Z$, while the second one is a function of $(Y,Z)$, hence measurable wrt $\sigma(Y,Z)$, the $\sigma$ algebra induced by $(Y,Z)$,
As a counter-example, consider the setting when
$X$ and $Y$ are independent
$X$ and $Z$ are dependent, with $\mathbb{E}[X|Z]\ne \mathbb{E}[X]$
Then, because of the independence between $X$ and $Y$, $\mathbb{E}(X|Y)=\mathbb{E}[X]$ and therefore$$\mathbb{E}[\mathbb{E}(X|Y)|Z]= \mathbb{E}[X]\ne\mathbb{E}[X|Y,Z]$$
A valid equality is instead$$\mathbb{E}[\mathbb{E}(X|Y,Z)|Z]=\mathbb{E}[X|Z]$$that holds for all dependence relations between the three random variables.
Notations: The difference between the notations $\mathbb{E}[\mathbb{E}(X|Y)|Z]$ and $\mathbb{E}[\mathbb{E}(X|Y=y)|Z=z]$ is that
$\mathbb{E}[\mathbb{E}(X|Y)|Z]$ is a random variable, transform of the random variable $Z$ (and not of the random variable $Y$ since $Y$Y is also conditioned on $Z$);
$\mathbb{E}[\mathbb{E}(X|Y=y)|Z=z]$ is a function of apparently both $y$ and $z$, but in fact only of $y$ (as explained below) which has no clear meaning from a probabilistic point of view. Indeed, for a given value $y$, $\mathbb{E}(X|Y=y)$ is a constant for which taking a conditional expectation conditional on the realisation $Z=z$ makes little sense as it also returns $\mathbb{E}(X|Y=y)$. For instance, if $X$ depends on both $Y$ and $X$ as a random variable, for a given realisation $y$ of $Y$ and $Z$ of $z$, $\mathbb{E}(X|Y=y)$ is a constant that generally differs from $\mathbb{E}(X)$ and from $\mathbb{E}(X|Y=y,Z=z)$. But $\mathbb{E}[\mathbb{E}(X|Y=y)|Z=z]$ is not a realisation of the random variable $\mathbb{E}[\mathbb{E}(X|Y)|Z]$. The correct realisation is $\mathbb{E}[\mathbb{E}(X|Y)|Z=z]$ | Is $E[E(X|Y)|Z] =E[X|Y,Z]$ If so, how to prove?
Those two conditional expectations differ in
general:$$\mathbb{E}[\mathbb{E}(X|Y)|Z] \ne\mathbb{E}[X|Y,Z]$$
As a matter of fact, strictly speaking, they do not even live in the same functional spac |
31,462 | What happens when merging random variables in Dirichlet distribution? | It is a Dirichlet distribution having the expected parameters.
To see this, note that the vector-valued random variable $\mathbf{X}=(X_1, X_2, \ldots, X_k)$ has the same distribution as the variable
$$\frac{1}{\sum_i^k Y_i}\left(Y_1, Y_2, \ldots, Y_k\right)$$
where $Y_i \sim \Gamma(\alpha_i)$ are independently Gamma distributed. Write $Y_i^\prime=Y_i$ for $i=1, 2, \ldots, k-2$ and $Y_{k-1}^\prime = Y_{k-1}+Y_k$. The sum of all the $Y_i$ equals the sum of all the $Y_i^\prime$ and the distribution of $Y_{k-1}^\prime=Y_{k-1}+Y_k$ is $\Gamma(\alpha_{k-1}+ \alpha_k)$. Thus
$$X_{k-1} + X_k = \frac{1}{\sum_i^k Y_i} Y_{k-1} + \frac{1}{\sum_i^k Y_i} Y_{k} = \frac{1}{\sum_i^{k-1} Y_i^\prime} Y_{k-1}^\prime$$
and, for $i < k-1$,
$$X_i = \frac{1}{\sum_i^k Y_i} Y_{k-1} = \frac{1}{\sum_i^{k-1} Y_i^\prime} Y_{k-1}^\prime.$$
Therefore $\mathbf{X}^\prime=(X_1, X_2, \ldots, X_{k-2}, X_{k-1}+X_k)$ has the same distribution as
$$\frac{1}{\sum_i^{k-1} Y_i^\prime}\left(Y_1^\prime, Y_2^\prime, \ldots, Y_k^\prime\right).$$
This demonstrates that $\mathbf{X}^\prime$ has a Dirichlet$(\alpha_1, \alpha_2, \ldots, \alpha_{k-2}, \alpha_{k-1}+\alpha_k)$ distribution, QED.
The fault in the argument in the question lies in confusing the arithmetic sum of values $x_{k-1}+x_k$ with the sum of random variables $X_{k-1}+X_k$. The latter is performed with a convolution, of course. | What happens when merging random variables in Dirichlet distribution? | It is a Dirichlet distribution having the expected parameters.
To see this, note that the vector-valued random variable $\mathbf{X}=(X_1, X_2, \ldots, X_k)$ has the same distribution as the variable
$ | What happens when merging random variables in Dirichlet distribution?
It is a Dirichlet distribution having the expected parameters.
To see this, note that the vector-valued random variable $\mathbf{X}=(X_1, X_2, \ldots, X_k)$ has the same distribution as the variable
$$\frac{1}{\sum_i^k Y_i}\left(Y_1, Y_2, \ldots, Y_k\right)$$
where $Y_i \sim \Gamma(\alpha_i)$ are independently Gamma distributed. Write $Y_i^\prime=Y_i$ for $i=1, 2, \ldots, k-2$ and $Y_{k-1}^\prime = Y_{k-1}+Y_k$. The sum of all the $Y_i$ equals the sum of all the $Y_i^\prime$ and the distribution of $Y_{k-1}^\prime=Y_{k-1}+Y_k$ is $\Gamma(\alpha_{k-1}+ \alpha_k)$. Thus
$$X_{k-1} + X_k = \frac{1}{\sum_i^k Y_i} Y_{k-1} + \frac{1}{\sum_i^k Y_i} Y_{k} = \frac{1}{\sum_i^{k-1} Y_i^\prime} Y_{k-1}^\prime$$
and, for $i < k-1$,
$$X_i = \frac{1}{\sum_i^k Y_i} Y_{k-1} = \frac{1}{\sum_i^{k-1} Y_i^\prime} Y_{k-1}^\prime.$$
Therefore $\mathbf{X}^\prime=(X_1, X_2, \ldots, X_{k-2}, X_{k-1}+X_k)$ has the same distribution as
$$\frac{1}{\sum_i^{k-1} Y_i^\prime}\left(Y_1^\prime, Y_2^\prime, \ldots, Y_k^\prime\right).$$
This demonstrates that $\mathbf{X}^\prime$ has a Dirichlet$(\alpha_1, \alpha_2, \ldots, \alpha_{k-2}, \alpha_{k-1}+\alpha_k)$ distribution, QED.
The fault in the argument in the question lies in confusing the arithmetic sum of values $x_{k-1}+x_k$ with the sum of random variables $X_{k-1}+X_k$. The latter is performed with a convolution, of course. | What happens when merging random variables in Dirichlet distribution?
It is a Dirichlet distribution having the expected parameters.
To see this, note that the vector-valued random variable $\mathbf{X}=(X_1, X_2, \ldots, X_k)$ has the same distribution as the variable
$ |
31,463 | What happens when merging random variables in Dirichlet distribution? | Like I mentioned in the comments, all I am trying suggests that what you are suggesting actually does work.
As you mentioned, intuitively it makes sense if this would work, if $X_i$ represents the posterior draw for some probability $p_i$ for event $i$ happening, you should indeed be able to sum multiple $X_i$ to get the probability of multiple events $i$, if there is no possibility of both events happening at the same time. Since this is a multinomial setting, this is not the case, so we're good.
So let's show my simulations:
library('gtools')
K <- 10
alpha <- c(rpois(K, 50)) #randomly generated alphas, just cause
k <- 2 # the number of alphas we are summing together
sim <- rdirichlet(10000, alpha)
plot(density(rowSums(sim[, 1:k]))) # the density of the summed variable
lines(density(rdirichlet(10000, c(sum(alpha[1:k]), alpha[-(1:k)]))[,1]), col = 'blue')
# the density of the variable drawn from the Dirichlet distribution with summed alphas
Let's start with $\alpha = \{10, 10, 10\}$. Summing $\alpha_1$ and $\alpha_2$ should get us $Dir(2, \{20, 10\})$:
These marginal densities look pretty similar. According to wikipedia and this random lecture I found on the internet (through wikipedia), the marginal distribution of $X_i$ to the Dirichlet distribution is as follows:
$$X_i = Beta(\alpha_i, \sum_{k=1}^K\left[\alpha_k\right] - \alpha_i)$$
This relies on actually the same principle: summing all the $\alpha$ that are not $\alpha_i$ together, turning the corresponding multinomial to a binomial distributions with the outcomes $i$ and $not\textrm{-}i$. And indeed, if we fit the marginal distribution we would expect from the sum over the density in the previous picture, we see that it looks the same:
So theoretically, we should be able to take a Dirichlet distribution with a high $K$, sum all but one together and end up with a Beta distribution. Heck, let's try:
(99 times $\alpha \sim Pois(50)$ and 1 $\alpha = 1000$, summing together the random $\alpha\mathrm{s}$.)
To show that it also works for the joint densities, this is an example with $K=4$ and $\alpha = \{10,10,10,10\}$:
And this is with $K=3$ and $\alpha=\{20,10,10\}$:
$$\ddot{\smile}$$
So where does the confusion about $x_1^{\alpha_1-1}x_2^{\alpha_2-1}\neq (x_1 + x_2)^{\alpha_1+\alpha_2 -1 }$ come from?
Because when we sum $x_1$ and $x_2$ together, we don't just care about the density at $x_1$ and $x_2$, but for any combination of two $x$ that sums to $x_1+x_2$. I am not that strong in integration, so I'll not try and burn myself with that, but I really suggest reading this (page 3-4) for more information.
EDIT:
As @whuber correctly remarked, here is an example with low alphas, $K=4$, summing the first two $X_1$ and $X_2$: | What happens when merging random variables in Dirichlet distribution? | Like I mentioned in the comments, all I am trying suggests that what you are suggesting actually does work.
As you mentioned, intuitively it makes sense if this would work, if $X_i$ represents the pos | What happens when merging random variables in Dirichlet distribution?
Like I mentioned in the comments, all I am trying suggests that what you are suggesting actually does work.
As you mentioned, intuitively it makes sense if this would work, if $X_i$ represents the posterior draw for some probability $p_i$ for event $i$ happening, you should indeed be able to sum multiple $X_i$ to get the probability of multiple events $i$, if there is no possibility of both events happening at the same time. Since this is a multinomial setting, this is not the case, so we're good.
So let's show my simulations:
library('gtools')
K <- 10
alpha <- c(rpois(K, 50)) #randomly generated alphas, just cause
k <- 2 # the number of alphas we are summing together
sim <- rdirichlet(10000, alpha)
plot(density(rowSums(sim[, 1:k]))) # the density of the summed variable
lines(density(rdirichlet(10000, c(sum(alpha[1:k]), alpha[-(1:k)]))[,1]), col = 'blue')
# the density of the variable drawn from the Dirichlet distribution with summed alphas
Let's start with $\alpha = \{10, 10, 10\}$. Summing $\alpha_1$ and $\alpha_2$ should get us $Dir(2, \{20, 10\})$:
These marginal densities look pretty similar. According to wikipedia and this random lecture I found on the internet (through wikipedia), the marginal distribution of $X_i$ to the Dirichlet distribution is as follows:
$$X_i = Beta(\alpha_i, \sum_{k=1}^K\left[\alpha_k\right] - \alpha_i)$$
This relies on actually the same principle: summing all the $\alpha$ that are not $\alpha_i$ together, turning the corresponding multinomial to a binomial distributions with the outcomes $i$ and $not\textrm{-}i$. And indeed, if we fit the marginal distribution we would expect from the sum over the density in the previous picture, we see that it looks the same:
So theoretically, we should be able to take a Dirichlet distribution with a high $K$, sum all but one together and end up with a Beta distribution. Heck, let's try:
(99 times $\alpha \sim Pois(50)$ and 1 $\alpha = 1000$, summing together the random $\alpha\mathrm{s}$.)
To show that it also works for the joint densities, this is an example with $K=4$ and $\alpha = \{10,10,10,10\}$:
And this is with $K=3$ and $\alpha=\{20,10,10\}$:
$$\ddot{\smile}$$
So where does the confusion about $x_1^{\alpha_1-1}x_2^{\alpha_2-1}\neq (x_1 + x_2)^{\alpha_1+\alpha_2 -1 }$ come from?
Because when we sum $x_1$ and $x_2$ together, we don't just care about the density at $x_1$ and $x_2$, but for any combination of two $x$ that sums to $x_1+x_2$. I am not that strong in integration, so I'll not try and burn myself with that, but I really suggest reading this (page 3-4) for more information.
EDIT:
As @whuber correctly remarked, here is an example with low alphas, $K=4$, summing the first two $X_1$ and $X_2$: | What happens when merging random variables in Dirichlet distribution?
Like I mentioned in the comments, all I am trying suggests that what you are suggesting actually does work.
As you mentioned, intuitively it makes sense if this would work, if $X_i$ represents the pos |
31,464 | Why is cv.glmnet returning absurd coefficients when intercept term is omitted? | I can explain what you're seeing but not necessarily why it is the way it is. glmnet is starting the no-intercept solution at a much higher initial regularization penalty $\lambda_{max}$ than the with-intercept solution, and then hitting an early-stop in the path before it can explore better solutions.
How $\lambda_{max}$ is chosen
For $0 \lt \alpha \leq 1$, $\lambda_{max}$ is chosen as the highest value of $\lambda$ that still produces one nonzero coefficient (other than the intercept, which is not regularised). Ridge pushes coefficients asymptotically towards zero, whereas LASSO can entirely zero out coefficients. As $\alpha \rightarrow 0$, the LASSO contribution diminishes and the $\lambda$ value that results in exactly one nonzero coefficient gets higher and higher.
For $\alpha = 0$ or L2 regularization, coefficients are never regularized all the way to zero, even as $\lambda \rightarrow \infty$. How glmnet chooses $\lambda_{max}$ here is hard to glean from the source code or paper, but it seems like it sets $\alpha$ to a very small positive number and finds $\lambda_{max}$ the conventional way. $\alpha=0$ has a $\lambda_{max}$ of 120,761.2, the same value as for $\alpha=0.001$.
How the full $\lambda$ vector is chosen
Usually the minimum lambda $\lambda_{min}$ is chosen as $0.001 * \lambda_{max}$ and the algorithm searches 100 evenly-spaced-on-the-log-scale points between $\lambda_{min}$ and $\lambda_{max}$. For some reason, the no-intercept model stops after only 31 values. I have no idea why this is. glmnet will early stop searching the $\lambda$ vector early if the most recently fit $\lambda$ doesn't significantly improve training deviance, but this is not the case for your example. The source code is a complete black box. Who knows what's happening.
Why no-intercept has a higher $\lambda_{max}$
Since the intercept is regularization-free, it's a no-cost way for the model to fit the data. An intercept leaves the coefficients with less work to do, as the no-coefficient model has much lower error than it would without an intercept. $\lambda_{max}$ for the with-intercept model is much lower, at 8496.6. It searches as far as 0.8497 and finds good solutions along the way. The no-intercept model searches from 120761.2 to 7409.8, barely grazing the top of the with-intercept model's $\lambda$ path.
How to get a better set of solutions
If you just transplant the with-intercept $\lambda$ path into the no-intercept model, you get much better solutions.
cv.ridge.wi = cv.glmnet(x, y, alpha = 0, intercept = TRUE)
cv.ridge.ni = cv.glmnet(x, y, alpha = 0, intercept = FALSE, lambda = cv.ridge.wi$lambda)
plot(cv.ridge.ni)
Why coef(cv.ridge) returns very small numbers
coef on a cv.glmnet by default targets the s = "lambda.1se" heuristic, described in the docs. Since the no-intercept model searches 31 $\lambda$ and their error is very flat, $\lambda_{1se}$ is $\lambda_{max}$. You can see this from plot(cv.ridge). The with-intercept model's $\lambda_{1se}$ is much lower and the coefficients are more developed.
Will edit in some images later. | Why is cv.glmnet returning absurd coefficients when intercept term is omitted? | I can explain what you're seeing but not necessarily why it is the way it is. glmnet is starting the no-intercept solution at a much higher initial regularization penalty $\lambda_{max}$ than the with | Why is cv.glmnet returning absurd coefficients when intercept term is omitted?
I can explain what you're seeing but not necessarily why it is the way it is. glmnet is starting the no-intercept solution at a much higher initial regularization penalty $\lambda_{max}$ than the with-intercept solution, and then hitting an early-stop in the path before it can explore better solutions.
How $\lambda_{max}$ is chosen
For $0 \lt \alpha \leq 1$, $\lambda_{max}$ is chosen as the highest value of $\lambda$ that still produces one nonzero coefficient (other than the intercept, which is not regularised). Ridge pushes coefficients asymptotically towards zero, whereas LASSO can entirely zero out coefficients. As $\alpha \rightarrow 0$, the LASSO contribution diminishes and the $\lambda$ value that results in exactly one nonzero coefficient gets higher and higher.
For $\alpha = 0$ or L2 regularization, coefficients are never regularized all the way to zero, even as $\lambda \rightarrow \infty$. How glmnet chooses $\lambda_{max}$ here is hard to glean from the source code or paper, but it seems like it sets $\alpha$ to a very small positive number and finds $\lambda_{max}$ the conventional way. $\alpha=0$ has a $\lambda_{max}$ of 120,761.2, the same value as for $\alpha=0.001$.
How the full $\lambda$ vector is chosen
Usually the minimum lambda $\lambda_{min}$ is chosen as $0.001 * \lambda_{max}$ and the algorithm searches 100 evenly-spaced-on-the-log-scale points between $\lambda_{min}$ and $\lambda_{max}$. For some reason, the no-intercept model stops after only 31 values. I have no idea why this is. glmnet will early stop searching the $\lambda$ vector early if the most recently fit $\lambda$ doesn't significantly improve training deviance, but this is not the case for your example. The source code is a complete black box. Who knows what's happening.
Why no-intercept has a higher $\lambda_{max}$
Since the intercept is regularization-free, it's a no-cost way for the model to fit the data. An intercept leaves the coefficients with less work to do, as the no-coefficient model has much lower error than it would without an intercept. $\lambda_{max}$ for the with-intercept model is much lower, at 8496.6. It searches as far as 0.8497 and finds good solutions along the way. The no-intercept model searches from 120761.2 to 7409.8, barely grazing the top of the with-intercept model's $\lambda$ path.
How to get a better set of solutions
If you just transplant the with-intercept $\lambda$ path into the no-intercept model, you get much better solutions.
cv.ridge.wi = cv.glmnet(x, y, alpha = 0, intercept = TRUE)
cv.ridge.ni = cv.glmnet(x, y, alpha = 0, intercept = FALSE, lambda = cv.ridge.wi$lambda)
plot(cv.ridge.ni)
Why coef(cv.ridge) returns very small numbers
coef on a cv.glmnet by default targets the s = "lambda.1se" heuristic, described in the docs. Since the no-intercept model searches 31 $\lambda$ and their error is very flat, $\lambda_{1se}$ is $\lambda_{max}$. You can see this from plot(cv.ridge). The with-intercept model's $\lambda_{1se}$ is much lower and the coefficients are more developed.
Will edit in some images later. | Why is cv.glmnet returning absurd coefficients when intercept term is omitted?
I can explain what you're seeing but not necessarily why it is the way it is. glmnet is starting the no-intercept solution at a much higher initial regularization penalty $\lambda_{max}$ than the with |
31,465 | Why is cv.glmnet returning absurd coefficients when intercept term is omitted? | I'll begin by stating this is not the answer to this problem, however I was having a similar problem and have identified the cause in my case which may help someone looking here in the future if they happened to make the same mistake as me.
I was fitting the LASSO to a reasonably large training set (p = 20, n = 100000) and knew there was a relationship between the majority of features and the response, with some level of collinearity. The optimal fit selected by lambda.1se had all zero coefficients which seemed odd given my knowledge of the relationships in play.
The LASSO model was fit using cv.glmnet with alpha = 1.
Plotting the MSE using plot(fit_object) showed lambda.min as the smallest lamdbda and lambda.1se as the largest, with all other values in between the two, the error bars at each point were large.
the model using lambda.min had all coefficients as zero apart from 3 and the intercept
the model using lambda.1se had all coefficients as zero apart from the intercept
There were some massive outliers in my response variable due to having missed a step in my initial cleansing. This resulted in very little difference between MSE across all values of lambda and a large overall level of MSE. The outliers were a number of magnitudes higher and few in value. | Why is cv.glmnet returning absurd coefficients when intercept term is omitted? | I'll begin by stating this is not the answer to this problem, however I was having a similar problem and have identified the cause in my case which may help someone looking here in the future if they | Why is cv.glmnet returning absurd coefficients when intercept term is omitted?
I'll begin by stating this is not the answer to this problem, however I was having a similar problem and have identified the cause in my case which may help someone looking here in the future if they happened to make the same mistake as me.
I was fitting the LASSO to a reasonably large training set (p = 20, n = 100000) and knew there was a relationship between the majority of features and the response, with some level of collinearity. The optimal fit selected by lambda.1se had all zero coefficients which seemed odd given my knowledge of the relationships in play.
The LASSO model was fit using cv.glmnet with alpha = 1.
Plotting the MSE using plot(fit_object) showed lambda.min as the smallest lamdbda and lambda.1se as the largest, with all other values in between the two, the error bars at each point were large.
the model using lambda.min had all coefficients as zero apart from 3 and the intercept
the model using lambda.1se had all coefficients as zero apart from the intercept
There were some massive outliers in my response variable due to having missed a step in my initial cleansing. This resulted in very little difference between MSE across all values of lambda and a large overall level of MSE. The outliers were a number of magnitudes higher and few in value. | Why is cv.glmnet returning absurd coefficients when intercept term is omitted?
I'll begin by stating this is not the answer to this problem, however I was having a similar problem and have identified the cause in my case which may help someone looking here in the future if they |
31,466 | What is Epsilon Convergence in Probability? | Since we're talking about convergence - specifically, in this case, $X_n$ converging to $X_\infty$ - we want to show that $X_n$ gets really, really, really close to $X_\infty$ as $n$ gets larger and larger.
Think of $\varepsilon$ as any really small positive number; say you think $\varepsilon = 0.01$ is good enough. Then in order to show that $X_n$ is really, really, really close to $X_\infty$, we want to show that $X_n$ falls inside $(X_\infty-0.01,X_\infty+0.01)$ for sufficiently large $n$. (Sufficiently large $n$ just means that there is some $n'$ such that for every $n > n'$, $X_n$ is within plus or minus $0.01$ of $X_\infty$ with probability 1.)
But say that I'm not convinced that $X_n$ converges to $X_\infty$ because $\varepsilon=0.01$ just seems too big for me. So instead, let $\varepsilon = 0.0001$. Then I'm convinced that $X_n$ converges to $X_\infty$ (or that $X_n$ is really, really, really close to $X_\infty$) if we can show that, for sufficiently large $n$, $X_n$ falls inside $(X_\infty-0.0001,X_\infty+0.0001)$.
Suppose you have a lot of friends who pick $\varepsilon$ to be smaller and smaller. The idea behind convergence is that for any $\varepsilon > 0$, no matter how small $\varepsilon$ gets, showing that $X_n$ falls inside $X_\infty\pm\varepsilon$ for sufficiently large $n$ demonstrates that $X_n$ converges to $X_\infty$.
In the most basic terms, $\varepsilon$ is just a small positive number. As it relates to convergence, you want to be able to show that for any $\varepsilon > 0$ (so that all of your infinite friends with different $\varepsilon$ values are convinced), the sequence that converges will, at some point, get within plus or minus $\varepsilon$ of the limit to which you believe the sequence converges. If you cannot show that your sequence falls within $\varepsilon$ of the believed limit for some $\varepsilon$, then the sequence cannot converge to that limit. | What is Epsilon Convergence in Probability? | Since we're talking about convergence - specifically, in this case, $X_n$ converging to $X_\infty$ - we want to show that $X_n$ gets really, really, really close to $X_\infty$ as $n$ gets larger and l | What is Epsilon Convergence in Probability?
Since we're talking about convergence - specifically, in this case, $X_n$ converging to $X_\infty$ - we want to show that $X_n$ gets really, really, really close to $X_\infty$ as $n$ gets larger and larger.
Think of $\varepsilon$ as any really small positive number; say you think $\varepsilon = 0.01$ is good enough. Then in order to show that $X_n$ is really, really, really close to $X_\infty$, we want to show that $X_n$ falls inside $(X_\infty-0.01,X_\infty+0.01)$ for sufficiently large $n$. (Sufficiently large $n$ just means that there is some $n'$ such that for every $n > n'$, $X_n$ is within plus or minus $0.01$ of $X_\infty$ with probability 1.)
But say that I'm not convinced that $X_n$ converges to $X_\infty$ because $\varepsilon=0.01$ just seems too big for me. So instead, let $\varepsilon = 0.0001$. Then I'm convinced that $X_n$ converges to $X_\infty$ (or that $X_n$ is really, really, really close to $X_\infty$) if we can show that, for sufficiently large $n$, $X_n$ falls inside $(X_\infty-0.0001,X_\infty+0.0001)$.
Suppose you have a lot of friends who pick $\varepsilon$ to be smaller and smaller. The idea behind convergence is that for any $\varepsilon > 0$, no matter how small $\varepsilon$ gets, showing that $X_n$ falls inside $X_\infty\pm\varepsilon$ for sufficiently large $n$ demonstrates that $X_n$ converges to $X_\infty$.
In the most basic terms, $\varepsilon$ is just a small positive number. As it relates to convergence, you want to be able to show that for any $\varepsilon > 0$ (so that all of your infinite friends with different $\varepsilon$ values are convinced), the sequence that converges will, at some point, get within plus or minus $\varepsilon$ of the limit to which you believe the sequence converges. If you cannot show that your sequence falls within $\varepsilon$ of the believed limit for some $\varepsilon$, then the sequence cannot converge to that limit. | What is Epsilon Convergence in Probability?
Since we're talking about convergence - specifically, in this case, $X_n$ converging to $X_\infty$ - we want to show that $X_n$ gets really, really, really close to $X_\infty$ as $n$ gets larger and l |
31,467 | What is Epsilon Convergence in Probability? | Sequences of random variables.
Intuition comes from metaphors. The following metaphor, which models random quantities by pulling slips of paper out of a container, captures all the essential mathematical elements while glossing over a technical condition ("measurability") needed to make sense of situations with uncountably many tickets.
Consider a tickets-in-a-box model of a sample space $\Omega$: the name of each element $\omega\in\Omega$ is written on a slip of paper (a "ticket") which is put into the box. Elements with greater probability are named on more tickets.
A random variable $X$ is a consistent way of writing a number on each ticket. "Consistent" means that all the tickets for any particular $\omega$ all get the same value of $X$, written $X(\omega)$.
A sequence of random variables $X_1, X_2, \ldots, X_n, \ldots$ therefore can be conceived of as a sequence $X_1(\omega), X_2(\omega),\ldots$ written on each ticket (again in a consistent way).
$X_\infty$ is another random variable, which is one more number written on each ticket.
Events and probability.
Let $\epsilon$ be any real number. We will say more about it below.
The event $|X_n - X_\infty| \ge \epsilon$ describes all the tickets $\omega\in\Omega$ for which the values $X_n(\omega)$ and $X_\infty(\omega)$ differ by $\epsilon$ or more. It's a subset of the tickets in the box. These tickets form some proportion of the box: that proportion models their probability, $\Pr\left(|X_n - X_\infty| \ge \epsilon\right)$.
Limits.
Every assertion about a limit is a form of mathematical game. When we write that some sequence has a limit $L$, what we mean is we can play a game against a hypothetical opponent (who is doing their best to make us lose) and we will always win. In the limit game, your opponent names some positive number--usually a tiny one--which we will call $\delta$. You win if you can remove a finite number of elements from that sequence and show that all the remaining elements are within a distance $\delta$ of $L$. As in any game, you may calibrate your response to your opponent's move: the elements you remove are allowed to depend on $\delta$.
Limits in probability.
Let's apply the limit game to the assertion $\Pr\left(|X_n - X_\infty| \ge \epsilon\right)\to 0$. Because this assertion involves an unspecified quantity $\epsilon$, your opponent may also specify its value. That makes the game as difficult as possible for you to win.
So, no matter what values of $\epsilon$ and $\delta \gt 0$ your opponent specifies, your response will be to cross out some finite number of the random variables $X_i$ on the tickets. For every remaining random variable $X_n$, let the tickets where $X_n(\omega)$ differs from $X_\infty(\omega)$ by $\epsilon$ or more be the "bad" ones for $n$. You win the game provided the proportions of bad tickets are always less than $\delta$ (for all the $X_n$ that remain).
A little thought reveals the subtlety of this game: the bad tickets for $n$ do not have to have any relationship to the bad tickets for $m$ (where $n$ and $m$ designate any of the remaining random variables you didn't cross out). In other words, on any given ticket the values $X_n(\omega)$ can bounce all over the place. The limit in probability is a statement about what's written on all the tickets in the box but it is not a statement about what might be written on any individual ticket. | What is Epsilon Convergence in Probability? | Sequences of random variables.
Intuition comes from metaphors. The following metaphor, which models random quantities by pulling slips of paper out of a container, captures all the essential mathemat | What is Epsilon Convergence in Probability?
Sequences of random variables.
Intuition comes from metaphors. The following metaphor, which models random quantities by pulling slips of paper out of a container, captures all the essential mathematical elements while glossing over a technical condition ("measurability") needed to make sense of situations with uncountably many tickets.
Consider a tickets-in-a-box model of a sample space $\Omega$: the name of each element $\omega\in\Omega$ is written on a slip of paper (a "ticket") which is put into the box. Elements with greater probability are named on more tickets.
A random variable $X$ is a consistent way of writing a number on each ticket. "Consistent" means that all the tickets for any particular $\omega$ all get the same value of $X$, written $X(\omega)$.
A sequence of random variables $X_1, X_2, \ldots, X_n, \ldots$ therefore can be conceived of as a sequence $X_1(\omega), X_2(\omega),\ldots$ written on each ticket (again in a consistent way).
$X_\infty$ is another random variable, which is one more number written on each ticket.
Events and probability.
Let $\epsilon$ be any real number. We will say more about it below.
The event $|X_n - X_\infty| \ge \epsilon$ describes all the tickets $\omega\in\Omega$ for which the values $X_n(\omega)$ and $X_\infty(\omega)$ differ by $\epsilon$ or more. It's a subset of the tickets in the box. These tickets form some proportion of the box: that proportion models their probability, $\Pr\left(|X_n - X_\infty| \ge \epsilon\right)$.
Limits.
Every assertion about a limit is a form of mathematical game. When we write that some sequence has a limit $L$, what we mean is we can play a game against a hypothetical opponent (who is doing their best to make us lose) and we will always win. In the limit game, your opponent names some positive number--usually a tiny one--which we will call $\delta$. You win if you can remove a finite number of elements from that sequence and show that all the remaining elements are within a distance $\delta$ of $L$. As in any game, you may calibrate your response to your opponent's move: the elements you remove are allowed to depend on $\delta$.
Limits in probability.
Let's apply the limit game to the assertion $\Pr\left(|X_n - X_\infty| \ge \epsilon\right)\to 0$. Because this assertion involves an unspecified quantity $\epsilon$, your opponent may also specify its value. That makes the game as difficult as possible for you to win.
So, no matter what values of $\epsilon$ and $\delta \gt 0$ your opponent specifies, your response will be to cross out some finite number of the random variables $X_i$ on the tickets. For every remaining random variable $X_n$, let the tickets where $X_n(\omega)$ differs from $X_\infty(\omega)$ by $\epsilon$ or more be the "bad" ones for $n$. You win the game provided the proportions of bad tickets are always less than $\delta$ (for all the $X_n$ that remain).
A little thought reveals the subtlety of this game: the bad tickets for $n$ do not have to have any relationship to the bad tickets for $m$ (where $n$ and $m$ designate any of the remaining random variables you didn't cross out). In other words, on any given ticket the values $X_n(\omega)$ can bounce all over the place. The limit in probability is a statement about what's written on all the tickets in the box but it is not a statement about what might be written on any individual ticket. | What is Epsilon Convergence in Probability?
Sequences of random variables.
Intuition comes from metaphors. The following metaphor, which models random quantities by pulling slips of paper out of a container, captures all the essential mathemat |
31,468 | What does mAP mean? [closed] | mAP probably stands for mean Average Precision. The AP provides a measure of quality across all recall levels for single class classification, it can be seen as the area under the precision-recall curve. Then the mAP is the mean of APs in multi-class classification. | What does mAP mean? [closed] | mAP probably stands for mean Average Precision. The AP provides a measure of quality across all recall levels for single class classification, it can be seen as the area under the precision-recall cur | What does mAP mean? [closed]
mAP probably stands for mean Average Precision. The AP provides a measure of quality across all recall levels for single class classification, it can be seen as the area under the precision-recall curve. Then the mAP is the mean of APs in multi-class classification. | What does mAP mean? [closed]
mAP probably stands for mean Average Precision. The AP provides a measure of quality across all recall levels for single class classification, it can be seen as the area under the precision-recall cur |
31,469 | R: Box-plot on log scale vs. log-transforming *then* creating box-plot: Don't get same result | Obviously, the box with the median "belt" looks the same. The difference are the whiskers. In the default settings, ?boxplot tells us that
If ‘range’ is positive, the whiskers extend to the most extreme data point which is no more than ‘range’ times the interquartile range from the box.
range is positive, namely 1.5 in the default. So do the whiskers extend 1.5 times the box, but in which scale? If you call boxplot(data, log="y"), it is 1.5 on the unscaled data; thus the lower whisker becomes longer. If you call boxplot(log(data)) the whiskers are necessarily symmetric. | R: Box-plot on log scale vs. log-transforming *then* creating box-plot: Don't get same result | Obviously, the box with the median "belt" looks the same. The difference are the whiskers. In the default settings, ?boxplot tells us that
If ‘range’ is positive, the whiskers extend to the most extr | R: Box-plot on log scale vs. log-transforming *then* creating box-plot: Don't get same result
Obviously, the box with the median "belt" looks the same. The difference are the whiskers. In the default settings, ?boxplot tells us that
If ‘range’ is positive, the whiskers extend to the most extreme data point which is no more than ‘range’ times the interquartile range from the box.
range is positive, namely 1.5 in the default. So do the whiskers extend 1.5 times the box, but in which scale? If you call boxplot(data, log="y"), it is 1.5 on the unscaled data; thus the lower whisker becomes longer. If you call boxplot(log(data)) the whiskers are necessarily symmetric. | R: Box-plot on log scale vs. log-transforming *then* creating box-plot: Don't get same result
Obviously, the box with the median "belt" looks the same. The difference are the whiskers. In the default settings, ?boxplot tells us that
If ‘range’ is positive, the whiskers extend to the most extr |
31,470 | R: Box-plot on log scale vs. log-transforming *then* creating box-plot: Don't get same result | From ?boxplot, you can read:
range
this determines how far the plot whiskers extend out from the
box. If range is positive, the whiskers extend to the most extreme
data point which is no more than range times the interquartile range
from the box. A value of zero causes the whiskers to extend to the
data extremes.
The default when plotting a boxplot, range=1.5, means that the whiskers will extend 1.5 times the interquartile range above the third quartile and below the first quartile; all other points will be labeled as outliers.
The differences you are seeing are based on the fact that log transformation of the data does not maintain the normalized distance of a point from the third or first quartile; as expected with your data, after log-transformation you have fewer outliers with very high values and more outliers with low values. | R: Box-plot on log scale vs. log-transforming *then* creating box-plot: Don't get same result | From ?boxplot, you can read:
range
this determines how far the plot whiskers extend out from the
box. If range is positive, the whiskers extend to the most extreme
data point which is no more tha | R: Box-plot on log scale vs. log-transforming *then* creating box-plot: Don't get same result
From ?boxplot, you can read:
range
this determines how far the plot whiskers extend out from the
box. If range is positive, the whiskers extend to the most extreme
data point which is no more than range times the interquartile range
from the box. A value of zero causes the whiskers to extend to the
data extremes.
The default when plotting a boxplot, range=1.5, means that the whiskers will extend 1.5 times the interquartile range above the third quartile and below the first quartile; all other points will be labeled as outliers.
The differences you are seeing are based on the fact that log transformation of the data does not maintain the normalized distance of a point from the third or first quartile; as expected with your data, after log-transformation you have fewer outliers with very high values and more outliers with low values. | R: Box-plot on log scale vs. log-transforming *then* creating box-plot: Don't get same result
From ?boxplot, you can read:
range
this determines how far the plot whiskers extend out from the
box. If range is positive, the whiskers extend to the most extreme
data point which is no more tha |
31,471 | Is it reasonable to study neural networks without mathematical education? | It depends upon your type of Work:
Maths is required if you are working in an applied Science role, i.e. you try to experiments with the known things in Hand i.e. try word embeddings, may be with CNN, and see if the results are good or NOT.
On the other hand , a lot of maths is required if you want to end up as a research scientist, example finding new ways to represent word embedding, or improve the existing word embeddings itself, in case of Text mining.
On the other hand, If you are working as a Software engineer in Machine Learning OR a Machine Learning Engineer, then you just need to train the models using existing knowledge of doing things and Tune it for better performance.
There is a trade off between research and Engineering. More towards Research is More Maths, but More towards Engineering is lesser Maths and More on performance of system in Production.
Another Example to explain would be, for chat Bots.
Research Scientist with Maths background require to write a paper for a new models like how LSTM works and can be Used.
A applied scientiest will try out a business problem like building a chat bot with LSTM first and publish papers how it worked for them in Labs.
A Machine Learning Engineer will replicate the concept which the Applied Scientist had published for their engineering Work (i.e. need to understand maths of paper and replicate it in code, that's it.)
Hope this helps with respect to requirement of knowledge of Maths in Machine Learning | Is it reasonable to study neural networks without mathematical education? | It depends upon your type of Work:
Maths is required if you are working in an applied Science role, i.e. you try to experiments with the known things in Hand i.e. try word embeddings, may be with CNN, | Is it reasonable to study neural networks without mathematical education?
It depends upon your type of Work:
Maths is required if you are working in an applied Science role, i.e. you try to experiments with the known things in Hand i.e. try word embeddings, may be with CNN, and see if the results are good or NOT.
On the other hand , a lot of maths is required if you want to end up as a research scientist, example finding new ways to represent word embedding, or improve the existing word embeddings itself, in case of Text mining.
On the other hand, If you are working as a Software engineer in Machine Learning OR a Machine Learning Engineer, then you just need to train the models using existing knowledge of doing things and Tune it for better performance.
There is a trade off between research and Engineering. More towards Research is More Maths, but More towards Engineering is lesser Maths and More on performance of system in Production.
Another Example to explain would be, for chat Bots.
Research Scientist with Maths background require to write a paper for a new models like how LSTM works and can be Used.
A applied scientiest will try out a business problem like building a chat bot with LSTM first and publish papers how it worked for them in Labs.
A Machine Learning Engineer will replicate the concept which the Applied Scientist had published for their engineering Work (i.e. need to understand maths of paper and replicate it in code, that's it.)
Hope this helps with respect to requirement of knowledge of Maths in Machine Learning | Is it reasonable to study neural networks without mathematical education?
It depends upon your type of Work:
Maths is required if you are working in an applied Science role, i.e. you try to experiments with the known things in Hand i.e. try word embeddings, may be with CNN, |
31,472 | Is it reasonable to study neural networks without mathematical education? | Google is having courses on Deep Learning to train its employees. Given that most of them are in the situation you describe (not much math experience, but good software skills) I would say it's proof that you can profit from Deep Learning without excelling at math.
Now there are tons of tools and sample codes online on lots of cool deep learning projects so it's easy to get started and play with them. For example there's tensorflow which already doesn't require much knowledge of how the backpropagation algorithm works, but there are even simpler layers build on top of it that require even less Deep Learning/theory knowledge, such as Keras.
If you want to build your own you have to keep in mind that you will sometimes need lots of data and lots of computing power for a subset of those projects. (For example, at MIT's Machine Learning class lots of students wanted to replicate the atari project you mentioned, but the TAs suggested not to because of lack of Google-level compute power).
Things you will probably be able to do with 1-2 days of effort include:
Build your own, relatively simple, architecture.
Train a complex architecture (using online code) on a dataset of your interest.
Finally, if what you want is to create your new cool architecture that overperforms the state of the art I would say this will be hard to do without understanding the math behind it well. | Is it reasonable to study neural networks without mathematical education? | Google is having courses on Deep Learning to train its employees. Given that most of them are in the situation you describe (not much math experience, but good software skills) I would say it's proof | Is it reasonable to study neural networks without mathematical education?
Google is having courses on Deep Learning to train its employees. Given that most of them are in the situation you describe (not much math experience, but good software skills) I would say it's proof that you can profit from Deep Learning without excelling at math.
Now there are tons of tools and sample codes online on lots of cool deep learning projects so it's easy to get started and play with them. For example there's tensorflow which already doesn't require much knowledge of how the backpropagation algorithm works, but there are even simpler layers build on top of it that require even less Deep Learning/theory knowledge, such as Keras.
If you want to build your own you have to keep in mind that you will sometimes need lots of data and lots of computing power for a subset of those projects. (For example, at MIT's Machine Learning class lots of students wanted to replicate the atari project you mentioned, but the TAs suggested not to because of lack of Google-level compute power).
Things you will probably be able to do with 1-2 days of effort include:
Build your own, relatively simple, architecture.
Train a complex architecture (using online code) on a dataset of your interest.
Finally, if what you want is to create your new cool architecture that overperforms the state of the art I would say this will be hard to do without understanding the math behind it well. | Is it reasonable to study neural networks without mathematical education?
Google is having courses on Deep Learning to train its employees. Given that most of them are in the situation you describe (not much math experience, but good software skills) I would say it's proof |
31,473 | Is it reasonable to study neural networks without mathematical education? | I'm a PhD candidate in Computational Neuroscience and I work with this kind of software and stuff every day. We also have many students coming in and doing their projects in this field. So I have a bit of experience.
Is it reasonable for someone with shallow knowledge in math but programming skills to dive into neural network/machine learning studies?
Yes, it is. You can use high level abstractions like Keras and get started right away. In my opinion you do not need to know the exact dynamics of the ANN to use it.
As with everything it depends highly on you and how much time and effort you want to invest. I'd say that you need a bit of math to understand the basics of it. An example is the activation functions in a neural net. They play a crucial role but are simple to understand.
If you want to get to the depths of it and really understand how and why it works you'll need pretty extensive math skills. There is no way around that. What I mean are advanced probability theory, advanced calculus and advanced algebra. For example, take a look at the Backpropagation Algorithm.. For more about maths in machine learning you can read this blog post.
Is it possible to build interesting projects in this area, like those playing atari, using only high-level tools?
Yes, it is. There are many great tools out there that allow you to do this. Of course as soon as you'd try to program something new you would hit your limits quite soon, for example, if you wanted to modify a neural network or an algorithm such that it improves or gets faster.
As for Atari I suggest you read this nice blog post. It explains everything in such a detail that you can implement it but still shallow enough to understand it.
So to add to the other answers: I've seen students coming in with low/basic maths skills but good programming skills and they were all able to implement, test and run a solid machine learning pipeline. Here a pipeline means gathering data, preprocessing, training and evaluation of the system as a whole.
So, yes, you can do it. | Is it reasonable to study neural networks without mathematical education? | I'm a PhD candidate in Computational Neuroscience and I work with this kind of software and stuff every day. We also have many students coming in and doing their projects in this field. So I have a bi | Is it reasonable to study neural networks without mathematical education?
I'm a PhD candidate in Computational Neuroscience and I work with this kind of software and stuff every day. We also have many students coming in and doing their projects in this field. So I have a bit of experience.
Is it reasonable for someone with shallow knowledge in math but programming skills to dive into neural network/machine learning studies?
Yes, it is. You can use high level abstractions like Keras and get started right away. In my opinion you do not need to know the exact dynamics of the ANN to use it.
As with everything it depends highly on you and how much time and effort you want to invest. I'd say that you need a bit of math to understand the basics of it. An example is the activation functions in a neural net. They play a crucial role but are simple to understand.
If you want to get to the depths of it and really understand how and why it works you'll need pretty extensive math skills. There is no way around that. What I mean are advanced probability theory, advanced calculus and advanced algebra. For example, take a look at the Backpropagation Algorithm.. For more about maths in machine learning you can read this blog post.
Is it possible to build interesting projects in this area, like those playing atari, using only high-level tools?
Yes, it is. There are many great tools out there that allow you to do this. Of course as soon as you'd try to program something new you would hit your limits quite soon, for example, if you wanted to modify a neural network or an algorithm such that it improves or gets faster.
As for Atari I suggest you read this nice blog post. It explains everything in such a detail that you can implement it but still shallow enough to understand it.
So to add to the other answers: I've seen students coming in with low/basic maths skills but good programming skills and they were all able to implement, test and run a solid machine learning pipeline. Here a pipeline means gathering data, preprocessing, training and evaluation of the system as a whole.
So, yes, you can do it. | Is it reasonable to study neural networks without mathematical education?
I'm a PhD candidate in Computational Neuroscience and I work with this kind of software and stuff every day. We also have many students coming in and doing their projects in this field. So I have a bi |
31,474 | Is it reasonable to study neural networks without mathematical education? | I'll limit my answer to neural networks.
Is it reasonable for someone with shallow knowledge in math but programming skills to dive into neural network/machine learning studies?
It's reasonable and possible. Here are few reasons to support this conclusion:
Neural networks are inspired by the functioning of our brains. Therefore lots of concepts are familiar and easy to understand: neurons, connections, activation etc. This makes the introduction to neural networks smooth and exciting, and doesn't require any math.
The basic operation of a neural network, regardless of its size, is easy to understand: forward passing, signals flowing from one level to another, neuron activation etc. Not too much math required here: wighted sums, and non-linear functions such as sigmoid.
The math underlying some of the most fundamental algorithms for training neural networks (e.g., back propagation) is not complex: sums, logarithms, multiplications and divisions. And you calculate values that have concrete meaning: error cost, gradient etc. Some other ML techniques require calculation of intermediary values (often matrices) whose meaning is not that clear or intuitive.
It's often not the more sophisticated math but rather understanding and experience with the basics that let you dive into more advanced topics such as regularisation, pre-training, dropout etc.
To make things clear there're more complex network architectures and mathematically demanding algorithms for training neural networks. Also, although calculations involved in back propagation are simple its derivation is complex for someone who didn't study calculus. Still the difficulty of derivation or existence of more complex algorithms doesn't mean that studying neural networks is unreasonable. These issues won't prevent you from building good understanding and making practical use of neural networks.
Is it possible to build interesting projects in this area, like those playing atari, using only high-level tools?
In the recent years the interest in neural networks (deep learning especially) is spiking. This resulted in the creation of many good tools and libraries as you observed, some of which are coming from factories such as Google, Microsoft or NVidia. No doubt the quality of these is sufficient to create interesting projects. What might prove more challenging is getting the right amount of quality data to train your network (given such data is not currently available). | Is it reasonable to study neural networks without mathematical education? | I'll limit my answer to neural networks.
Is it reasonable for someone with shallow knowledge in math but programming skills to dive into neural network/machine learning studies?
It's reasonable and | Is it reasonable to study neural networks without mathematical education?
I'll limit my answer to neural networks.
Is it reasonable for someone with shallow knowledge in math but programming skills to dive into neural network/machine learning studies?
It's reasonable and possible. Here are few reasons to support this conclusion:
Neural networks are inspired by the functioning of our brains. Therefore lots of concepts are familiar and easy to understand: neurons, connections, activation etc. This makes the introduction to neural networks smooth and exciting, and doesn't require any math.
The basic operation of a neural network, regardless of its size, is easy to understand: forward passing, signals flowing from one level to another, neuron activation etc. Not too much math required here: wighted sums, and non-linear functions such as sigmoid.
The math underlying some of the most fundamental algorithms for training neural networks (e.g., back propagation) is not complex: sums, logarithms, multiplications and divisions. And you calculate values that have concrete meaning: error cost, gradient etc. Some other ML techniques require calculation of intermediary values (often matrices) whose meaning is not that clear or intuitive.
It's often not the more sophisticated math but rather understanding and experience with the basics that let you dive into more advanced topics such as regularisation, pre-training, dropout etc.
To make things clear there're more complex network architectures and mathematically demanding algorithms for training neural networks. Also, although calculations involved in back propagation are simple its derivation is complex for someone who didn't study calculus. Still the difficulty of derivation or existence of more complex algorithms doesn't mean that studying neural networks is unreasonable. These issues won't prevent you from building good understanding and making practical use of neural networks.
Is it possible to build interesting projects in this area, like those playing atari, using only high-level tools?
In the recent years the interest in neural networks (deep learning especially) is spiking. This resulted in the creation of many good tools and libraries as you observed, some of which are coming from factories such as Google, Microsoft or NVidia. No doubt the quality of these is sufficient to create interesting projects. What might prove more challenging is getting the right amount of quality data to train your network (given such data is not currently available). | Is it reasonable to study neural networks without mathematical education?
I'll limit my answer to neural networks.
Is it reasonable for someone with shallow knowledge in math but programming skills to dive into neural network/machine learning studies?
It's reasonable and |
31,475 | Is it reasonable to study neural networks without mathematical education? | It depends. I assume you understand backpropagation algorithm, as it is used by most of NN architectures, and CNNs and RNNs and all that stuff is not that hard if you know backpropagation.
On the one hand, Theano/Tensorflow don't seem to be a good example since they are basically DSLs to write matrix/tensor computations, and they're pretty math-heavy and low-level (you write down actual mathematical operations, and not only use fit, transform/predict api).
On the other hand, there is Keras and scikit-learn, which only have high-level apis, and don't require as much plumbing.
In particular, in Keras you can use some models that were pretrained or have a predefined architecture that is known to work for some problems.
Of course if you don't have good math knowledge you can run into problems with black-box models, but if you just want to apply stuff that seems to work with something to some other thing, then it's definitely possible, for example check out this simple project.
You might also be interested in Creative Applications of Deep Learning with TensorFlow as it seems to be aimed at nontechnical people (I don't know if it's feasible to learn it without any technical background, but at least it contains lots of cool examples). | Is it reasonable to study neural networks without mathematical education? | It depends. I assume you understand backpropagation algorithm, as it is used by most of NN architectures, and CNNs and RNNs and all that stuff is not that hard if you know backpropagation.
On the one | Is it reasonable to study neural networks without mathematical education?
It depends. I assume you understand backpropagation algorithm, as it is used by most of NN architectures, and CNNs and RNNs and all that stuff is not that hard if you know backpropagation.
On the one hand, Theano/Tensorflow don't seem to be a good example since they are basically DSLs to write matrix/tensor computations, and they're pretty math-heavy and low-level (you write down actual mathematical operations, and not only use fit, transform/predict api).
On the other hand, there is Keras and scikit-learn, which only have high-level apis, and don't require as much plumbing.
In particular, in Keras you can use some models that were pretrained or have a predefined architecture that is known to work for some problems.
Of course if you don't have good math knowledge you can run into problems with black-box models, but if you just want to apply stuff that seems to work with something to some other thing, then it's definitely possible, for example check out this simple project.
You might also be interested in Creative Applications of Deep Learning with TensorFlow as it seems to be aimed at nontechnical people (I don't know if it's feasible to learn it without any technical background, but at least it contains lots of cool examples). | Is it reasonable to study neural networks without mathematical education?
It depends. I assume you understand backpropagation algorithm, as it is used by most of NN architectures, and CNNs and RNNs and all that stuff is not that hard if you know backpropagation.
On the one |
31,476 | Is it reasonable to study neural networks without mathematical education? | The essence of a neural network is the graph. While graphs may be part of math, their concepts are as old as relationship itself and pre-date it.
If it were necessary for learning to be complex, then brains probably wouldn't have evolved at all, for the probability of ordered complexity is too improbable.
So, then, one must ask: what is the simplest machine that can learn? But, of course, that begs the epistemological question: what is learning?
Learning is the juxtaposition of two novel states, forming a memory. And there you have the basis of AI: memory. | Is it reasonable to study neural networks without mathematical education? | The essence of a neural network is the graph. While graphs may be part of math, their concepts are as old as relationship itself and pre-date it.
If it were necessary for learning to be complex, th | Is it reasonable to study neural networks without mathematical education?
The essence of a neural network is the graph. While graphs may be part of math, their concepts are as old as relationship itself and pre-date it.
If it were necessary for learning to be complex, then brains probably wouldn't have evolved at all, for the probability of ordered complexity is too improbable.
So, then, one must ask: what is the simplest machine that can learn? But, of course, that begs the epistemological question: what is learning?
Learning is the juxtaposition of two novel states, forming a memory. And there you have the basis of AI: memory. | Is it reasonable to study neural networks without mathematical education?
The essence of a neural network is the graph. While graphs may be part of math, their concepts are as old as relationship itself and pre-date it.
If it were necessary for learning to be complex, th |
31,477 | Decision Tree with continuous input variable | The common method is to check only certain bins as splitting point / threshold. I think this is what the author of the presentation you posted is referring to. Lets say you have a continuous input random variable $X$ with the 10 samples
[1,3,4,6,2,5,18,10,-3,-5]
Probably you do not check every value of $X$ from the 10 observed values as a splitting point.
Instead you would for example calculate just check the 20%, 40%, 60%, 80% quantile from your data.
So you order your data
[-5,-3,1,2,3,4,5,6,10,18]
and "cluster" your data into bins
[-5,-3],[1,2],[3,4],[5,6],[10,18]
So then you would only have to check -1,2.5,4.5, and 8 as possible splitting point (you linearly interpolate between the bins)
The following paper is comparing three rules on how to choose the splitting points to test. I think it is what you are searching.
@article{chickeringefficient,
title={Efficient Determination of Dynamic Split Points in a Decision Tree},
author={Chickering, David Maxwell and Meek, Christopher and Rounthwaite, Robert}
} | Decision Tree with continuous input variable | The common method is to check only certain bins as splitting point / threshold. I think this is what the author of the presentation you posted is referring to. Lets say you have a continuous input ran | Decision Tree with continuous input variable
The common method is to check only certain bins as splitting point / threshold. I think this is what the author of the presentation you posted is referring to. Lets say you have a continuous input random variable $X$ with the 10 samples
[1,3,4,6,2,5,18,10,-3,-5]
Probably you do not check every value of $X$ from the 10 observed values as a splitting point.
Instead you would for example calculate just check the 20%, 40%, 60%, 80% quantile from your data.
So you order your data
[-5,-3,1,2,3,4,5,6,10,18]
and "cluster" your data into bins
[-5,-3],[1,2],[3,4],[5,6],[10,18]
So then you would only have to check -1,2.5,4.5, and 8 as possible splitting point (you linearly interpolate between the bins)
The following paper is comparing three rules on how to choose the splitting points to test. I think it is what you are searching.
@article{chickeringefficient,
title={Efficient Determination of Dynamic Split Points in a Decision Tree},
author={Chickering, David Maxwell and Meek, Christopher and Rounthwaite, Robert}
} | Decision Tree with continuous input variable
The common method is to check only certain bins as splitting point / threshold. I think this is what the author of the presentation you posted is referring to. Lets say you have a continuous input ran |
31,478 | Should I ever standardise/normalise the target data/ dependent variables in regression models? | Scaling or zeroing will will not change the regression or classification results. The only down side is lose of interpretability.
Here are working examples in R showing that any combination of scaling or zeroing produces the same regression line.
Coefficients can be different, and that is okay. Here are the coefficients calculated in the models below in order.
(Intercept) disp
1 29.59985 -0.04121512
2 20.09062 -0.04121512
3 26.66946 -16.52314159
4 26.66946 -16.52314159
No zeroing or scaling
# orginal data
df <- mtcars
png("mtcars_original.png")
plot(df$disp, df$mpg, main="MPG VS Displacment")
abline(lm(mpg ~ disp, df), col = 2)
dev.off()
Zeroed
# zeroed displacement
df <- mtcars
df$disp <- df$disp - mean(df$disp)
png("mtcars_zeroed.png")
plot(df$disp, df$mpg, main="MPG VS Zeroed Displacement")
abline(lm(mpg ~ disp, df), col = 2)
dev.off()
Scaled
# scaled displacment
df <- mtcars
df$disp <- (df$disp - min(df$disp)) / ( max(df$disp) - min(df$disp))
png("mtcars_scaled.png")
plot(df$disp, df$mpg, main="MPG VS Scaled Displacment")
abline(lm(mpg ~ disp, df), col = 2)
dev.off()
Zeroed & Scaled
# zeroed & scaled displacment
df <- mtcars
dt$disp <- df$disp - mean(df$disp)
df$disp <- (df$disp - min(df$disp)) / ( max(df$disp) - min(df$disp))
png("mtcars_zeroed_scaled.png")
plot(df$disp, df$mpg, main="MPG VS Scaled & Zeroed Displacment")
abline(lm(mpg ~ disp, df), col = 2)
dev.off() | Should I ever standardise/normalise the target data/ dependent variables in regression models? | Scaling or zeroing will will not change the regression or classification results. The only down side is lose of interpretability.
Here are working examples in R showing that any combination of scaling | Should I ever standardise/normalise the target data/ dependent variables in regression models?
Scaling or zeroing will will not change the regression or classification results. The only down side is lose of interpretability.
Here are working examples in R showing that any combination of scaling or zeroing produces the same regression line.
Coefficients can be different, and that is okay. Here are the coefficients calculated in the models below in order.
(Intercept) disp
1 29.59985 -0.04121512
2 20.09062 -0.04121512
3 26.66946 -16.52314159
4 26.66946 -16.52314159
No zeroing or scaling
# orginal data
df <- mtcars
png("mtcars_original.png")
plot(df$disp, df$mpg, main="MPG VS Displacment")
abline(lm(mpg ~ disp, df), col = 2)
dev.off()
Zeroed
# zeroed displacement
df <- mtcars
df$disp <- df$disp - mean(df$disp)
png("mtcars_zeroed.png")
plot(df$disp, df$mpg, main="MPG VS Zeroed Displacement")
abline(lm(mpg ~ disp, df), col = 2)
dev.off()
Scaled
# scaled displacment
df <- mtcars
df$disp <- (df$disp - min(df$disp)) / ( max(df$disp) - min(df$disp))
png("mtcars_scaled.png")
plot(df$disp, df$mpg, main="MPG VS Scaled Displacment")
abline(lm(mpg ~ disp, df), col = 2)
dev.off()
Zeroed & Scaled
# zeroed & scaled displacment
df <- mtcars
dt$disp <- df$disp - mean(df$disp)
df$disp <- (df$disp - min(df$disp)) / ( max(df$disp) - min(df$disp))
png("mtcars_zeroed_scaled.png")
plot(df$disp, df$mpg, main="MPG VS Scaled & Zeroed Displacment")
abline(lm(mpg ~ disp, df), col = 2)
dev.off() | Should I ever standardise/normalise the target data/ dependent variables in regression models?
Scaling or zeroing will will not change the regression or classification results. The only down side is lose of interpretability.
Here are working examples in R showing that any combination of scaling |
31,479 | Should I ever standardise/normalise the target data/ dependent variables in regression models? | It will. Your measurements are coordinates. For every value on the explanatory variable, you have a coordinate measurement on the target variable. If you don't change the order of either, then the relation remains intact. Right? | Should I ever standardise/normalise the target data/ dependent variables in regression models? | It will. Your measurements are coordinates. For every value on the explanatory variable, you have a coordinate measurement on the target variable. If you don't change the order of either, then the rel | Should I ever standardise/normalise the target data/ dependent variables in regression models?
It will. Your measurements are coordinates. For every value on the explanatory variable, you have a coordinate measurement on the target variable. If you don't change the order of either, then the relation remains intact. Right? | Should I ever standardise/normalise the target data/ dependent variables in regression models?
It will. Your measurements are coordinates. For every value on the explanatory variable, you have a coordinate measurement on the target variable. If you don't change the order of either, then the rel |
31,480 | The bottleneck of applying deep learning in practice | True, some details used for improving performance are considered as tricks and you won't always know if these tricks yield the same improvement for your data and your network.
Some things that you will definitely need:
Data, lots of it
GPUs will let you run experiments faster and try out more things in a shorter time span.
Learning curve analysis. In the end it comes down to performance on the test set, but looking at the both train and test metrics you can identify reasons for bad performance. Strong bias? Overfitting from too many hidden nodes?
The activation function. I don't think it counts as a trick to know which kind of activation function you need. ReLU have a critical charactersitic in that they do not saturate like sigmoids and tanh. A neuron with ReLU will longer have probability-like output, but you don't need this for neurons in mid-level layers anyway. The advantag you get is mitigating the vanishing or exploding of gradients and speed up convergence.
Regularization. Might apply as tricks, but if you're using any of the mainstream deep learning libraries you can get off-the-shelf implementations for regularization via dropout.
Data augmentation. You're basically expanding your dataset synthetically without the added cost of manual annotation. The key is to augment the data with transformations that actuall make sense. So that the network gets to see variants of the data it may encounter in the test phase or when it gets deployed into the product. For visual data it horizontal flipping is trivial and adds a lot of gain. Jitter is probably dependent on the type of data and how noisy it is.
Diving into hyperparameter exploration can be frustrating. Start off with small networks and simple training procedures. Smaller networks are faster to train. Add more layers when you see signs of overfitting.
Good initialization. Random intitialization are appropriate for gauging the network's ability to converge but will not necessarily lead t optimal performance. At the same time, just keeping on iterating might lead to the network overfitting to the training data. If possible use a pre-trained network that has already learned a representation and fine tune it to your dataset. Unsupervised pre-training is another way to go and can allow the supervised training procedure to start from a far more promising position in weight space.
Scrutinize tricks. Understand what the trick really does. A paper describing a small detail that was used in improving the performance of a network will focus on that new aspect. The paper could be part of a sequence of projects that the authors have been working on. The context of the trick may not always be clear right away but for the authors it's not a trick but a technique that solves a problem they had. Sometimes a technique comes out and is treated as a trick and later someone will analyze its impact and describe its function. For example that this trick is equivalent to L2 regularization which more people are familiar with. We can the decide if we should try out this new technique or stick with the L2 regularization that we already know about. A lot of these tricks try to solve problems in deep learning, like risk of overfitting, costly computations, over parameterization and highly redundant weights. It's worth taking the time to understand what these tricks really do. By understanding the problem they try to solve we can judge the applicability of different tricks and pick the one that works well with constraints we may have (e.g. little computing power, small dataset) | The bottleneck of applying deep learning in practice | True, some details used for improving performance are considered as tricks and you won't always know if these tricks yield the same improvement for your data and your network.
Some things that you wil | The bottleneck of applying deep learning in practice
True, some details used for improving performance are considered as tricks and you won't always know if these tricks yield the same improvement for your data and your network.
Some things that you will definitely need:
Data, lots of it
GPUs will let you run experiments faster and try out more things in a shorter time span.
Learning curve analysis. In the end it comes down to performance on the test set, but looking at the both train and test metrics you can identify reasons for bad performance. Strong bias? Overfitting from too many hidden nodes?
The activation function. I don't think it counts as a trick to know which kind of activation function you need. ReLU have a critical charactersitic in that they do not saturate like sigmoids and tanh. A neuron with ReLU will longer have probability-like output, but you don't need this for neurons in mid-level layers anyway. The advantag you get is mitigating the vanishing or exploding of gradients and speed up convergence.
Regularization. Might apply as tricks, but if you're using any of the mainstream deep learning libraries you can get off-the-shelf implementations for regularization via dropout.
Data augmentation. You're basically expanding your dataset synthetically without the added cost of manual annotation. The key is to augment the data with transformations that actuall make sense. So that the network gets to see variants of the data it may encounter in the test phase or when it gets deployed into the product. For visual data it horizontal flipping is trivial and adds a lot of gain. Jitter is probably dependent on the type of data and how noisy it is.
Diving into hyperparameter exploration can be frustrating. Start off with small networks and simple training procedures. Smaller networks are faster to train. Add more layers when you see signs of overfitting.
Good initialization. Random intitialization are appropriate for gauging the network's ability to converge but will not necessarily lead t optimal performance. At the same time, just keeping on iterating might lead to the network overfitting to the training data. If possible use a pre-trained network that has already learned a representation and fine tune it to your dataset. Unsupervised pre-training is another way to go and can allow the supervised training procedure to start from a far more promising position in weight space.
Scrutinize tricks. Understand what the trick really does. A paper describing a small detail that was used in improving the performance of a network will focus on that new aspect. The paper could be part of a sequence of projects that the authors have been working on. The context of the trick may not always be clear right away but for the authors it's not a trick but a technique that solves a problem they had. Sometimes a technique comes out and is treated as a trick and later someone will analyze its impact and describe its function. For example that this trick is equivalent to L2 regularization which more people are familiar with. We can the decide if we should try out this new technique or stick with the L2 regularization that we already know about. A lot of these tricks try to solve problems in deep learning, like risk of overfitting, costly computations, over parameterization and highly redundant weights. It's worth taking the time to understand what these tricks really do. By understanding the problem they try to solve we can judge the applicability of different tricks and pick the one that works well with constraints we may have (e.g. little computing power, small dataset) | The bottleneck of applying deep learning in practice
True, some details used for improving performance are considered as tricks and you won't always know if these tricks yield the same improvement for your data and your network.
Some things that you wil |
31,481 | The bottleneck of applying deep learning in practice | Here is an interesting book Neural Networks: Tricks of the Trade, an updated 2012 version of the book. Lots of articles by some of the pioneers of neural networks.
ypx beautifully touched on a lot of practical issues with training, so to touch upon the other issues you raised: a lot of the elite industrial labs still publish their results. For example Microsoft Research's team just won ImageNet 2015 and they released a technical report describing their new deep net module: Deep Residual Learning for Image Recognition, Google's team published their Inception architecture as well, Going Deeper with Convolutions. To a non-trivial degree there is still a culture in machine learning (for now) of sharing the big innovations. Possibly because the key is access to the data. Google and Facebook simply have access to data that we do not. Hard to say how much credit goes to raw algorithmic innovation and how much goes to massive amounts of data.
With regards to what will happen in the future? Hard to say. It's an issue that lots of people have raised given how valuable these data driven companies have become and how competitive the market is. But for now, I think there is a good enough balance of what industrial research labs share and don't share. I understand them not sharing their exact code implementation. But they do share some very novel innovations.
Find researchers who publish important results and read, read, read. I believe in Yann LeCun's AMA on Reddit he mentioned that he is a voracious reader. I believe this is the most important thing. And to the extent that it is practical, try to recreate their benchmarks, or apply their method to a dataset that is within your budget.
I think regardless of where you are or what your station in life is, this is the best way to stay sharp and continue to develop your skills. Be a voracious reader and implement things and build intuition. I personally do not have the resources to participate in ImageNet competitions, but reading all the top performing ImageNet group's articles has helped me tremendously. | The bottleneck of applying deep learning in practice | Here is an interesting book Neural Networks: Tricks of the Trade, an updated 2012 version of the book. Lots of articles by some of the pioneers of neural networks.
ypx beautifully touched on a lot of | The bottleneck of applying deep learning in practice
Here is an interesting book Neural Networks: Tricks of the Trade, an updated 2012 version of the book. Lots of articles by some of the pioneers of neural networks.
ypx beautifully touched on a lot of practical issues with training, so to touch upon the other issues you raised: a lot of the elite industrial labs still publish their results. For example Microsoft Research's team just won ImageNet 2015 and they released a technical report describing their new deep net module: Deep Residual Learning for Image Recognition, Google's team published their Inception architecture as well, Going Deeper with Convolutions. To a non-trivial degree there is still a culture in machine learning (for now) of sharing the big innovations. Possibly because the key is access to the data. Google and Facebook simply have access to data that we do not. Hard to say how much credit goes to raw algorithmic innovation and how much goes to massive amounts of data.
With regards to what will happen in the future? Hard to say. It's an issue that lots of people have raised given how valuable these data driven companies have become and how competitive the market is. But for now, I think there is a good enough balance of what industrial research labs share and don't share. I understand them not sharing their exact code implementation. But they do share some very novel innovations.
Find researchers who publish important results and read, read, read. I believe in Yann LeCun's AMA on Reddit he mentioned that he is a voracious reader. I believe this is the most important thing. And to the extent that it is practical, try to recreate their benchmarks, or apply their method to a dataset that is within your budget.
I think regardless of where you are or what your station in life is, this is the best way to stay sharp and continue to develop your skills. Be a voracious reader and implement things and build intuition. I personally do not have the resources to participate in ImageNet competitions, but reading all the top performing ImageNet group's articles has helped me tremendously. | The bottleneck of applying deep learning in practice
Here is an interesting book Neural Networks: Tricks of the Trade, an updated 2012 version of the book. Lots of articles by some of the pioneers of neural networks.
ypx beautifully touched on a lot of |
31,482 | What is the difference between data mining and data fishing? | There is plenty of overlap between these two concepts, so there is not a clear distinction. However, I try to point out what I believe to be the differences.
In terms of statistical analysis, "a fishing expedition" just about always has a negative connotation; the idea being that the researchers started with one question about their data (i.e. "is there a linear relation between these two variables in our data?"). After coming up negative, they "recast their net" with a different question (i.e. "is there a quadratic relation between these two variables?") and so on until they finally find a "statistical significant" relation. Of course, the issue here is that the researcher did many comparisons and reported the top hit. Assuming they did not adjust their p-values for the multiple comparisons, this result will not be valid.
In contrast, with data mining (done correctly) you are starting with the understanding that you do not know which hypothesis you want to test in your data, but rather that you would like to search your data for interesting relations. As such, you will comb through your data and look for potentially interesting relations that will be reported. It is important to note that this step is really hypothesis generating, rather than confirming; to really decisively decide that the interesting relations you found in your data set are not just due to random chance, they should be confirmed in a follow up study (or moreover, independent data).
The similarities between data-fishing and data-mining is that in both cases you are inspecting a very large number of hypotheses from your data. If done correctly, data-mining is not frowned upon because it is acknowledged that you are doing this to generate interesting hypotheses to be tested later, where as data-fishing implies that the researcher did not confirm the final hypothesis they inspected in a new data set. | What is the difference between data mining and data fishing? | There is plenty of overlap between these two concepts, so there is not a clear distinction. However, I try to point out what I believe to be the differences.
In terms of statistical analysis, "a fish | What is the difference between data mining and data fishing?
There is plenty of overlap between these two concepts, so there is not a clear distinction. However, I try to point out what I believe to be the differences.
In terms of statistical analysis, "a fishing expedition" just about always has a negative connotation; the idea being that the researchers started with one question about their data (i.e. "is there a linear relation between these two variables in our data?"). After coming up negative, they "recast their net" with a different question (i.e. "is there a quadratic relation between these two variables?") and so on until they finally find a "statistical significant" relation. Of course, the issue here is that the researcher did many comparisons and reported the top hit. Assuming they did not adjust their p-values for the multiple comparisons, this result will not be valid.
In contrast, with data mining (done correctly) you are starting with the understanding that you do not know which hypothesis you want to test in your data, but rather that you would like to search your data for interesting relations. As such, you will comb through your data and look for potentially interesting relations that will be reported. It is important to note that this step is really hypothesis generating, rather than confirming; to really decisively decide that the interesting relations you found in your data set are not just due to random chance, they should be confirmed in a follow up study (or moreover, independent data).
The similarities between data-fishing and data-mining is that in both cases you are inspecting a very large number of hypotheses from your data. If done correctly, data-mining is not frowned upon because it is acknowledged that you are doing this to generate interesting hypotheses to be tested later, where as data-fishing implies that the researcher did not confirm the final hypothesis they inspected in a new data set. | What is the difference between data mining and data fishing?
There is plenty of overlap between these two concepts, so there is not a clear distinction. However, I try to point out what I believe to be the differences.
In terms of statistical analysis, "a fish |
31,483 | Why do some regression estimates differ by a change of sign, but others don't, when I change reference level? | Let me rig up a simple example for you to explain the concept, then we can check it against your coefficients.
Note that by including both the "A/B" dummy variable and the interaction term, you are effectively giving your model the flexibility to fit a different intercept (using the dummy) and slope (using the interaction) on the "A" data and the "B" data. In what follows it really does not matter whether the other predictor $x$ is a continuous variable or, as in your case, another dummy variable. If I speak in terms of its "intercept" and "slope", this can be interpreted as "level when the dummy is zero" and "change in level when the dummy is changed from $0$ to $1$" if you prefer.
Suppose the OLS fitted model on the "A" data alone is $\hat y = 12 + 5x$ and on the "B" data alone is $\hat y = 11 + 7x$. The data might look like this:
Now suppose we take "A" as our reference level, and use a dummy variable $b$ so that $b=1$ for observations in Group B but $b=0$ in Group A. The fitted model on the whole dataset is
$$\hat y_i = \hat \beta_0 + \hat \beta_1 x_i + \hat \beta_2 b_i + \hat \beta_3 x_ib_i$$
For observations in Group A we have $\hat y_i = \hat \beta_0 + \hat \beta_1 x_i$ and we can minimise their sum of squared residuals by setting $\hat \beta_0 = 12$ and $\hat \beta_1 = 5$. For Group B data, $\hat y_i = (\hat \beta_0 + \hat \beta_2) + (\hat \beta_1 + \hat \beta_3) x_i$ and we can minimise their sum of squared residuals by taking $\hat \beta_0 + \hat \beta_2 = 11$ and $\hat \beta_1 + \hat \beta_3 = 7$. It's clear that we can minimise the sum of squared residuals in the overall regression by minimising the sums for both groups, and that this can be achieved by setting $\hat \beta_0 = 12$ and $\hat \beta_1 = 5$ (from Group A) and $\hat \beta_2 = -1$ and $\hat \beta_3 = 2$ (since the "B" data should have an intercept one lower and a slope two higher). Observe how the presence of an interaction term was necessary for us to have sufficient flexibility to minimise the sum of squared residuals for both groups at once. My fitted model will be:
$$\hat y_i = 12 + 5 x_i - 1 b_i +2 x_i b_i$$
Switch this all around so "B" is the reference level and $a$ is a dummy variable coding for Group A. Can you see that I must now fit the model
$$\hat y_i = 11 + 7 x_i + 1 a_i -2 x_i a_i$$
That is, I take the intercept ($11$) and slope ($7$) from my baseline "B" group, and use the dummy and interaction term to adjust them for my "A" group. These adjustments this time are in the reverse direction (I need an intercept one higher and a slope two lower) therefore the signs are reversed compared to when I took "A" as the reference group, but it should be clear why the other coefficients have not simply switched sign.
Let's compare that to your output. In a similar notation to above, your first fitted model with baseline "A" is:
$$\hat y_i = 100.7484158 + 0.9030541 b_i -0.8693598 x_i + 0.8709116 x_i b_i$$
Your second fitted model with baseline "B" is:
$$\hat y_i = 101.651469922 -0.903054145 a_i + 0.001551843 x_i -0.870911601 x_i a_i$$
Firstly, let's verify that these two models are going to give the same results. Let's put $b_i = 1 - a_i$ in the first equation, and we obtain:
$$\hat y_i = 100.7484158 + 0.9030541 (1-a_i) -0.8693598 x_i + 0.8709116 x_i (1-a_i)$$
This simplifies to:
$$\hat y_i = (100.7484158 + 0.9030541) - 0.9030541 a_i + (-0.8693598 + 0.8709116) x_i - 0.8709116 x_i a_i$$
A quick bit of arithmetic confirms that this is the same as the second fitted model; moreover it should now be clear which coefficients have swapped in signs and which coefficients have simply been adjusted to the other baseline!
Secondly, let's see what the different fitted models are on groups "A" and "B". Your first model immediately gives $\hat y_i = 100.7484158 -0.8693598 x_i$ for group "A", and your second model immediately gives $\hat y_i = 101.651469922 + 0.001551843 x_i$ for group "B". You can verify the first model gives the correct result for group "B" by substituting $b_i = 1$ into its equation; the algebra, of course, works out in the same way as the more general example above. Similarly, you can verify that the second model gives the correct result for group "A" by setting $a_i = 1$.
Thirdly, since in your case the other regressor was also a dummy variable, I suggest you calculate the fitted conditional means for all four categories ("A" with $x=0$, "A" with $x=1$, "B" with $x=0$, "B" with $x=1$) under both models and check you understand why they agree. Strictly speaking this is unnecessary, as we have already performed the more general algebra above to show the results will be consistent even if $x$ is continuous, but I think it remains a valuable exercise. I won't fill the details in as the arithmetic is straightforward and it is more in line with the spirit of JonB's very nice answer. A key point to understand is that, whichever reference group you use, your model has enough flexibility to fit each conditional mean separately. (This is where it makes a difference that your $x$ is a dummy for a binary factor rather than a continuous variable — with continuous predictors we don't generally expect the estimated conditional mean $\hat y$ to match the sample mean for every observed combination of predictors.) Calculate the sample mean for each of those four combinations of categories, and you should find they match your fitted conditional means.
R code to draw plot and explore fitted models, predicted $\hat y$ and group means
#Make data set with desired conditional means
data.df <- data.frame(
x = c(0,0,0, 1,1,1, 0,0,0, 1,1,1),
b = c(0,0,0, 0,0,0, 1,1,1, 1,1,1),
y = c(11.8,12,12.2, 16.8,17,17.2, 10.8,11,11.2, 17.8,18,18.2)
)
data.df$a <- 1 - data.df$b
baselineA.lm <- lm(y ~ x * b, data.df)
summary(baselineA.lm) #check this matches y = 12 + 5x - 1b + 2xb
baselineB.lm <- lm(y ~ x * a, data.df)
summary(baselineB.lm) #check this matches y = 11 + 7x + 1a - 2xa
fitted(baselineA.lm)
fitted(baselineB.lm) #check the two models give the same fitted values for y...
with(data.df, tapply(y, interaction(x, b), mean)) #...which are the group sample means
colorSet <- c("red", "blue")
symbolSet <- c(19,17)
with(data.df, plot(x, y, yaxt="n", col=colorSet[b+1], pch=symbolSet[b+1],
main="Response y against other predictor x",
panel.first = {
axis(2, at=10:20)
abline(h = 10:20, col="gray70")
abline(v = 0:1, col="gray70")
}))
abline(lm(y ~ x, data.df[data.df$b==0,]), col=colorSet[1])
abline(lm(y ~ x, data.df[data.df$b==1,]), col=colorSet[2])
legend(0.1, 17, c("Group A", "Group B"), col = colorSet,
pch = symbolSet, bg = "gray95") | Why do some regression estimates differ by a change of sign, but others don't, when I change referen | Let me rig up a simple example for you to explain the concept, then we can check it against your coefficients.
Note that by including both the "A/B" dummy variable and the interaction term, you are ef | Why do some regression estimates differ by a change of sign, but others don't, when I change reference level?
Let me rig up a simple example for you to explain the concept, then we can check it against your coefficients.
Note that by including both the "A/B" dummy variable and the interaction term, you are effectively giving your model the flexibility to fit a different intercept (using the dummy) and slope (using the interaction) on the "A" data and the "B" data. In what follows it really does not matter whether the other predictor $x$ is a continuous variable or, as in your case, another dummy variable. If I speak in terms of its "intercept" and "slope", this can be interpreted as "level when the dummy is zero" and "change in level when the dummy is changed from $0$ to $1$" if you prefer.
Suppose the OLS fitted model on the "A" data alone is $\hat y = 12 + 5x$ and on the "B" data alone is $\hat y = 11 + 7x$. The data might look like this:
Now suppose we take "A" as our reference level, and use a dummy variable $b$ so that $b=1$ for observations in Group B but $b=0$ in Group A. The fitted model on the whole dataset is
$$\hat y_i = \hat \beta_0 + \hat \beta_1 x_i + \hat \beta_2 b_i + \hat \beta_3 x_ib_i$$
For observations in Group A we have $\hat y_i = \hat \beta_0 + \hat \beta_1 x_i$ and we can minimise their sum of squared residuals by setting $\hat \beta_0 = 12$ and $\hat \beta_1 = 5$. For Group B data, $\hat y_i = (\hat \beta_0 + \hat \beta_2) + (\hat \beta_1 + \hat \beta_3) x_i$ and we can minimise their sum of squared residuals by taking $\hat \beta_0 + \hat \beta_2 = 11$ and $\hat \beta_1 + \hat \beta_3 = 7$. It's clear that we can minimise the sum of squared residuals in the overall regression by minimising the sums for both groups, and that this can be achieved by setting $\hat \beta_0 = 12$ and $\hat \beta_1 = 5$ (from Group A) and $\hat \beta_2 = -1$ and $\hat \beta_3 = 2$ (since the "B" data should have an intercept one lower and a slope two higher). Observe how the presence of an interaction term was necessary for us to have sufficient flexibility to minimise the sum of squared residuals for both groups at once. My fitted model will be:
$$\hat y_i = 12 + 5 x_i - 1 b_i +2 x_i b_i$$
Switch this all around so "B" is the reference level and $a$ is a dummy variable coding for Group A. Can you see that I must now fit the model
$$\hat y_i = 11 + 7 x_i + 1 a_i -2 x_i a_i$$
That is, I take the intercept ($11$) and slope ($7$) from my baseline "B" group, and use the dummy and interaction term to adjust them for my "A" group. These adjustments this time are in the reverse direction (I need an intercept one higher and a slope two lower) therefore the signs are reversed compared to when I took "A" as the reference group, but it should be clear why the other coefficients have not simply switched sign.
Let's compare that to your output. In a similar notation to above, your first fitted model with baseline "A" is:
$$\hat y_i = 100.7484158 + 0.9030541 b_i -0.8693598 x_i + 0.8709116 x_i b_i$$
Your second fitted model with baseline "B" is:
$$\hat y_i = 101.651469922 -0.903054145 a_i + 0.001551843 x_i -0.870911601 x_i a_i$$
Firstly, let's verify that these two models are going to give the same results. Let's put $b_i = 1 - a_i$ in the first equation, and we obtain:
$$\hat y_i = 100.7484158 + 0.9030541 (1-a_i) -0.8693598 x_i + 0.8709116 x_i (1-a_i)$$
This simplifies to:
$$\hat y_i = (100.7484158 + 0.9030541) - 0.9030541 a_i + (-0.8693598 + 0.8709116) x_i - 0.8709116 x_i a_i$$
A quick bit of arithmetic confirms that this is the same as the second fitted model; moreover it should now be clear which coefficients have swapped in signs and which coefficients have simply been adjusted to the other baseline!
Secondly, let's see what the different fitted models are on groups "A" and "B". Your first model immediately gives $\hat y_i = 100.7484158 -0.8693598 x_i$ for group "A", and your second model immediately gives $\hat y_i = 101.651469922 + 0.001551843 x_i$ for group "B". You can verify the first model gives the correct result for group "B" by substituting $b_i = 1$ into its equation; the algebra, of course, works out in the same way as the more general example above. Similarly, you can verify that the second model gives the correct result for group "A" by setting $a_i = 1$.
Thirdly, since in your case the other regressor was also a dummy variable, I suggest you calculate the fitted conditional means for all four categories ("A" with $x=0$, "A" with $x=1$, "B" with $x=0$, "B" with $x=1$) under both models and check you understand why they agree. Strictly speaking this is unnecessary, as we have already performed the more general algebra above to show the results will be consistent even if $x$ is continuous, but I think it remains a valuable exercise. I won't fill the details in as the arithmetic is straightforward and it is more in line with the spirit of JonB's very nice answer. A key point to understand is that, whichever reference group you use, your model has enough flexibility to fit each conditional mean separately. (This is where it makes a difference that your $x$ is a dummy for a binary factor rather than a continuous variable — with continuous predictors we don't generally expect the estimated conditional mean $\hat y$ to match the sample mean for every observed combination of predictors.) Calculate the sample mean for each of those four combinations of categories, and you should find they match your fitted conditional means.
R code to draw plot and explore fitted models, predicted $\hat y$ and group means
#Make data set with desired conditional means
data.df <- data.frame(
x = c(0,0,0, 1,1,1, 0,0,0, 1,1,1),
b = c(0,0,0, 0,0,0, 1,1,1, 1,1,1),
y = c(11.8,12,12.2, 16.8,17,17.2, 10.8,11,11.2, 17.8,18,18.2)
)
data.df$a <- 1 - data.df$b
baselineA.lm <- lm(y ~ x * b, data.df)
summary(baselineA.lm) #check this matches y = 12 + 5x - 1b + 2xb
baselineB.lm <- lm(y ~ x * a, data.df)
summary(baselineB.lm) #check this matches y = 11 + 7x + 1a - 2xa
fitted(baselineA.lm)
fitted(baselineB.lm) #check the two models give the same fitted values for y...
with(data.df, tapply(y, interaction(x, b), mean)) #...which are the group sample means
colorSet <- c("red", "blue")
symbolSet <- c(19,17)
with(data.df, plot(x, y, yaxt="n", col=colorSet[b+1], pch=symbolSet[b+1],
main="Response y against other predictor x",
panel.first = {
axis(2, at=10:20)
abline(h = 10:20, col="gray70")
abline(v = 0:1, col="gray70")
}))
abline(lm(y ~ x, data.df[data.df$b==0,]), col=colorSet[1])
abline(lm(y ~ x, data.df[data.df$b==1,]), col=colorSet[2])
legend(0.1, 17, c("Group A", "Group B"), col = colorSet,
pch = symbolSet, bg = "gray95") | Why do some regression estimates differ by a change of sign, but others don't, when I change referen
Let me rig up a simple example for you to explain the concept, then we can check it against your coefficients.
Note that by including both the "A/B" dummy variable and the interaction term, you are ef |
31,484 | Why do some regression estimates differ by a change of sign, but others don't, when I change reference level? | That has to do with how the intercept is defined. In the first example, the intercept is defined as those who do not smoke and who have drug A. The smokers, who also have drug A, will have a value of 100.75 - 0.87 = 99.9 while the smokers who have drug B will have a value of 100.75 + 0.90 - 0.87 + 0.87 = 101.65.
In the second example, the intercept is defined as those who do not smoke and have drug B. Smokers with drug B will then have a value of 101.65 + 0.001 = 101.65, and smokers with drug A will have a value of 100.65 - 0.90 + 0.001-0.87 = 99.9.
So it all adds upp, it just a matter of how the intercept is defined, that is, the level when all the factors are set to the reference category. | Why do some regression estimates differ by a change of sign, but others don't, when I change referen | That has to do with how the intercept is defined. In the first example, the intercept is defined as those who do not smoke and who have drug A. The smokers, who also have drug A, will have a value of | Why do some regression estimates differ by a change of sign, but others don't, when I change reference level?
That has to do with how the intercept is defined. In the first example, the intercept is defined as those who do not smoke and who have drug A. The smokers, who also have drug A, will have a value of 100.75 - 0.87 = 99.9 while the smokers who have drug B will have a value of 100.75 + 0.90 - 0.87 + 0.87 = 101.65.
In the second example, the intercept is defined as those who do not smoke and have drug B. Smokers with drug B will then have a value of 101.65 + 0.001 = 101.65, and smokers with drug A will have a value of 100.65 - 0.90 + 0.001-0.87 = 99.9.
So it all adds upp, it just a matter of how the intercept is defined, that is, the level when all the factors are set to the reference category. | Why do some regression estimates differ by a change of sign, but others don't, when I change referen
That has to do with how the intercept is defined. In the first example, the intercept is defined as those who do not smoke and who have drug A. The smokers, who also have drug A, will have a value of |
31,485 | Why doesn't deep learning work well with small amount of data? | The neural networks used in typical deep learning models have a very large number of nodes with many layers, and therefore many parameters that must be estimated. This requires a lot of data. A small neural network (with fewer layers and fewer free parameters) can be successfully trained with a small data set - but this would not usually be described as "deep learning". | Why doesn't deep learning work well with small amount of data? | The neural networks used in typical deep learning models have a very large number of nodes with many layers, and therefore many parameters that must be estimated. This requires a lot of data. A small | Why doesn't deep learning work well with small amount of data?
The neural networks used in typical deep learning models have a very large number of nodes with many layers, and therefore many parameters that must be estimated. This requires a lot of data. A small neural network (with fewer layers and fewer free parameters) can be successfully trained with a small data set - but this would not usually be described as "deep learning". | Why doesn't deep learning work well with small amount of data?
The neural networks used in typical deep learning models have a very large number of nodes with many layers, and therefore many parameters that must be estimated. This requires a lot of data. A small |
31,486 | Probability of letters occurring in order in a string | That regular expression represents a Markov chain on $m+1$ states corresponding to a start state $s$ and each of the letters. A transition is made from $s$ to $a$, from $a$ to $b$, ..., and from the penultimate letter to the last, always with probability $p$. Otherwise the state remains the same. The final state is an absorbing state: when it has been reached, all letters have been observed in sequence.
In terms of the states $(s, a, b, \ldots)$, the transition matrix is
$$\mathbb{P}_m = \pmatrix{1-p & p & 0 &\cdots & 0\\
0 & 1-p & p &\cdots & 0 \\
\vdots & 0 & \ddots & p & \vdots \\
0 & \cdots & 0 &1-p & p\\
0 & 0 & \cdots & 0 & 1
}$$
Standard linear algebraic techniques (the Jordan normal form of $\mathbb{P}_m$ and its change of basis matrix are simple and sparse, making this fairly easy to do) establish that for $n\ge m$ the last entry in the first row of the matrix power $\mathbb{P}_m^n$ is
$$\mathbb{P}_m^n(1,m+1) = p^m \sum_{i=0}^{n-m} \binom{m-1+i}{m-1}(1-p)^i.$$
This is the chance of reaching the absorbing state from the start state after $n$ transitions: it answers the question. If you like, it can be expressed in "closed form" in terms of a Hypergeometric function as
$$\mathbb{P}_m^n(1,m+1) =1-p^m \binom{n}{m-1} (1-p)^{-m+n+1} \, _2F_1(1,n+1;n+2-m;1-p).$$
The sum has a pleasant combinatorial interpretation. Let $m+i$ be the position at which the last letter first occurs. It is preceded by a (possibly empty) sequence of non-$a$s, each with a $1-p$ chance of occurring; then an $a$ with a $p$ chance of occurring; then a (possibly non-empty) sequence of non-$b$s, etc. There are $\binom{m-1+i}{m-1}$ locations at which to place the first appearance of an $a$, then the first appearance of a $b$ after that, etc. Thus--including the first appearance of the last letter in position $m+i$--the probability is $\binom{m-1+i}{m-1}p^m(1-p)^k$. This gives one term of the sum. Thus, the sum breaks up the sequences according to where the last letter first occurs, which can be anywhere from position $m+0$ through $m+(n-m)$--these are obviously disjoint--and adds up their probabilities.
As a simple example to clarify the interpretation, suppose $m=2$ and consider $n=3$. There are four sequences of three symbols, each of probability $p^3$, and three other sequences of probability $p^2(1-2p)$, in which the symbols $a$ and $b$ appear in order:
$$aab, aba, abb, bab; ab\$,a\$b, $ab.$$
The chance therefore is
$$4p^3 + 3p^2(1-2p) = 3p^2 - 2p^3 = p^2(3-2p) = p^2(1 + 2(1-p)) = \mathbb{P}_2^3(1,3).$$
The combinatorial interpretation is that the regular expression ^ab (with $b$ in position $2$) occurs with probability $p^2$; and ^[^a]*a[^b]*b, with $b$ in position $3$, occurs in two ways as ^a[^b]b and ^[^a]ab, each with probability $p^2(1-p)$. | Probability of letters occurring in order in a string | That regular expression represents a Markov chain on $m+1$ states corresponding to a start state $s$ and each of the letters. A transition is made from $s$ to $a$, from $a$ to $b$, ..., and from the | Probability of letters occurring in order in a string
That regular expression represents a Markov chain on $m+1$ states corresponding to a start state $s$ and each of the letters. A transition is made from $s$ to $a$, from $a$ to $b$, ..., and from the penultimate letter to the last, always with probability $p$. Otherwise the state remains the same. The final state is an absorbing state: when it has been reached, all letters have been observed in sequence.
In terms of the states $(s, a, b, \ldots)$, the transition matrix is
$$\mathbb{P}_m = \pmatrix{1-p & p & 0 &\cdots & 0\\
0 & 1-p & p &\cdots & 0 \\
\vdots & 0 & \ddots & p & \vdots \\
0 & \cdots & 0 &1-p & p\\
0 & 0 & \cdots & 0 & 1
}$$
Standard linear algebraic techniques (the Jordan normal form of $\mathbb{P}_m$ and its change of basis matrix are simple and sparse, making this fairly easy to do) establish that for $n\ge m$ the last entry in the first row of the matrix power $\mathbb{P}_m^n$ is
$$\mathbb{P}_m^n(1,m+1) = p^m \sum_{i=0}^{n-m} \binom{m-1+i}{m-1}(1-p)^i.$$
This is the chance of reaching the absorbing state from the start state after $n$ transitions: it answers the question. If you like, it can be expressed in "closed form" in terms of a Hypergeometric function as
$$\mathbb{P}_m^n(1,m+1) =1-p^m \binom{n}{m-1} (1-p)^{-m+n+1} \, _2F_1(1,n+1;n+2-m;1-p).$$
The sum has a pleasant combinatorial interpretation. Let $m+i$ be the position at which the last letter first occurs. It is preceded by a (possibly empty) sequence of non-$a$s, each with a $1-p$ chance of occurring; then an $a$ with a $p$ chance of occurring; then a (possibly non-empty) sequence of non-$b$s, etc. There are $\binom{m-1+i}{m-1}$ locations at which to place the first appearance of an $a$, then the first appearance of a $b$ after that, etc. Thus--including the first appearance of the last letter in position $m+i$--the probability is $\binom{m-1+i}{m-1}p^m(1-p)^k$. This gives one term of the sum. Thus, the sum breaks up the sequences according to where the last letter first occurs, which can be anywhere from position $m+0$ through $m+(n-m)$--these are obviously disjoint--and adds up their probabilities.
As a simple example to clarify the interpretation, suppose $m=2$ and consider $n=3$. There are four sequences of three symbols, each of probability $p^3$, and three other sequences of probability $p^2(1-2p)$, in which the symbols $a$ and $b$ appear in order:
$$aab, aba, abb, bab; ab\$,a\$b, $ab.$$
The chance therefore is
$$4p^3 + 3p^2(1-2p) = 3p^2 - 2p^3 = p^2(3-2p) = p^2(1 + 2(1-p)) = \mathbb{P}_2^3(1,3).$$
The combinatorial interpretation is that the regular expression ^ab (with $b$ in position $2$) occurs with probability $p^2$; and ^[^a]*a[^b]*b, with $b$ in position $3$, occurs in two ways as ^a[^b]b and ^[^a]ab, each with probability $p^2(1-p)$. | Probability of letters occurring in order in a string
That regular expression represents a Markov chain on $m+1$ states corresponding to a start state $s$ and each of the letters. A transition is made from $s$ to $a$, from $a$ to $b$, ..., and from the |
31,487 | Probability of letters occurring in order in a string | By "Letters can be repeated" you mean that abbc is a valid string? They 'appear in order'?
If not, $1 - (1-p^m)^{n-m+1}$ seems to be the answer for me. $1-p^m$ is the probability that in a given space of $m$ characters there is no such combination, then you extend it to all $n-m+1$ possible spaces of $m$ characters
If yes then you have a lower bound | Probability of letters occurring in order in a string | By "Letters can be repeated" you mean that abbc is a valid string? They 'appear in order'?
If not, $1 - (1-p^m)^{n-m+1}$ seems to be the answer for me. $1-p^m$ is the probability that in a given space | Probability of letters occurring in order in a string
By "Letters can be repeated" you mean that abbc is a valid string? They 'appear in order'?
If not, $1 - (1-p^m)^{n-m+1}$ seems to be the answer for me. $1-p^m$ is the probability that in a given space of $m$ characters there is no such combination, then you extend it to all $n-m+1$ possible spaces of $m$ characters
If yes then you have a lower bound | Probability of letters occurring in order in a string
By "Letters can be repeated" you mean that abbc is a valid string? They 'appear in order'?
If not, $1 - (1-p^m)^{n-m+1}$ seems to be the answer for me. $1-p^m$ is the probability that in a given space |
31,488 | What text or tutorials would you recommend for learning machine learning for image processing? | The book by Prince, recommended by @seanv507 is indeed an excellent book on the topic (+1). And while it is not really compact, it has very logical structure and even a generous refresher chapter on probability as well as great focus on machine learning within computer vision context.
However, I'd like to recommend another excellent book on the topic (also freely downloadable), which, while having more focus on computer vision per se, IMHO contains enough machine learning material to qualify for an answer. The book that I'm talking about is "Computer Vision: Algorithms and Applications" by Richard Szeliski (Microsoft Research). One of the advantages of this book versus the one by Price is... narrower margins, which allow for larger font size and, thus, better readability. Also, the book by Szeliski is very practical. Since both books share significant content, but have somewhat different focus, in my opinion, they very well complement each other. All this, among other advantages, makes it very easy for me to highly recommend Szeliski's book. | What text or tutorials would you recommend for learning machine learning for image processing? | The book by Prince, recommended by @seanv507 is indeed an excellent book on the topic (+1). And while it is not really compact, it has very logical structure and even a generous refresher chapter on p | What text or tutorials would you recommend for learning machine learning for image processing?
The book by Prince, recommended by @seanv507 is indeed an excellent book on the topic (+1). And while it is not really compact, it has very logical structure and even a generous refresher chapter on probability as well as great focus on machine learning within computer vision context.
However, I'd like to recommend another excellent book on the topic (also freely downloadable), which, while having more focus on computer vision per se, IMHO contains enough machine learning material to qualify for an answer. The book that I'm talking about is "Computer Vision: Algorithms and Applications" by Richard Szeliski (Microsoft Research). One of the advantages of this book versus the one by Price is... narrower margins, which allow for larger font size and, thus, better readability. Also, the book by Szeliski is very practical. Since both books share significant content, but have somewhat different focus, in my opinion, they very well complement each other. All this, among other advantages, makes it very easy for me to highly recommend Szeliski's book. | What text or tutorials would you recommend for learning machine learning for image processing?
The book by Prince, recommended by @seanv507 is indeed an excellent book on the topic (+1). And while it is not really compact, it has very logical structure and even a generous refresher chapter on p |
31,489 | What text or tutorials would you recommend for learning machine learning for image processing? | I would recommend Computer Vision: Models, Learning, and Inference by Simon Prince
the pdf is available (free) to students at the above link. It is exactly aiming at combining ML and image processing | What text or tutorials would you recommend for learning machine learning for image processing? | I would recommend Computer Vision: Models, Learning, and Inference by Simon Prince
the pdf is available (free) to students at the above link. It is exactly aiming at combining ML and image processing | What text or tutorials would you recommend for learning machine learning for image processing?
I would recommend Computer Vision: Models, Learning, and Inference by Simon Prince
the pdf is available (free) to students at the above link. It is exactly aiming at combining ML and image processing | What text or tutorials would you recommend for learning machine learning for image processing?
I would recommend Computer Vision: Models, Learning, and Inference by Simon Prince
the pdf is available (free) to students at the above link. It is exactly aiming at combining ML and image processing |
31,490 | Alternative notions to that of proper scoring rules, and using scoring rules to evaluate models | Contrary to what you said about geometric mean shenanigans, there are actually proper scoring rules for the geometric mean.
The geometric mean of a random variable $X$ is equal to $e^{E(\log X)}$. Therefore minimizing the geometric mean of a random score $S$ corresponds to minimizing the arithmetic mean of a random score $\log S$. So if $f(\hat p)$ is a standard proper scoring rule (where $f(\hat p)$ is the score you get if you predict a probability $\hat p$ and the event happens), then $g(\hat p) = \log f(\hat p)$ is a proper scoring rule for the geometric mean.
Similarly, the harmonic mean of $X$ is $E(X^{-1})^{-1}$, so $g(\hat p) = -f(\hat p)^{-1}$ is a harmonic-proper scoring rule. (The negative sign is in there so the coordinate transformation is monotone increasing.)
This works for any central tendency that is the arithmetic mean in a monotonically transformed space. The problem is that the median doesn't work like this. More generally, any central tendency with a nonzero breakdown point will not work, because it will be insensitive to changes in probability when $p$ is small. For instance the interquartile range won't work, because if $p < 0.25$, then the interquartile range of the scores doesn't depend on $p$ (so the same $\hat p$ must minimize the IQR for all values of $p$ less than $0.25$, which is bad).
Off the top of my head I can't think of any central tendencies with 0 breakdown point that can't be rewritten as a monotone transformation of the arithmetic mean, but that's probably because I don't know enough variational calculus (certainly not enough to prove I'm right). If I'm correct, however, then it would be "essentially" true that
in order for the theory of proper scoring rules to work as intended, the statistical functional must be the mean.
One other remark: you suggest using the RMSE as a scoring rule, but that you shouldn't do it because it coincides with the absolute error when there is one data point. This seems like it might reflect some confusion. You always evaluate a scoring rule on each individual prediction. Then if you want to summarize the scores, you can take the scores' central tendency afterwards. So predicting to optimize the RMSE is always identical to optimizing the absolute error.
On the other hand, you could do something like take the square root of the mean Brier score as your summary if you wanted to have a score summary that was in "units of probability." But I think it would be more productive to simply familiarize yourself with benchmarks for the Brier score scale, since that's what you'll typically see:
0 is a perfect predictor;
0.25 means no predictive ability ($\hat p = 0.5$);
1 is a perfect anti-predictor ($\hat p = 1, p = 0$ or $\hat p = 0, p = 1$).
You can also construct other benchmarks by using very simple models--for instance, if you ignore all info about the events and simply predict the base rate $p$, then your Brier score is $p(1-p)$. Or if you're predicting time series you can see how well a weighted average of the past few events does, etc. | Alternative notions to that of proper scoring rules, and using scoring rules to evaluate models | Contrary to what you said about geometric mean shenanigans, there are actually proper scoring rules for the geometric mean.
The geometric mean of a random variable $X$ is equal to $e^{E(\log X)}$. The | Alternative notions to that of proper scoring rules, and using scoring rules to evaluate models
Contrary to what you said about geometric mean shenanigans, there are actually proper scoring rules for the geometric mean.
The geometric mean of a random variable $X$ is equal to $e^{E(\log X)}$. Therefore minimizing the geometric mean of a random score $S$ corresponds to minimizing the arithmetic mean of a random score $\log S$. So if $f(\hat p)$ is a standard proper scoring rule (where $f(\hat p)$ is the score you get if you predict a probability $\hat p$ and the event happens), then $g(\hat p) = \log f(\hat p)$ is a proper scoring rule for the geometric mean.
Similarly, the harmonic mean of $X$ is $E(X^{-1})^{-1}$, so $g(\hat p) = -f(\hat p)^{-1}$ is a harmonic-proper scoring rule. (The negative sign is in there so the coordinate transformation is monotone increasing.)
This works for any central tendency that is the arithmetic mean in a monotonically transformed space. The problem is that the median doesn't work like this. More generally, any central tendency with a nonzero breakdown point will not work, because it will be insensitive to changes in probability when $p$ is small. For instance the interquartile range won't work, because if $p < 0.25$, then the interquartile range of the scores doesn't depend on $p$ (so the same $\hat p$ must minimize the IQR for all values of $p$ less than $0.25$, which is bad).
Off the top of my head I can't think of any central tendencies with 0 breakdown point that can't be rewritten as a monotone transformation of the arithmetic mean, but that's probably because I don't know enough variational calculus (certainly not enough to prove I'm right). If I'm correct, however, then it would be "essentially" true that
in order for the theory of proper scoring rules to work as intended, the statistical functional must be the mean.
One other remark: you suggest using the RMSE as a scoring rule, but that you shouldn't do it because it coincides with the absolute error when there is one data point. This seems like it might reflect some confusion. You always evaluate a scoring rule on each individual prediction. Then if you want to summarize the scores, you can take the scores' central tendency afterwards. So predicting to optimize the RMSE is always identical to optimizing the absolute error.
On the other hand, you could do something like take the square root of the mean Brier score as your summary if you wanted to have a score summary that was in "units of probability." But I think it would be more productive to simply familiarize yourself with benchmarks for the Brier score scale, since that's what you'll typically see:
0 is a perfect predictor;
0.25 means no predictive ability ($\hat p = 0.5$);
1 is a perfect anti-predictor ($\hat p = 1, p = 0$ or $\hat p = 0, p = 1$).
You can also construct other benchmarks by using very simple models--for instance, if you ignore all info about the events and simply predict the base rate $p$, then your Brier score is $p(1-p)$. Or if you're predicting time series you can see how well a weighted average of the past few events does, etc. | Alternative notions to that of proper scoring rules, and using scoring rules to evaluate models
Contrary to what you said about geometric mean shenanigans, there are actually proper scoring rules for the geometric mean.
The geometric mean of a random variable $X$ is equal to $e^{E(\log X)}$. The |
31,491 | Alternative notions to that of proper scoring rules, and using scoring rules to evaluate models | You have to go back to the motivation for a proper scoring rule, which you state loosely as "the agent with the least score makes the most accurate guesses." To be precise, the origin of scoring rules are to elicit probabilities that reflect true beliefs -as you state, a person can do no better than offer a probability corresponding to their belief when offered a scoring-rule as a reward. Scoring rules have been used to define what a probability means without referring to the limit of a large number of repetitions.
Such a scoring rule is derived by taking expectation over the rule, hence the appearance of the mean over the set of predictions. So when you ask must "the statistical functional must be the mean?" you are really asking how can we take the expectation over a set of scores by some other method than the conventional use of the mean?
I read into your concern that "proper scoring rules aren't on the same scale as probabilities" that perhaps you are looking to express how good or bad the computed score is? Aside from the Brier score, the log of the absolute difference between the offered probability and a 0,1 outcome is also a proper scoring rule, but that may not give more interpretable results, especially since it can diverge to extreme values for large errors.
Buried in the derivation of scoring rules is that the decision maker has linear utility, hence expectation is taken over the scoring rule directly, not over the utility of the scoring rule outcome. (A person may be risk adverse to large deviations from the truth, and that would bias their elicited probabilities.) Perhaps you are implicitly thinking of a utility function that expresses how good or bad are the "probabilities of what people will choose" instead of just the probabilities themselves? | Alternative notions to that of proper scoring rules, and using scoring rules to evaluate models | You have to go back to the motivation for a proper scoring rule, which you state loosely as "the agent with the least score makes the most accurate guesses." To be precise, the origin of scoring rules | Alternative notions to that of proper scoring rules, and using scoring rules to evaluate models
You have to go back to the motivation for a proper scoring rule, which you state loosely as "the agent with the least score makes the most accurate guesses." To be precise, the origin of scoring rules are to elicit probabilities that reflect true beliefs -as you state, a person can do no better than offer a probability corresponding to their belief when offered a scoring-rule as a reward. Scoring rules have been used to define what a probability means without referring to the limit of a large number of repetitions.
Such a scoring rule is derived by taking expectation over the rule, hence the appearance of the mean over the set of predictions. So when you ask must "the statistical functional must be the mean?" you are really asking how can we take the expectation over a set of scores by some other method than the conventional use of the mean?
I read into your concern that "proper scoring rules aren't on the same scale as probabilities" that perhaps you are looking to express how good or bad the computed score is? Aside from the Brier score, the log of the absolute difference between the offered probability and a 0,1 outcome is also a proper scoring rule, but that may not give more interpretable results, especially since it can diverge to extreme values for large errors.
Buried in the derivation of scoring rules is that the decision maker has linear utility, hence expectation is taken over the scoring rule directly, not over the utility of the scoring rule outcome. (A person may be risk adverse to large deviations from the truth, and that would bias their elicited probabilities.) Perhaps you are implicitly thinking of a utility function that expresses how good or bad are the "probabilities of what people will choose" instead of just the probabilities themselves? | Alternative notions to that of proper scoring rules, and using scoring rules to evaluate models
You have to go back to the motivation for a proper scoring rule, which you state loosely as "the agent with the least score makes the most accurate guesses." To be precise, the origin of scoring rules |
31,492 | What does a random walk do exactly? | I am going to try and answer your first question
A random walk is a series of measurements in which the value at any given point in the series is the value of the previous point in the series plus some random quantity.
For example, suppose you flip a fair coin in a series of tosses, and every time the coin comes up heads you add 1 to the previous value of your serial variable, and every time the coin comes up tails you subtract 1 from the previous value of your serial variable. If the starting value is 0, and if you flip the following sequence of coin tosses:
T H T T T H H H T T H T H T H
The the random walk, $y$ based on these values as described above would be:
0 -1 0 -1 -2 -3 -2 -3 -1 -2 -2 -1 -2 -1 -2 -1
So the value of $y$ is:
$$y_{t} = y_{t-1} + 2\mathcal{Bernoulli}(0.5)–1$$
The distribution of $y$ is dependent on time $t$, giving some interesting properties to a sample of $y$ across different times:
The mean of $y$ is undefined. This may seem counter-intuitive, since you might expect that the heads and tails of a balanced coin are centered on zero. This is true as far as it goes, but zero was just an arbitrary starting value of $y$. So there's no real mean!
The variance of $y=t$. As time (the number of flips) increases, the variance also increases. For example, at the first flip ($t=1$), the possible values are $1$ or $-1$, and indeed the variance then is 1. But at the second flip ($t=2$) the possible values are $2$, $0$ or $-2$, and the variance is equal to 2. For an infinite number of flips (at $t=\infty$, when the range of all possible values of $y$ goes from $-\infty$ to $\infty$), the variance is infinite.
These two facts play havoc on trying to draw inferences about the distribution of $y$ (rather than $y_{t}$ for a given $y_{0}$) given only a sample when using the basic tools of statistical inference. (How can a finite $\bar{y}$ estimate undefined? How can a finite $s^{2}_{y}$ estimate $\sigma^{2}_{y}=\infty$?)
There are many kinds of random walk, and more generally, of autogregressive process (i.e. any variable that depends in some way on its previous values). The example here uses a simple Bernouli random variable (the coin toss), but one could:
add a normally distributed random value to successive values of $y$ instead... or indeed a random value drawn from any sort of distribution;
make the value of $y$ at some point in time depend on previous values of $y$ from more than one point in time (e.g. $y_{t} = y_{t-1} + y_{t-2} + \text{Something Random}$);
pair the value of $y$ with a random value of $x$ to create a two-dimensional random walk;
make $y_{t}$ some fancy function of $y_{t-1}$, a simple example is $y_{t} = \alpha y_{t-1} + \text{Something Random}$, where $|\alpha| < 1$, meaning that the memory of any specific moment of $y$ decays over time (with the memory lasting longer the closer $|\alpha|$ is to 1)—per Alecos' comments, this would simply be 'autoregressive' (a pure random walk would have $|\alpha|=1$);
do lots of other things to make random walks and/or autoregressive processes more complex.
But they are all the Dickens to try and analyze using the basic methods. Which is why we have cointegrating regressions and error correction models and other time series analysis techniques for dealing with these kind of data (which we sometimes refer to as 'non-integrated', 'long-memoried' or 'unit root' among other labels, depending on the details).
The origin of the term "random walk" is from a pair of very brief letters to Nature in 1905.
References
Pearson, K. (1905). Letters to the Editor: The problem of the random walk. Nature, 72(1865):294.
Pearson, K. (1905). Letters to the Editor: The problem of the random walk. Nature, 72(1867):342. | What does a random walk do exactly? | I am going to try and answer your first question
A random walk is a series of measurements in which the value at any given point in the series is the value of the previous point in the series plus som | What does a random walk do exactly?
I am going to try and answer your first question
A random walk is a series of measurements in which the value at any given point in the series is the value of the previous point in the series plus some random quantity.
For example, suppose you flip a fair coin in a series of tosses, and every time the coin comes up heads you add 1 to the previous value of your serial variable, and every time the coin comes up tails you subtract 1 from the previous value of your serial variable. If the starting value is 0, and if you flip the following sequence of coin tosses:
T H T T T H H H T T H T H T H
The the random walk, $y$ based on these values as described above would be:
0 -1 0 -1 -2 -3 -2 -3 -1 -2 -2 -1 -2 -1 -2 -1
So the value of $y$ is:
$$y_{t} = y_{t-1} + 2\mathcal{Bernoulli}(0.5)–1$$
The distribution of $y$ is dependent on time $t$, giving some interesting properties to a sample of $y$ across different times:
The mean of $y$ is undefined. This may seem counter-intuitive, since you might expect that the heads and tails of a balanced coin are centered on zero. This is true as far as it goes, but zero was just an arbitrary starting value of $y$. So there's no real mean!
The variance of $y=t$. As time (the number of flips) increases, the variance also increases. For example, at the first flip ($t=1$), the possible values are $1$ or $-1$, and indeed the variance then is 1. But at the second flip ($t=2$) the possible values are $2$, $0$ or $-2$, and the variance is equal to 2. For an infinite number of flips (at $t=\infty$, when the range of all possible values of $y$ goes from $-\infty$ to $\infty$), the variance is infinite.
These two facts play havoc on trying to draw inferences about the distribution of $y$ (rather than $y_{t}$ for a given $y_{0}$) given only a sample when using the basic tools of statistical inference. (How can a finite $\bar{y}$ estimate undefined? How can a finite $s^{2}_{y}$ estimate $\sigma^{2}_{y}=\infty$?)
There are many kinds of random walk, and more generally, of autogregressive process (i.e. any variable that depends in some way on its previous values). The example here uses a simple Bernouli random variable (the coin toss), but one could:
add a normally distributed random value to successive values of $y$ instead... or indeed a random value drawn from any sort of distribution;
make the value of $y$ at some point in time depend on previous values of $y$ from more than one point in time (e.g. $y_{t} = y_{t-1} + y_{t-2} + \text{Something Random}$);
pair the value of $y$ with a random value of $x$ to create a two-dimensional random walk;
make $y_{t}$ some fancy function of $y_{t-1}$, a simple example is $y_{t} = \alpha y_{t-1} + \text{Something Random}$, where $|\alpha| < 1$, meaning that the memory of any specific moment of $y$ decays over time (with the memory lasting longer the closer $|\alpha|$ is to 1)—per Alecos' comments, this would simply be 'autoregressive' (a pure random walk would have $|\alpha|=1$);
do lots of other things to make random walks and/or autoregressive processes more complex.
But they are all the Dickens to try and analyze using the basic methods. Which is why we have cointegrating regressions and error correction models and other time series analysis techniques for dealing with these kind of data (which we sometimes refer to as 'non-integrated', 'long-memoried' or 'unit root' among other labels, depending on the details).
The origin of the term "random walk" is from a pair of very brief letters to Nature in 1905.
References
Pearson, K. (1905). Letters to the Editor: The problem of the random walk. Nature, 72(1865):294.
Pearson, K. (1905). Letters to the Editor: The problem of the random walk. Nature, 72(1867):342. | What does a random walk do exactly?
I am going to try and answer your first question
A random walk is a series of measurements in which the value at any given point in the series is the value of the previous point in the series plus som |
31,493 | Example of sample $X_1,X_2,\ldots,X_n$ | Here is a quick summary of the way I (try to) explain this to my students (who are unfortunately not fluent in mathematics...).
a random experiment is an experiment which, when repeated, can produce different outputs.
such an experiment can be, e.g.: pick a random person in Paris and measure them. The output is a height. Each particular experiment leads a height $x$, which is a real number. We denote $X$ the random variable which is associated to this experiment; $X$ is not a number. A way to see it is as function from the set $\Omega$ of all possible experiment results, in our case the set of Parisians, to the real numbers. In this optic, a random variable is a measure done on a random experiment.
if you repeat this experiment, say, 10 times, you’ll get 10 sizes. But the day after, you do this again: pick 10 random guys, measure them. You’ll get 10 other heights. You can repeat this over and over, and you’ll get a bunch of different results. This is a (new) random experiment. The set of possible outcomes is the set of all 10-tuples of Parisians. For each of these experiments, you have 10 measures, that is 10 random variables $X_1, \dots, X_{10}$. This also explain that the arithmetic mean ${1\over 10}(X_1 + \cdots + X_{10})$ is a random variable, to be studied as such.
I hope this helps a bit. I swear that when I make the gestures, this is somehow convincing. | Example of sample $X_1,X_2,\ldots,X_n$ | Here is a quick summary of the way I (try to) explain this to my students (who are unfortunately not fluent in mathematics...).
a random experiment is an experiment which, when repeated, can produce | Example of sample $X_1,X_2,\ldots,X_n$
Here is a quick summary of the way I (try to) explain this to my students (who are unfortunately not fluent in mathematics...).
a random experiment is an experiment which, when repeated, can produce different outputs.
such an experiment can be, e.g.: pick a random person in Paris and measure them. The output is a height. Each particular experiment leads a height $x$, which is a real number. We denote $X$ the random variable which is associated to this experiment; $X$ is not a number. A way to see it is as function from the set $\Omega$ of all possible experiment results, in our case the set of Parisians, to the real numbers. In this optic, a random variable is a measure done on a random experiment.
if you repeat this experiment, say, 10 times, you’ll get 10 sizes. But the day after, you do this again: pick 10 random guys, measure them. You’ll get 10 other heights. You can repeat this over and over, and you’ll get a bunch of different results. This is a (new) random experiment. The set of possible outcomes is the set of all 10-tuples of Parisians. For each of these experiments, you have 10 measures, that is 10 random variables $X_1, \dots, X_{10}$. This also explain that the arithmetic mean ${1\over 10}(X_1 + \cdots + X_{10})$ is a random variable, to be studied as such.
I hope this helps a bit. I swear that when I make the gestures, this is somehow convincing. | Example of sample $X_1,X_2,\ldots,X_n$
Here is a quick summary of the way I (try to) explain this to my students (who are unfortunately not fluent in mathematics...).
a random experiment is an experiment which, when repeated, can produce |
31,494 | How to find average and median age from an aggregated frequency table | General comments: If the union of all bins was a finite interval, you could compute a mean with certain assumptions, or you could get bounds without any assumptions. A common (though often untenable) assumption is uniformity within a bin. If the bins are not wide it can still be a useful approximation.
With an open upper-end bin (75+), you can't compute an average without some strong assumptions. It would be useful to explore sensitivity of the mean estimate to those assumptions.
Usually you can compute a median category, and it's straightforward, so let's begin there.
Median: The median age is the age of the "middle person" (or any value between the middle two people if there's an even number - with binned data you want those two to be in the same bin; fortunately it's rare for a bin boundary to be between them, in which case either bin could be regarded as the median bin; you might choose the boundary itself as the median in that case).
With 107769 people, the age of the (107769 + 1)/2 = 53885-th oldest person is the median age.
Agegroup Count cumsum(age$Count)
1 Under 5 6360 6360
2 5-9 6360 12720
3 10-14 10986 23706
4 15-17 5204 28910
5 18-24 7886 36796
6 25-34 9463 46259
7 35-44 17349 63608
8 45-54 18926 82534
9 55-64 13406 95940
10 65-74 6309 102249
11 75 and over 5520 107769
there are 46259 people aged 34 or younger and 63608 aged 44 or younger, so the median age group is 35-44.
You could go further by making some assumptions to try to make an estimate of the year within that - e.g. if you assume uniform age distribution within bins, the median age would be (53885-46259)/17349 = 43.96% of the way through the range of ages in that age group, which suggests a median age of about 39.4. However, you would need to assess the reasonableness of that assumption. Being close to the mode with what looks like (and probably is) a fairly smooth distribution, it may not be so bad an assumption for a rough approximation]
Some books give formulas by which to calculate an estimate of the median which amount to doing pretty much what I just did, such as a formula like this: median = $L + w\frac{(\frac{n}{2} − c)}{f}$ (where $L$ is the lower limit of the bin containing the median, $w$ is the width of that bin, $n$ is the total population, $c$ is the cumulative count (cumulative frequency) up to $L$ (the end of the previous bin), and $f$ is the count (frequency) in the median bin does pretty much the same thing (aside from the (n+1)/2 vs n/2, it is the same).
Mean: The mean is most often calculated by treating the data as if it occurred at the bin-centers. For the mean, this is equivalent to assuming the data are uniformly spread within each bin.
Clearly this presents a problem with the last category which has no upper bound. Even if you imposed one ("well, let's say nobody lives past 120"), the midpoint is still a terrible estimate of the mean within the group. You can do things like assume the distribution is similar to some population and get estimates from life tables (many countries make life tables available, which allow calculation of the proportion of people alive at each age, say).
You could also simply assume some average (say 80, or 85), and then see how much difference it made. Nine year old (or so) figures from one Western country (one with longer average lifespan than the US) suggests that the average age of males 75+ is 82.2 - If you can't get suitable figures, I'd think assuming 82 and trying 80 and 85 to get some idea of sensitivity to the assumption would be reasonable.
(More complicated assumptions than the ones described here are possible but not as often used) | How to find average and median age from an aggregated frequency table | General comments: If the union of all bins was a finite interval, you could compute a mean with certain assumptions, or you could get bounds without any assumptions. A common (though often untenable) | How to find average and median age from an aggregated frequency table
General comments: If the union of all bins was a finite interval, you could compute a mean with certain assumptions, or you could get bounds without any assumptions. A common (though often untenable) assumption is uniformity within a bin. If the bins are not wide it can still be a useful approximation.
With an open upper-end bin (75+), you can't compute an average without some strong assumptions. It would be useful to explore sensitivity of the mean estimate to those assumptions.
Usually you can compute a median category, and it's straightforward, so let's begin there.
Median: The median age is the age of the "middle person" (or any value between the middle two people if there's an even number - with binned data you want those two to be in the same bin; fortunately it's rare for a bin boundary to be between them, in which case either bin could be regarded as the median bin; you might choose the boundary itself as the median in that case).
With 107769 people, the age of the (107769 + 1)/2 = 53885-th oldest person is the median age.
Agegroup Count cumsum(age$Count)
1 Under 5 6360 6360
2 5-9 6360 12720
3 10-14 10986 23706
4 15-17 5204 28910
5 18-24 7886 36796
6 25-34 9463 46259
7 35-44 17349 63608
8 45-54 18926 82534
9 55-64 13406 95940
10 65-74 6309 102249
11 75 and over 5520 107769
there are 46259 people aged 34 or younger and 63608 aged 44 or younger, so the median age group is 35-44.
You could go further by making some assumptions to try to make an estimate of the year within that - e.g. if you assume uniform age distribution within bins, the median age would be (53885-46259)/17349 = 43.96% of the way through the range of ages in that age group, which suggests a median age of about 39.4. However, you would need to assess the reasonableness of that assumption. Being close to the mode with what looks like (and probably is) a fairly smooth distribution, it may not be so bad an assumption for a rough approximation]
Some books give formulas by which to calculate an estimate of the median which amount to doing pretty much what I just did, such as a formula like this: median = $L + w\frac{(\frac{n}{2} − c)}{f}$ (where $L$ is the lower limit of the bin containing the median, $w$ is the width of that bin, $n$ is the total population, $c$ is the cumulative count (cumulative frequency) up to $L$ (the end of the previous bin), and $f$ is the count (frequency) in the median bin does pretty much the same thing (aside from the (n+1)/2 vs n/2, it is the same).
Mean: The mean is most often calculated by treating the data as if it occurred at the bin-centers. For the mean, this is equivalent to assuming the data are uniformly spread within each bin.
Clearly this presents a problem with the last category which has no upper bound. Even if you imposed one ("well, let's say nobody lives past 120"), the midpoint is still a terrible estimate of the mean within the group. You can do things like assume the distribution is similar to some population and get estimates from life tables (many countries make life tables available, which allow calculation of the proportion of people alive at each age, say).
You could also simply assume some average (say 80, or 85), and then see how much difference it made. Nine year old (or so) figures from one Western country (one with longer average lifespan than the US) suggests that the average age of males 75+ is 82.2 - If you can't get suitable figures, I'd think assuming 82 and trying 80 and 85 to get some idea of sensitivity to the assumption would be reasonable.
(More complicated assumptions than the ones described here are possible but not as often used) | How to find average and median age from an aggregated frequency table
General comments: If the union of all bins was a finite interval, you could compute a mean with certain assumptions, or you could get bounds without any assumptions. A common (though often untenable) |
31,495 | How to find average and median age from an aggregated frequency table | I realize this is an old post, but since it came up in my quest to find a VBA script to calculate the median from a range of values (values in bins) like the original poster asked for, I thought I'd post my solution to share with others.
I am beginner when it comes to VB so its possible there are easier ways to do some of the things I did. I have included comments to document what each step of my script is doing.
You will need to have at least 2 columns in your spreadsheet/range of values. The first column must be the beginning of the range (i.e. if it is for income values with the first two ranges
$0 to $9,9999
$10,000 to $14,9999
Then the first 2 rows of the first colmun should be 0 and 10000). Example in attached screen shot (highlighted portion would be my input).
The script prompts for the input range of values. You can have multiple columns of population that you want to get the median for. It will also prompt for the cell you want to put the output, median value(s), into.
here is the script
Sub GetMedian()
'have user select the range for the input data
'the first column must be the number for the beginning of the range
'for the bin
'the second column (can have more than one if doing mulitple areas)
'has the population for that bin
Dim UserRange As Range
Prompt = "Select the input range." & vbCrLf & _
vbCrLf & "The first column must be the beginning of the " & _
vbCrLf & "range for the bin. The second column has the " & _
vbCrLf & "population for the bin. You can have more than " & _
vbCrLf & "one column of populations." & _
vbCrLf
Title = "Select a range"
'Display the Input Box
Set UserRange = Application.InputBox( _
Prompt:=Prompt, _
Title:=Title, _
Default:=Selection.Address, _
Type:=8) 'Range selection
'get current selected range
Dim myString As String
'myString = Selection.Address
myString = UserRange.Address
'go though the columns
'how many columns are in the UserRange?
NoOfCol = Range(myString).Columns.count
'get the output range from the user
Dim OutRange As Range
Prompt = "Select a cell for the output" & vbCrLf & _
vbCrLf & "Values for multiple medians will be " & _
vbCrLf & "returned in a row beginning with the " & _
vbCrLf & "selected cell " & _
vbCrLf
' Display the Input Box
On Error Resume Next
Set OutRange = Application.InputBox( _
Prompt:=Prompt, _
Title:=Title, _
Default:=ActiveCell.Address, _
Type:=8) 'Range selection
'now get to work
'for loop starts with the first population column (2nd in range)
'end is how many pop columns are in the user input range
For col = 2 To NoOfCol
'set range as an array
Dim myArray() As Variant
myArray = Range(myString).Value
'get sum of pop and divide by 2 to get halfpoint
'initialize a total to aggregate values
popSum = 0
For i = 1 To UBound(myArray)
popSum = popSum + myArray(i, col)
Next
'MsgBox popSum
MedianIndex = popSum / 2
'MsgBox MedianIndex
'initialize for running total
runtotal = 0
'step through each row
For i = 1 To UBound(myArray)
'add the cumulative total pop
runtotal = runtotal + myArray(i, col)
'check if the runtotal exceeds the medianIndex
If runtotal > MedianIndex Then
'get the cumulative pop for the bin just before we exceeded
'so subtract the current array value from the current runTotal
prevTotal = runtotal - myArray(i, col)
'determine how much into the bin it is to reach the medianIndex
howMany = MedianIndex - prevTotal
'get the pop value in the previous bin
Binpop = myArray(i, col)
'determine the pct of how far into this bin the medianIndex falls
pctInto = howMany / Binpop
'determine the span of the bin
'and multiply it by the pct into the bin
MultiSpan = (myArray(i, 1) - myArray(i - 1, 1)) * pctInto
'calculate the median by adding the result to
'the number for the beginning of hte range
Median = myArray(i, 1) + MultiSpan
'put the median in the output cell
OutRange.Offset(0, col - 2).Value = Median
Exit For
End If
Next
Next
End Sub | How to find average and median age from an aggregated frequency table | I realize this is an old post, but since it came up in my quest to find a VBA script to calculate the median from a range of values (values in bins) like the original poster asked for, I thought I'd p | How to find average and median age from an aggregated frequency table
I realize this is an old post, but since it came up in my quest to find a VBA script to calculate the median from a range of values (values in bins) like the original poster asked for, I thought I'd post my solution to share with others.
I am beginner when it comes to VB so its possible there are easier ways to do some of the things I did. I have included comments to document what each step of my script is doing.
You will need to have at least 2 columns in your spreadsheet/range of values. The first column must be the beginning of the range (i.e. if it is for income values with the first two ranges
$0 to $9,9999
$10,000 to $14,9999
Then the first 2 rows of the first colmun should be 0 and 10000). Example in attached screen shot (highlighted portion would be my input).
The script prompts for the input range of values. You can have multiple columns of population that you want to get the median for. It will also prompt for the cell you want to put the output, median value(s), into.
here is the script
Sub GetMedian()
'have user select the range for the input data
'the first column must be the number for the beginning of the range
'for the bin
'the second column (can have more than one if doing mulitple areas)
'has the population for that bin
Dim UserRange As Range
Prompt = "Select the input range." & vbCrLf & _
vbCrLf & "The first column must be the beginning of the " & _
vbCrLf & "range for the bin. The second column has the " & _
vbCrLf & "population for the bin. You can have more than " & _
vbCrLf & "one column of populations." & _
vbCrLf
Title = "Select a range"
'Display the Input Box
Set UserRange = Application.InputBox( _
Prompt:=Prompt, _
Title:=Title, _
Default:=Selection.Address, _
Type:=8) 'Range selection
'get current selected range
Dim myString As String
'myString = Selection.Address
myString = UserRange.Address
'go though the columns
'how many columns are in the UserRange?
NoOfCol = Range(myString).Columns.count
'get the output range from the user
Dim OutRange As Range
Prompt = "Select a cell for the output" & vbCrLf & _
vbCrLf & "Values for multiple medians will be " & _
vbCrLf & "returned in a row beginning with the " & _
vbCrLf & "selected cell " & _
vbCrLf
' Display the Input Box
On Error Resume Next
Set OutRange = Application.InputBox( _
Prompt:=Prompt, _
Title:=Title, _
Default:=ActiveCell.Address, _
Type:=8) 'Range selection
'now get to work
'for loop starts with the first population column (2nd in range)
'end is how many pop columns are in the user input range
For col = 2 To NoOfCol
'set range as an array
Dim myArray() As Variant
myArray = Range(myString).Value
'get sum of pop and divide by 2 to get halfpoint
'initialize a total to aggregate values
popSum = 0
For i = 1 To UBound(myArray)
popSum = popSum + myArray(i, col)
Next
'MsgBox popSum
MedianIndex = popSum / 2
'MsgBox MedianIndex
'initialize for running total
runtotal = 0
'step through each row
For i = 1 To UBound(myArray)
'add the cumulative total pop
runtotal = runtotal + myArray(i, col)
'check if the runtotal exceeds the medianIndex
If runtotal > MedianIndex Then
'get the cumulative pop for the bin just before we exceeded
'so subtract the current array value from the current runTotal
prevTotal = runtotal - myArray(i, col)
'determine how much into the bin it is to reach the medianIndex
howMany = MedianIndex - prevTotal
'get the pop value in the previous bin
Binpop = myArray(i, col)
'determine the pct of how far into this bin the medianIndex falls
pctInto = howMany / Binpop
'determine the span of the bin
'and multiply it by the pct into the bin
MultiSpan = (myArray(i, 1) - myArray(i - 1, 1)) * pctInto
'calculate the median by adding the result to
'the number for the beginning of hte range
Median = myArray(i, 1) + MultiSpan
'put the median in the output cell
OutRange.Offset(0, col - 2).Value = Median
Exit For
End If
Next
Next
End Sub | How to find average and median age from an aggregated frequency table
I realize this is an old post, but since it came up in my quest to find a VBA script to calculate the median from a range of values (values in bins) like the original poster asked for, I thought I'd p |
31,496 | On Negative AIC Values | $L$ is not a joint probability (joint cumulative probability density) but joint probability density. Since density only needs to be non-negative and is not bounded from above, $\operatorname{ln}(L)$ can be both positive and negative. Hence, $AIC$ can also be both positive and negative. | On Negative AIC Values | $L$ is not a joint probability (joint cumulative probability density) but joint probability density. Since density only needs to be non-negative and is not bounded from above, $\operatorname{ln}(L)$ c | On Negative AIC Values
$L$ is not a joint probability (joint cumulative probability density) but joint probability density. Since density only needs to be non-negative and is not bounded from above, $\operatorname{ln}(L)$ can be both positive and negative. Hence, $AIC$ can also be both positive and negative. | On Negative AIC Values
$L$ is not a joint probability (joint cumulative probability density) but joint probability density. Since density only needs to be non-negative and is not bounded from above, $\operatorname{ln}(L)$ c |
31,497 | Granger causality interpretation using R | The help page for the grangertest function is pretty clear, it should be of major help.
Model 1 is the unrestricted model that includes the Granger-causal terms.
Model 2 is the restricted model where the Granger-causal terms are omitted.
The test is a Wald test that assesses whether using the restricted Model 2 in place of Model 1 makes statistical sense (roughly speaking).
You interpret the results as follows:
if Pr(>F)$ < \alpha$ (where $\alpha$ is your desired level of significance), you reject the null hypothesis of no Granger causality. This indicates that Model 2 is too restrictive as compared with Model 1.
If the inequality is reversed, you do not reject the null hypothesis as the richer Model 1 is preferred to the restricted Model 2.
Note: you say we are checking to see if one variable can be used to predict another.
A more precise statement would be we are checking to see if including $x$ is useful for predicting $y$ when $y$'s own history is already being used for prediction. That is, do not miss the fact the $x$ has to be useful beyond (or extra to) the own history of $y$. | Granger causality interpretation using R | The help page for the grangertest function is pretty clear, it should be of major help.
Model 1 is the unrestricted model that includes the Granger-causal terms.
Model 2 is the restricted model where | Granger causality interpretation using R
The help page for the grangertest function is pretty clear, it should be of major help.
Model 1 is the unrestricted model that includes the Granger-causal terms.
Model 2 is the restricted model where the Granger-causal terms are omitted.
The test is a Wald test that assesses whether using the restricted Model 2 in place of Model 1 makes statistical sense (roughly speaking).
You interpret the results as follows:
if Pr(>F)$ < \alpha$ (where $\alpha$ is your desired level of significance), you reject the null hypothesis of no Granger causality. This indicates that Model 2 is too restrictive as compared with Model 1.
If the inequality is reversed, you do not reject the null hypothesis as the richer Model 1 is preferred to the restricted Model 2.
Note: you say we are checking to see if one variable can be used to predict another.
A more precise statement would be we are checking to see if including $x$ is useful for predicting $y$ when $y$'s own history is already being used for prediction. That is, do not miss the fact the $x$ has to be useful beyond (or extra to) the own history of $y$. | Granger causality interpretation using R
The help page for the grangertest function is pretty clear, it should be of major help.
Model 1 is the unrestricted model that includes the Granger-causal terms.
Model 2 is the restricted model where |
31,498 | Minimum sample size for 1 way ANOVA? | Described below are three approaches to estimating sample size for completely randomized designs. Note that the procedures differ in terms of the information you must provide.
Approach #1 (requires most information)
To calculate sample size, the researcher first needs to specify:
1) level of significance, α (alpha)
2) power, 1-β
3) size of the population variance, σ2
4) sum of the squared population treatment effects.
In practice, 3 and 4 are unknown. However, you can estimate both from a pilot stud. Alternatively, you might estimate these parameters from previous research.
As an example, let's assume we conducted a pilot study and estimated the population variance and sum of squared population treatment effects. If we let α = 0.05 and 1-β = 0.80, then we can use trial and error to calculate the required sample size. The test statistic you calculate is phi (Φ), where:
Φ = (n^0.5)[(average of squared treatment effects/population variance)], where n is a sample size value. The Φ test statistic can then be used to look up power that corresponds to the sample size in Tang's Charts (citation below).
Approach #2
If accurate estimates of #3 and #4 are not available from a pilot study or previous research, then one can use an alternative approach that requires a general idea about the size of the difference between the largest and smallest population means relative to the standard deviation of the population standard deviation:
μmax - μmin = dσ, where d is a multiple of the population standard deviation. In other words, this approach allows you to calculate the sample size if you wanted to detect a difference between the highest and smallest means that would equal to some multiplier of the pop. standard deviation (whether it's one half, or 1.5, or anything else). For the math for this approach, see Kirk (2013) [I have a PDF].
Approach 3
If you know nothing about #3 and #4 from Approach 1, and are unable to express μmax - μmin as a multiple of pop. standard deviation, then you can use strength of association or the effect size to calculate the sample size. This approach also requires the researcher to specify the level of significance, α, as well as the power, 1 - β.
Remember that the strength of an association indicates the proportion of the population variance in the dependent variable that is accounted for by the independent variable. Omega squared is used to measure the strength of association in analysis of variances with fixed treatment effects, whereas intraclass correlation is used in analysis of variance with random treatment effects.
Based on Cohen (1988), we know that (for strength of association):
ω^2 = 0.010 is a small association
ω^2 = 0.059 is a medium association
ω^2 = 0.138 or larger is a large association
And for effect size:
f = 0.10 is a small effect size
f = 0.25 is a medium effect size
f = 0.40 or larger is a large effect size.
Back to the Approach 3: if we have a completely randomized design with p treatment levels, then we can calculate the sample size necessary to detect any magnitude of strength of association OR any magnitude of effect size (the mathematics are equivalent). Again, if you are interested for working out the math for this approach, I refer you to Kirk (2013).
Cohen, J. (1988). Statistical power analysis for the behavioral sciences (2nd ed.). Hillsdale, NJ: Lawrence Erlbaum
Kirk, R.E. (2013) Experimental Design: Procedures for the Behavioral Sciences
Tang, P. C. The power function of the analysis of variance test with tables and illustrations of their use.Statist. res. Memoirs. 1938,2, 126–149. | Minimum sample size for 1 way ANOVA? | Described below are three approaches to estimating sample size for completely randomized designs. Note that the procedures differ in terms of the information you must provide.
Approach #1 (requires m | Minimum sample size for 1 way ANOVA?
Described below are three approaches to estimating sample size for completely randomized designs. Note that the procedures differ in terms of the information you must provide.
Approach #1 (requires most information)
To calculate sample size, the researcher first needs to specify:
1) level of significance, α (alpha)
2) power, 1-β
3) size of the population variance, σ2
4) sum of the squared population treatment effects.
In practice, 3 and 4 are unknown. However, you can estimate both from a pilot stud. Alternatively, you might estimate these parameters from previous research.
As an example, let's assume we conducted a pilot study and estimated the population variance and sum of squared population treatment effects. If we let α = 0.05 and 1-β = 0.80, then we can use trial and error to calculate the required sample size. The test statistic you calculate is phi (Φ), where:
Φ = (n^0.5)[(average of squared treatment effects/population variance)], where n is a sample size value. The Φ test statistic can then be used to look up power that corresponds to the sample size in Tang's Charts (citation below).
Approach #2
If accurate estimates of #3 and #4 are not available from a pilot study or previous research, then one can use an alternative approach that requires a general idea about the size of the difference between the largest and smallest population means relative to the standard deviation of the population standard deviation:
μmax - μmin = dσ, where d is a multiple of the population standard deviation. In other words, this approach allows you to calculate the sample size if you wanted to detect a difference between the highest and smallest means that would equal to some multiplier of the pop. standard deviation (whether it's one half, or 1.5, or anything else). For the math for this approach, see Kirk (2013) [I have a PDF].
Approach 3
If you know nothing about #3 and #4 from Approach 1, and are unable to express μmax - μmin as a multiple of pop. standard deviation, then you can use strength of association or the effect size to calculate the sample size. This approach also requires the researcher to specify the level of significance, α, as well as the power, 1 - β.
Remember that the strength of an association indicates the proportion of the population variance in the dependent variable that is accounted for by the independent variable. Omega squared is used to measure the strength of association in analysis of variances with fixed treatment effects, whereas intraclass correlation is used in analysis of variance with random treatment effects.
Based on Cohen (1988), we know that (for strength of association):
ω^2 = 0.010 is a small association
ω^2 = 0.059 is a medium association
ω^2 = 0.138 or larger is a large association
And for effect size:
f = 0.10 is a small effect size
f = 0.25 is a medium effect size
f = 0.40 or larger is a large effect size.
Back to the Approach 3: if we have a completely randomized design with p treatment levels, then we can calculate the sample size necessary to detect any magnitude of strength of association OR any magnitude of effect size (the mathematics are equivalent). Again, if you are interested for working out the math for this approach, I refer you to Kirk (2013).
Cohen, J. (1988). Statistical power analysis for the behavioral sciences (2nd ed.). Hillsdale, NJ: Lawrence Erlbaum
Kirk, R.E. (2013) Experimental Design: Procedures for the Behavioral Sciences
Tang, P. C. The power function of the analysis of variance test with tables and illustrations of their use.Statist. res. Memoirs. 1938,2, 126–149. | Minimum sample size for 1 way ANOVA?
Described below are three approaches to estimating sample size for completely randomized designs. Note that the procedures differ in terms of the information you must provide.
Approach #1 (requires m |
31,499 | Minimum sample size for 1 way ANOVA? | The absolute minimum possible sample size for a one way ANOVA F-test would be one more than the number of groups. It's unclear in your question, but it sounds like you have 6 per group.
(It's not advisable to have so few, but it's possible to do ANOVA in that situation and still have the theory work when the assumptions hold -- though you can't check them.)
If I correctly understand Dunnett's procedure, the minimum would be the same for that, since its pariwise comparisons appear to be based off the same common estimate of $\sigma$ as the ANOVA.
The biggest concerns at really small sample sizes would be very low power and higher-than-usual sensitivity to the normality assumption at very low sample size; if you specify power you may then be able to calculate a minimum sample size for that; similarly I can't really decide how much impact (on significance level or power) from sensitivity to non-normality you can bear. | Minimum sample size for 1 way ANOVA? | The absolute minimum possible sample size for a one way ANOVA F-test would be one more than the number of groups. It's unclear in your question, but it sounds like you have 6 per group.
(It's not advi | Minimum sample size for 1 way ANOVA?
The absolute minimum possible sample size for a one way ANOVA F-test would be one more than the number of groups. It's unclear in your question, but it sounds like you have 6 per group.
(It's not advisable to have so few, but it's possible to do ANOVA in that situation and still have the theory work when the assumptions hold -- though you can't check them.)
If I correctly understand Dunnett's procedure, the minimum would be the same for that, since its pariwise comparisons appear to be based off the same common estimate of $\sigma$ as the ANOVA.
The biggest concerns at really small sample sizes would be very low power and higher-than-usual sensitivity to the normality assumption at very low sample size; if you specify power you may then be able to calculate a minimum sample size for that; similarly I can't really decide how much impact (on significance level or power) from sensitivity to non-normality you can bear. | Minimum sample size for 1 way ANOVA?
The absolute minimum possible sample size for a one way ANOVA F-test would be one more than the number of groups. It's unclear in your question, but it sounds like you have 6 per group.
(It's not advi |
31,500 | Minimum sample size for 1 way ANOVA? | There is not a minimum sample size for ANOVA, but you might have problems with statistical power which is your ability to reject a false null hypothesis. If the effect size differences between baseline and the other measures is not large enough you may not be able to reject the null. If you reject the Null then no worries. If you fail to reject but you think that there are meaningful differences, try collecting more data to increase your statistical power. If you cannot collect more data and want to know if more data would have made a difference, copy and paste your data thus doubling its size and then re-run the analysis. If the results are significant then you know the problem is low power due to small sample size. You can then report that your results would have been significant if you had more cases, but do not report the results you get from artificially doubling your sample size - this would not be appropriate. | Minimum sample size for 1 way ANOVA? | There is not a minimum sample size for ANOVA, but you might have problems with statistical power which is your ability to reject a false null hypothesis. If the effect size differences between baselin | Minimum sample size for 1 way ANOVA?
There is not a minimum sample size for ANOVA, but you might have problems with statistical power which is your ability to reject a false null hypothesis. If the effect size differences between baseline and the other measures is not large enough you may not be able to reject the null. If you reject the Null then no worries. If you fail to reject but you think that there are meaningful differences, try collecting more data to increase your statistical power. If you cannot collect more data and want to know if more data would have made a difference, copy and paste your data thus doubling its size and then re-run the analysis. If the results are significant then you know the problem is low power due to small sample size. You can then report that your results would have been significant if you had more cases, but do not report the results you get from artificially doubling your sample size - this would not be appropriate. | Minimum sample size for 1 way ANOVA?
There is not a minimum sample size for ANOVA, but you might have problems with statistical power which is your ability to reject a false null hypothesis. If the effect size differences between baselin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.