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 |
|---|---|---|---|---|---|---|
32,001 | Is neural network able to learn from zero inputs? | In fact the OP intuition is right, an input value of exactly zero prevents the network from learning something from it. The solution is to be found in the algorithm of gradient retropropagation. The delta between a previous weight and the new weight is a multiplication of several terms that depends on the learning algorithm you use. One of its terms is always the value of the previous neuron. Hence, if an input value is zero, all connected weight will not change at this iteration.
Lets be a little more formal here. Let is an arbitrary weigth at the iteration t, we are looking to get , the new weight, after retropropagating the error calculated at the end of the forward pass is defined by:
With , the output value of a neuron from the previous layer, the partial error of the current neuron (that depends of the learning algorithm) and a learning rate. If is zero, there is no weight modification.
This is the classic formula of error retropropagation, obviously nowadays things get more complex because we train samples in batch and learning algorithms evolved but for sake of simplicity we can jump to the conclusion that it is perfectly safe to replace missing values by zero. | Is neural network able to learn from zero inputs? | In fact the OP intuition is right, an input value of exactly zero prevents the network from learning something from it. The solution is to be found in the algorithm of gradient retropropagation. The d | Is neural network able to learn from zero inputs?
In fact the OP intuition is right, an input value of exactly zero prevents the network from learning something from it. The solution is to be found in the algorithm of gradient retropropagation. The delta between a previous weight and the new weight is a multiplication of several terms that depends on the learning algorithm you use. One of its terms is always the value of the previous neuron. Hence, if an input value is zero, all connected weight will not change at this iteration.
Lets be a little more formal here. Let is an arbitrary weigth at the iteration t, we are looking to get , the new weight, after retropropagating the error calculated at the end of the forward pass is defined by:
With , the output value of a neuron from the previous layer, the partial error of the current neuron (that depends of the learning algorithm) and a learning rate. If is zero, there is no weight modification.
This is the classic formula of error retropropagation, obviously nowadays things get more complex because we train samples in batch and learning algorithms evolved but for sake of simplicity we can jump to the conclusion that it is perfectly safe to replace missing values by zero. | Is neural network able to learn from zero inputs?
In fact the OP intuition is right, an input value of exactly zero prevents the network from learning something from it. The solution is to be found in the algorithm of gradient retropropagation. The d |
32,002 | How to define multiple losses in machine learning? | Using two losses means that you are interested in optimizing both of them. It may come from that you are doing two different tasks and you are sharing some part of your model between two tasks. Or in some way, it may come from that you look for optimizing over a multi objective situation.
Here is some examples using multiple losses:
Training a classifier and using regularization term (e.g. L1 L2 etc. regularization terms). In this case you are interested in classifying inputs but you don't want your weights to grow too large. So you will optimize some linear combination of two losses. (that linear combination weight would be a hyper parameter and you can tune it using hyper parameter tuning techniques just like Cross Validation)
Training a network that has an input (images of clothes) and classifies it in two ways: 1- its color 2- its size. In this example, one can think its better to train two disjoint models, but in some situations sharing some layers of Neural Network helps the generalization of the model. In this example, you would like to optimize a summation of two losses and it would work nicely in most cases. (I think it isn't necessary to add a hyper parameter to it because minimizing summation of partially independent losses, leads to optimizing both of them in the best way.)
Doing this optimization in Tensorflow would be a piece of cake :)
# add both loss
final_loss = tf.add(loss1,loss2)
train_op = tf.train.AdamOptimizer().minimize(final_loss)
Or you may like to:
optimizer1 = tf.train.AdamOptimizer().minimize(loss1)
optimizer2 = tf.train.AdamOptimizer().minimize(loss2)
# in training:
_, _, l1, l2 = sess.run(fetches=[optimizer1, optimizer2, loss1, loss2], feed_dict={x: batch_x, y: batch_y})
Or maybe:
optimizer1 = tf.train.AdamOptimizer().minimize(loss1)
optimizer2 = tf.train.AdamOptimizer().minimize(loss2)
# in training:
_, l1 = sess.run(fetches=[optimizer1, loss1], feed_dict={x: batch_x, y: batch_y})
_, l2 = sess.run(fetches=[optimizer2, loss2], feed_dict={x: batch_x, y: batch_y})
Hope that be helpful :) | How to define multiple losses in machine learning? | Using two losses means that you are interested in optimizing both of them. It may come from that you are doing two different tasks and you are sharing some part of your model between two tasks. Or in | How to define multiple losses in machine learning?
Using two losses means that you are interested in optimizing both of them. It may come from that you are doing two different tasks and you are sharing some part of your model between two tasks. Or in some way, it may come from that you look for optimizing over a multi objective situation.
Here is some examples using multiple losses:
Training a classifier and using regularization term (e.g. L1 L2 etc. regularization terms). In this case you are interested in classifying inputs but you don't want your weights to grow too large. So you will optimize some linear combination of two losses. (that linear combination weight would be a hyper parameter and you can tune it using hyper parameter tuning techniques just like Cross Validation)
Training a network that has an input (images of clothes) and classifies it in two ways: 1- its color 2- its size. In this example, one can think its better to train two disjoint models, but in some situations sharing some layers of Neural Network helps the generalization of the model. In this example, you would like to optimize a summation of two losses and it would work nicely in most cases. (I think it isn't necessary to add a hyper parameter to it because minimizing summation of partially independent losses, leads to optimizing both of them in the best way.)
Doing this optimization in Tensorflow would be a piece of cake :)
# add both loss
final_loss = tf.add(loss1,loss2)
train_op = tf.train.AdamOptimizer().minimize(final_loss)
Or you may like to:
optimizer1 = tf.train.AdamOptimizer().minimize(loss1)
optimizer2 = tf.train.AdamOptimizer().minimize(loss2)
# in training:
_, _, l1, l2 = sess.run(fetches=[optimizer1, optimizer2, loss1, loss2], feed_dict={x: batch_x, y: batch_y})
Or maybe:
optimizer1 = tf.train.AdamOptimizer().minimize(loss1)
optimizer2 = tf.train.AdamOptimizer().minimize(loss2)
# in training:
_, l1 = sess.run(fetches=[optimizer1, loss1], feed_dict={x: batch_x, y: batch_y})
_, l2 = sess.run(fetches=[optimizer2, loss2], feed_dict={x: batch_x, y: batch_y})
Hope that be helpful :) | How to define multiple losses in machine learning?
Using two losses means that you are interested in optimizing both of them. It may come from that you are doing two different tasks and you are sharing some part of your model between two tasks. Or in |
32,003 | Feature Importance/Impact for Individual Predictions | The topic you are addressing is known as model explanation or model interpretation and quite an active topic in research. The general idea is to find out, which features contributed to the model, and which not.
You already mentioned some popular techniques, such as the Partial Dependence Plots (PDP) or LIME. In a PDP, the influence of a features' value to the model output is displayed by creating new instances from the data that have a modified feature value and predict them by the model. LIME creates a local approximation of the model by sampling instances around a requested instance and learning a simpler, more interpretable model.
In the naive method you described, the impact of a feature is neutralised by setting it to the population mean. You are absolutely right, that this is not an appropriate method, as the prediction of the mean value is not probably not the mean prediction. Also, it does not reflect the feature distribution and does not work for categorical attributes.
Robnik-Sikonja and Kononenko [1] addressed this problem. Their basic idea is the same: the prediction difference between the unchanged instance, and an instance with a neutralised feature. However, instead of taking the mean value to get rid of the features' impact, they create several instance copies, each with a different value. For categorical values, they iterate over all possible categories; for numerical values, they discretise the data into bins. The decomposed instances are weighted by the feature value frequency in the data. Missing data can be ignored by using classifiers that can handle it, or imputing it, e.g. by setting the values to the mean. Conditional importance has been addressed in a second publication by Strumbelj et al [2]. They extended the original approach by not only creating decomposed instances of a single feature, but observed how the prediction changes for each subset of the power set of feature values. This is of course computationally very expensive (as they mention themselves and tried to improve by smarter sampling in Strumbelj and Kononenko [3]).
By the way: for binary data, this problem becomes much easier, as you just have to compare the prediction between attribute is present and not present. Martens and Provost [4] discussed this for document classification.
Another approach for finding groups of meaningful features has been proposed by Andreas Henelius in [5] and [6]. The idea of his GoldenEye algorithm is to permute the data within-class and feature group. Imagine a data table where each row represents an instance and each column is a feature. In each column, all rows that share the same class are permuted. Features are grouped, i.e. permuted together. If the classification on the permuted data is very different (worse) than the original data, the current grouping did not reflect the true grouping. Check out the publications, its better described there. This approach becomes computationally expensive, too.
I'd also like to refer to the publications by Josua Krause [7], [8]. He developed interactive visual analytics workflows for the analysis of binary instance-based classification problems, including an enhanced PDP. They are well-written and an interesting read.
[1] Robnik-Šikonja, M. (2004, September). Improving random forests. In European conference on machine learning (pp. 359-370). Springer, Berlin, Heidelberg.
[2] Štrumbelj, E., Kononenko, I., & Šikonja, M. R. (2009). Explaining instance classifications with interactions of subsets of feature values. Data & Knowledge Engineering, 68(10), 886-904.
[3] Štrumbelj, E., & Kononenko, I. (2014). Explaining prediction models and individual predictions with feature contributions. Knowledge and information systems, 41(3), 647-665.
[4] Martens, D., & Provost, F. (2013). Explaining data-driven document classifications.
[5] Henelius, A., Puolamäki, K., Boström, H., Asker, L., & Papapetrou, P. (2014). A peek into the black box: exploring classifiers by randomization. Data mining and knowledge discovery, 28(5-6), 1503-1529.#
[6] Henelius, A., Puolamäki, K., Karlsson, I., Zhao, J., Asker, L., Boström, H., & Papapetrou, P. (2015, April). Goldeneye++: A closer look into the black box. In International Symposium on Statistical Learning and Data Sciences (pp. 96-105). Springer, Cham.
[7] Krause, J., Perer, A., & Ng, K. (2016, May). Interacting with predictions: Visual inspection of black-box machine learning models. In Proceedings of the 2016 CHI Conference on Human Factors in Computing Systems (pp. 5686-5697). ACM.
[8] Krause, J., Dasgupta, A., Swartz, J., Aphinyanaphongs, Y., & Bertini, E. (2017). A Workflow for Visual Diagnostics of Binary Classifiers using Instance-Level Explanations. arXiv preprint arXiv:1705.01968. | Feature Importance/Impact for Individual Predictions | The topic you are addressing is known as model explanation or model interpretation and quite an active topic in research. The general idea is to find out, which features contributed to the model, and | Feature Importance/Impact for Individual Predictions
The topic you are addressing is known as model explanation or model interpretation and quite an active topic in research. The general idea is to find out, which features contributed to the model, and which not.
You already mentioned some popular techniques, such as the Partial Dependence Plots (PDP) or LIME. In a PDP, the influence of a features' value to the model output is displayed by creating new instances from the data that have a modified feature value and predict them by the model. LIME creates a local approximation of the model by sampling instances around a requested instance and learning a simpler, more interpretable model.
In the naive method you described, the impact of a feature is neutralised by setting it to the population mean. You are absolutely right, that this is not an appropriate method, as the prediction of the mean value is not probably not the mean prediction. Also, it does not reflect the feature distribution and does not work for categorical attributes.
Robnik-Sikonja and Kononenko [1] addressed this problem. Their basic idea is the same: the prediction difference between the unchanged instance, and an instance with a neutralised feature. However, instead of taking the mean value to get rid of the features' impact, they create several instance copies, each with a different value. For categorical values, they iterate over all possible categories; for numerical values, they discretise the data into bins. The decomposed instances are weighted by the feature value frequency in the data. Missing data can be ignored by using classifiers that can handle it, or imputing it, e.g. by setting the values to the mean. Conditional importance has been addressed in a second publication by Strumbelj et al [2]. They extended the original approach by not only creating decomposed instances of a single feature, but observed how the prediction changes for each subset of the power set of feature values. This is of course computationally very expensive (as they mention themselves and tried to improve by smarter sampling in Strumbelj and Kononenko [3]).
By the way: for binary data, this problem becomes much easier, as you just have to compare the prediction between attribute is present and not present. Martens and Provost [4] discussed this for document classification.
Another approach for finding groups of meaningful features has been proposed by Andreas Henelius in [5] and [6]. The idea of his GoldenEye algorithm is to permute the data within-class and feature group. Imagine a data table where each row represents an instance and each column is a feature. In each column, all rows that share the same class are permuted. Features are grouped, i.e. permuted together. If the classification on the permuted data is very different (worse) than the original data, the current grouping did not reflect the true grouping. Check out the publications, its better described there. This approach becomes computationally expensive, too.
I'd also like to refer to the publications by Josua Krause [7], [8]. He developed interactive visual analytics workflows for the analysis of binary instance-based classification problems, including an enhanced PDP. They are well-written and an interesting read.
[1] Robnik-Šikonja, M. (2004, September). Improving random forests. In European conference on machine learning (pp. 359-370). Springer, Berlin, Heidelberg.
[2] Štrumbelj, E., Kononenko, I., & Šikonja, M. R. (2009). Explaining instance classifications with interactions of subsets of feature values. Data & Knowledge Engineering, 68(10), 886-904.
[3] Štrumbelj, E., & Kononenko, I. (2014). Explaining prediction models and individual predictions with feature contributions. Knowledge and information systems, 41(3), 647-665.
[4] Martens, D., & Provost, F. (2013). Explaining data-driven document classifications.
[5] Henelius, A., Puolamäki, K., Boström, H., Asker, L., & Papapetrou, P. (2014). A peek into the black box: exploring classifiers by randomization. Data mining and knowledge discovery, 28(5-6), 1503-1529.#
[6] Henelius, A., Puolamäki, K., Karlsson, I., Zhao, J., Asker, L., Boström, H., & Papapetrou, P. (2015, April). Goldeneye++: A closer look into the black box. In International Symposium on Statistical Learning and Data Sciences (pp. 96-105). Springer, Cham.
[7] Krause, J., Perer, A., & Ng, K. (2016, May). Interacting with predictions: Visual inspection of black-box machine learning models. In Proceedings of the 2016 CHI Conference on Human Factors in Computing Systems (pp. 5686-5697). ACM.
[8] Krause, J., Dasgupta, A., Swartz, J., Aphinyanaphongs, Y., & Bertini, E. (2017). A Workflow for Visual Diagnostics of Binary Classifiers using Instance-Level Explanations. arXiv preprint arXiv:1705.01968. | Feature Importance/Impact for Individual Predictions
The topic you are addressing is known as model explanation or model interpretation and quite an active topic in research. The general idea is to find out, which features contributed to the model, and |
32,004 | Feature Importance/Impact for Individual Predictions | Two other methods worth mentioning here are:
1) Lundberg & Lee's SHAP algorithm, an extension of Štrumbelj & Kononenko's game theoretic approach that they claim unifies LIME and a number of other local importance measures; and
2) Wachter et al.'s counterfactual method, based on generative adversarial networks.
Both methods have advantages and disadvantages. SHAP is very fast and comes with a user-friendly Python implementation. Unfortunately, however, it always compares points against the data centroid, which may not be the relevant contrast in some cases. Also, like LIME and a number of other algorithms, it assumes (or enforces) local linearity, which can lead to unstable or uninformative results when our case of interest is near a distinctly nonlinear region of the decision boundary or regression surface.
Wachter et al.'s solution is more flexible in this regard, a refreshing deviation from what Lundberg & Lee call the "additive feature attribution" paradigm. I'm unaware of any open source implementation, however. The added overhead of GAN training can also be extremely onerous for some datasets. | Feature Importance/Impact for Individual Predictions | Two other methods worth mentioning here are:
1) Lundberg & Lee's SHAP algorithm, an extension of Štrumbelj & Kononenko's game theoretic approach that they claim unifies LIME and a number of other loca | Feature Importance/Impact for Individual Predictions
Two other methods worth mentioning here are:
1) Lundberg & Lee's SHAP algorithm, an extension of Štrumbelj & Kononenko's game theoretic approach that they claim unifies LIME and a number of other local importance measures; and
2) Wachter et al.'s counterfactual method, based on generative adversarial networks.
Both methods have advantages and disadvantages. SHAP is very fast and comes with a user-friendly Python implementation. Unfortunately, however, it always compares points against the data centroid, which may not be the relevant contrast in some cases. Also, like LIME and a number of other algorithms, it assumes (or enforces) local linearity, which can lead to unstable or uninformative results when our case of interest is near a distinctly nonlinear region of the decision boundary or regression surface.
Wachter et al.'s solution is more flexible in this regard, a refreshing deviation from what Lundberg & Lee call the "additive feature attribution" paradigm. I'm unaware of any open source implementation, however. The added overhead of GAN training can also be extremely onerous for some datasets. | Feature Importance/Impact for Individual Predictions
Two other methods worth mentioning here are:
1) Lundberg & Lee's SHAP algorithm, an extension of Štrumbelj & Kononenko's game theoretic approach that they claim unifies LIME and a number of other loca |
32,005 | Expected value and variance of the square root of a random variable | If you only have the sequence of moments, the $\frac12$-th moment is not necessarily determined by them.
If the MGF exists in a neighborhood of zero, then the moment sequence would determined the distribution and the $\frac12$-th moment should be determined (though not always amenable to algebraic calculation).
However if you have the pdf, we can avoid all that, since we can try to compute $E(X^\frac12)$ directly (e.g. by calculating the integral $\int_0^\infty x^\frac12 f(x) dx$ -- I presume $X$ is on the non-negative half line,for the obvious reason). Note also that the distribution of $\sqrt{X}$ will be very easy to write down (if $Y=\sqrt{X},\, F_Y(y)=F_X(y^2)$ and $f_Y(y)=2yf_X(y^2)$). If, for example, we recognize that density as a standard one - it might be very fast to identify the expectation that way.
As whuber points out in comments, all we need to find is $E(\sqrt{X})$, since $\text{Var}(\sqrt{X})=E(X)-E(\sqrt{X})^2$. | Expected value and variance of the square root of a random variable | If you only have the sequence of moments, the $\frac12$-th moment is not necessarily determined by them.
If the MGF exists in a neighborhood of zero, then the moment sequence would determined the dis | Expected value and variance of the square root of a random variable
If you only have the sequence of moments, the $\frac12$-th moment is not necessarily determined by them.
If the MGF exists in a neighborhood of zero, then the moment sequence would determined the distribution and the $\frac12$-th moment should be determined (though not always amenable to algebraic calculation).
However if you have the pdf, we can avoid all that, since we can try to compute $E(X^\frac12)$ directly (e.g. by calculating the integral $\int_0^\infty x^\frac12 f(x) dx$ -- I presume $X$ is on the non-negative half line,for the obvious reason). Note also that the distribution of $\sqrt{X}$ will be very easy to write down (if $Y=\sqrt{X},\, F_Y(y)=F_X(y^2)$ and $f_Y(y)=2yf_X(y^2)$). If, for example, we recognize that density as a standard one - it might be very fast to identify the expectation that way.
As whuber points out in comments, all we need to find is $E(\sqrt{X})$, since $\text{Var}(\sqrt{X})=E(X)-E(\sqrt{X})^2$. | Expected value and variance of the square root of a random variable
If you only have the sequence of moments, the $\frac12$-th moment is not necessarily determined by them.
If the MGF exists in a neighborhood of zero, then the moment sequence would determined the dis |
32,006 | Expected value and variance of the square root of a random variable | if you are only interested in the upper bound of the expectation, you can use Jensen's Inequality to immediately upper bound $E[\sqrt{X}] \leq \sqrt{E[X]}$, if $E[X]$ is sufficiently close to 1, the approximation would be quite good..
Otherwise the standard tool to approximate the expectation is to use the Taylor series of $y = X-1$, $\sqrt{1+y} = 1 - y/2 + y^2/8 - y^3/16 + 5y^4/128 \dots$
and since you already have the the MGF of $X$, you should be able to calculate that quickly... | Expected value and variance of the square root of a random variable | if you are only interested in the upper bound of the expectation, you can use Jensen's Inequality to immediately upper bound $E[\sqrt{X}] \leq \sqrt{E[X]}$, if $E[X]$ is sufficiently close to 1, the a | Expected value and variance of the square root of a random variable
if you are only interested in the upper bound of the expectation, you can use Jensen's Inequality to immediately upper bound $E[\sqrt{X}] \leq \sqrt{E[X]}$, if $E[X]$ is sufficiently close to 1, the approximation would be quite good..
Otherwise the standard tool to approximate the expectation is to use the Taylor series of $y = X-1$, $\sqrt{1+y} = 1 - y/2 + y^2/8 - y^3/16 + 5y^4/128 \dots$
and since you already have the the MGF of $X$, you should be able to calculate that quickly... | Expected value and variance of the square root of a random variable
if you are only interested in the upper bound of the expectation, you can use Jensen's Inequality to immediately upper bound $E[\sqrt{X}] \leq \sqrt{E[X]}$, if $E[X]$ is sufficiently close to 1, the a |
32,007 | Why does glmnet use coordinate descent for Ridge regression? | I think this is due to speed. Cyclical coordinate descent does not find the exact solution in finite time, but it is faster, not only for a grid of $\lambda$'s but also for a single $\lambda$.
Consider the task of solving ridge regression for a single $\lambda$, with a data matrix of size $n \times p$. I believe the optimal runtime for exact ridge regression is $O(n^2p)$ if $n < p$ and $O(np^2)$ if $n > p$. See Murphy, Machine Learning, section 7.5.2 for a reference.
With the cyclical coordinate descent algorithm, "a complete cycle through all $p$ variables costs $O(pN)$ operations" (p. 6, Friedman et al. 2010, https://www.jstatsoft.org/article/view/v033i01). One can then specify a number of cycles $c$ with $c \ll min(n, p)$ to get a faster big-Oh runtime for a single $\lambda$. For solving over many $\lambda$'s, the glmnet method should yield further improvement using warm starts. | Why does glmnet use coordinate descent for Ridge regression? | I think this is due to speed. Cyclical coordinate descent does not find the exact solution in finite time, but it is faster, not only for a grid of $\lambda$'s but also for a single $\lambda$.
Conside | Why does glmnet use coordinate descent for Ridge regression?
I think this is due to speed. Cyclical coordinate descent does not find the exact solution in finite time, but it is faster, not only for a grid of $\lambda$'s but also for a single $\lambda$.
Consider the task of solving ridge regression for a single $\lambda$, with a data matrix of size $n \times p$. I believe the optimal runtime for exact ridge regression is $O(n^2p)$ if $n < p$ and $O(np^2)$ if $n > p$. See Murphy, Machine Learning, section 7.5.2 for a reference.
With the cyclical coordinate descent algorithm, "a complete cycle through all $p$ variables costs $O(pN)$ operations" (p. 6, Friedman et al. 2010, https://www.jstatsoft.org/article/view/v033i01). One can then specify a number of cycles $c$ with $c \ll min(n, p)$ to get a faster big-Oh runtime for a single $\lambda$. For solving over many $\lambda$'s, the glmnet method should yield further improvement using warm starts. | Why does glmnet use coordinate descent for Ridge regression?
I think this is due to speed. Cyclical coordinate descent does not find the exact solution in finite time, but it is faster, not only for a grid of $\lambda$'s but also for a single $\lambda$.
Conside |
32,008 | Why does glmnet use coordinate descent for Ridge regression? | Other solvers for ridge exists and the point of the glmnet solver is exactly to use CCD for tractability and speed reasons. They use the same code for all elasticnet solutions. Elasticnet includes ridge and LASSO by setting $\lambda_1$ or $\lambda_2$ to $0$. | Why does glmnet use coordinate descent for Ridge regression? | Other solvers for ridge exists and the point of the glmnet solver is exactly to use CCD for tractability and speed reasons. They use the same code for all elasticnet solutions. Elasticnet includes rid | Why does glmnet use coordinate descent for Ridge regression?
Other solvers for ridge exists and the point of the glmnet solver is exactly to use CCD for tractability and speed reasons. They use the same code for all elasticnet solutions. Elasticnet includes ridge and LASSO by setting $\lambda_1$ or $\lambda_2$ to $0$. | Why does glmnet use coordinate descent for Ridge regression?
Other solvers for ridge exists and the point of the glmnet solver is exactly to use CCD for tractability and speed reasons. They use the same code for all elasticnet solutions. Elasticnet includes rid |
32,009 | Investigating differences between populations | Let's think the problem as follows.
Say $X=(X_1,X_2,..X_n)$ and $Y$ is a binary variable standing for the population : $Y=0$ means first population, $Y=1$ means second population. The null hypothesis can be expressed in several equivalent ways:
$H_0$: the populations are the same
$H_0$:
the distribution of $X$ given $Y=0$ is the same as the distribution of $X$ given $Y=1$
$H_0$: $X$ and $Y$ are independent
$H_0$: for any function $f$ into $\{0,1\}$, $f(X)$ and $Y$ are independent
I don't know much about random forests, but they may be thought as an all purpose predictor that avoids over-fitting. If we idealize them quite a bit: it is something capable of detecting any kind of relationship between $Y$ and any kind of features $X$ without over-fitting.
It is possible to try something based on this. Split the original dataset into a training set and a test set. Then:
train a random forest $f$ that predicts $Y$ from $X$ on the training set.
make a simple chi-squared independence test (with risk $\alpha$) between $f(X)$ and $Y$ on the test set
This test is quite conservative. If the random forest is a poor method, at worst outputting a dumb $f(X)$, then it will reject $H_0$ with a probability less than $\alpha$ anyway (when $H_0$ is true). The over-fitting would not even be a problem since we use a test and a training set. However, the power of the test directly depends on the intelligence of the random forest method (or any predictor used).
Note that you can use several possible predictors: like plain old logistic regression first, then logistic regression with some cross features, then a few decision trees, then a random forest... But if you do so you should adjust $\alpha$ to the number of tests to avoid "false discoveries". See: Alpha adjustment for multiple testing | Investigating differences between populations | Let's think the problem as follows.
Say $X=(X_1,X_2,..X_n)$ and $Y$ is a binary variable standing for the population : $Y=0$ means first population, $Y=1$ means second population. The null hypothesis | Investigating differences between populations
Let's think the problem as follows.
Say $X=(X_1,X_2,..X_n)$ and $Y$ is a binary variable standing for the population : $Y=0$ means first population, $Y=1$ means second population. The null hypothesis can be expressed in several equivalent ways:
$H_0$: the populations are the same
$H_0$:
the distribution of $X$ given $Y=0$ is the same as the distribution of $X$ given $Y=1$
$H_0$: $X$ and $Y$ are independent
$H_0$: for any function $f$ into $\{0,1\}$, $f(X)$ and $Y$ are independent
I don't know much about random forests, but they may be thought as an all purpose predictor that avoids over-fitting. If we idealize them quite a bit: it is something capable of detecting any kind of relationship between $Y$ and any kind of features $X$ without over-fitting.
It is possible to try something based on this. Split the original dataset into a training set and a test set. Then:
train a random forest $f$ that predicts $Y$ from $X$ on the training set.
make a simple chi-squared independence test (with risk $\alpha$) between $f(X)$ and $Y$ on the test set
This test is quite conservative. If the random forest is a poor method, at worst outputting a dumb $f(X)$, then it will reject $H_0$ with a probability less than $\alpha$ anyway (when $H_0$ is true). The over-fitting would not even be a problem since we use a test and a training set. However, the power of the test directly depends on the intelligence of the random forest method (or any predictor used).
Note that you can use several possible predictors: like plain old logistic regression first, then logistic regression with some cross features, then a few decision trees, then a random forest... But if you do so you should adjust $\alpha$ to the number of tests to avoid "false discoveries". See: Alpha adjustment for multiple testing | Investigating differences between populations
Let's think the problem as follows.
Say $X=(X_1,X_2,..X_n)$ and $Y$ is a binary variable standing for the population : $Y=0$ means first population, $Y=1$ means second population. The null hypothesis |
32,010 | Investigating differences between populations | You don't say how many features are available in the data. Few, many, massive? Can we assume they are the same features between populations, all measured using the same tools, methods and modalities? If not, then you have a bigger problem where an errors-in-variables measurement model might work.
@benoitsanchez appears to have answered question #1).
Wrt #2), I'm not sure RFs can help. By using a more formal model such as one-way ANOVA applied to one feature at a time, a test of the difference between populations for features can be developed. By summarizing the results of those tests, based on the magnitude of the test as well as its significance, a descriptive profile of how the populations differ across features becomes possible. This is an admittedly ad hoc and heuristic solution which may not be rigorous enough for your tastes, preferences and training.
Not being good at Latex-type notation, let me simply describe how these tests might work: first, construct some kind of macro loop which passes all features through, one feature at a time. With each pass of the loop, the new feature becomes the target or DV with X consisting of a dummy variable for population as well as any control variables that are appropriate. Make sure that the same controls are used for each feature as well as that the underlying data is exactly the same for all ANOVAs, eliminating variation attributable to the vicissitudes of finite data samples. Aggregate the F-test values for the dummy variable for each feature. This will provide a standardized metric enabling comparison across features. F-tests are preferable to fitted betas since betas are not standardized, being expressed in the unit and std devs of each individual feature.
Your last comment, "I worry that the answer I get to (1) may depend on the particular set of classification/regression models that I use," is always true. The answers are quite likely to vary as a function of the model(s) used. It is also an expression of a commonly observed malaise among the more strongly theoretical and classically trained statisticians who aren't comfortable with or have trouble acknowledging the non-deterministic nature of applied statistical modeling. An excellent antidote for these symptoms is Efron and Hastie's recent book Computer Age Statistical Inference. They bring statistical modeling into the 21st c, an age of data science and machine learning, by candidly acknowledging the iterative, approximating, heuristic nature of all models possessing an error term. One doesn't have to be a Bayesian to recognize the truth inherent in this observation. Their's is a refreshing perspective that differs from the rigid determinism of classical, 20th c statistical practice which threw up its hands when, e.g., a cross-products matrix wouldn't invert and/or some pedantic model assumption wasn't met. | Investigating differences between populations | You don't say how many features are available in the data. Few, many, massive? Can we assume they are the same features between populations, all measured using the same tools, methods and modalities? | Investigating differences between populations
You don't say how many features are available in the data. Few, many, massive? Can we assume they are the same features between populations, all measured using the same tools, methods and modalities? If not, then you have a bigger problem where an errors-in-variables measurement model might work.
@benoitsanchez appears to have answered question #1).
Wrt #2), I'm not sure RFs can help. By using a more formal model such as one-way ANOVA applied to one feature at a time, a test of the difference between populations for features can be developed. By summarizing the results of those tests, based on the magnitude of the test as well as its significance, a descriptive profile of how the populations differ across features becomes possible. This is an admittedly ad hoc and heuristic solution which may not be rigorous enough for your tastes, preferences and training.
Not being good at Latex-type notation, let me simply describe how these tests might work: first, construct some kind of macro loop which passes all features through, one feature at a time. With each pass of the loop, the new feature becomes the target or DV with X consisting of a dummy variable for population as well as any control variables that are appropriate. Make sure that the same controls are used for each feature as well as that the underlying data is exactly the same for all ANOVAs, eliminating variation attributable to the vicissitudes of finite data samples. Aggregate the F-test values for the dummy variable for each feature. This will provide a standardized metric enabling comparison across features. F-tests are preferable to fitted betas since betas are not standardized, being expressed in the unit and std devs of each individual feature.
Your last comment, "I worry that the answer I get to (1) may depend on the particular set of classification/regression models that I use," is always true. The answers are quite likely to vary as a function of the model(s) used. It is also an expression of a commonly observed malaise among the more strongly theoretical and classically trained statisticians who aren't comfortable with or have trouble acknowledging the non-deterministic nature of applied statistical modeling. An excellent antidote for these symptoms is Efron and Hastie's recent book Computer Age Statistical Inference. They bring statistical modeling into the 21st c, an age of data science and machine learning, by candidly acknowledging the iterative, approximating, heuristic nature of all models possessing an error term. One doesn't have to be a Bayesian to recognize the truth inherent in this observation. Their's is a refreshing perspective that differs from the rigid determinism of classical, 20th c statistical practice which threw up its hands when, e.g., a cross-products matrix wouldn't invert and/or some pedantic model assumption wasn't met. | Investigating differences between populations
You don't say how many features are available in the data. Few, many, massive? Can we assume they are the same features between populations, all measured using the same tools, methods and modalities? |
32,011 | Yule Walker equations of an ARMA(1,1)-process | Yule Walker (for parameter estimation) is usually only used for AR models, but this method you're using is still a valid technique for finding the autocovariance function. I'm assuming that's what you're after.
Multiply both sides of an ARMA(p,q) model by $Y_{t-k} = \sum_{j=0}^{\infty}\psi_j \epsilon_{t-j-k}$ (this is where causality assumption comes in)
$$
Y_t Y_{t-k} - \phi_1 Y_{t-1}Y_{t-k} - \cdots - \phi_p Y_{t-p}Y_{t-k} = \left[\sum_{l=0}^q \theta_l \epsilon_{t-l}\right]\left[\sum_{j=0}^{\infty}\psi_j \epsilon_{t-j-k} \right]. \tag{1}
$$
Then take expectations. Note that $\psi_j = 0$ for $j < 0$ and $\theta_j = 0$ for $j \not \in \{1,\ldots,q\}$. If $0 \le k < \text{max}(p,q+1)$ you get these $p$ (1 in your case) equations here
$$
\gamma(k) - \phi_1 \gamma(k-1) - \cdots - \phi_p\gamma(k-p) = \sigma^2 \sum_{j=0}^{\infty}\theta_{k+j}\psi_j. \tag{2}
$$
And if $k \ge \text{max}(p,q+1)$ you get
$$
\gamma(k) - \phi_1 \gamma(k-1) - \cdots - \phi_p\gamma(k-p) = 0 \tag{3}
$$
($0$ on RHS because $l > q$).
You can solve your two equations by using results of homogeneous difference equations, or by just solving the system directly.
For your specific ARMA(1,1) model (I'll turn the $\phi$s back into $\alpha$s) you have
$\gamma(0) - \alpha \gamma(1) = \sigma^2[1 + \theta_1 (\theta + \alpha)]$
$\gamma(1) - \alpha \gamma(0) = \sigma^2[\theta]$
$\gamma(k) - \alpha \gamma(k-1) = 0$ for $k \ge 2$
Plugging (2) into (1) gives us
$$
\gamma(0) = \sigma^2\left[ 1 + \frac{(\theta+\alpha)^2 }{1 - \alpha^2 } \right]
$$
(which is the same as before) and plugging this into (2) gives us
$$
\gamma(1) = \sigma^2\left[ \theta + \alpha + \frac{(\theta+\alpha)^2\alpha }{1 - \alpha^2 } \right].
$$
If you want to get it at higher lags, just use (3) repeatedly.
When the model is a pure AR model, the RHS of (1) is simplified tremendously, and the resulting set of equations to solve is linear in the parameters $\phi_1,\ldots,\phi_p$. | Yule Walker equations of an ARMA(1,1)-process | Yule Walker (for parameter estimation) is usually only used for AR models, but this method you're using is still a valid technique for finding the autocovariance function. I'm assuming that's what you | Yule Walker equations of an ARMA(1,1)-process
Yule Walker (for parameter estimation) is usually only used for AR models, but this method you're using is still a valid technique for finding the autocovariance function. I'm assuming that's what you're after.
Multiply both sides of an ARMA(p,q) model by $Y_{t-k} = \sum_{j=0}^{\infty}\psi_j \epsilon_{t-j-k}$ (this is where causality assumption comes in)
$$
Y_t Y_{t-k} - \phi_1 Y_{t-1}Y_{t-k} - \cdots - \phi_p Y_{t-p}Y_{t-k} = \left[\sum_{l=0}^q \theta_l \epsilon_{t-l}\right]\left[\sum_{j=0}^{\infty}\psi_j \epsilon_{t-j-k} \right]. \tag{1}
$$
Then take expectations. Note that $\psi_j = 0$ for $j < 0$ and $\theta_j = 0$ for $j \not \in \{1,\ldots,q\}$. If $0 \le k < \text{max}(p,q+1)$ you get these $p$ (1 in your case) equations here
$$
\gamma(k) - \phi_1 \gamma(k-1) - \cdots - \phi_p\gamma(k-p) = \sigma^2 \sum_{j=0}^{\infty}\theta_{k+j}\psi_j. \tag{2}
$$
And if $k \ge \text{max}(p,q+1)$ you get
$$
\gamma(k) - \phi_1 \gamma(k-1) - \cdots - \phi_p\gamma(k-p) = 0 \tag{3}
$$
($0$ on RHS because $l > q$).
You can solve your two equations by using results of homogeneous difference equations, or by just solving the system directly.
For your specific ARMA(1,1) model (I'll turn the $\phi$s back into $\alpha$s) you have
$\gamma(0) - \alpha \gamma(1) = \sigma^2[1 + \theta_1 (\theta + \alpha)]$
$\gamma(1) - \alpha \gamma(0) = \sigma^2[\theta]$
$\gamma(k) - \alpha \gamma(k-1) = 0$ for $k \ge 2$
Plugging (2) into (1) gives us
$$
\gamma(0) = \sigma^2\left[ 1 + \frac{(\theta+\alpha)^2 }{1 - \alpha^2 } \right]
$$
(which is the same as before) and plugging this into (2) gives us
$$
\gamma(1) = \sigma^2\left[ \theta + \alpha + \frac{(\theta+\alpha)^2\alpha }{1 - \alpha^2 } \right].
$$
If you want to get it at higher lags, just use (3) repeatedly.
When the model is a pure AR model, the RHS of (1) is simplified tremendously, and the resulting set of equations to solve is linear in the parameters $\phi_1,\ldots,\phi_p$. | Yule Walker equations of an ARMA(1,1)-process
Yule Walker (for parameter estimation) is usually only used for AR models, but this method you're using is still a valid technique for finding the autocovariance function. I'm assuming that's what you |
32,012 | Classification (regression) with rolling window for time series-type data | How you divide your data set into training/test depends on the data you have available and how your model will be used. Ideally you wouldn't randomly separate the time-points, since as you say, they are not independent if there is any temporal signal at all.
If you have multiple time-series then I'd divide the time-series themselves into training and test in whatever fashion you want.
If your training data is a single time-series and you intend to predict future values of this time-series then I'd segment it accordingly. I.e. use the first 60% of the samples as your training data and the remaining 40% as your test. Of course, these sets aren't independent but given the nature of your data this is unavoidable.
If you have a single time-series for training but the actual time-series that you want to predict future values for is entirely separate then I'd still follow the procedure from the above paragraph, but bear in mind that any estimates of model fit you derive are very likely to be inaccurate.
As an aside, I would be tempted to use a Recurrent Neural Network approach to a problem like this. This would allow you to model the temporal aspect elegantly - something like an an LSTM can maintain a memory of previous values without having to explicitly specify a window size. Of course, if you wish to use a window approach then you could in theory use any classification algorithm you want.
EDIT
That technical paper looks to have covered the issue in far more depth than my answer so I'd follow their recommendations instead. The main difference from your use case is that they are dealing with standard forecasting the next sample, rather than classification | Classification (regression) with rolling window for time series-type data | How you divide your data set into training/test depends on the data you have available and how your model will be used. Ideally you wouldn't randomly separate the time-points, since as you say, they a | Classification (regression) with rolling window for time series-type data
How you divide your data set into training/test depends on the data you have available and how your model will be used. Ideally you wouldn't randomly separate the time-points, since as you say, they are not independent if there is any temporal signal at all.
If you have multiple time-series then I'd divide the time-series themselves into training and test in whatever fashion you want.
If your training data is a single time-series and you intend to predict future values of this time-series then I'd segment it accordingly. I.e. use the first 60% of the samples as your training data and the remaining 40% as your test. Of course, these sets aren't independent but given the nature of your data this is unavoidable.
If you have a single time-series for training but the actual time-series that you want to predict future values for is entirely separate then I'd still follow the procedure from the above paragraph, but bear in mind that any estimates of model fit you derive are very likely to be inaccurate.
As an aside, I would be tempted to use a Recurrent Neural Network approach to a problem like this. This would allow you to model the temporal aspect elegantly - something like an an LSTM can maintain a memory of previous values without having to explicitly specify a window size. Of course, if you wish to use a window approach then you could in theory use any classification algorithm you want.
EDIT
That technical paper looks to have covered the issue in far more depth than my answer so I'd follow their recommendations instead. The main difference from your use case is that they are dealing with standard forecasting the next sample, rather than classification | Classification (regression) with rolling window for time series-type data
How you divide your data set into training/test depends on the data you have available and how your model will be used. Ideally you wouldn't randomly separate the time-points, since as you say, they a |
32,013 | Encoding high-cardinality (many-category) categorical features when features greatly differ on the cardinality | If one categorical variable has high cardinality, wouldn't encoding it this way "overpower" other (for example binary) variables?
It depends on the algorithm.
Algorithms based on the sampling of the columns (random forests, extremely randomized trees, gradient boosting or a bagged classifier...) train a lot of models on subsamples of the data. If 90% of your columns represent a "dummified" variable, it is likely that a large number of the models are actually working on the same variable, therefore, making them more correlated than they should be, thus arming performance.
Linear regression methods will not be affected, they will simply give a weight to every binary variable produced by the encoded variable.
With nearest neighbours and similarity based methods (such as kernel SVMs) the impact should be limited as well. No matter the number of columns, the only thing that matters in the end is the inner product or the distance between two lines of your data. However, the number of columns that stems from a nominal variable, the distance (or inner product) can only be 0 or 1 (the nominal variables were equal or not).
If our classifier model is aware of relationships between variables, wouldn't it unnecessarily attempt to find relationships between introduced binary "components" of the same variable?
How is your classifier "aware" of relationships between variables ? I am not sure I can address this question.
And if so, how could this be addressed?
In the case of any method relying on samples of the columns, prior weights could be given to the columns (so that they are not selected with the same probabilities). However, I do not have any implementations in mind that do this. A quick fix could be to repeat the other columns, so that there likelihood to be selected artificially increases. | Encoding high-cardinality (many-category) categorical features when features greatly differ on the c | If one categorical variable has high cardinality, wouldn't encoding it this way "overpower" other (for example binary) variables?
It depends on the algorithm.
Algorithms based on the sampling of the c | Encoding high-cardinality (many-category) categorical features when features greatly differ on the cardinality
If one categorical variable has high cardinality, wouldn't encoding it this way "overpower" other (for example binary) variables?
It depends on the algorithm.
Algorithms based on the sampling of the columns (random forests, extremely randomized trees, gradient boosting or a bagged classifier...) train a lot of models on subsamples of the data. If 90% of your columns represent a "dummified" variable, it is likely that a large number of the models are actually working on the same variable, therefore, making them more correlated than they should be, thus arming performance.
Linear regression methods will not be affected, they will simply give a weight to every binary variable produced by the encoded variable.
With nearest neighbours and similarity based methods (such as kernel SVMs) the impact should be limited as well. No matter the number of columns, the only thing that matters in the end is the inner product or the distance between two lines of your data. However, the number of columns that stems from a nominal variable, the distance (or inner product) can only be 0 or 1 (the nominal variables were equal or not).
If our classifier model is aware of relationships between variables, wouldn't it unnecessarily attempt to find relationships between introduced binary "components" of the same variable?
How is your classifier "aware" of relationships between variables ? I am not sure I can address this question.
And if so, how could this be addressed?
In the case of any method relying on samples of the columns, prior weights could be given to the columns (so that they are not selected with the same probabilities). However, I do not have any implementations in mind that do this. A quick fix could be to repeat the other columns, so that there likelihood to be selected artificially increases. | Encoding high-cardinality (many-category) categorical features when features greatly differ on the c
If one categorical variable has high cardinality, wouldn't encoding it this way "overpower" other (for example binary) variables?
It depends on the algorithm.
Algorithms based on the sampling of the c |
32,014 | Integral identity of lemma contained in infoGAN paper | Consider the difference
$$
D = \int_x \int_y P(x,y) \int_{x'} P(x'|y) \left[ f(x,y) - f(x',y) \right] \, dx' dx dy
$$
obtained by moving $f(x,y)$ into the $x'$ integral, and taking the difference with $x$ replaced by $x'$.
Conditionalizing $x$ on $y$,
$$
D = \int_y P(y) \int_x \int_{x'} P(x|y) P(x'|y) \left[ f(x,y) - f(x',y) \right] \, dx' dx dy.
$$
This interior object
$$
\delta = \int_x \int_{x'} P(x|y) P(x'|y) \left[ f(x,y) - f(x',y) \right] \, dx' dx
$$
is antisymmetric after swapping the dummy variables $x$ and $x'$, becoming its own negative, and so it is equal to zero.
I suspect that the regularity conditions are simply those that prevent these integrals from diverging. | Integral identity of lemma contained in infoGAN paper | Consider the difference
$$
D = \int_x \int_y P(x,y) \int_{x'} P(x'|y) \left[ f(x,y) - f(x',y) \right] \, dx' dx dy
$$
obtained by moving $f(x,y)$ into the $x'$ integral, and taking the difference with | Integral identity of lemma contained in infoGAN paper
Consider the difference
$$
D = \int_x \int_y P(x,y) \int_{x'} P(x'|y) \left[ f(x,y) - f(x',y) \right] \, dx' dx dy
$$
obtained by moving $f(x,y)$ into the $x'$ integral, and taking the difference with $x$ replaced by $x'$.
Conditionalizing $x$ on $y$,
$$
D = \int_y P(y) \int_x \int_{x'} P(x|y) P(x'|y) \left[ f(x,y) - f(x',y) \right] \, dx' dx dy.
$$
This interior object
$$
\delta = \int_x \int_{x'} P(x|y) P(x'|y) \left[ f(x,y) - f(x',y) \right] \, dx' dx
$$
is antisymmetric after swapping the dummy variables $x$ and $x'$, becoming its own negative, and so it is equal to zero.
I suspect that the regularity conditions are simply those that prevent these integrals from diverging. | Integral identity of lemma contained in infoGAN paper
Consider the difference
$$
D = \int_x \int_y P(x,y) \int_{x'} P(x'|y) \left[ f(x,y) - f(x',y) \right] \, dx' dx dy
$$
obtained by moving $f(x,y)$ into the $x'$ integral, and taking the difference with |
32,015 | Integral identity of lemma contained in infoGAN paper | Or, after the third row
\begin{align}
&=\int_x\int_yp(x|y)p(y)f(x,y)\int_{x'}p(x'|y)dx'dydx\\
&=\int_x\int_yp(x|y)f(x,y)\int_{x'}p(x',y)dx'dydx.
\end{align}
Swap $x$ and $x'$ then exchange the order of variables. Done | Integral identity of lemma contained in infoGAN paper | Or, after the third row
\begin{align}
&=\int_x\int_yp(x|y)p(y)f(x,y)\int_{x'}p(x'|y)dx'dydx\\
&=\int_x\int_yp(x|y)f(x,y)\int_{x'}p(x',y)dx'dydx.
\end{align}
Swap $x$ and $x'$ then exchange the order o | Integral identity of lemma contained in infoGAN paper
Or, after the third row
\begin{align}
&=\int_x\int_yp(x|y)p(y)f(x,y)\int_{x'}p(x'|y)dx'dydx\\
&=\int_x\int_yp(x|y)f(x,y)\int_{x'}p(x',y)dx'dydx.
\end{align}
Swap $x$ and $x'$ then exchange the order of variables. Done | Integral identity of lemma contained in infoGAN paper
Or, after the third row
\begin{align}
&=\int_x\int_yp(x|y)p(y)f(x,y)\int_{x'}p(x'|y)dx'dydx\\
&=\int_x\int_yp(x|y)f(x,y)\int_{x'}p(x',y)dx'dydx.
\end{align}
Swap $x$ and $x'$ then exchange the order o |
32,016 | Integral identity of lemma contained in infoGAN paper | Well, I think it will be more intuitive if we derive the equation reversely as
\begin{align*}
E_{x \sim X, y \sim Y|x, x' \sim X|y} \left[ f(x', y) \right]
& = \int_x p(x) \int_y p(y|x) \int_{x'} p(x'|y) f(x', y) dx'dydx \\
& = \int_y p(y) \int_x p(x|y) \int_{x'} p(x'|y) f(x', y) dx'dxdy \\
& = \int_y p(y) \int_{x'} p(x'|y) f(x', y) \underbrace{\int_x p(x|y) dx}_{=1}dx'dy \\
& = \int_y p(y) \int_{x} p(x|y) f(x, y) dxdy \\
& = \int_x p(x) \int_{y} p(y|x) f(x, y) dydx \\
& = E_{x \sim X, y \sim Y|x} \left[ f(x, y) \right]
\end{align*} | Integral identity of lemma contained in infoGAN paper | Well, I think it will be more intuitive if we derive the equation reversely as
\begin{align*}
E_{x \sim X, y \sim Y|x, x' \sim X|y} \left[ f(x', y) \right]
& = \int_x p(x) \int_y p(y|x) \int_{x'} p(x' | Integral identity of lemma contained in infoGAN paper
Well, I think it will be more intuitive if we derive the equation reversely as
\begin{align*}
E_{x \sim X, y \sim Y|x, x' \sim X|y} \left[ f(x', y) \right]
& = \int_x p(x) \int_y p(y|x) \int_{x'} p(x'|y) f(x', y) dx'dydx \\
& = \int_y p(y) \int_x p(x|y) \int_{x'} p(x'|y) f(x', y) dx'dxdy \\
& = \int_y p(y) \int_{x'} p(x'|y) f(x', y) \underbrace{\int_x p(x|y) dx}_{=1}dx'dy \\
& = \int_y p(y) \int_{x} p(x|y) f(x, y) dxdy \\
& = \int_x p(x) \int_{y} p(y|x) f(x, y) dydx \\
& = E_{x \sim X, y \sim Y|x} \left[ f(x, y) \right]
\end{align*} | Integral identity of lemma contained in infoGAN paper
Well, I think it will be more intuitive if we derive the equation reversely as
\begin{align*}
E_{x \sim X, y \sim Y|x, x' \sim X|y} \left[ f(x', y) \right]
& = \int_x p(x) \int_y p(y|x) \int_{x'} p(x' |
32,017 | Integral identity of lemma contained in infoGAN paper | The assertion
$$
E_{x \sim X, y \sim Y|x} \left[ f(x, y) \right]
=
E_{x \sim X, y \sim Y|x, x' \sim X|y} \left[ f(x', y) \right]\tag1
$$
is really saying:
If the random vector $(X,Y,X')$ has joint distribution $$P_{X,Y,X'}(x,y,z)=P_X(x)P_{Y|X}(y|x)P_{X|Y}(z|y),\tag2$$ then $E[f(X,Y)] = E[f(X',Y)]$.
The result follows from the fact that $(X,Y)$ has the same distribution as $(X',Y)$, which is seen from:
$$P_{X'|Y}(z|y)=\int_x\frac{ P_{X,Y,X'}(x,y,z)}{P_Y(y)}\,dx\stackrel{(2)}=
\int_x P_{X|Y}(x|y)P_{X|Y}(z|y)\,dx=P_{X|Y}(z|y).$$
Not much regularity is required here besides the existence of the expectation $Ef(X,Y)$. | Integral identity of lemma contained in infoGAN paper | The assertion
$$
E_{x \sim X, y \sim Y|x} \left[ f(x, y) \right]
=
E_{x \sim X, y \sim Y|x, x' \sim X|y} \left[ f(x', y) \right]\tag1
$$
is really saying:
If the random vector $(X,Y,X')$ has joint di | Integral identity of lemma contained in infoGAN paper
The assertion
$$
E_{x \sim X, y \sim Y|x} \left[ f(x, y) \right]
=
E_{x \sim X, y \sim Y|x, x' \sim X|y} \left[ f(x', y) \right]\tag1
$$
is really saying:
If the random vector $(X,Y,X')$ has joint distribution $$P_{X,Y,X'}(x,y,z)=P_X(x)P_{Y|X}(y|x)P_{X|Y}(z|y),\tag2$$ then $E[f(X,Y)] = E[f(X',Y)]$.
The result follows from the fact that $(X,Y)$ has the same distribution as $(X',Y)$, which is seen from:
$$P_{X'|Y}(z|y)=\int_x\frac{ P_{X,Y,X'}(x,y,z)}{P_Y(y)}\,dx\stackrel{(2)}=
\int_x P_{X|Y}(x|y)P_{X|Y}(z|y)\,dx=P_{X|Y}(z|y).$$
Not much regularity is required here besides the existence of the expectation $Ef(X,Y)$. | Integral identity of lemma contained in infoGAN paper
The assertion
$$
E_{x \sim X, y \sim Y|x} \left[ f(x, y) \right]
=
E_{x \sim X, y \sim Y|x, x' \sim X|y} \left[ f(x', y) \right]\tag1
$$
is really saying:
If the random vector $(X,Y,X')$ has joint di |
32,018 | Sum of Product of Bernoulli and Normal Random Variables | $Z_i$ can also be expressed as a mixture with distribution function
$$(1-p)F + p \delta$$
where $\delta(x)=0$ for $x\lt 0$ and $\delta(x)=1$ for $x\ge 1$. Consequently the distribution function of the sum of $n$ iid variates with this distribution is the convolution of those distributions. Because convolution is linear, the Binomial Theorem gives an answer in the form
$$F_n = \sum_{k=0}^n \binom{n}{k}(1-p)^{n-k}p^k\,\delta^{*n-k}*F^{*k}.$$
The stars remind us these are repeated convolutions rather than products.
Note that the convolution of $\delta$ merely adds a constant zero and that the convolution $F^{*k}$ is the distribution of a sum of $k$ iid Normal$(\mu,\sigma)$ variables. It therefore is a Normal distribution with mean $k\mu$ and variance $k\sigma^2$. This yields $F_n$ as a mixture of $(1-p)^n$ times a jump at zero (from the $k=0$ term) along with $n$ Normal components.
To illustrate, the figure shows the case $n=5$ where $\mu=2$, $\sigma=1$, and $p=1/3$.
On the left is the empirical cumulative distribution function of $2000$ independent draws of $Z$, in black. (These draws were made by multiplying Normal and Bernoulli variates and then adding them, according to the original description of $Z$.) A plot of $F_n$ is superimposed in red. That they are nearly the same provides support for the formula.
On the right is the continuous part of the $F_n$ (in gray) along with graphs of its five Normal components, each appropriately scaled. The (discrete) contribution from $(1-p)^n$ is depicted merely as a vertical line at zero of height $(1-p)^n$. | Sum of Product of Bernoulli and Normal Random Variables | $Z_i$ can also be expressed as a mixture with distribution function
$$(1-p)F + p \delta$$
where $\delta(x)=0$ for $x\lt 0$ and $\delta(x)=1$ for $x\ge 1$. Consequently the distribution function of th | Sum of Product of Bernoulli and Normal Random Variables
$Z_i$ can also be expressed as a mixture with distribution function
$$(1-p)F + p \delta$$
where $\delta(x)=0$ for $x\lt 0$ and $\delta(x)=1$ for $x\ge 1$. Consequently the distribution function of the sum of $n$ iid variates with this distribution is the convolution of those distributions. Because convolution is linear, the Binomial Theorem gives an answer in the form
$$F_n = \sum_{k=0}^n \binom{n}{k}(1-p)^{n-k}p^k\,\delta^{*n-k}*F^{*k}.$$
The stars remind us these are repeated convolutions rather than products.
Note that the convolution of $\delta$ merely adds a constant zero and that the convolution $F^{*k}$ is the distribution of a sum of $k$ iid Normal$(\mu,\sigma)$ variables. It therefore is a Normal distribution with mean $k\mu$ and variance $k\sigma^2$. This yields $F_n$ as a mixture of $(1-p)^n$ times a jump at zero (from the $k=0$ term) along with $n$ Normal components.
To illustrate, the figure shows the case $n=5$ where $\mu=2$, $\sigma=1$, and $p=1/3$.
On the left is the empirical cumulative distribution function of $2000$ independent draws of $Z$, in black. (These draws were made by multiplying Normal and Bernoulli variates and then adding them, according to the original description of $Z$.) A plot of $F_n$ is superimposed in red. That they are nearly the same provides support for the formula.
On the right is the continuous part of the $F_n$ (in gray) along with graphs of its five Normal components, each appropriately scaled. The (discrete) contribution from $(1-p)^n$ is depicted merely as a vertical line at zero of height $(1-p)^n$. | Sum of Product of Bernoulli and Normal Random Variables
$Z_i$ can also be expressed as a mixture with distribution function
$$(1-p)F + p \delta$$
where $\delta(x)=0$ for $x\lt 0$ and $\delta(x)=1$ for $x\ge 1$. Consequently the distribution function of th |
32,019 | Learning initial state in RNNs | I am assuming you understood how to learn all the other weights in the RNN.
All states need to be computed, i.e. we have to take some input and multiply them with some weight matrix and then pass the resulting product through some activation function and finally obtain a state.
Initial states are odd because we do not compute them by taking the product of some initial input and weight matrix and use an activation function - we can simply "give" them some random value. They are essentially weights.
Instead of "manually" assigning them some value, why not just learn them like we learn any other weights? Which means we will have to take the gradient with respect to these initial weights and update them just like the other weights.
An alternate way to think about it is by considering the following scenario:
Let's use an initial input. We can fix the initial input to be $1$ and learn an initial weight matrix. The product of the initial input ($1$) and the initial weight matrix will give you an initial state. At test time we will continue to use initial input $1$ and multiply it with the initial weight matrix which will result in the initial state. The weights won't change so the initial state won't change either, instead of always multiplying $1$ with the initial weight matrix you can just save the initial state. Now you have essentially learned an initial state! | Learning initial state in RNNs | I am assuming you understood how to learn all the other weights in the RNN.
All states need to be computed, i.e. we have to take some input and multiply them with some weight matrix and then pass the | Learning initial state in RNNs
I am assuming you understood how to learn all the other weights in the RNN.
All states need to be computed, i.e. we have to take some input and multiply them with some weight matrix and then pass the resulting product through some activation function and finally obtain a state.
Initial states are odd because we do not compute them by taking the product of some initial input and weight matrix and use an activation function - we can simply "give" them some random value. They are essentially weights.
Instead of "manually" assigning them some value, why not just learn them like we learn any other weights? Which means we will have to take the gradient with respect to these initial weights and update them just like the other weights.
An alternate way to think about it is by considering the following scenario:
Let's use an initial input. We can fix the initial input to be $1$ and learn an initial weight matrix. The product of the initial input ($1$) and the initial weight matrix will give you an initial state. At test time we will continue to use initial input $1$ and multiply it with the initial weight matrix which will result in the initial state. The weights won't change so the initial state won't change either, instead of always multiplying $1$ with the initial weight matrix you can just save the initial state. Now you have essentially learned an initial state! | Learning initial state in RNNs
I am assuming you understood how to learn all the other weights in the RNN.
All states need to be computed, i.e. we have to take some input and multiply them with some weight matrix and then pass the |
32,020 | Learning initial state in RNNs | One of the approach is here:
http://r2rt.com/non-zero-initial-states-for-recurrent-neural-networks.html
Maybe you can create two RNNs(I never tried this, it just come in my mind):
First RNN will look on the series and learn the state. Then you can copy the state to the next rnn which will try to do the stuff you need. You learn both of them end-to-end. | Learning initial state in RNNs | One of the approach is here:
http://r2rt.com/non-zero-initial-states-for-recurrent-neural-networks.html
Maybe you can create two RNNs(I never tried this, it just come in my mind):
First RNN will look | Learning initial state in RNNs
One of the approach is here:
http://r2rt.com/non-zero-initial-states-for-recurrent-neural-networks.html
Maybe you can create two RNNs(I never tried this, it just come in my mind):
First RNN will look on the series and learn the state. Then you can copy the state to the next rnn which will try to do the stuff you need. You learn both of them end-to-end. | Learning initial state in RNNs
One of the approach is here:
http://r2rt.com/non-zero-initial-states-for-recurrent-neural-networks.html
Maybe you can create two RNNs(I never tried this, it just come in my mind):
First RNN will look |
32,021 | interpretation of gbm single tree prediction in pretty.gbm.tree | There's a subtlety about how the gbm algorithm works that you are missing, and it's leading to your confusion.
The predict method returns predictions from the entire boosted model, and these are indeed log-odds when fitting to minimize the Bernoulli deviance. On the other hand, the predictions from the individual trees are not log odds, they are something quite different.
Indeed, while the entire model in total is fit to predict the response, the individual trees are not, the individual trees are fit to predict the gradient of the loss function evaluated at the current prediction and the response. The is the "gradient" part of "gradient boosting".
Here's a minimal example that will hopefully clarify what is going on, I'll use a booster minimizing the gaussian loss function to keep the math simple and focus on the important concepts.
x <- seq(0, 1, length.out = 6)
y <- c(0, 0, 0, 1, 1, 1)
df <- data.frame(x = x, y = y)
M <- gbm(y ~ x, data = df,
distribution="gaussian",
n.trees = 1,
bag.fraction = 1.0, n.minobsinnode = 1, shrinkage = 1.0)
t <- pretty.gbm.tree(M, i = 1)
t[, c("SplitVar", "LeftNode", "RightNode", "MissingNode", "Prediction")]
Which looks like
SplitVar LeftNode RightNode MissingNode Prediction
0 0 1 2 3 0.0
1 -1 -1 -1 -1 -0.5
2 -1 -1 -1 -1 0.5
3 -1 -1 -1 -1 0.0
Let me break this down. In this model, we are miinimizing the following loss function:
$$ L(y, \hat y) = \frac{1}{2} (y - \hat y)^2 $$
The gradient with respect to the prediction is:
$$ \nabla L (y, \hat y) = y - \hat y $$
The tree is fit to predict the value of this function.
In detail, the model starts out at the zero'th stage predicting a constant, the mean response. In our example data, the mean response is $0.5$. Then, the gradient of the loss function is evaluated at the data and current predictions:
grad <- function(y, current_preds) {
y - current_preds
}
grad(y, 0.5)
which results in
[1] -0.5 -0.5 -0.5 0.5 0.5 0.5
Now you can see what has happened by comparing the tree predictions to this. The tree predictions have recovered exactly the gradients.
The same thing is true in the case of a bernoulli model, though the details are more complex. The loss function being minimized is
$$ L(y, f) = y f - \log(1 + e^f) $$
Note here that $f$ is the predicted log-oods, not the probability. The gradient is
$$ \nabla L(y, f) = y - \frac{1}{1 + e^{-f}} $$
and it is this that the predictions from the trees are approximating.
In short, the predictions from the trees in a gradient booster are not interpretable by comparison to the response, you must take great care when interpreting the internal structure of a boosted model. | interpretation of gbm single tree prediction in pretty.gbm.tree | There's a subtlety about how the gbm algorithm works that you are missing, and it's leading to your confusion.
The predict method returns predictions from the entire boosted model, and these are indee | interpretation of gbm single tree prediction in pretty.gbm.tree
There's a subtlety about how the gbm algorithm works that you are missing, and it's leading to your confusion.
The predict method returns predictions from the entire boosted model, and these are indeed log-odds when fitting to minimize the Bernoulli deviance. On the other hand, the predictions from the individual trees are not log odds, they are something quite different.
Indeed, while the entire model in total is fit to predict the response, the individual trees are not, the individual trees are fit to predict the gradient of the loss function evaluated at the current prediction and the response. The is the "gradient" part of "gradient boosting".
Here's a minimal example that will hopefully clarify what is going on, I'll use a booster minimizing the gaussian loss function to keep the math simple and focus on the important concepts.
x <- seq(0, 1, length.out = 6)
y <- c(0, 0, 0, 1, 1, 1)
df <- data.frame(x = x, y = y)
M <- gbm(y ~ x, data = df,
distribution="gaussian",
n.trees = 1,
bag.fraction = 1.0, n.minobsinnode = 1, shrinkage = 1.0)
t <- pretty.gbm.tree(M, i = 1)
t[, c("SplitVar", "LeftNode", "RightNode", "MissingNode", "Prediction")]
Which looks like
SplitVar LeftNode RightNode MissingNode Prediction
0 0 1 2 3 0.0
1 -1 -1 -1 -1 -0.5
2 -1 -1 -1 -1 0.5
3 -1 -1 -1 -1 0.0
Let me break this down. In this model, we are miinimizing the following loss function:
$$ L(y, \hat y) = \frac{1}{2} (y - \hat y)^2 $$
The gradient with respect to the prediction is:
$$ \nabla L (y, \hat y) = y - \hat y $$
The tree is fit to predict the value of this function.
In detail, the model starts out at the zero'th stage predicting a constant, the mean response. In our example data, the mean response is $0.5$. Then, the gradient of the loss function is evaluated at the data and current predictions:
grad <- function(y, current_preds) {
y - current_preds
}
grad(y, 0.5)
which results in
[1] -0.5 -0.5 -0.5 0.5 0.5 0.5
Now you can see what has happened by comparing the tree predictions to this. The tree predictions have recovered exactly the gradients.
The same thing is true in the case of a bernoulli model, though the details are more complex. The loss function being minimized is
$$ L(y, f) = y f - \log(1 + e^f) $$
Note here that $f$ is the predicted log-oods, not the probability. The gradient is
$$ \nabla L(y, f) = y - \frac{1}{1 + e^{-f}} $$
and it is this that the predictions from the trees are approximating.
In short, the predictions from the trees in a gradient booster are not interpretable by comparison to the response, you must take great care when interpreting the internal structure of a boosted model. | interpretation of gbm single tree prediction in pretty.gbm.tree
There's a subtlety about how the gbm algorithm works that you are missing, and it's leading to your confusion.
The predict method returns predictions from the entire boosted model, and these are indee |
32,022 | New factors levels not present in training data | RF handles factors by one-hot encoding them. It makes one new dummy column for every level of the factor variable. When there are new or different factor levels in a scoring dataframe, bad things happen.
If the train and test existed together in the same data structure at the point that the factor was defined, there isn't a problem. When the test has its factor defined separately then you get issues.
library("randomForest")
# Fit an RF on a few numerics and a factor. Give test set a new level.
N <- 100
df <- data.frame(num1 = rnorm(N),
num2 = rnorm(N),
fac = sample(letters[1:4], N, TRUE),
y = rnorm(N),
stringsAsFactors = FALSE)
df[100, "fac"] <- "a suffusion of yellow"
df$fac <- as.factor(df$fac)
train <- df[1:50, ]
test <- df[51:100, ]
rf <- randomForest(y ~ ., data=train)
# This is fine, even though the "yellow" level doesn't exist in train, RF
# is aware that it is a valid factor level
predict(rf, test)
# This is not fine. The factor level is introduced and RF can't know of it
test$fac <- as.character(test$fac)
test[50, "fac"] <- "toyota corolla"
test$fac <- as.factor(test$fac)
predict(rf, test)
You can get around this issue by relevelling your scoring factors to match the training data.
# Can get around by relevelling the new factor. "toyota corolla" becomes NA
test$fac <- factor(test$fac, levels = levels(train$fac))
predict(rf, test) | New factors levels not present in training data | RF handles factors by one-hot encoding them. It makes one new dummy column for every level of the factor variable. When there are new or different factor levels in a scoring dataframe, bad things happ | New factors levels not present in training data
RF handles factors by one-hot encoding them. It makes one new dummy column for every level of the factor variable. When there are new or different factor levels in a scoring dataframe, bad things happen.
If the train and test existed together in the same data structure at the point that the factor was defined, there isn't a problem. When the test has its factor defined separately then you get issues.
library("randomForest")
# Fit an RF on a few numerics and a factor. Give test set a new level.
N <- 100
df <- data.frame(num1 = rnorm(N),
num2 = rnorm(N),
fac = sample(letters[1:4], N, TRUE),
y = rnorm(N),
stringsAsFactors = FALSE)
df[100, "fac"] <- "a suffusion of yellow"
df$fac <- as.factor(df$fac)
train <- df[1:50, ]
test <- df[51:100, ]
rf <- randomForest(y ~ ., data=train)
# This is fine, even though the "yellow" level doesn't exist in train, RF
# is aware that it is a valid factor level
predict(rf, test)
# This is not fine. The factor level is introduced and RF can't know of it
test$fac <- as.character(test$fac)
test[50, "fac"] <- "toyota corolla"
test$fac <- as.factor(test$fac)
predict(rf, test)
You can get around this issue by relevelling your scoring factors to match the training data.
# Can get around by relevelling the new factor. "toyota corolla" becomes NA
test$fac <- factor(test$fac, levels = levels(train$fac))
predict(rf, test) | New factors levels not present in training data
RF handles factors by one-hot encoding them. It makes one new dummy column for every level of the factor variable. When there are new or different factor levels in a scoring dataframe, bad things happ |
32,023 | New factors levels not present in training data | I just encountered the issue as well when using expand.grid() to examine predictions of randomForest() across various factor levels.
The issue is created by expand.grid() setting stringsAsFactors = T by default, which coerces strings to factors using the available levels of the data. This creates a problem when one is only using a subset of factor levels for predictions.
I fixed the issue by setting stringsAsFactors = F which then allows randomForest() to do the one hot encoding as the previous answer suggested. | New factors levels not present in training data | I just encountered the issue as well when using expand.grid() to examine predictions of randomForest() across various factor levels.
The issue is created by expand.grid() setting stringsAsFactors = T | New factors levels not present in training data
I just encountered the issue as well when using expand.grid() to examine predictions of randomForest() across various factor levels.
The issue is created by expand.grid() setting stringsAsFactors = T by default, which coerces strings to factors using the available levels of the data. This creates a problem when one is only using a subset of factor levels for predictions.
I fixed the issue by setting stringsAsFactors = F which then allows randomForest() to do the one hot encoding as the previous answer suggested. | New factors levels not present in training data
I just encountered the issue as well when using expand.grid() to examine predictions of randomForest() across various factor levels.
The issue is created by expand.grid() setting stringsAsFactors = T |
32,024 | Difference between predictive and prognostic | This is an excellent question because the two are being terribly misused in personalized medicine and biomarker studies. The correct definition of the two, at least when it comes to data, is the same. Here is how the terms are being misused in personalized/precision medicine: prognostic is taken to mean predictive and predictive is taken to mean interaction, i.e., the ability to predict differences in treatment effectiveness over values of patient covariates. The correct terminology should be: predictive/prognostic for ability to forecast outcomes, and modeling interactions/differential treatment effect for the other. | Difference between predictive and prognostic | This is an excellent question because the two are being terribly misused in personalized medicine and biomarker studies. The correct definition of the two, at least when it comes to data, is the same | Difference between predictive and prognostic
This is an excellent question because the two are being terribly misused in personalized medicine and biomarker studies. The correct definition of the two, at least when it comes to data, is the same. Here is how the terms are being misused in personalized/precision medicine: prognostic is taken to mean predictive and predictive is taken to mean interaction, i.e., the ability to predict differences in treatment effectiveness over values of patient covariates. The correct terminology should be: predictive/prognostic for ability to forecast outcomes, and modeling interactions/differential treatment effect for the other. | Difference between predictive and prognostic
This is an excellent question because the two are being terribly misused in personalized medicine and biomarker studies. The correct definition of the two, at least when it comes to data, is the same |
32,025 | Question with Matrix Derivative: Why do I have to transpose? | As noted in the comments, it is best to write out the matrix equations and then apply the standard derivative rules. After a bit of experience with small cases, where you expand out all the terms, you can try just writing out the equations using summations and subscripts.
In terms of mathematical rules, for completeness I will note that there is a pretty good reference called The Matrix Cookbook*, that documents a large number of rules for calculus on matrix equations. (*I am not sure if there is a stable home for this document, so I am linking a Google search, which has always reliably found (many) copies, in my experience!)
That said, I find it difficult to follow these usually, so I end up using summation/subscript forms when I need to compute these sorts of derivatives. (Or sometimes I will use index notation.)
EDIT: For your specific problem, I think you may be getting stuck on the large equations. Here I would suggest that intermediate variables can be your friend, helping to break down the structure (similar to functions in modular programming).
EDIT the second: When I first looked at your problem, I thought the lowercase $h$ variables were vectors. Now I realize they are matrices, which changes things. Given this, it does not make sense to me that the result would be a matrix, rather than a higher-order tensor. The order of a tensor is the number of indices. If you take a derivative of one tensor $U$ with respect to another tensor $V$, the order of the resulting tensor $W$ will be the sum of the two, i.e.
$$W_{ij,pq}=\frac{\partial U_{ij}}{\partial V_{pq}}$$
For instance the gradient of a scalar function is a vector ($0+1=1$), and the Jacobian of a vector function is a matrix ($1+1=2$). For an example of a physically-meaningful $4_{th}$ order tensor, a simple example is the "spring constant" for the continuum-mechanics generalization of Hooke's Law (the last equation on that page is essentially the same as the one I give above).
When I work through your case, I find that the result is sparse, so is effectively $3_{rd}$ order, but it is not so sparse as to be $2_{nd}$ order $\ldots$ unless I made a mistake. (More precisely: I find $W_{ij,pq}=0$ for $p\neq i$, so we can effectively work with $\hat{W}_{ij,k}\equiv W_{ij,ik}$ as an order-3 tensor.)
EDIT the third: As the OP requested clarification, here is a simple example to demonstrate the issue. Consider the matrix equation
$$U=VA\implies U_{ij}=\sum_kV_{ik}A_{kj}\implies \frac{\partial U_{ij}}{\partial V_{pq}}=\sum_k\frac{\partial V_{ik}}{\partial V_{pq}}A_{kj}$$
To proceed, we introduce the Kronecker delta symbol (essentially the identity matrix):
$$\delta_{ij} =
\begin{cases}
1 & i=j\\
0 & i\neq j
\end{cases}$$
Then the derivative within the summation can be expressed as
$$\frac{\partial V_{ik}}{\partial V_{pq}}=\delta_{ip}\delta_{kq}$$
i.e. it is one if the both indices match and zero otherwise.
Noting the "index replacement" property of a summed tensor-$\delta$ product
$$\sum_k\delta_{kq}A_{kj}=A_{qj}$$
we then have
$$\frac{\partial U_{ij}}{\partial V_{pq}}=\delta_{ip}A_{qj}$$
So finally
$$W_{ij,pq}=
\begin{cases}
A_{qj} & p=i\\
0 & p\neq i
\end{cases}$$
(and $\hat{W}_{ij,k}=A_{kj}$) | Question with Matrix Derivative: Why do I have to transpose? | As noted in the comments, it is best to write out the matrix equations and then apply the standard derivative rules. After a bit of experience with small cases, where you expand out all the terms, you | Question with Matrix Derivative: Why do I have to transpose?
As noted in the comments, it is best to write out the matrix equations and then apply the standard derivative rules. After a bit of experience with small cases, where you expand out all the terms, you can try just writing out the equations using summations and subscripts.
In terms of mathematical rules, for completeness I will note that there is a pretty good reference called The Matrix Cookbook*, that documents a large number of rules for calculus on matrix equations. (*I am not sure if there is a stable home for this document, so I am linking a Google search, which has always reliably found (many) copies, in my experience!)
That said, I find it difficult to follow these usually, so I end up using summation/subscript forms when I need to compute these sorts of derivatives. (Or sometimes I will use index notation.)
EDIT: For your specific problem, I think you may be getting stuck on the large equations. Here I would suggest that intermediate variables can be your friend, helping to break down the structure (similar to functions in modular programming).
EDIT the second: When I first looked at your problem, I thought the lowercase $h$ variables were vectors. Now I realize they are matrices, which changes things. Given this, it does not make sense to me that the result would be a matrix, rather than a higher-order tensor. The order of a tensor is the number of indices. If you take a derivative of one tensor $U$ with respect to another tensor $V$, the order of the resulting tensor $W$ will be the sum of the two, i.e.
$$W_{ij,pq}=\frac{\partial U_{ij}}{\partial V_{pq}}$$
For instance the gradient of a scalar function is a vector ($0+1=1$), and the Jacobian of a vector function is a matrix ($1+1=2$). For an example of a physically-meaningful $4_{th}$ order tensor, a simple example is the "spring constant" for the continuum-mechanics generalization of Hooke's Law (the last equation on that page is essentially the same as the one I give above).
When I work through your case, I find that the result is sparse, so is effectively $3_{rd}$ order, but it is not so sparse as to be $2_{nd}$ order $\ldots$ unless I made a mistake. (More precisely: I find $W_{ij,pq}=0$ for $p\neq i$, so we can effectively work with $\hat{W}_{ij,k}\equiv W_{ij,ik}$ as an order-3 tensor.)
EDIT the third: As the OP requested clarification, here is a simple example to demonstrate the issue. Consider the matrix equation
$$U=VA\implies U_{ij}=\sum_kV_{ik}A_{kj}\implies \frac{\partial U_{ij}}{\partial V_{pq}}=\sum_k\frac{\partial V_{ik}}{\partial V_{pq}}A_{kj}$$
To proceed, we introduce the Kronecker delta symbol (essentially the identity matrix):
$$\delta_{ij} =
\begin{cases}
1 & i=j\\
0 & i\neq j
\end{cases}$$
Then the derivative within the summation can be expressed as
$$\frac{\partial V_{ik}}{\partial V_{pq}}=\delta_{ip}\delta_{kq}$$
i.e. it is one if the both indices match and zero otherwise.
Noting the "index replacement" property of a summed tensor-$\delta$ product
$$\sum_k\delta_{kq}A_{kj}=A_{qj}$$
we then have
$$\frac{\partial U_{ij}}{\partial V_{pq}}=\delta_{ip}A_{qj}$$
So finally
$$W_{ij,pq}=
\begin{cases}
A_{qj} & p=i\\
0 & p\neq i
\end{cases}$$
(and $\hat{W}_{ij,k}=A_{kj}$) | Question with Matrix Derivative: Why do I have to transpose?
As noted in the comments, it is best to write out the matrix equations and then apply the standard derivative rules. After a bit of experience with small cases, where you expand out all the terms, you |
32,026 | When approximating a posterior using MCMC, why don't we save the posterior probabilities but use the parameter value frequencies afterwards? | This is an interesting question, with different issues:
MCMC algorithms do not always recycle the computation of the posterior density at all proposed values, but some variance reduction techniques like Rao-Blackwellisation do. For instance, in a 1996 Biometrika paper with George Casella, we propose to use all simulated values, $\theta_i$ $(i=1,\ldots,T)$, accepted or not, by introducing weights $\omega_i$ that turn the average$$\sum_{i=1}^T \omega_ih(\theta_i)\big/\sum_{i=1}^T \omega_i$$into an almost unbiased estimator. (The almost being due to the normalisation by the sum of the weights.)
MCMC is often used on problems of large (parameter) dimension. Proposing an approximation to the whole posterior based on the observed density values at some parameter values is quite a challenge, including the issue of the normalising constant mentioned in Tim's answer and comments. One can imagine an approach that is a mix of non-parametric kernel estimation (as in e.g. krigging) and regression, but the experts I discussed with about this solution [a few years ago] were quite skeptical. The issue is that the resulting estimator remains non-parametric and hence "enjoys" non-parametric convergence speeds that are slower than Monte Carlo convergence speeds, the worse the larger the dimension.
Another potential use of the availability of the posterior values $\pi(\theta|\mathcal{D})$ is to weight each simulated value by its associated posterior, as in $$\frac{1}{T}\sum_{t=1}^T h(\theta_t) \pi(\theta_t|\mathcal{D})$$ Unfortunately, this creates a bias as the simulated values are already simulated from the posterior:
$$\mathbb{E}[h(\theta_t) \pi(\theta_t|\mathcal{D})]=\int h(\theta) h(\theta_t) \pi(\theta_t|\mathcal{D})^2\text{d}\theta$$ Even without a normalisation issue, those simulations should thus be targeting $\pi(\theta|\mathcal{D})^{1/2}$ and use a weight proportional to $\pi(\theta|\mathcal{D})^{1/2}$ but I do not know of results advocating this switch of target. As you mention in the comments, this is connected with tempering in that all simulations produced within a simulated tempering cycle can be recycled for Monte Carlo (integration) purposes this way. A numerical issue, however, is to handle several importance functions of the form $\pi(\theta)^{1/T}$ with missing normalising constants. | When approximating a posterior using MCMC, why don't we save the posterior probabilities but use the | This is an interesting question, with different issues:
MCMC algorithms do not always recycle the computation of the posterior density at all proposed values, but some variance reduction techniques l | When approximating a posterior using MCMC, why don't we save the posterior probabilities but use the parameter value frequencies afterwards?
This is an interesting question, with different issues:
MCMC algorithms do not always recycle the computation of the posterior density at all proposed values, but some variance reduction techniques like Rao-Blackwellisation do. For instance, in a 1996 Biometrika paper with George Casella, we propose to use all simulated values, $\theta_i$ $(i=1,\ldots,T)$, accepted or not, by introducing weights $\omega_i$ that turn the average$$\sum_{i=1}^T \omega_ih(\theta_i)\big/\sum_{i=1}^T \omega_i$$into an almost unbiased estimator. (The almost being due to the normalisation by the sum of the weights.)
MCMC is often used on problems of large (parameter) dimension. Proposing an approximation to the whole posterior based on the observed density values at some parameter values is quite a challenge, including the issue of the normalising constant mentioned in Tim's answer and comments. One can imagine an approach that is a mix of non-parametric kernel estimation (as in e.g. krigging) and regression, but the experts I discussed with about this solution [a few years ago] were quite skeptical. The issue is that the resulting estimator remains non-parametric and hence "enjoys" non-parametric convergence speeds that are slower than Monte Carlo convergence speeds, the worse the larger the dimension.
Another potential use of the availability of the posterior values $\pi(\theta|\mathcal{D})$ is to weight each simulated value by its associated posterior, as in $$\frac{1}{T}\sum_{t=1}^T h(\theta_t) \pi(\theta_t|\mathcal{D})$$ Unfortunately, this creates a bias as the simulated values are already simulated from the posterior:
$$\mathbb{E}[h(\theta_t) \pi(\theta_t|\mathcal{D})]=\int h(\theta) h(\theta_t) \pi(\theta_t|\mathcal{D})^2\text{d}\theta$$ Even without a normalisation issue, those simulations should thus be targeting $\pi(\theta|\mathcal{D})^{1/2}$ and use a weight proportional to $\pi(\theta|\mathcal{D})^{1/2}$ but I do not know of results advocating this switch of target. As you mention in the comments, this is connected with tempering in that all simulations produced within a simulated tempering cycle can be recycled for Monte Carlo (integration) purposes this way. A numerical issue, however, is to handle several importance functions of the form $\pi(\theta)^{1/T}$ with missing normalising constants. | When approximating a posterior using MCMC, why don't we save the posterior probabilities but use the
This is an interesting question, with different issues:
MCMC algorithms do not always recycle the computation of the posterior density at all proposed values, but some variance reduction techniques l |
32,027 | When approximating a posterior using MCMC, why don't we save the posterior probabilities but use the parameter value frequencies afterwards? | As you correctly noticed, the probabilities we are dealing with are unnormalized. Basically, we use MCMC to compute the normalizing factor in Bayes theorem. We cannot use the probabilities because they are unnormalized. The procedure that you suggest: to save the unnormalized probabilities and then divide them by their sum is incorrect.
Let me show it to you by example. Imagine that you used Monte Carlo to draw ten values from Bernoulli distribution parametrized by $p=0.9$, they are as follows:
1 0 1 1 1 1 1 1 1 1
you also have corresponding probabilities:
0.9 0.1 0.9 0.9 0.9 0.9 0.9 0.9 0.9 0.9
In this case the probabilities are normalized, but dividing them by their sum (that by axioms of probability is equal to unity) should not change anything. Unfortunatelly, using your procedure it does change the results to:
> f/sum(f)
[1] 0.10975610 0.01219512 0.10975610 0.10975610 0.10975610 0.10975610 0.10975610 0.10975610 0.10975610 0.10975610
Why is that? The answer is simple, in your sample each saved "probability" f appears with probability f, so you are weighting the probabilities by themselves! | When approximating a posterior using MCMC, why don't we save the posterior probabilities but use the | As you correctly noticed, the probabilities we are dealing with are unnormalized. Basically, we use MCMC to compute the normalizing factor in Bayes theorem. We cannot use the probabilities because the | When approximating a posterior using MCMC, why don't we save the posterior probabilities but use the parameter value frequencies afterwards?
As you correctly noticed, the probabilities we are dealing with are unnormalized. Basically, we use MCMC to compute the normalizing factor in Bayes theorem. We cannot use the probabilities because they are unnormalized. The procedure that you suggest: to save the unnormalized probabilities and then divide them by their sum is incorrect.
Let me show it to you by example. Imagine that you used Monte Carlo to draw ten values from Bernoulli distribution parametrized by $p=0.9$, they are as follows:
1 0 1 1 1 1 1 1 1 1
you also have corresponding probabilities:
0.9 0.1 0.9 0.9 0.9 0.9 0.9 0.9 0.9 0.9
In this case the probabilities are normalized, but dividing them by their sum (that by axioms of probability is equal to unity) should not change anything. Unfortunatelly, using your procedure it does change the results to:
> f/sum(f)
[1] 0.10975610 0.01219512 0.10975610 0.10975610 0.10975610 0.10975610 0.10975610 0.10975610 0.10975610 0.10975610
Why is that? The answer is simple, in your sample each saved "probability" f appears with probability f, so you are weighting the probabilities by themselves! | When approximating a posterior using MCMC, why don't we save the posterior probabilities but use the
As you correctly noticed, the probabilities we are dealing with are unnormalized. Basically, we use MCMC to compute the normalizing factor in Bayes theorem. We cannot use the probabilities because the |
32,028 | What is the relation between belief networks and Bayesian networks? | No, Bayesian network and deep belief network are not the same thing.
Bayesian network is a type of probabilistic graphical model where vertexes are random variables and edges are conditional dependencies. For large number of random variables, we use the graphical structure assumptions to decompose the joint distribution in a manageable level. In Bayesian network, there are two major tasks, learning and inference. The ultimate goal of learning is getting the joint distribution of the data, and the goal of inferences is trying to calculate the probability for a given events, assuming you already have the model
As mentioned in the link you provided:
"Neural networks" is a term usually used to refer to feedforward neural networks. Deep Neural Networks are feedforward Neural Networks with many layers.
You can think about neural network is just a big non-linear function, that it can approximate complicated outcomes. Here the nodes are "neurons" and the edges are "connections", where they are essentially building blocks for a function. | What is the relation between belief networks and Bayesian networks? | No, Bayesian network and deep belief network are not the same thing.
Bayesian network is a type of probabilistic graphical model where vertexes are random variables and edges are conditional dependen | What is the relation between belief networks and Bayesian networks?
No, Bayesian network and deep belief network are not the same thing.
Bayesian network is a type of probabilistic graphical model where vertexes are random variables and edges are conditional dependencies. For large number of random variables, we use the graphical structure assumptions to decompose the joint distribution in a manageable level. In Bayesian network, there are two major tasks, learning and inference. The ultimate goal of learning is getting the joint distribution of the data, and the goal of inferences is trying to calculate the probability for a given events, assuming you already have the model
As mentioned in the link you provided:
"Neural networks" is a term usually used to refer to feedforward neural networks. Deep Neural Networks are feedforward Neural Networks with many layers.
You can think about neural network is just a big non-linear function, that it can approximate complicated outcomes. Here the nodes are "neurons" and the edges are "connections", where they are essentially building blocks for a function. | What is the relation between belief networks and Bayesian networks?
No, Bayesian network and deep belief network are not the same thing.
Bayesian network is a type of probabilistic graphical model where vertexes are random variables and edges are conditional dependen |
32,029 | What is the relation between belief networks and Bayesian networks? | Belief network is a synonym of the Bayesian network, while deep belief networks are a class of deep neural networks(actually hybrid graphical models with both directed edges and undirected edges but are equivalent to the deep neural networks).
Deep neural networks are nothing more than complex functional compositions that can
be represented by computation graphs, and the values in their hidden neurons cannot be interpreted as probabilities(often black box), but it can be seen as a process of learning to learn. Belief networks are acyclic directed graphs and the parameters can all be interpreted as probabilities, and they are best for provably correct inference. | What is the relation between belief networks and Bayesian networks? | Belief network is a synonym of the Bayesian network, while deep belief networks are a class of deep neural networks(actually hybrid graphical models with both directed edges and undirected edges but a | What is the relation between belief networks and Bayesian networks?
Belief network is a synonym of the Bayesian network, while deep belief networks are a class of deep neural networks(actually hybrid graphical models with both directed edges and undirected edges but are equivalent to the deep neural networks).
Deep neural networks are nothing more than complex functional compositions that can
be represented by computation graphs, and the values in their hidden neurons cannot be interpreted as probabilities(often black box), but it can be seen as a process of learning to learn. Belief networks are acyclic directed graphs and the parameters can all be interpreted as probabilities, and they are best for provably correct inference. | What is the relation between belief networks and Bayesian networks?
Belief network is a synonym of the Bayesian network, while deep belief networks are a class of deep neural networks(actually hybrid graphical models with both directed edges and undirected edges but a |
32,030 | Modelling a win-draw-loss outcome in sports | You can use bivariate Poisson distribution with probability mass function
$$
f(x,y) = \exp\{-(\lambda_1+\lambda_2+\lambda_3)\}
\frac{\lambda_1^x}{x!}
\frac{\lambda_2^y}{y!}
\sum^{\min(x,y)}_{k=0}
{x \choose k}
{y \choose k}
k!\left(\frac{\lambda_3}{\lambda_1\lambda_2}\right)^k
$$
where $E(X) = \lambda_1+\lambda_3$ and $E(Y) = \lambda_2+\lambda_3$ and $\mathrm{cov}(X,Y) = \lambda_3$, so you can treat $\lambda_3$ as a measure of dependence between the two marginal Poisson distributions. The pmf and random generation for this distribution is implemented in extraDistr package if you are using R.
In fact, this distribution was described in terms of analyzing sports data by Karlis and Ntzoufras (2003), so you can check their paper for further details. Those authors in their earlier paper discussed also the univariate Poisson model, where they concluded that independence assumption provides fair approximation since the difference between scores of both teams does not depend on the correlation parameter of bivariate Poisson (Karlis and Ntzoufras, 2000).
Kawamura (1984) described estimating parameters for bivariate Poisson distribution by direct search using maximum likelihood. As about regression models, you can use EM algorithm for maximum likelihood estimation, as Karlis and Ntzoufras (2003), or Bayesian model estimated using MCMC. The EM algorithm for bivariate Poisson regression is implemented in bivpois package (Karlis and Ntzoufras, 2005) that is unfortunately out of CRAN at this moment.
Karlis, D., & Ntzoufras, I. (2003). Analysis of sports data by using bivariate Poisson models. Journal of the Royal Statistical Society: Series D (The Statistician), 52(3), 381-393.
Karlis, D. and Ntzoufras, I. (2000) On modelling soccer data.
Student, 3, 229-244.
Kawamura, K. (1984). Direct calculation of maximum likelihood estimator for the bivariate Poisson distribution. Kodai mathematical journal, 7(2), 211-221.
Karlis, D., and Ntzoufras, I. (2005). Bivariate Poisson and diagonal inflated bivariate Poisson regression models in R. Journal of Statistical Software, 14(10), 1-36. | Modelling a win-draw-loss outcome in sports | You can use bivariate Poisson distribution with probability mass function
$$
f(x,y) = \exp\{-(\lambda_1+\lambda_2+\lambda_3)\}
\frac{\lambda_1^x}{x!}
\frac{\lambda_2^y}{y!}
\sum^{\min(x,y)}_{k=0}
{x \ | Modelling a win-draw-loss outcome in sports
You can use bivariate Poisson distribution with probability mass function
$$
f(x,y) = \exp\{-(\lambda_1+\lambda_2+\lambda_3)\}
\frac{\lambda_1^x}{x!}
\frac{\lambda_2^y}{y!}
\sum^{\min(x,y)}_{k=0}
{x \choose k}
{y \choose k}
k!\left(\frac{\lambda_3}{\lambda_1\lambda_2}\right)^k
$$
where $E(X) = \lambda_1+\lambda_3$ and $E(Y) = \lambda_2+\lambda_3$ and $\mathrm{cov}(X,Y) = \lambda_3$, so you can treat $\lambda_3$ as a measure of dependence between the two marginal Poisson distributions. The pmf and random generation for this distribution is implemented in extraDistr package if you are using R.
In fact, this distribution was described in terms of analyzing sports data by Karlis and Ntzoufras (2003), so you can check their paper for further details. Those authors in their earlier paper discussed also the univariate Poisson model, where they concluded that independence assumption provides fair approximation since the difference between scores of both teams does not depend on the correlation parameter of bivariate Poisson (Karlis and Ntzoufras, 2000).
Kawamura (1984) described estimating parameters for bivariate Poisson distribution by direct search using maximum likelihood. As about regression models, you can use EM algorithm for maximum likelihood estimation, as Karlis and Ntzoufras (2003), or Bayesian model estimated using MCMC. The EM algorithm for bivariate Poisson regression is implemented in bivpois package (Karlis and Ntzoufras, 2005) that is unfortunately out of CRAN at this moment.
Karlis, D., & Ntzoufras, I. (2003). Analysis of sports data by using bivariate Poisson models. Journal of the Royal Statistical Society: Series D (The Statistician), 52(3), 381-393.
Karlis, D. and Ntzoufras, I. (2000) On modelling soccer data.
Student, 3, 229-244.
Kawamura, K. (1984). Direct calculation of maximum likelihood estimator for the bivariate Poisson distribution. Kodai mathematical journal, 7(2), 211-221.
Karlis, D., and Ntzoufras, I. (2005). Bivariate Poisson and diagonal inflated bivariate Poisson regression models in R. Journal of Statistical Software, 14(10), 1-36. | Modelling a win-draw-loss outcome in sports
You can use bivariate Poisson distribution with probability mass function
$$
f(x,y) = \exp\{-(\lambda_1+\lambda_2+\lambda_3)\}
\frac{\lambda_1^x}{x!}
\frac{\lambda_2^y}{y!}
\sum^{\min(x,y)}_{k=0}
{x \ |
32,031 | Modelling a win-draw-loss outcome in sports | The bivariate Poisson does not accommodate negative correlation between $x_1$ and $x_2$. A model for this could be constructed by applying the Poisson quantile function to each component of a Gaussian copula. The resulting bivariate probability mass function is easily computed in R with following code where the vector lambda contains the parameters of the two marginal Poisson distributions and rho is the correlation of the standard binormal distribution.
library(mvtnorm)
dbipoisgausscopula <- function(x, lambda, rho) {
pmvnorm(lower=qnorm(ppois(x-1,lambda)),
upper=qnorm(ppois(x,lambda)),
mean=c(0,0),
sigma=matrix(c(1,rho,rho,1),2,2)
)
} | Modelling a win-draw-loss outcome in sports | The bivariate Poisson does not accommodate negative correlation between $x_1$ and $x_2$. A model for this could be constructed by applying the Poisson quantile function to each component of a Gaussia | Modelling a win-draw-loss outcome in sports
The bivariate Poisson does not accommodate negative correlation between $x_1$ and $x_2$. A model for this could be constructed by applying the Poisson quantile function to each component of a Gaussian copula. The resulting bivariate probability mass function is easily computed in R with following code where the vector lambda contains the parameters of the two marginal Poisson distributions and rho is the correlation of the standard binormal distribution.
library(mvtnorm)
dbipoisgausscopula <- function(x, lambda, rho) {
pmvnorm(lower=qnorm(ppois(x-1,lambda)),
upper=qnorm(ppois(x,lambda)),
mean=c(0,0),
sigma=matrix(c(1,rho,rho,1),2,2)
)
} | Modelling a win-draw-loss outcome in sports
The bivariate Poisson does not accommodate negative correlation between $x_1$ and $x_2$. A model for this could be constructed by applying the Poisson quantile function to each component of a Gaussia |
32,032 | Forecasting ARIMA with `predict` vs `forecast` in R [closed] | They will give you the same answers. But the combination of Arima (not arima) and forecast from the forecast package are enhanced versions with additional functionality.
Arima calls stats::arima for the estimation, but stores more information in the returned object. It also allows some additional model functionality such as including a drift term in a model with a unit root.
forecast calls stats::predict to generate the forecasts. It will automatically handle the drift term from Arima. It returns a forecast object (rather than a simple list) which is useful for plotting, displaying, summarizing and analysing the results. | Forecasting ARIMA with `predict` vs `forecast` in R [closed] | They will give you the same answers. But the combination of Arima (not arima) and forecast from the forecast package are enhanced versions with additional functionality.
Arima calls stats::arima for t | Forecasting ARIMA with `predict` vs `forecast` in R [closed]
They will give you the same answers. But the combination of Arima (not arima) and forecast from the forecast package are enhanced versions with additional functionality.
Arima calls stats::arima for the estimation, but stores more information in the returned object. It also allows some additional model functionality such as including a drift term in a model with a unit root.
forecast calls stats::predict to generate the forecasts. It will automatically handle the drift term from Arima. It returns a forecast object (rather than a simple list) which is useful for plotting, displaying, summarizing and analysing the results. | Forecasting ARIMA with `predict` vs `forecast` in R [closed]
They will give you the same answers. But the combination of Arima (not arima) and forecast from the forecast package are enhanced versions with additional functionality.
Arima calls stats::arima for t |
32,033 | Tuning an exponential moving average to a moving window mean? | Let $x$ be the original time series and $x_m$ be the result of smoothing with a simple moving average with some window width. Let $f(x, \alpha)$ be a function that returns a smoothed version of $x$ using smoothing parameter $\alpha$.
Define a loss function $L$ that measures the dissimilarity between the windowed moving average and the exponential moving average. A simple choice would be the squared error:
$$L(\alpha) = \|x_m - f(x, \alpha)\|^2$$
If you want the error to be invariant to shift/scaling, you could define $L$ to be something like the negative of the peak height of the normalized cross correlation.
Find the value of $\alpha$ that minimizes $L$:
$$\underset{\alpha}{\min} L(\alpha)$$
Here's an example using a noisy sinusoidal signal and the mean squared error as the loss function:
Another example using white noise as the signal:
The loss function appears to be well behaved and have a single global minimum for these two different signals, suggesting a standard 1d optimization solver could work (as I used to select $\alpha$ here). But, I haven't verified that this must be the case. If in doubt, plot the loss function and use a more sophisticated optimization method if necessary.
Edit:
Here's a plot of the optimal alpha (for exponential smoothing) as a function of window size (for simple moving average). Plotted for each of the signals shown above. | Tuning an exponential moving average to a moving window mean? | Let $x$ be the original time series and $x_m$ be the result of smoothing with a simple moving average with some window width. Let $f(x, \alpha)$ be a function that returns a smoothed version of $x$ us | Tuning an exponential moving average to a moving window mean?
Let $x$ be the original time series and $x_m$ be the result of smoothing with a simple moving average with some window width. Let $f(x, \alpha)$ be a function that returns a smoothed version of $x$ using smoothing parameter $\alpha$.
Define a loss function $L$ that measures the dissimilarity between the windowed moving average and the exponential moving average. A simple choice would be the squared error:
$$L(\alpha) = \|x_m - f(x, \alpha)\|^2$$
If you want the error to be invariant to shift/scaling, you could define $L$ to be something like the negative of the peak height of the normalized cross correlation.
Find the value of $\alpha$ that minimizes $L$:
$$\underset{\alpha}{\min} L(\alpha)$$
Here's an example using a noisy sinusoidal signal and the mean squared error as the loss function:
Another example using white noise as the signal:
The loss function appears to be well behaved and have a single global minimum for these two different signals, suggesting a standard 1d optimization solver could work (as I used to select $\alpha$ here). But, I haven't verified that this must be the case. If in doubt, plot the loss function and use a more sophisticated optimization method if necessary.
Edit:
Here's a plot of the optimal alpha (for exponential smoothing) as a function of window size (for simple moving average). Plotted for each of the signals shown above. | Tuning an exponential moving average to a moving window mean?
Let $x$ be the original time series and $x_m$ be the result of smoothing with a simple moving average with some window width. Let $f(x, \alpha)$ be a function that returns a smoothed version of $x$ us |
32,034 | Tuning an exponential moving average to a moving window mean? | If I understand the question correctly, the issue is one of trying to make an exponentially decreasing weight series fit to a discrete uniform (constant weight with cutoff):
Clearly either an EWMA decreases quickly (fitting badly at older lags where the ordinary moving average still has high weight) or has a tail much further into the past, fitting the weight-distribution badly where the ordinary moving average has no weight).
Exactly which choice of $\alpha$ will do best at matching the results from uniform-weights will depend crucially on how you measure performance and (naturally) on the characteristics of the series (both ordinary moving average and EWMA would only be reasonably suitable for weakly-stationary series for example, but that covers a lot of cases with potentially different relative performance for different $\alpha$ values)
The question leaves both of these things vague, so I suspect there's not a lot more to be said than "it depends" - about either the similarity of the conditional mean or the size of the conditional variance, here. | Tuning an exponential moving average to a moving window mean? | If I understand the question correctly, the issue is one of trying to make an exponentially decreasing weight series fit to a discrete uniform (constant weight with cutoff):
Clearly either an EWMA de | Tuning an exponential moving average to a moving window mean?
If I understand the question correctly, the issue is one of trying to make an exponentially decreasing weight series fit to a discrete uniform (constant weight with cutoff):
Clearly either an EWMA decreases quickly (fitting badly at older lags where the ordinary moving average still has high weight) or has a tail much further into the past, fitting the weight-distribution badly where the ordinary moving average has no weight).
Exactly which choice of $\alpha$ will do best at matching the results from uniform-weights will depend crucially on how you measure performance and (naturally) on the characteristics of the series (both ordinary moving average and EWMA would only be reasonably suitable for weakly-stationary series for example, but that covers a lot of cases with potentially different relative performance for different $\alpha$ values)
The question leaves both of these things vague, so I suspect there's not a lot more to be said than "it depends" - about either the similarity of the conditional mean or the size of the conditional variance, here. | Tuning an exponential moving average to a moving window mean?
If I understand the question correctly, the issue is one of trying to make an exponentially decreasing weight series fit to a discrete uniform (constant weight with cutoff):
Clearly either an EWMA de |
32,035 | Tuning an exponential moving average to a moving window mean? | We can think of this as a hyperparameter optimization problem.
We have a target X_mean which is the target value.
We also have a loss function e.g. L2 (X_exponential - X_mean).
We are searching for a hyperparameter (alpha) for the exponential moving average to minimize loss. | Tuning an exponential moving average to a moving window mean? | We can think of this as a hyperparameter optimization problem.
We have a target X_mean which is the target value.
We also have a loss function e.g. L2 (X_exponential - X_mean).
We are searching for a | Tuning an exponential moving average to a moving window mean?
We can think of this as a hyperparameter optimization problem.
We have a target X_mean which is the target value.
We also have a loss function e.g. L2 (X_exponential - X_mean).
We are searching for a hyperparameter (alpha) for the exponential moving average to minimize loss. | Tuning an exponential moving average to a moving window mean?
We can think of this as a hyperparameter optimization problem.
We have a target X_mean which is the target value.
We also have a loss function e.g. L2 (X_exponential - X_mean).
We are searching for a |
32,036 | Tuning an exponential moving average to a moving window mean? | An exponential moving average ($EMA$) is an IIR filter: Infinite impulse response, meaning that, technically, the "weights" vector of the $EMA$ is of infinite length, because an $EMA$ uses its own output in the previous time step as an input in the current one:
$EMA =$ $\alpha$ $*$ $Close$ $+$ $(1 –$ $\alpha$) $*$ $EMA[1]$
with:
$EMA[1]$ the value of the EMA in the previous step
$Close$ the value of your input signal in the current time step.
However, you can approximate an $EMA$ with a finite window length $n$, depending on the number of decimals you require: I refer to this thread.
It is known that the $\alpha$ of the $EMA$ is associated with window length $n$ like this:
$\alpha$ $= 2 / (n + 1)$
or
$n =$ $(2 / $ $\alpha$$)$$-1$
So an $\alpha$ of i.e. $0.1$ would correspond to a window $n$ of $19$, a window of i.e. $n=10$, would correspond to an $\alpha$ of $0.181818...$
And the general shape of the $EMA$ weights will look like this (although I would plot them in reverse order, because a window slides over a time series from left to right, if it's a causal filter).
The interesting aspect about this question is that all these different types of moving averages (SMA, EMA, LWMA, HMA, ...) are more or less the same once you express them in function of lag. I refer to this thread. | Tuning an exponential moving average to a moving window mean? | An exponential moving average ($EMA$) is an IIR filter: Infinite impulse response, meaning that, technically, the "weights" vector of the $EMA$ is of infinite length, because an $EMA$ uses its own out | Tuning an exponential moving average to a moving window mean?
An exponential moving average ($EMA$) is an IIR filter: Infinite impulse response, meaning that, technically, the "weights" vector of the $EMA$ is of infinite length, because an $EMA$ uses its own output in the previous time step as an input in the current one:
$EMA =$ $\alpha$ $*$ $Close$ $+$ $(1 –$ $\alpha$) $*$ $EMA[1]$
with:
$EMA[1]$ the value of the EMA in the previous step
$Close$ the value of your input signal in the current time step.
However, you can approximate an $EMA$ with a finite window length $n$, depending on the number of decimals you require: I refer to this thread.
It is known that the $\alpha$ of the $EMA$ is associated with window length $n$ like this:
$\alpha$ $= 2 / (n + 1)$
or
$n =$ $(2 / $ $\alpha$$)$$-1$
So an $\alpha$ of i.e. $0.1$ would correspond to a window $n$ of $19$, a window of i.e. $n=10$, would correspond to an $\alpha$ of $0.181818...$
And the general shape of the $EMA$ weights will look like this (although I would plot them in reverse order, because a window slides over a time series from left to right, if it's a causal filter).
The interesting aspect about this question is that all these different types of moving averages (SMA, EMA, LWMA, HMA, ...) are more or less the same once you express them in function of lag. I refer to this thread. | Tuning an exponential moving average to a moving window mean?
An exponential moving average ($EMA$) is an IIR filter: Infinite impulse response, meaning that, technically, the "weights" vector of the $EMA$ is of infinite length, because an $EMA$ uses its own out |
32,037 | Can a proper prior lead to an improper posterior? | I think that everything you need is contained in the several answers for this related but slighly different question (Does the Bayesian posterior need to be a proper distribution?). Here is a proposal of summary for your specific question:
From the sketch of proof https://stats.stackexchange.com/a/89157/14346: if the prior is proper and $p(x|\theta)$ none degenerate then the set of observations for which the posterior is improper is a Lesbegue null set. In other words:
$$
\mbox{proper prior} \Rightarrow \mbox{proper posterior almost everywhere}.
$$
So, there exists some observations $x$ (but a null set) leading to an improper $p(\theta|x)$. An example of such $x$ for a given $p(\theta|x)$ is given here https://stats.stackexchange.com/a/89150/14346.
Nevertheless, (as pointed out in the comment of the example below) density functions are equivalent (roughly, can be treated as the same) if they only differ on a null set. So the specific observations leading to improperness are complelety arbitrary depending on which specific forms of the density you choose from the equivalent sets. | Can a proper prior lead to an improper posterior? | I think that everything you need is contained in the several answers for this related but slighly different question (Does the Bayesian posterior need to be a proper distribution?). Here is a proposal | Can a proper prior lead to an improper posterior?
I think that everything you need is contained in the several answers for this related but slighly different question (Does the Bayesian posterior need to be a proper distribution?). Here is a proposal of summary for your specific question:
From the sketch of proof https://stats.stackexchange.com/a/89157/14346: if the prior is proper and $p(x|\theta)$ none degenerate then the set of observations for which the posterior is improper is a Lesbegue null set. In other words:
$$
\mbox{proper prior} \Rightarrow \mbox{proper posterior almost everywhere}.
$$
So, there exists some observations $x$ (but a null set) leading to an improper $p(\theta|x)$. An example of such $x$ for a given $p(\theta|x)$ is given here https://stats.stackexchange.com/a/89150/14346.
Nevertheless, (as pointed out in the comment of the example below) density functions are equivalent (roughly, can be treated as the same) if they only differ on a null set. So the specific observations leading to improperness are complelety arbitrary depending on which specific forms of the density you choose from the equivalent sets. | Can a proper prior lead to an improper posterior?
I think that everything you need is contained in the several answers for this related but slighly different question (Does the Bayesian posterior need to be a proper distribution?). Here is a proposal |
32,038 | R: regression coefficients and lubridate | Possible solution
It would help if you were to report specific quantities in the question, but even so one can make reasonable guesses. My eye says the slope of the fitted line is around $2$ per 5 months, or $5$ per year. If your output is "on the order of" $10^{-7}$, that means it is around $5/10^{-7}$ times what you expected. That is close to the number of seconds per year (equal to $10^7\pi$ to a good approximation), suggesting that the internal numerical value of your "month" variable is in terms of seconds rather than years. All you need to do, therefore, is convert it back from a rate of change per second into a rate of change per year. The conversion factor is approximately
$$60\text{ seconds/minute}\times 60\text{ minutes/hour}\times 24\text{ hours/day}\times 365.2422\text{ days/year} = 3.1556926 \times 10^7\text{ seconds/year}.$$
General advice and comments
I have provided this answer, rather than migrating the question to StackOverflow, because such problems with dates are common: they occur on almost every computing platfrom, from Excel through R. Experience with a large number of platforms suggests some simple principles to follow:
Use a system's internal date datatype to store dates, perform date-specific manipulation (such as finding the day of the week, etc.), and to produce good labels on graphics.
For statistical analysis, circumvent the system's default by computing a numeric equivalent of the dates. It is often best to establish a project-specific date origin and to represent all dates in terms of days, months, or years from that particular origin. This achieves several important things:
You will not make mistakes concerning the units in which dates are represented.
Your statistical output, such as regression coefficients, will be readily interpretable.
Your calculations will tend to be more numerically stable, because they will involve numbers of reasonable size. (R's internal date values, which are in seconds since the end of 1969, are in the many billions: even in double-precision computation, the sums of squares involved in many statistical procedures cause catastrophic loss of precision. See https://stats.stackexchange.com/a/318516/919 for a discussion.)
Allow an exception to rule (2) when working with time series procedures that "understand" how to cope with varying-length months, how annual, monthly, and weekly seasons work, etc. | R: regression coefficients and lubridate | Possible solution
It would help if you were to report specific quantities in the question, but even so one can make reasonable guesses. My eye says the slope of the fitted line is around $2$ per 5 mo | R: regression coefficients and lubridate
Possible solution
It would help if you were to report specific quantities in the question, but even so one can make reasonable guesses. My eye says the slope of the fitted line is around $2$ per 5 months, or $5$ per year. If your output is "on the order of" $10^{-7}$, that means it is around $5/10^{-7}$ times what you expected. That is close to the number of seconds per year (equal to $10^7\pi$ to a good approximation), suggesting that the internal numerical value of your "month" variable is in terms of seconds rather than years. All you need to do, therefore, is convert it back from a rate of change per second into a rate of change per year. The conversion factor is approximately
$$60\text{ seconds/minute}\times 60\text{ minutes/hour}\times 24\text{ hours/day}\times 365.2422\text{ days/year} = 3.1556926 \times 10^7\text{ seconds/year}.$$
General advice and comments
I have provided this answer, rather than migrating the question to StackOverflow, because such problems with dates are common: they occur on almost every computing platfrom, from Excel through R. Experience with a large number of platforms suggests some simple principles to follow:
Use a system's internal date datatype to store dates, perform date-specific manipulation (such as finding the day of the week, etc.), and to produce good labels on graphics.
For statistical analysis, circumvent the system's default by computing a numeric equivalent of the dates. It is often best to establish a project-specific date origin and to represent all dates in terms of days, months, or years from that particular origin. This achieves several important things:
You will not make mistakes concerning the units in which dates are represented.
Your statistical output, such as regression coefficients, will be readily interpretable.
Your calculations will tend to be more numerically stable, because they will involve numbers of reasonable size. (R's internal date values, which are in seconds since the end of 1969, are in the many billions: even in double-precision computation, the sums of squares involved in many statistical procedures cause catastrophic loss of precision. See https://stats.stackexchange.com/a/318516/919 for a discussion.)
Allow an exception to rule (2) when working with time series procedures that "understand" how to cope with varying-length months, how annual, monthly, and weekly seasons work, etc. | R: regression coefficients and lubridate
Possible solution
It would help if you were to report specific quantities in the question, but even so one can make reasonable guesses. My eye says the slope of the fitted line is around $2$ per 5 mo |
32,039 | How to perform a logistic regression for more than 2 response classes in R | Take a look at the multinom function of the package nnet in R:
glm.fit=multinom(direccion~., data=datos)
summary(glm.fit)
#Prediction
predict(glm.fit, newdata, "probs")
You should also consider separating you data set into 2 sets: training and testing, build your model based on training set, and test it on the testing set:
alpha=0.7
d = sort(sample(nrow(datos), nrow(datos)*alpha))
train = datos[d,]
test = datos[-d,]
glm.fit=multinom(direccion~., data=train)
predict(glm.fit, test, "probs")
And then measuring the performance of your model by comparing the predicted trends on your testing set with the actual trends.
You might need also to choose the relevant threshold to make the decision from your predicted probabilities. | How to perform a logistic regression for more than 2 response classes in R | Take a look at the multinom function of the package nnet in R:
glm.fit=multinom(direccion~., data=datos)
summary(glm.fit)
#Prediction
predict(glm.fit, newdata, "probs")
You should also consider separ | How to perform a logistic regression for more than 2 response classes in R
Take a look at the multinom function of the package nnet in R:
glm.fit=multinom(direccion~., data=datos)
summary(glm.fit)
#Prediction
predict(glm.fit, newdata, "probs")
You should also consider separating you data set into 2 sets: training and testing, build your model based on training set, and test it on the testing set:
alpha=0.7
d = sort(sample(nrow(datos), nrow(datos)*alpha))
train = datos[d,]
test = datos[-d,]
glm.fit=multinom(direccion~., data=train)
predict(glm.fit, test, "probs")
And then measuring the performance of your model by comparing the predicted trends on your testing set with the actual trends.
You might need also to choose the relevant threshold to make the decision from your predicted probabilities. | How to perform a logistic regression for more than 2 response classes in R
Take a look at the multinom function of the package nnet in R:
glm.fit=multinom(direccion~., data=datos)
summary(glm.fit)
#Prediction
predict(glm.fit, newdata, "probs")
You should also consider separ |
32,040 | Arimax Prediction : Using Forecast Package | Prediction intervals are based on residual variance as estimated by the maximum likelihood optimization.
I like forecast function from the forecast package:
fc <- forecast(forecast.arima,h = 5, xreg=tf[114:length(tf)])
which gives me the following predictions:
Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
Jun 2005 17.61393 17.47222 17.75565 17.39720 17.83067
Jul 2005 17.51725 17.35753 17.67697 17.27299 17.76152
Aug 2005 17.51725 17.35753 17.67697 17.27299 17.76152
Sep 2005 17.51725 17.35753 17.67697 17.27299 17.76152
Oct 2005 17.51725 17.35753 17.67697 17.27299 17.76152
the way prediction interval works is by following formula:
$y_t \pm z\sigma$ where $z$ is a multiplier which takes values such as 1.96 for 95% prediction interval and 1.28 for 80% prediction interval $\sigma$ is the standard deviation of the residual also forecast distribution which is also the square root of sigma^2 in the maximum likelihood estimate. As you show sigma^2 ( 0.01223) is identical in both your models, prediction intervals will also be same and will match.
If you want to check it,
Upper Limits:
> fc$mean[1]+sqrt(forecast.arima$sigma2)*1.96
[1] 17.83068
Lower Limits:
> fc$mean[1]-sqrt(forecast.arima$sigma2)*1.96
[1] 17.39719
which matches the prediction interval provided by the forecast function. To answer your question, yes leveraging forecast package will work in this case and the prediction intervals will be correct. | Arimax Prediction : Using Forecast Package | Prediction intervals are based on residual variance as estimated by the maximum likelihood optimization.
I like forecast function from the forecast package:
fc <- forecast(forecast.arima,h = 5, xreg= | Arimax Prediction : Using Forecast Package
Prediction intervals are based on residual variance as estimated by the maximum likelihood optimization.
I like forecast function from the forecast package:
fc <- forecast(forecast.arima,h = 5, xreg=tf[114:length(tf)])
which gives me the following predictions:
Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
Jun 2005 17.61393 17.47222 17.75565 17.39720 17.83067
Jul 2005 17.51725 17.35753 17.67697 17.27299 17.76152
Aug 2005 17.51725 17.35753 17.67697 17.27299 17.76152
Sep 2005 17.51725 17.35753 17.67697 17.27299 17.76152
Oct 2005 17.51725 17.35753 17.67697 17.27299 17.76152
the way prediction interval works is by following formula:
$y_t \pm z\sigma$ where $z$ is a multiplier which takes values such as 1.96 for 95% prediction interval and 1.28 for 80% prediction interval $\sigma$ is the standard deviation of the residual also forecast distribution which is also the square root of sigma^2 in the maximum likelihood estimate. As you show sigma^2 ( 0.01223) is identical in both your models, prediction intervals will also be same and will match.
If you want to check it,
Upper Limits:
> fc$mean[1]+sqrt(forecast.arima$sigma2)*1.96
[1] 17.83068
Lower Limits:
> fc$mean[1]-sqrt(forecast.arima$sigma2)*1.96
[1] 17.39719
which matches the prediction interval provided by the forecast function. To answer your question, yes leveraging forecast package will work in this case and the prediction intervals will be correct. | Arimax Prediction : Using Forecast Package
Prediction intervals are based on residual variance as estimated by the maximum likelihood optimization.
I like forecast function from the forecast package:
fc <- forecast(forecast.arima,h = 5, xreg= |
32,041 | CART: Selection of best predictor for splitting when gains in impurity decrease are equal? | I confess to be a mediocre c-code interpreter and this old code is not not user-friendly. That said I went through the source code and made these observations which makes me quite sure to say: "rpart literally picks the first and best variable column". As column 1 and 2 produce inferior splits, petal.length will be first split-variable because this column is before petal.width in data.frame/matrix. Lastly, I show this by inverting column order such that petal.with will be first split-variable.
In in the c source file "bsplit.c" in source code for rpart I quote from line 38:
* test out the variables 1 at at time
me->primary = (pSplit) NULL;
for (i = 0; i < rp.nvar; i++) {
... thus iterating in a for loop starting from i=1 to rp.nvar a loss function will be called to scan all split by one variable, inside gini.c for "non-categorical split" line 230 the best found split is updated if a new split is better. (This could also be a user defined loss-function)
if (temp < best) {
best = temp;
where = i;
direction = lmean < rmean ? LEFT : RIGHT;
}
and last line 323, the improvement for best split by a variable is calculated...
*improve = total_ss - best
...back in bsplit.c the improvement is checked if larger than what previously seen, and only updated if larger.
if (improve > rp.iscale)
rp.iscale = improve; /* largest seen so far */
My impression on this is that the first and best (of possible ties will be chosen), because only if new break point have a better score it will be saved. This concerns both the first best break point found and the first best variable found. Break points seems not to be scanned simply left to right in gini.c so the first found tying break point may be tricky to predict. But variables are very predictable scanned from first column to last column.
This behavior is different from the randomForest implementation where in classTree.c the following solution is used:
/* Break ties at random: */
if (crit == critmax) {
if (unif_rand() < 1.0 / ntie) {
*bestSplit = j;
critmax = crit;
*splitVar = mvar;
}
ntie++;
}
very lastly I confirm this behaviour by flipping the columns of iris, such that petal.width is chosen first
library(rpart)
data(iris)
iris = iris[,5:1] #flip/flop", invert order of columns columns
obj = rpart(Species~.,data=iris)
print(obj) #now petal width is first split
1) root 150 100 setosa (0.33333333 0.33333333 0.33333333)
2) Petal.Width< 0.8 50 0 setosa (1.00000000 0.00000000 0.00000000) *
3) Petal.Width>=0.8 100 50 versicolor (0.00000000 0.50000000 0.50000000)
6) Petal.Width< 1.75 54 5 versicolor (0.00000000 0.90740741 0.09259259) *
7) Petal.Width>=1.75 46 1 virginica (0.00000000 0.02173913 0.97826087) *
...and flip back again
iris = iris[,5:1] #flop/flip", revert order of columns columns
obj = rpart(Species~.,data=iris)
print(obj) #now petal length is first split
1) root 150 100 setosa (0.33333333 0.33333333 0.33333333)
2) Petal.Length< 2.45 50 0 setosa (1.00000000 0.00000000 0.00000000) *
3) Petal.Length>=2.45 100 50 versicolor (0.00000000 0.50000000 0.50000000)
6) Petal.Width< 1.75 54 5 versicolor (0.00000000 0.90740741 0.09259259) *
7) Petal.Width>=1.75 46 1 virginica (0.00000000 0.02173913 0.97826087) * | CART: Selection of best predictor for splitting when gains in impurity decrease are equal? | I confess to be a mediocre c-code interpreter and this old code is not not user-friendly. That said I went through the source code and made these observations which makes me quite sure to say: "rpart | CART: Selection of best predictor for splitting when gains in impurity decrease are equal?
I confess to be a mediocre c-code interpreter and this old code is not not user-friendly. That said I went through the source code and made these observations which makes me quite sure to say: "rpart literally picks the first and best variable column". As column 1 and 2 produce inferior splits, petal.length will be first split-variable because this column is before petal.width in data.frame/matrix. Lastly, I show this by inverting column order such that petal.with will be first split-variable.
In in the c source file "bsplit.c" in source code for rpart I quote from line 38:
* test out the variables 1 at at time
me->primary = (pSplit) NULL;
for (i = 0; i < rp.nvar; i++) {
... thus iterating in a for loop starting from i=1 to rp.nvar a loss function will be called to scan all split by one variable, inside gini.c for "non-categorical split" line 230 the best found split is updated if a new split is better. (This could also be a user defined loss-function)
if (temp < best) {
best = temp;
where = i;
direction = lmean < rmean ? LEFT : RIGHT;
}
and last line 323, the improvement for best split by a variable is calculated...
*improve = total_ss - best
...back in bsplit.c the improvement is checked if larger than what previously seen, and only updated if larger.
if (improve > rp.iscale)
rp.iscale = improve; /* largest seen so far */
My impression on this is that the first and best (of possible ties will be chosen), because only if new break point have a better score it will be saved. This concerns both the first best break point found and the first best variable found. Break points seems not to be scanned simply left to right in gini.c so the first found tying break point may be tricky to predict. But variables are very predictable scanned from first column to last column.
This behavior is different from the randomForest implementation where in classTree.c the following solution is used:
/* Break ties at random: */
if (crit == critmax) {
if (unif_rand() < 1.0 / ntie) {
*bestSplit = j;
critmax = crit;
*splitVar = mvar;
}
ntie++;
}
very lastly I confirm this behaviour by flipping the columns of iris, such that petal.width is chosen first
library(rpart)
data(iris)
iris = iris[,5:1] #flip/flop", invert order of columns columns
obj = rpart(Species~.,data=iris)
print(obj) #now petal width is first split
1) root 150 100 setosa (0.33333333 0.33333333 0.33333333)
2) Petal.Width< 0.8 50 0 setosa (1.00000000 0.00000000 0.00000000) *
3) Petal.Width>=0.8 100 50 versicolor (0.00000000 0.50000000 0.50000000)
6) Petal.Width< 1.75 54 5 versicolor (0.00000000 0.90740741 0.09259259) *
7) Petal.Width>=1.75 46 1 virginica (0.00000000 0.02173913 0.97826087) *
...and flip back again
iris = iris[,5:1] #flop/flip", revert order of columns columns
obj = rpart(Species~.,data=iris)
print(obj) #now petal length is first split
1) root 150 100 setosa (0.33333333 0.33333333 0.33333333)
2) Petal.Length< 2.45 50 0 setosa (1.00000000 0.00000000 0.00000000) *
3) Petal.Length>=2.45 100 50 versicolor (0.00000000 0.50000000 0.50000000)
6) Petal.Width< 1.75 54 5 versicolor (0.00000000 0.90740741 0.09259259) *
7) Petal.Width>=1.75 46 1 virginica (0.00000000 0.02173913 0.97826087) * | CART: Selection of best predictor for splitting when gains in impurity decrease are equal?
I confess to be a mediocre c-code interpreter and this old code is not not user-friendly. That said I went through the source code and made these observations which makes me quite sure to say: "rpart |
32,042 | Difference between Time delayed neural networks and Recurrent neural networks | I have never worked with recurrent networks, but from what I know, in practice, some RNN and TDNN can be used for the same purpose that you want: Predict time series values. However, they work different.
It is possible with TDNN:
Predict process' values
Find a relationship between two processes.
Some RNN, like NARX also allow you to do that, and it is also used to predict financial time series, usually better than TDNN.
A TDNN looks more like a feedforward network, because time aspect is only inserted through its inputs, unlike NARX that also needs the predicted/real future value as input. This characteristic makes TDNN less robust than NARX for predicting values, but requires less processing and is easier to train.
If you are trying to find a relationship between a process $X(t)$ and a process $Y(t)$, NARX requires you to have past values of $Y$, while TDNN does not.
I recommend reading Simon Haykin's Neural Networks: A Comprehensive Foundation (2nd Edition) and this FAQ. There are lots of neural networks architectures and variations. Sometimes they have many names or there is no consensus about their classification. | Difference between Time delayed neural networks and Recurrent neural networks | I have never worked with recurrent networks, but from what I know, in practice, some RNN and TDNN can be used for the same purpose that you want: Predict time series values. However, they work differe | Difference between Time delayed neural networks and Recurrent neural networks
I have never worked with recurrent networks, but from what I know, in practice, some RNN and TDNN can be used for the same purpose that you want: Predict time series values. However, they work different.
It is possible with TDNN:
Predict process' values
Find a relationship between two processes.
Some RNN, like NARX also allow you to do that, and it is also used to predict financial time series, usually better than TDNN.
A TDNN looks more like a feedforward network, because time aspect is only inserted through its inputs, unlike NARX that also needs the predicted/real future value as input. This characteristic makes TDNN less robust than NARX for predicting values, but requires less processing and is easier to train.
If you are trying to find a relationship between a process $X(t)$ and a process $Y(t)$, NARX requires you to have past values of $Y$, while TDNN does not.
I recommend reading Simon Haykin's Neural Networks: A Comprehensive Foundation (2nd Edition) and this FAQ. There are lots of neural networks architectures and variations. Sometimes they have many names or there is no consensus about their classification. | Difference between Time delayed neural networks and Recurrent neural networks
I have never worked with recurrent networks, but from what I know, in practice, some RNN and TDNN can be used for the same purpose that you want: Predict time series values. However, they work differe |
32,043 | Difference between Time delayed neural networks and Recurrent neural networks | TDNNs is a simple way to represent a mapping between past and present values. The delays in the TDNN remain constant throughout the training procedure and are estimated before by using trial and error along with some heuristics. It, however, may be the case that these fixed delays do not capture the actual temporal locations of the time dependencies. On the other hand, the "memory" feature of the RNN structures can capture this information by learning these dependencies. The problem with RNNs is that they are impractical to use when trained with traditional techniques (e.g Backpropagation through time) for learning long term dependencies. This problem arises from the so-called "vanishing/exploding" gradient which basically means that as we propagate the error signals backwards through the networks structure they tend to vanish or explode. More advanced recurrent structures (eg LSTM) have properties that mitigate this problem and can learn long term dependencies and are particularly suited for learning sequential data. | Difference between Time delayed neural networks and Recurrent neural networks | TDNNs is a simple way to represent a mapping between past and present values. The delays in the TDNN remain constant throughout the training procedure and are estimated before by using trial and error | Difference between Time delayed neural networks and Recurrent neural networks
TDNNs is a simple way to represent a mapping between past and present values. The delays in the TDNN remain constant throughout the training procedure and are estimated before by using trial and error along with some heuristics. It, however, may be the case that these fixed delays do not capture the actual temporal locations of the time dependencies. On the other hand, the "memory" feature of the RNN structures can capture this information by learning these dependencies. The problem with RNNs is that they are impractical to use when trained with traditional techniques (e.g Backpropagation through time) for learning long term dependencies. This problem arises from the so-called "vanishing/exploding" gradient which basically means that as we propagate the error signals backwards through the networks structure they tend to vanish or explode. More advanced recurrent structures (eg LSTM) have properties that mitigate this problem and can learn long term dependencies and are particularly suited for learning sequential data. | Difference between Time delayed neural networks and Recurrent neural networks
TDNNs is a simple way to represent a mapping between past and present values. The delays in the TDNN remain constant throughout the training procedure and are estimated before by using trial and error |
32,044 | Inverse probability weighting (IPW): standard errors after weighting observations | To provide a somewhat orthogonal answer to Noah's, let us see what's technically going on in the weighted least squares (WLS) case.
We aim to solve
$$
\theta_{WLS} = \arg\min_\theta\sum_{k=1}^N w_k (y_k - f(x_k;\theta))^2.
$$
Computing the gradient, we note that the solution fulfills the weighted normal equation
$$
(X^T W X) \theta_{WLS} = X^T W y,
$$
and thus we have
$$
\theta_{WLS} = (X^T W X)^{-1} X^T W y.
$$
Recalling that $$\mathrm{Var}(Ax) = A \mathrm{Var}(x) A^T,$$ we observe that
$$
\mathrm{Var}(\theta_{WLS}) = (X^T W X)^{-1} X^T W \mathrm{Var}(y) W^T X (X^T W^T X)^{-1}.
$$
Now we can distinguish a few different cases.
Basic ordinary least squares (OLS): Assume $W=I$ and $\mathrm{Var}(y)=\sigma_{\varepsilon}^2 I$. In this case, the formula above simplifies to $$\mathrm{Var}(\theta_{WLS}) = \mathrm{Var}(\theta_{OLS}) = \sigma_{\varepsilon}^2 (X^T X)^{-1}.$$
Classic weighted least squares (WLS): Assume $W=\mathrm{Var}(y)^{-1}$, where $\mathrm{Var}(y)$ is assumed diagonal but heteroscedastic, i.e., the diagonal entries vary. In this case, we obtain $$\mathrm{Var}(\theta_{WLS}) = (X^T W X)^{-1}.$$
Weighted least squares, but $W\neq\mathrm{Var}(y)^{-1}$: this includes the case of propensity weighting which you alluded to. In this situation, we simply have to content ourselves with the general variance equation given above: $$
\mathrm{Var}(\theta_{WLS}) = (X^T W X)^{-1} X^T W \mathrm{Var}(y) W^T X (X^T W^T X)^{-1}.
$$ | Inverse probability weighting (IPW): standard errors after weighting observations | To provide a somewhat orthogonal answer to Noah's, let us see what's technically going on in the weighted least squares (WLS) case.
We aim to solve
$$
\theta_{WLS} = \arg\min_\theta\sum_{k=1}^N w_k (y | Inverse probability weighting (IPW): standard errors after weighting observations
To provide a somewhat orthogonal answer to Noah's, let us see what's technically going on in the weighted least squares (WLS) case.
We aim to solve
$$
\theta_{WLS} = \arg\min_\theta\sum_{k=1}^N w_k (y_k - f(x_k;\theta))^2.
$$
Computing the gradient, we note that the solution fulfills the weighted normal equation
$$
(X^T W X) \theta_{WLS} = X^T W y,
$$
and thus we have
$$
\theta_{WLS} = (X^T W X)^{-1} X^T W y.
$$
Recalling that $$\mathrm{Var}(Ax) = A \mathrm{Var}(x) A^T,$$ we observe that
$$
\mathrm{Var}(\theta_{WLS}) = (X^T W X)^{-1} X^T W \mathrm{Var}(y) W^T X (X^T W^T X)^{-1}.
$$
Now we can distinguish a few different cases.
Basic ordinary least squares (OLS): Assume $W=I$ and $\mathrm{Var}(y)=\sigma_{\varepsilon}^2 I$. In this case, the formula above simplifies to $$\mathrm{Var}(\theta_{WLS}) = \mathrm{Var}(\theta_{OLS}) = \sigma_{\varepsilon}^2 (X^T X)^{-1}.$$
Classic weighted least squares (WLS): Assume $W=\mathrm{Var}(y)^{-1}$, where $\mathrm{Var}(y)$ is assumed diagonal but heteroscedastic, i.e., the diagonal entries vary. In this case, we obtain $$\mathrm{Var}(\theta_{WLS}) = (X^T W X)^{-1}.$$
Weighted least squares, but $W\neq\mathrm{Var}(y)^{-1}$: this includes the case of propensity weighting which you alluded to. In this situation, we simply have to content ourselves with the general variance equation given above: $$
\mathrm{Var}(\theta_{WLS}) = (X^T W X)^{-1} X^T W \mathrm{Var}(y) W^T X (X^T W^T X)^{-1}.
$$ | Inverse probability weighting (IPW): standard errors after weighting observations
To provide a somewhat orthogonal answer to Noah's, let us see what's technically going on in the weighted least squares (WLS) case.
We aim to solve
$$
\theta_{WLS} = \arg\min_\theta\sum_{k=1}^N w_k (y |
32,045 | Inverse probability weighting (IPW): standard errors after weighting observations | Lunceford and Davidian (2004) derive the asymptotic standard errors for IPW estimators. These rely on a generalized estimating equations approach and assume the propensity scores are estimated using a method that can be represented as a system of estimating equations (e.g., logistic regression, but not random forests). Their proof also indicates that IPW estimators are smooth and asymptotically normal, making them amenable to bootstrapping. They also find that excluding the propensity score estimation from the estimating equations and treating the weights as fixed yields conservative estimates of the standard error. This is equivalent to using a robust standard error in the outcome regression model.
This leads to three ways to validly estimate the standard error in IPW:
Using generalized estimating equations with the propensity scores and outcome model included together. This can be manually programmed using geex in R, and some R packages like PSweightcan also compute them. In SAS, PROC CAUSALTRT automatically computes the correct standard errors, and in Stata, teffects ipw uses the same approach.
Using a robust standard error for the outcome model. This will generally be conservative and is the simplest and most flexible approach because it can be used with weight-estimation methods that are not implemented in those packages or can't be represented as systems of estimating equations, like generalized boosted modeling, which is a somewhat popular method. To do this in R, you would use survey::vcovHC() after a glm() or lm() call with the outcome model, survey::svyglm(), which is recommended in the twang and WeightIt documentation, or geepack::geeglm() as recommended by Hernán and Robins (2020). In SAS, you would use PROC SURVEYREG, and in Stata you would use supply the weights to the aweights argument in any regression model, which automatically requests robust standard errors.
Using the bootstrap. The bootstrap, where you include the propensity score estimation and effect estimation within each replication, is a very effective method because it does not rely on asymptotic arguments, can be used with weight-estimation methods that can't be or aren't implemented in the packages named above, and can be used for any estimand, regardless of whether analytical standard errors have been derived for them (e.g., for the rate ratio in a negative binomial outcome model). The difficulty is that one needs to know how to program a bootstrap and one needs to be prepared to wait a potentially long time when the estimation procedure takes a while, e.g., for some machine learning methods. Also, the bootstrap will tend to yield different estimates each time, adding an additional layer of uncertainty into the estimation. Using the bootstrap is easiest in R with the boot package.
I am most inclined to use robust standard errors because of their flexibility and ease of use. For a serious project where conservative standard errors could be a liability and I had a lot of time, I would use the bootstrap. | Inverse probability weighting (IPW): standard errors after weighting observations | Lunceford and Davidian (2004) derive the asymptotic standard errors for IPW estimators. These rely on a generalized estimating equations approach and assume the propensity scores are estimated using a | Inverse probability weighting (IPW): standard errors after weighting observations
Lunceford and Davidian (2004) derive the asymptotic standard errors for IPW estimators. These rely on a generalized estimating equations approach and assume the propensity scores are estimated using a method that can be represented as a system of estimating equations (e.g., logistic regression, but not random forests). Their proof also indicates that IPW estimators are smooth and asymptotically normal, making them amenable to bootstrapping. They also find that excluding the propensity score estimation from the estimating equations and treating the weights as fixed yields conservative estimates of the standard error. This is equivalent to using a robust standard error in the outcome regression model.
This leads to three ways to validly estimate the standard error in IPW:
Using generalized estimating equations with the propensity scores and outcome model included together. This can be manually programmed using geex in R, and some R packages like PSweightcan also compute them. In SAS, PROC CAUSALTRT automatically computes the correct standard errors, and in Stata, teffects ipw uses the same approach.
Using a robust standard error for the outcome model. This will generally be conservative and is the simplest and most flexible approach because it can be used with weight-estimation methods that are not implemented in those packages or can't be represented as systems of estimating equations, like generalized boosted modeling, which is a somewhat popular method. To do this in R, you would use survey::vcovHC() after a glm() or lm() call with the outcome model, survey::svyglm(), which is recommended in the twang and WeightIt documentation, or geepack::geeglm() as recommended by Hernán and Robins (2020). In SAS, you would use PROC SURVEYREG, and in Stata you would use supply the weights to the aweights argument in any regression model, which automatically requests robust standard errors.
Using the bootstrap. The bootstrap, where you include the propensity score estimation and effect estimation within each replication, is a very effective method because it does not rely on asymptotic arguments, can be used with weight-estimation methods that can't be or aren't implemented in the packages named above, and can be used for any estimand, regardless of whether analytical standard errors have been derived for them (e.g., for the rate ratio in a negative binomial outcome model). The difficulty is that one needs to know how to program a bootstrap and one needs to be prepared to wait a potentially long time when the estimation procedure takes a while, e.g., for some machine learning methods. Also, the bootstrap will tend to yield different estimates each time, adding an additional layer of uncertainty into the estimation. Using the bootstrap is easiest in R with the boot package.
I am most inclined to use robust standard errors because of their flexibility and ease of use. For a serious project where conservative standard errors could be a liability and I had a lot of time, I would use the bootstrap. | Inverse probability weighting (IPW): standard errors after weighting observations
Lunceford and Davidian (2004) derive the asymptotic standard errors for IPW estimators. These rely on a generalized estimating equations approach and assume the propensity scores are estimated using a |
32,046 | R: prop.test - Chi-squared approximation may be incorrect | The warning is because one of the expected values in the chi-squared is less than 5.
a <- c(6, 15)
b <- c(26, 171)
m <- matrix(c(a, b-a), ncol=2)
chisq.test(m)
chisq.test(m)$expected
However, that rule of thumb is a bit conservative and there are other rules of thumb that you can consider. Some of those other rules of thumb are passed and some are not.
Instead of a chi-squared test, there is also a binomial proportion test.
p1 <- 6/26
n1 <- 26
p2 <- 15/171
n2 <- 171
p <- (n1 * p1 + n2 * p2)/ (n1 + n2)
z <- (p1 - p2) / sqrt(p * (1-p) * (1/n1 + 1/n2))
z
Here we use a normal approximation to the binomial distribution. For this approximiation, there is a rule of thumb that both $np > 5$ and $n(1-p) > 5$ which is true for both proportions. Also, for these two proportions, the normal approximation looks reasonable to me when plotted.
hist(rbinom(10000, 26, 6/26))
hist(rbinom(10000, 171, 15/171))
For this data, the binomial proportion test give a one-sided p-value=0.0139. The one sided prop.test gives a p-value=0.03137.
As @EdM mentions in the comments below, some people feel Fisher's exact test maybe suitable in this situation. This other page nicely gives references to a few people about the appropriateness of Fisher's exact test and it looks like the matter is not yet decided. This test gives a one-sided p-value=0.03963
fisher.test(m, alternative = 'greater') | R: prop.test - Chi-squared approximation may be incorrect | The warning is because one of the expected values in the chi-squared is less than 5.
a <- c(6, 15)
b <- c(26, 171)
m <- matrix(c(a, b-a), ncol=2)
chisq.test(m)
chisq.test(m)$expected
However, that r | R: prop.test - Chi-squared approximation may be incorrect
The warning is because one of the expected values in the chi-squared is less than 5.
a <- c(6, 15)
b <- c(26, 171)
m <- matrix(c(a, b-a), ncol=2)
chisq.test(m)
chisq.test(m)$expected
However, that rule of thumb is a bit conservative and there are other rules of thumb that you can consider. Some of those other rules of thumb are passed and some are not.
Instead of a chi-squared test, there is also a binomial proportion test.
p1 <- 6/26
n1 <- 26
p2 <- 15/171
n2 <- 171
p <- (n1 * p1 + n2 * p2)/ (n1 + n2)
z <- (p1 - p2) / sqrt(p * (1-p) * (1/n1 + 1/n2))
z
Here we use a normal approximation to the binomial distribution. For this approximiation, there is a rule of thumb that both $np > 5$ and $n(1-p) > 5$ which is true for both proportions. Also, for these two proportions, the normal approximation looks reasonable to me when plotted.
hist(rbinom(10000, 26, 6/26))
hist(rbinom(10000, 171, 15/171))
For this data, the binomial proportion test give a one-sided p-value=0.0139. The one sided prop.test gives a p-value=0.03137.
As @EdM mentions in the comments below, some people feel Fisher's exact test maybe suitable in this situation. This other page nicely gives references to a few people about the appropriateness of Fisher's exact test and it looks like the matter is not yet decided. This test gives a one-sided p-value=0.03963
fisher.test(m, alternative = 'greater') | R: prop.test - Chi-squared approximation may be incorrect
The warning is because one of the expected values in the chi-squared is less than 5.
a <- c(6, 15)
b <- c(26, 171)
m <- matrix(c(a, b-a), ncol=2)
chisq.test(m)
chisq.test(m)$expected
However, that r |
32,047 | Explosive processes, non-stationarity and unit roots, how to distinguish? | I think your understanding is quite correct. The issue is, as you noticed, that the DF test is a left-tailed test, testing $H_0:\rho=1$ against $H_1:|\rho|<1$, using a standard t-statistic
$$
t=\frac{\hat\rho-1}{s.e.(\hat\rho)}
$$
and negative critical values ($c.v.$) from the Dickey-Fuller distribution (a distribution that is skewed to the left). For example, the 5%-quantile is -1.96 (which, btw, is only spuriously the same as the 5% c.v. of a normal test statistic - it is the 5% quantile, this being a one-sided test, not the 2.5%-quantile!), and one rejects if $t< c.v.$. Now, if you have an explosive process with $\rho>1$, and OLS correctly estimates this, there is of course no way the DF test statistic can be negative, as $t>0$, too. Hence, it won't reject against stationary alternatives, and it shouldn't.
Now, why do people typically proceed in this way and should they?
The reasoning is that explosive processes are thought to be unlikely to arise in economics (where the DF test is mainly used), which is why it is typically of interest to test against stationary alternatives.
That said, there is a recent and burgeoning literature on testing the unit root null against explosive alternatives, see e.g. Peter C. B. Phillips, Yangru Wu and Jun Yu, International Economic Review 2011: EXPLOSIVE BEHAVIOR IN THE 1990s NASDAQ: WHEN DID EXUBERANCE ESCALATE ASSET VALUES?. I guess the title of the paper already provides motivation for why this might be interesting. And indeed, these tests proceed by looking at the right tails of the DF distribution.
Finally (your first question actually), that OLS can consistently estimate an explosive AR(1) coefficient is shown in work like Anderson, T.W., 1959. On asymptotic distributions of estimates of parameters of stochastic difference equations. Annals of Mathematical Statistics 30, 676–687. | Explosive processes, non-stationarity and unit roots, how to distinguish? | I think your understanding is quite correct. The issue is, as you noticed, that the DF test is a left-tailed test, testing $H_0:\rho=1$ against $H_1:|\rho|<1$, using a standard t-statistic
$$
t=\frac | Explosive processes, non-stationarity and unit roots, how to distinguish?
I think your understanding is quite correct. The issue is, as you noticed, that the DF test is a left-tailed test, testing $H_0:\rho=1$ against $H_1:|\rho|<1$, using a standard t-statistic
$$
t=\frac{\hat\rho-1}{s.e.(\hat\rho)}
$$
and negative critical values ($c.v.$) from the Dickey-Fuller distribution (a distribution that is skewed to the left). For example, the 5%-quantile is -1.96 (which, btw, is only spuriously the same as the 5% c.v. of a normal test statistic - it is the 5% quantile, this being a one-sided test, not the 2.5%-quantile!), and one rejects if $t< c.v.$. Now, if you have an explosive process with $\rho>1$, and OLS correctly estimates this, there is of course no way the DF test statistic can be negative, as $t>0$, too. Hence, it won't reject against stationary alternatives, and it shouldn't.
Now, why do people typically proceed in this way and should they?
The reasoning is that explosive processes are thought to be unlikely to arise in economics (where the DF test is mainly used), which is why it is typically of interest to test against stationary alternatives.
That said, there is a recent and burgeoning literature on testing the unit root null against explosive alternatives, see e.g. Peter C. B. Phillips, Yangru Wu and Jun Yu, International Economic Review 2011: EXPLOSIVE BEHAVIOR IN THE 1990s NASDAQ: WHEN DID EXUBERANCE ESCALATE ASSET VALUES?. I guess the title of the paper already provides motivation for why this might be interesting. And indeed, these tests proceed by looking at the right tails of the DF distribution.
Finally (your first question actually), that OLS can consistently estimate an explosive AR(1) coefficient is shown in work like Anderson, T.W., 1959. On asymptotic distributions of estimates of parameters of stochastic difference equations. Annals of Mathematical Statistics 30, 676–687. | Explosive processes, non-stationarity and unit roots, how to distinguish?
I think your understanding is quite correct. The issue is, as you noticed, that the DF test is a left-tailed test, testing $H_0:\rho=1$ against $H_1:|\rho|<1$, using a standard t-statistic
$$
t=\frac |
32,048 | What is the chance level accuracy in unbalanced classification problems? | The performance of a random classifier depends on the fraction of times it predicts positive, e.g. $P(\hat{y} = 1)$. A random model essentially means a model whose predictions $\hat{y}$ are independent of the true label $y$, which means:
$$
P(\hat{y} = 1\ |\ y = 1) = P(\hat{y} = 1),
$$
and
$$
P(y = 1\ |\ \hat{y} = 1) = P(y = 1).
$$
The probability of being right, that is the expected accuracy is then:
$$
P(\hat{y} = y) = P(\hat{y} = 1) P(y = 1) + P(\hat{y} = 0) P(y = 0).
$$
If the dataset is imbalanced, then the 'random' model with the best expected accuracy is the one that always predicts the majority class, with expected accuracy equal to the fraction of data in the majority class.
The main issue with highly imbalanced datasets (say 99% negative) is that you are likely to end up with trivial models as described above, that is a model which always predicts the majority class (negative) and achieves high accuracy (99%) so this useless model actually looks good. If you use a poor scoring function (such as accuracy) when optimizing hyperparameters you are quite likely to obtain a very bad model in imbalanced settings.
This is one of the many reasons why discrete measures like accuracy should be avoided. You won't have such issues with measures like area under the ROC or PR curve. | What is the chance level accuracy in unbalanced classification problems? | The performance of a random classifier depends on the fraction of times it predicts positive, e.g. $P(\hat{y} = 1)$. A random model essentially means a model whose predictions $\hat{y}$ are independen | What is the chance level accuracy in unbalanced classification problems?
The performance of a random classifier depends on the fraction of times it predicts positive, e.g. $P(\hat{y} = 1)$. A random model essentially means a model whose predictions $\hat{y}$ are independent of the true label $y$, which means:
$$
P(\hat{y} = 1\ |\ y = 1) = P(\hat{y} = 1),
$$
and
$$
P(y = 1\ |\ \hat{y} = 1) = P(y = 1).
$$
The probability of being right, that is the expected accuracy is then:
$$
P(\hat{y} = y) = P(\hat{y} = 1) P(y = 1) + P(\hat{y} = 0) P(y = 0).
$$
If the dataset is imbalanced, then the 'random' model with the best expected accuracy is the one that always predicts the majority class, with expected accuracy equal to the fraction of data in the majority class.
The main issue with highly imbalanced datasets (say 99% negative) is that you are likely to end up with trivial models as described above, that is a model which always predicts the majority class (negative) and achieves high accuracy (99%) so this useless model actually looks good. If you use a poor scoring function (such as accuracy) when optimizing hyperparameters you are quite likely to obtain a very bad model in imbalanced settings.
This is one of the many reasons why discrete measures like accuracy should be avoided. You won't have such issues with measures like area under the ROC or PR curve. | What is the chance level accuracy in unbalanced classification problems?
The performance of a random classifier depends on the fraction of times it predicts positive, e.g. $P(\hat{y} = 1)$. A random model essentially means a model whose predictions $\hat{y}$ are independen |
32,049 | Generating Binomial Random Variables with given Correlation | You cannot use the linear representation of the correlation in discrete support distributions.
In the special case of the Binomial distribution, the representation
$$X=\sum_{i=1}^8 \delta_i\quad Y=\sum_{i=1}^{18} \gamma_i\quad \delta_i,\gamma_i\sim \text{B}(1,2/3)$$
can be exploited since
$$\text{cov}(X,Y)=\sum_{i=1}^8\sum_{j=1}^{18}\text{cov}(\delta_i,\gamma_j)$$
If we choose some of the $\delta_i$'s to be equal to some of the $\gamma_j$'s, and independently generated otherwise, we obtain
$$\text{cov}(X,Y)=\sum_{i=1}^8\sum_{j=1}^{18}\mathbb{I}(\delta_i:=\gamma_j)\text{var}(\gamma_j)$$
where the notation $\mathbb{I}(\delta_i:=\gamma_j)$ indicates that $\delta_i$ is chosen identical to $\gamma_j$ rather than generated as a Bernoulli $\text{B}(1,2/3)$.
Since the constraint is$$\text{cov}(X,Y)=0.5\times\sqrt{8\times 18}\times\frac{2}{3}\times\frac{1}{3}$$we have to solve
$$\sum_{i=1}^8\sum_{j=1}^{18}\mathbb{I}(\delta_i:=\gamma_j)=0.5\times\sqrt{8\times 18}=6$$This means that if we pick 6 of the 8 $\delta_i$'s equal to 6 of the 18 $\gamma_j$'s we should get this correlation of 0.5.
The implementation goes as follows:
Generate $Z\sim\text{B}(6,2/3)$, $Y_1\sim\text{B}(12,2/3)$, $X_1\sim\text{B}(2,2/3)$;
Takes $X=Z+Z_1$ and $Y=Z+Y_1$
We can check this result with an R simulation
> z=rbinom(10^8,6,.66)
> y=z+rbinom(10^8,12,.66)
> x=z+rbinom(10^8,2,.66)
cor(x,y)
> cor(x,y)
[1] 0.5000539
Comment
This is a rather artificial solution to the problem in that it only works because $8\times 18$ is a perfect square and because $\text{cor}(X,Y)\times\sqrt{8\times 18}$ is an integer. For other acceptable correlations, randomisation would be necessary, i.e. $\mathbb{I}(\delta_i:=\gamma_j)$ would be zero or one with some probability $\varrho$.
Addendum
The problem was proposed and solved years ago on Stack Overflow with the same idea of sharing Bernoullis. | Generating Binomial Random Variables with given Correlation | You cannot use the linear representation of the correlation in discrete support distributions.
In the special case of the Binomial distribution, the representation
$$X=\sum_{i=1}^8 \delta_i\quad Y=\su | Generating Binomial Random Variables with given Correlation
You cannot use the linear representation of the correlation in discrete support distributions.
In the special case of the Binomial distribution, the representation
$$X=\sum_{i=1}^8 \delta_i\quad Y=\sum_{i=1}^{18} \gamma_i\quad \delta_i,\gamma_i\sim \text{B}(1,2/3)$$
can be exploited since
$$\text{cov}(X,Y)=\sum_{i=1}^8\sum_{j=1}^{18}\text{cov}(\delta_i,\gamma_j)$$
If we choose some of the $\delta_i$'s to be equal to some of the $\gamma_j$'s, and independently generated otherwise, we obtain
$$\text{cov}(X,Y)=\sum_{i=1}^8\sum_{j=1}^{18}\mathbb{I}(\delta_i:=\gamma_j)\text{var}(\gamma_j)$$
where the notation $\mathbb{I}(\delta_i:=\gamma_j)$ indicates that $\delta_i$ is chosen identical to $\gamma_j$ rather than generated as a Bernoulli $\text{B}(1,2/3)$.
Since the constraint is$$\text{cov}(X,Y)=0.5\times\sqrt{8\times 18}\times\frac{2}{3}\times\frac{1}{3}$$we have to solve
$$\sum_{i=1}^8\sum_{j=1}^{18}\mathbb{I}(\delta_i:=\gamma_j)=0.5\times\sqrt{8\times 18}=6$$This means that if we pick 6 of the 8 $\delta_i$'s equal to 6 of the 18 $\gamma_j$'s we should get this correlation of 0.5.
The implementation goes as follows:
Generate $Z\sim\text{B}(6,2/3)$, $Y_1\sim\text{B}(12,2/3)$, $X_1\sim\text{B}(2,2/3)$;
Takes $X=Z+Z_1$ and $Y=Z+Y_1$
We can check this result with an R simulation
> z=rbinom(10^8,6,.66)
> y=z+rbinom(10^8,12,.66)
> x=z+rbinom(10^8,2,.66)
cor(x,y)
> cor(x,y)
[1] 0.5000539
Comment
This is a rather artificial solution to the problem in that it only works because $8\times 18$ is a perfect square and because $\text{cor}(X,Y)\times\sqrt{8\times 18}$ is an integer. For other acceptable correlations, randomisation would be necessary, i.e. $\mathbb{I}(\delta_i:=\gamma_j)$ would be zero or one with some probability $\varrho$.
Addendum
The problem was proposed and solved years ago on Stack Overflow with the same idea of sharing Bernoullis. | Generating Binomial Random Variables with given Correlation
You cannot use the linear representation of the correlation in discrete support distributions.
In the special case of the Binomial distribution, the representation
$$X=\sum_{i=1}^8 \delta_i\quad Y=\su |
32,050 | How can I use this data to calibrate markers with different levels of generosity in grading student papers? | This sounds like a great opportunity to use a matrix factorization recommender system. Briefly, this works as follows:
Put your observations into a partially-observed matrix $M$ where $M_{ij}$ is the score teacher $i$ gave to student $j$.
Assume that this matrix is the outer product of some latent feature vectors, $\vec t$ and $\vec s$--that is, $M_{ij} = t_i s_j$.
Solve for the latent feature vectors that minimize the squared reconstruction error $\sum_{i,j} (t_is_j - M_{ij})^2$ (where the sum ranges over all observed cells of $M$).
You can do this expectation-maximization style by fixing a guess for $\vec t$ and solving for $\vec s$ via least squares, then fixing that guess for $\vec s$ and solving for $\vec t$ and iterating until convergence.
Note that this makes a fairly strong assumption on the form of a teacher's bias--in particular, if you think of the students' latent features as their "true score", then a teacher's bias multiplies each true score by a constant amount (to make it additive instead you would exponentiate the scores that you insert into the matrix, and then learn the exponentials of the "true scores"). With so little calibration data, you probably can't get very far without making a strong assumption of this form, but if you had more data, you could add a second dimension of latent features, etc. (i.e., assume $M_{ij} = \sum_{k=1}^n s_{ik} t_{kj}$ and again try to minimize the squared reconstruction error).
EDIT: in order to have a well-defined problem you need to have more matrix operations than latent parameters (or you can use some kind of regularization). You just barely have that here (you have 636 observations and 612 latent parameters), so the matrix factorization may not work super well--I haven't worked with them on such small samples, so I don't really know.
If the calibration turns out to be insufficient to use a good recommender model, you could try a multilevel regression on Score ~ IsGradStudent + <whatever other student covariates you have> + (1|Teacher) (ignoring the calibration data) to extract estimates of an additive teacher bias, and then check if this bias is consistent with the calibration data you took. (You should allow for heteroskedasticity by teacher if possible.) This is more ad-hoc but may give you less severe data collection problems. | How can I use this data to calibrate markers with different levels of generosity in grading student | This sounds like a great opportunity to use a matrix factorization recommender system. Briefly, this works as follows:
Put your observations into a partially-observed matrix $M$ where $M_{ij}$ is the | How can I use this data to calibrate markers with different levels of generosity in grading student papers?
This sounds like a great opportunity to use a matrix factorization recommender system. Briefly, this works as follows:
Put your observations into a partially-observed matrix $M$ where $M_{ij}$ is the score teacher $i$ gave to student $j$.
Assume that this matrix is the outer product of some latent feature vectors, $\vec t$ and $\vec s$--that is, $M_{ij} = t_i s_j$.
Solve for the latent feature vectors that minimize the squared reconstruction error $\sum_{i,j} (t_is_j - M_{ij})^2$ (where the sum ranges over all observed cells of $M$).
You can do this expectation-maximization style by fixing a guess for $\vec t$ and solving for $\vec s$ via least squares, then fixing that guess for $\vec s$ and solving for $\vec t$ and iterating until convergence.
Note that this makes a fairly strong assumption on the form of a teacher's bias--in particular, if you think of the students' latent features as their "true score", then a teacher's bias multiplies each true score by a constant amount (to make it additive instead you would exponentiate the scores that you insert into the matrix, and then learn the exponentials of the "true scores"). With so little calibration data, you probably can't get very far without making a strong assumption of this form, but if you had more data, you could add a second dimension of latent features, etc. (i.e., assume $M_{ij} = \sum_{k=1}^n s_{ik} t_{kj}$ and again try to minimize the squared reconstruction error).
EDIT: in order to have a well-defined problem you need to have more matrix operations than latent parameters (or you can use some kind of regularization). You just barely have that here (you have 636 observations and 612 latent parameters), so the matrix factorization may not work super well--I haven't worked with them on such small samples, so I don't really know.
If the calibration turns out to be insufficient to use a good recommender model, you could try a multilevel regression on Score ~ IsGradStudent + <whatever other student covariates you have> + (1|Teacher) (ignoring the calibration data) to extract estimates of an additive teacher bias, and then check if this bias is consistent with the calibration data you took. (You should allow for heteroskedasticity by teacher if possible.) This is more ad-hoc but may give you less severe data collection problems. | How can I use this data to calibrate markers with different levels of generosity in grading student
This sounds like a great opportunity to use a matrix factorization recommender system. Briefly, this works as follows:
Put your observations into a partially-observed matrix $M$ where $M_{ij}$ is the |
32,051 | How can I use this data to calibrate markers with different levels of generosity in grading student papers? | Here's a couple of related approaches.
Take the set of papers marked by more than one teacher, since those contain the most information about teacher effects and outside those papers, the teacher and cohort effects are confounded (if there was some way of getting at the cohort effect -- perhaps via GPA or some other predictor, for example, then you could use all of the data, but it will complicate the models quite a bit).
Label the students $i=1,2, ... n$, and the markers $j=1, 2, ...,m$. Let the set of marks be $y_{ij}, i=1,2, ... m$.
You first have to consider your model for how the marker-effect applies. Is it additive? Is it multiplicative? Do you need to worry about boundary effects (e.g. would an additive or multiplicative effect on a logit-scale be better)?
Imagine two given markers on two papers and imagine the second marker is more generous. Let's say the first marker would give the papers 30 and 60. Will the second marker tend to add a constant number of marks (say 6 marks) to both? Will they tend to add constant percentages (say 10% to both, or 3 marks vs 6 marks)? What if the first marker gave 99? -- what would happen then? What about 0? What if the second marker were less generous? what would happen at 99 or 0? (this is why I mention a logit model - one might treat the marks as a proportion of the possible marks ($p_{ij}=m_{ij}/100$), and then the marker effect could be to add a constant (say) to the logit of $p$ - i.e. $\log(p_{ij}/(1-p_{ij})$).
(You won't have enough data here to estimate the form of generousness as well as its size. You have to choose a model from your understanding of the situation. You'll also need to ignore any possibility of interaction; you don't have the data for it)
Possibility 1 - plain additive model. This might be suitable if no marks were really close to 0 or 100:
Consider a model like $E(y_{ij}) = \mu_{i}+\tau_j$
This is essentially a two-way ANOVA. You need constraints on this, so you might set up a deviation coding/set up the model so that of marker effects is 0, or you might set up a model where one marker is the baseline (whose effect is 0, and whose marks you will try to adjust every other marker toward).
Then take the $\hat{\tau}_j$ values and adjust the wider population of marks $y_{kj}^\text{adj}=y_{kj}-\hat{\tau}_j$.
Possibility 2: In effect, a similar kind of idea but $E(y_{ij}) = \mu_{i}\tau_j$. Here you might fit a nonlinear least squares model, or a GLM with a log-link (I'd probably lean toward the second out of those two). Again you need a constraint on the $\tau$s.
Then a suitable adjustment would be to divide by $\hat{\tau_j}$.
Possibility 3: additive on the logit scale. This might be more suitable if some marks get close to 0 or 100. It will look roughly multiplicative for very small marks, additive for middling marks and roughly multiplicative in $1-p=(100-m)/100$ for very high marks. You might use a beta regression or a quasi-binomial GLM with logit link to fit this model. | How can I use this data to calibrate markers with different levels of generosity in grading student | Here's a couple of related approaches.
Take the set of papers marked by more than one teacher, since those contain the most information about teacher effects and outside those papers, the teacher and | How can I use this data to calibrate markers with different levels of generosity in grading student papers?
Here's a couple of related approaches.
Take the set of papers marked by more than one teacher, since those contain the most information about teacher effects and outside those papers, the teacher and cohort effects are confounded (if there was some way of getting at the cohort effect -- perhaps via GPA or some other predictor, for example, then you could use all of the data, but it will complicate the models quite a bit).
Label the students $i=1,2, ... n$, and the markers $j=1, 2, ...,m$. Let the set of marks be $y_{ij}, i=1,2, ... m$.
You first have to consider your model for how the marker-effect applies. Is it additive? Is it multiplicative? Do you need to worry about boundary effects (e.g. would an additive or multiplicative effect on a logit-scale be better)?
Imagine two given markers on two papers and imagine the second marker is more generous. Let's say the first marker would give the papers 30 and 60. Will the second marker tend to add a constant number of marks (say 6 marks) to both? Will they tend to add constant percentages (say 10% to both, or 3 marks vs 6 marks)? What if the first marker gave 99? -- what would happen then? What about 0? What if the second marker were less generous? what would happen at 99 or 0? (this is why I mention a logit model - one might treat the marks as a proportion of the possible marks ($p_{ij}=m_{ij}/100$), and then the marker effect could be to add a constant (say) to the logit of $p$ - i.e. $\log(p_{ij}/(1-p_{ij})$).
(You won't have enough data here to estimate the form of generousness as well as its size. You have to choose a model from your understanding of the situation. You'll also need to ignore any possibility of interaction; you don't have the data for it)
Possibility 1 - plain additive model. This might be suitable if no marks were really close to 0 or 100:
Consider a model like $E(y_{ij}) = \mu_{i}+\tau_j$
This is essentially a two-way ANOVA. You need constraints on this, so you might set up a deviation coding/set up the model so that of marker effects is 0, or you might set up a model where one marker is the baseline (whose effect is 0, and whose marks you will try to adjust every other marker toward).
Then take the $\hat{\tau}_j$ values and adjust the wider population of marks $y_{kj}^\text{adj}=y_{kj}-\hat{\tau}_j$.
Possibility 2: In effect, a similar kind of idea but $E(y_{ij}) = \mu_{i}\tau_j$. Here you might fit a nonlinear least squares model, or a GLM with a log-link (I'd probably lean toward the second out of those two). Again you need a constraint on the $\tau$s.
Then a suitable adjustment would be to divide by $\hat{\tau_j}$.
Possibility 3: additive on the logit scale. This might be more suitable if some marks get close to 0 or 100. It will look roughly multiplicative for very small marks, additive for middling marks and roughly multiplicative in $1-p=(100-m)/100$ for very high marks. You might use a beta regression or a quasi-binomial GLM with logit link to fit this model. | How can I use this data to calibrate markers with different levels of generosity in grading student
Here's a couple of related approaches.
Take the set of papers marked by more than one teacher, since those contain the most information about teacher effects and outside those papers, the teacher and |
32,052 | Optimizing for AUC | There are actually multiple ways to do this.
Remember that the AUC is a normalized form of the Mann-Whitney-U statistic, that is, the sum of ranks in either of the class. This means that finding optimal AUC is the problem of ordering all scores $s_1,\ldots,s_N$ so that the scores are higher in one class than the other.
This can be framed for example as a highly infeasible linear-programming-problem which can be solved heuristically with appropriate relaxations, but one method that interests me more is to find approximate gradients to the AUC so that we can optimize with stochastic-gradient-descent.
There's plenty to read about this, here is a naive approach:
Using '$[]$' as the Iverson-Bracket, another way to look at the sought ordering over the scores could be that
$[s_i\leq s_j]=1$ for all $i,j$ where response $y_i=0$ and $y_j=1$
So if the scores are a function of inputs and parameters $s_i = f(x_i,\theta)$
We want to maximize
$$M^*=max_\theta \sum_{i,j}[s_i\leq s_j]$$
Consider the relaxation $\tanh(\alpha(s_j-s_i)) \leq [s_i\leq s_j]$
So $$M^*\geq \sum_{i,j}\tanh(\alpha(s_j-s_i))$$
And we could then sample $i$ and $j$ from each class to get contributions $\nabla_\theta \tanh(\alpha(s_j-s_i))$ to the full gradient. | Optimizing for AUC | There are actually multiple ways to do this.
Remember that the AUC is a normalized form of the Mann-Whitney-U statistic, that is, the sum of ranks in either of the class. This means that finding opti | Optimizing for AUC
There are actually multiple ways to do this.
Remember that the AUC is a normalized form of the Mann-Whitney-U statistic, that is, the sum of ranks in either of the class. This means that finding optimal AUC is the problem of ordering all scores $s_1,\ldots,s_N$ so that the scores are higher in one class than the other.
This can be framed for example as a highly infeasible linear-programming-problem which can be solved heuristically with appropriate relaxations, but one method that interests me more is to find approximate gradients to the AUC so that we can optimize with stochastic-gradient-descent.
There's plenty to read about this, here is a naive approach:
Using '$[]$' as the Iverson-Bracket, another way to look at the sought ordering over the scores could be that
$[s_i\leq s_j]=1$ for all $i,j$ where response $y_i=0$ and $y_j=1$
So if the scores are a function of inputs and parameters $s_i = f(x_i,\theta)$
We want to maximize
$$M^*=max_\theta \sum_{i,j}[s_i\leq s_j]$$
Consider the relaxation $\tanh(\alpha(s_j-s_i)) \leq [s_i\leq s_j]$
So $$M^*\geq \sum_{i,j}\tanh(\alpha(s_j-s_i))$$
And we could then sample $i$ and $j$ from each class to get contributions $\nabla_\theta \tanh(\alpha(s_j-s_i))$ to the full gradient. | Optimizing for AUC
There are actually multiple ways to do this.
Remember that the AUC is a normalized form of the Mann-Whitney-U statistic, that is, the sum of ranks in either of the class. This means that finding opti |
32,053 | Feature selection for time series data | The Cross Correlation function will help you identify relationships in your X variables. Box-Jenkins discussed this in their text book. Time Series Analysis: Forecasting and Control
Of course, you will also need to identify outliers as the relationship can be impacted by these events along with changes in trend and level.
Plotting the Y and X in standardized form in a scatterplot and line plot will also support your hypothesis. | Feature selection for time series data | The Cross Correlation function will help you identify relationships in your X variables. Box-Jenkins discussed this in their text book. Time Series Analysis: Forecasting and Control
Of course, you wi | Feature selection for time series data
The Cross Correlation function will help you identify relationships in your X variables. Box-Jenkins discussed this in their text book. Time Series Analysis: Forecasting and Control
Of course, you will also need to identify outliers as the relationship can be impacted by these events along with changes in trend and level.
Plotting the Y and X in standardized form in a scatterplot and line plot will also support your hypothesis. | Feature selection for time series data
The Cross Correlation function will help you identify relationships in your X variables. Box-Jenkins discussed this in their text book. Time Series Analysis: Forecasting and Control
Of course, you wi |
32,054 | Feature selection for time series data | I was also on the search for a list of time series features quite a while ago. There are publications inspecting individual features but I was not able to find a comprehensive list of features.
tsfresh automates extraction of features
While working on industrial machine learning projects I made my own list of features that proved helpful in different applications.
This list is contained in the python package tsfresh, which allows to automatically extract a huge of number of features and filter them for their importance.
Comprehensive list of time series features
So regarding your question: You can find inspiration about other features in the comprehensive documentation about the calculated features of tsfresh here. There are simple features such as the mean, time series related features such as the coefficients of an AR model or highly sophisticated features such as the test statistic of the augmented dickey fuller hypothesis test.
I am sure you will find some interesting features for your application there.
Disclaimer: I am one of the authors of tsfresh. | Feature selection for time series data | I was also on the search for a list of time series features quite a while ago. There are publications inspecting individual features but I was not able to find a comprehensive list of features.
tsfre | Feature selection for time series data
I was also on the search for a list of time series features quite a while ago. There are publications inspecting individual features but I was not able to find a comprehensive list of features.
tsfresh automates extraction of features
While working on industrial machine learning projects I made my own list of features that proved helpful in different applications.
This list is contained in the python package tsfresh, which allows to automatically extract a huge of number of features and filter them for their importance.
Comprehensive list of time series features
So regarding your question: You can find inspiration about other features in the comprehensive documentation about the calculated features of tsfresh here. There are simple features such as the mean, time series related features such as the coefficients of an AR model or highly sophisticated features such as the test statistic of the augmented dickey fuller hypothesis test.
I am sure you will find some interesting features for your application there.
Disclaimer: I am one of the authors of tsfresh. | Feature selection for time series data
I was also on the search for a list of time series features quite a while ago. There are publications inspecting individual features but I was not able to find a comprehensive list of features.
tsfre |
32,055 | Convergence from the EM Algorithm with bivariate mixture distribution | The objective of EM is to maximize the observed data log-likelihood,
$$l(\theta) = \sum_i \ln \left[ \sum_{z} p(x_i, z| \theta) \right] $$
Unfortunately, this tends to be difficult to optimize with respect to $\theta$. Instead, EM repeatedly forms and maximizes the auxiliary function
$$Q(\theta , \theta^t) = \mathbb{E}_{z|\theta^t} \left (\sum_i \ln p(x_i, z_i| \theta) \right)$$
If $\theta^{t+1}$ maximizes $Q(\theta, \theta^t)$, EM guarantees that
$$l(\theta^{t+1}) \geq Q(\theta^{t+1}, \theta^t) \geq Q(\theta^t, \theta^t) = l(\theta^t)$$
If you'd like to know exactly why this is the case, Section 11.4.7 of Murphy's Machine Learning: A Probabilistic Perspective gives a good explanation. If your implementation doesn't satisfy these inequalities, you've made a mistake somewhere. Saying things like
I have a close to perfect fit, indicating there are no programming errors
is dangerous. With a lot of optimization and learning algorithms, it's very easy to make mistakes yet still get correct-looking answers most of the time. An intuition I'm fond of is that these algorithms are intended to deal with messy data, so it's not surprising that they also deal well with bugs!
On to the other half of your question,
is there a conventional search heuristic or likewise to increase the likelihood of finding the global minimum (or maximum)
Random restarts is the easiest approach; next easiest is probably simulated annealing over the initial parameters. I've also heard of a variant of EM called deterministic annealing, but I haven't used it personally so can't tell you much about it. | Convergence from the EM Algorithm with bivariate mixture distribution | The objective of EM is to maximize the observed data log-likelihood,
$$l(\theta) = \sum_i \ln \left[ \sum_{z} p(x_i, z| \theta) \right] $$
Unfortunately, this tends to be difficult to optimize with r | Convergence from the EM Algorithm with bivariate mixture distribution
The objective of EM is to maximize the observed data log-likelihood,
$$l(\theta) = \sum_i \ln \left[ \sum_{z} p(x_i, z| \theta) \right] $$
Unfortunately, this tends to be difficult to optimize with respect to $\theta$. Instead, EM repeatedly forms and maximizes the auxiliary function
$$Q(\theta , \theta^t) = \mathbb{E}_{z|\theta^t} \left (\sum_i \ln p(x_i, z_i| \theta) \right)$$
If $\theta^{t+1}$ maximizes $Q(\theta, \theta^t)$, EM guarantees that
$$l(\theta^{t+1}) \geq Q(\theta^{t+1}, \theta^t) \geq Q(\theta^t, \theta^t) = l(\theta^t)$$
If you'd like to know exactly why this is the case, Section 11.4.7 of Murphy's Machine Learning: A Probabilistic Perspective gives a good explanation. If your implementation doesn't satisfy these inequalities, you've made a mistake somewhere. Saying things like
I have a close to perfect fit, indicating there are no programming errors
is dangerous. With a lot of optimization and learning algorithms, it's very easy to make mistakes yet still get correct-looking answers most of the time. An intuition I'm fond of is that these algorithms are intended to deal with messy data, so it's not surprising that they also deal well with bugs!
On to the other half of your question,
is there a conventional search heuristic or likewise to increase the likelihood of finding the global minimum (or maximum)
Random restarts is the easiest approach; next easiest is probably simulated annealing over the initial parameters. I've also heard of a variant of EM called deterministic annealing, but I haven't used it personally so can't tell you much about it. | Convergence from the EM Algorithm with bivariate mixture distribution
The objective of EM is to maximize the observed data log-likelihood,
$$l(\theta) = \sum_i \ln \left[ \sum_{z} p(x_i, z| \theta) \right] $$
Unfortunately, this tends to be difficult to optimize with r |
32,056 | conditional difference between 2 uniform random variables. Surely Breiman can't be wrong? | The following are automatic, proceeding immediately from definitions and the information given:
The uniform distribution on any interval $[a,b]$ has density $1/(b-a)$. Therefore (measuring in days), the density of the turn-on time $X$ is
$$f_X(x) = \frac{1}{1-0} = 1.$$
The turn-off time $Y$ has a uniform distribution on the interval $[X, 1]$ and therefore has density
$$f_{Y|X}(y) = \frac{1}{1-X},$$
which is conditional on $X$.
Let $I$ be the event "electricity is on for at least half the day;" namely, $0 \le X \le 1$, $Y-X \ge 1/2$, and $Y \le 1$. Then
$$\Pr(I) = \iint_I f_X(x) f_{Y|X}(y) dx dy.$$
The rest is Calculus, which tells us (by Fubini's Theorem) that this can be computed as an iterated single integral,
$$\eqalign{
\iint_I f_X(x) f_{Y|X}(y) dx dy &= \int_{0}^{1/2} dx \left(\int_{x+1/2}^1 \frac{dy}{1-x}\right) \\
&= \int_{0}^{1/2} \frac{1/2 - x}{1-x}dx\\
&= \int_{0}^{1/2} \left(1 - \frac{1}{2} \frac{1}{1-x}\right) dx \\
&= \frac{1}{2} - \frac{1}{2} \log(2).
}$$ | conditional difference between 2 uniform random variables. Surely Breiman can't be wrong? | The following are automatic, proceeding immediately from definitions and the information given:
The uniform distribution on any interval $[a,b]$ has density $1/(b-a)$. Therefore (measuring in days), | conditional difference between 2 uniform random variables. Surely Breiman can't be wrong?
The following are automatic, proceeding immediately from definitions and the information given:
The uniform distribution on any interval $[a,b]$ has density $1/(b-a)$. Therefore (measuring in days), the density of the turn-on time $X$ is
$$f_X(x) = \frac{1}{1-0} = 1.$$
The turn-off time $Y$ has a uniform distribution on the interval $[X, 1]$ and therefore has density
$$f_{Y|X}(y) = \frac{1}{1-X},$$
which is conditional on $X$.
Let $I$ be the event "electricity is on for at least half the day;" namely, $0 \le X \le 1$, $Y-X \ge 1/2$, and $Y \le 1$. Then
$$\Pr(I) = \iint_I f_X(x) f_{Y|X}(y) dx dy.$$
The rest is Calculus, which tells us (by Fubini's Theorem) that this can be computed as an iterated single integral,
$$\eqalign{
\iint_I f_X(x) f_{Y|X}(y) dx dy &= \int_{0}^{1/2} dx \left(\int_{x+1/2}^1 \frac{dy}{1-x}\right) \\
&= \int_{0}^{1/2} \frac{1/2 - x}{1-x}dx\\
&= \int_{0}^{1/2} \left(1 - \frac{1}{2} \frac{1}{1-x}\right) dx \\
&= \frac{1}{2} - \frac{1}{2} \log(2).
}$$ | conditional difference between 2 uniform random variables. Surely Breiman can't be wrong?
The following are automatic, proceeding immediately from definitions and the information given:
The uniform distribution on any interval $[a,b]$ has density $1/(b-a)$. Therefore (measuring in days), |
32,057 | How to prepare/construct features for anomaly detection (network security data) | I'm definitely not an expert on anomaly detection. However, it's an interesting area and here's my two cents. First, considering your note that "Mahalanobis distance could be only applied to normally distributed features". I ran across some research that argues that it is still possible to use that metric in cases of non-normal data. Take a look for yourself at this paper and this technical report.
I also hope that you'll find useful the following resources on unsupervised anomaly detection (AD) in the IT network security context, using various approaches and methods: this paper, presenting a geometric framework for unsupervised AD; this paper, which uses density-based and grid-based clustering approach; this presentation slides, which mention using of self-organizing maps for AD.
Finally, I suggest you to take a look at following answers of mine, which I believe are relevant to the topic and, thus, might be helpful: answer on clustering approaches, answer on non-distance-based clustering and answer on software options for AD. | How to prepare/construct features for anomaly detection (network security data) | I'm definitely not an expert on anomaly detection. However, it's an interesting area and here's my two cents. First, considering your note that "Mahalanobis distance could be only applied to normally | How to prepare/construct features for anomaly detection (network security data)
I'm definitely not an expert on anomaly detection. However, it's an interesting area and here's my two cents. First, considering your note that "Mahalanobis distance could be only applied to normally distributed features". I ran across some research that argues that it is still possible to use that metric in cases of non-normal data. Take a look for yourself at this paper and this technical report.
I also hope that you'll find useful the following resources on unsupervised anomaly detection (AD) in the IT network security context, using various approaches and methods: this paper, presenting a geometric framework for unsupervised AD; this paper, which uses density-based and grid-based clustering approach; this presentation slides, which mention using of self-organizing maps for AD.
Finally, I suggest you to take a look at following answers of mine, which I believe are relevant to the topic and, thus, might be helpful: answer on clustering approaches, answer on non-distance-based clustering and answer on software options for AD. | How to prepare/construct features for anomaly detection (network security data)
I'm definitely not an expert on anomaly detection. However, it's an interesting area and here's my two cents. First, considering your note that "Mahalanobis distance could be only applied to normally |
32,058 | How to prepare/construct features for anomaly detection (network security data) | First of all, I think there are some things that you may have to resign yourself to.
One hard constraint that I see on this problem is that you should probably be prepared to have a quite high false positive rate. As far as I know, the base rate of records being part of a network anomaly is quite low (citation needed). Let's call it 1000:1 odds, for the sake of argument. Then even if you observe a pattern that is 100 times more likely to happen if the record is an intrusion then if it's legit, Bayes' Rule says that the posterior odds are 10:1 that the traffic is still legit.
The other problem is that some intrusions are hard to detect even in principle. For instance, if somebody socially engineered me into giving them my computer, and then they logged into this service and downloaded one top-secret file which I had been working on, this would be quite hard to find. Basically, a sufficiently determined attacker can make their intrusive behavior almost arbitrarily close to the normal behavior of the system.
Furthermore, your adversaries are intelligent, not statistical processes, so if you start detecting some pattern and shutting it out, they may simply respond by not following that pattern anymore. This is why, for instance, you'll see lots of spam messages with spaces in between all the letters (offering you "V I A G R A" or whatever). Spam filters figured out that the string "viagra" was spammy, so the attackers just started doing something else.
Because of this, I think it's worth thinking pretty hard about what types of intrustions you think it's worth the effort to be able to detect. There are certainly low-hanging fruit here, so don't let the perfect be the enemy of the good and try to come up with an algorithm that can detect all intrusions.
That aside, let's talk about the low-hanging fruit. Here, I think it might be productive for you to shift your unit of analysis from individual records, to a group of records.
For instance, you said that half of all records have unique combinations of fields. But presumably, for instance, most source IPs appear in more than one record--it's the other fields in the request that are changing and making the combination unique. If you group the requests by IP, you can then ask questions like:
Do some IPs seem to authenticate as unusually many users (or unusually few)?
Do some IPs have an unusually large number of authentication failures?
Do some IPs have an unusual pattern of access timings (for instance, lots of activity around 3am in their timezone, or requests every 1 second throughout the day)?
You can do similar things for other groupings, like username:
Is this user authenticating from a different computer when they previously used the same computer for all requests?
Is this user suddenly touching a part of the filesystem they've never touched before?
I don't know of any off-the-shelf classifiers that seem particularly suited to this, because the potential behavior of your users is so varied, and you're probably mostly interested in changes in behavior over time. That means you probably want to build some kind of model of what each user/IP/whatever is likely to do in the future, and flag any deviations from this model. But that's quite an intensive process if your users have different behavior patterns!
Because of this difficulty, I think for now it might be more productive to do the kind of exploratory-mode analysis I outlined above. That's likely to inform you about what types of patterns are the most interesting ones, and then you can start using fancy statistical algorithms to detect those patterns. | How to prepare/construct features for anomaly detection (network security data) | First of all, I think there are some things that you may have to resign yourself to.
One hard constraint that I see on this problem is that you should probably be prepared to have a quite high false p | How to prepare/construct features for anomaly detection (network security data)
First of all, I think there are some things that you may have to resign yourself to.
One hard constraint that I see on this problem is that you should probably be prepared to have a quite high false positive rate. As far as I know, the base rate of records being part of a network anomaly is quite low (citation needed). Let's call it 1000:1 odds, for the sake of argument. Then even if you observe a pattern that is 100 times more likely to happen if the record is an intrusion then if it's legit, Bayes' Rule says that the posterior odds are 10:1 that the traffic is still legit.
The other problem is that some intrusions are hard to detect even in principle. For instance, if somebody socially engineered me into giving them my computer, and then they logged into this service and downloaded one top-secret file which I had been working on, this would be quite hard to find. Basically, a sufficiently determined attacker can make their intrusive behavior almost arbitrarily close to the normal behavior of the system.
Furthermore, your adversaries are intelligent, not statistical processes, so if you start detecting some pattern and shutting it out, they may simply respond by not following that pattern anymore. This is why, for instance, you'll see lots of spam messages with spaces in between all the letters (offering you "V I A G R A" or whatever). Spam filters figured out that the string "viagra" was spammy, so the attackers just started doing something else.
Because of this, I think it's worth thinking pretty hard about what types of intrustions you think it's worth the effort to be able to detect. There are certainly low-hanging fruit here, so don't let the perfect be the enemy of the good and try to come up with an algorithm that can detect all intrusions.
That aside, let's talk about the low-hanging fruit. Here, I think it might be productive for you to shift your unit of analysis from individual records, to a group of records.
For instance, you said that half of all records have unique combinations of fields. But presumably, for instance, most source IPs appear in more than one record--it's the other fields in the request that are changing and making the combination unique. If you group the requests by IP, you can then ask questions like:
Do some IPs seem to authenticate as unusually many users (or unusually few)?
Do some IPs have an unusually large number of authentication failures?
Do some IPs have an unusual pattern of access timings (for instance, lots of activity around 3am in their timezone, or requests every 1 second throughout the day)?
You can do similar things for other groupings, like username:
Is this user authenticating from a different computer when they previously used the same computer for all requests?
Is this user suddenly touching a part of the filesystem they've never touched before?
I don't know of any off-the-shelf classifiers that seem particularly suited to this, because the potential behavior of your users is so varied, and you're probably mostly interested in changes in behavior over time. That means you probably want to build some kind of model of what each user/IP/whatever is likely to do in the future, and flag any deviations from this model. But that's quite an intensive process if your users have different behavior patterns!
Because of this difficulty, I think for now it might be more productive to do the kind of exploratory-mode analysis I outlined above. That's likely to inform you about what types of patterns are the most interesting ones, and then you can start using fancy statistical algorithms to detect those patterns. | How to prepare/construct features for anomaly detection (network security data)
First of all, I think there are some things that you may have to resign yourself to.
One hard constraint that I see on this problem is that you should probably be prepared to have a quite high false p |
32,059 | How to prepare/construct features for anomaly detection (network security data) | I think that in first place you need to have a dataset which records data for a period of no attacks. This dataset should capture the variations that are inherent to a system behaving normally. I would like to stress the point that this is not about having an annotated dataset.
Next, I would try to combine all (or subset) of metrics into one. This new metric should reflect the amount of "surprise". For example, low value means system runs normally, high value peak/plateau means that there is some rapid change. Here I am thinking about CUSUM or Shewhart chart style charts.
Can you provide some examples of the available data? Is it mainly strings, numbers, 1/0 indicators? | How to prepare/construct features for anomaly detection (network security data) | I think that in first place you need to have a dataset which records data for a period of no attacks. This dataset should capture the variations that are inherent to a system behaving normally. I woul | How to prepare/construct features for anomaly detection (network security data)
I think that in first place you need to have a dataset which records data for a period of no attacks. This dataset should capture the variations that are inherent to a system behaving normally. I would like to stress the point that this is not about having an annotated dataset.
Next, I would try to combine all (or subset) of metrics into one. This new metric should reflect the amount of "surprise". For example, low value means system runs normally, high value peak/plateau means that there is some rapid change. Here I am thinking about CUSUM or Shewhart chart style charts.
Can you provide some examples of the available data? Is it mainly strings, numbers, 1/0 indicators? | How to prepare/construct features for anomaly detection (network security data)
I think that in first place you need to have a dataset which records data for a period of no attacks. This dataset should capture the variations that are inherent to a system behaving normally. I woul |
32,060 | How to prepare/construct features for anomaly detection (network security data) | A possibility is to learn a bayesian network between the features given some background data with no attacks. Learning a bayesian network is useful because it brings out conditional independence between features. Hence, you are not dealing with each and every possible combination of features. For example, if feature A affects B and C and features B and C together affect D, then you only learn a model for how A affects B, how affects C, and how B and C jointly affect D. This model will require far fewer parameters than the entire probability distribution and is the primary reason why bayesian networks are used instead of just storing the entire joint probability distribution. To test for anomaly given a Bayesian network, calculate the probability of incoming datapoint using the learnt Bayesian network model. If the probability is very low, you can flag that as an anomaly. | How to prepare/construct features for anomaly detection (network security data) | A possibility is to learn a bayesian network between the features given some background data with no attacks. Learning a bayesian network is useful because it brings out conditional independence betwe | How to prepare/construct features for anomaly detection (network security data)
A possibility is to learn a bayesian network between the features given some background data with no attacks. Learning a bayesian network is useful because it brings out conditional independence between features. Hence, you are not dealing with each and every possible combination of features. For example, if feature A affects B and C and features B and C together affect D, then you only learn a model for how A affects B, how affects C, and how B and C jointly affect D. This model will require far fewer parameters than the entire probability distribution and is the primary reason why bayesian networks are used instead of just storing the entire joint probability distribution. To test for anomaly given a Bayesian network, calculate the probability of incoming datapoint using the learnt Bayesian network model. If the probability is very low, you can flag that as an anomaly. | How to prepare/construct features for anomaly detection (network security data)
A possibility is to learn a bayesian network between the features given some background data with no attacks. Learning a bayesian network is useful because it brings out conditional independence betwe |
32,061 | How to prepare/construct features for anomaly detection (network security data) | I thought that the response from Ben Kuhn was pragmatic and insightful.
Now my own background includes in text classification, expert systems, clustering and security. Given this background, I would like to think that I might have something to add to the conversation. But the previous statements by Ben Kuhn highlight that straightforward approaches could produce many false positives. IT staff, when faced with many false positives, typically "tune out" because they simply do not have the time to chase false positives all the time.
So what to do?
Certainly logs with attacks in them could be helpful but then we have a catch-22 unless companies somehow share attack data. While some Silicon Valley start-ups might be pursuing such threat sharing, what else might we do?
One possible approach is to create a simulation of the network and then find a way to generate attacks against the simulation. That is, suppose we create a simulation where the black hats (also simulated) are not known in advance to the white hats. Given these attacks, we can then attempt to create algorithms that should discover these attacks. If the black hats operate independently of the white hats, then we have a real battle that will play out. If the attackers break into the system, or are undetected, then the white hats have, to some degree, failed.
One could even have an incentive structure when the security analysts on the black hat team are rewarded for their successes (breeches or undiscovered attacks). Similarly, the group comprising the white hats are rewarded for stopping breeches and/or detecting attacks.
There is nothing perfect about this arrangement. Obviously real black hats might exceed the talents of the "friendly" black hat team. Nonetheless, as person who has a fair amount of data analysis, it seems to me that it is very hard to quantify the success of white hats without a better understanding of the black hats. Bottom line is this. If we can't know what real black hats are doing, the next best thing is friendly black hats.
I also have a rather unusual idea. Suppose in addition to the friendly black hats and the white hats, there is a gray hat team. What does it mean to be a grey hat? The idea is simple. Grey hats are permitted to look at what the friendly black hats are doing and the white hats. But why?
Suppose that the friendly black hats launch attacks using approaches A, B and C, and the white hats never discover any of these three approaches. Well, the grey hats are empowered to look at what both the friendly black hats are doing as well as the white hats are doing, and they try to consider what principles might be used to discover these undetected attacks. If the grey hat finds such principles, the grey hat team can then share these principles with the white hat team without describing the exact attacks in detail.
The hope is that these "hints" provided by the grey hat team give the white hat team a push in the right direction without revealing too much.
In retrospect, I apologize if my response is really not about specific techniques. Obviously my response is not about specific techniques. But in my experience, a lot of problems in machine learning - including those in security - often fail because the data is inadequate. This approach, using white hats, grey hats and black hats, might help produce the data that would allow a security company (or IT staff) to not only quantify the effectiveness of their defenses, but provide an organizational structure that pushes the white hat team to progressively improved their defenses and their monitoring.
I really don't have any idea if the approach I am suggesting is original.
I have never heard of grey hats, but I actually think that the role of grey hats could be critical to pushing the white team forward, without revealing too much.
Note: my use of the term "grey hat" here is not standard. See http://www.howtogeek.com/157460/hacker-hat-colors-explained-black-hats-white-hats-and-gray-hats/. So some other term, perhaps "striped hat" should be used instead.
But still the idea remains the same: a striped hat can help mediate between the work of friendly black hats and defenders (white hats), so that certain ideas and hints can be judiciously shared with the white hats. | How to prepare/construct features for anomaly detection (network security data) | I thought that the response from Ben Kuhn was pragmatic and insightful.
Now my own background includes in text classification, expert systems, clustering and security. Given this background, I would | How to prepare/construct features for anomaly detection (network security data)
I thought that the response from Ben Kuhn was pragmatic and insightful.
Now my own background includes in text classification, expert systems, clustering and security. Given this background, I would like to think that I might have something to add to the conversation. But the previous statements by Ben Kuhn highlight that straightforward approaches could produce many false positives. IT staff, when faced with many false positives, typically "tune out" because they simply do not have the time to chase false positives all the time.
So what to do?
Certainly logs with attacks in them could be helpful but then we have a catch-22 unless companies somehow share attack data. While some Silicon Valley start-ups might be pursuing such threat sharing, what else might we do?
One possible approach is to create a simulation of the network and then find a way to generate attacks against the simulation. That is, suppose we create a simulation where the black hats (also simulated) are not known in advance to the white hats. Given these attacks, we can then attempt to create algorithms that should discover these attacks. If the black hats operate independently of the white hats, then we have a real battle that will play out. If the attackers break into the system, or are undetected, then the white hats have, to some degree, failed.
One could even have an incentive structure when the security analysts on the black hat team are rewarded for their successes (breeches or undiscovered attacks). Similarly, the group comprising the white hats are rewarded for stopping breeches and/or detecting attacks.
There is nothing perfect about this arrangement. Obviously real black hats might exceed the talents of the "friendly" black hat team. Nonetheless, as person who has a fair amount of data analysis, it seems to me that it is very hard to quantify the success of white hats without a better understanding of the black hats. Bottom line is this. If we can't know what real black hats are doing, the next best thing is friendly black hats.
I also have a rather unusual idea. Suppose in addition to the friendly black hats and the white hats, there is a gray hat team. What does it mean to be a grey hat? The idea is simple. Grey hats are permitted to look at what the friendly black hats are doing and the white hats. But why?
Suppose that the friendly black hats launch attacks using approaches A, B and C, and the white hats never discover any of these three approaches. Well, the grey hats are empowered to look at what both the friendly black hats are doing as well as the white hats are doing, and they try to consider what principles might be used to discover these undetected attacks. If the grey hat finds such principles, the grey hat team can then share these principles with the white hat team without describing the exact attacks in detail.
The hope is that these "hints" provided by the grey hat team give the white hat team a push in the right direction without revealing too much.
In retrospect, I apologize if my response is really not about specific techniques. Obviously my response is not about specific techniques. But in my experience, a lot of problems in machine learning - including those in security - often fail because the data is inadequate. This approach, using white hats, grey hats and black hats, might help produce the data that would allow a security company (or IT staff) to not only quantify the effectiveness of their defenses, but provide an organizational structure that pushes the white hat team to progressively improved their defenses and their monitoring.
I really don't have any idea if the approach I am suggesting is original.
I have never heard of grey hats, but I actually think that the role of grey hats could be critical to pushing the white team forward, without revealing too much.
Note: my use of the term "grey hat" here is not standard. See http://www.howtogeek.com/157460/hacker-hat-colors-explained-black-hats-white-hats-and-gray-hats/. So some other term, perhaps "striped hat" should be used instead.
But still the idea remains the same: a striped hat can help mediate between the work of friendly black hats and defenders (white hats), so that certain ideas and hints can be judiciously shared with the white hats. | How to prepare/construct features for anomaly detection (network security data)
I thought that the response from Ben Kuhn was pragmatic and insightful.
Now my own background includes in text classification, expert systems, clustering and security. Given this background, I would |
32,062 | How to prepare/construct features for anomaly detection (network security data) | Since I have posted the original question, I have performed a lot of research on this topic and can now provide my results as an answer.
First of all, in our lab, we develop a SIEM system that utilizes anomaly detection algorithms. The description of the system and algorithms is available in my paper Towards a system for complex analysis of security events in large-scale networks
Besides that I wrote a short summary on how to deal with such data in my answer to a similar question on Cross Validated | How to prepare/construct features for anomaly detection (network security data) | Since I have posted the original question, I have performed a lot of research on this topic and can now provide my results as an answer.
First of all, in our lab, we develop a SIEM system that utilize | How to prepare/construct features for anomaly detection (network security data)
Since I have posted the original question, I have performed a lot of research on this topic and can now provide my results as an answer.
First of all, in our lab, we develop a SIEM system that utilizes anomaly detection algorithms. The description of the system and algorithms is available in my paper Towards a system for complex analysis of security events in large-scale networks
Besides that I wrote a short summary on how to deal with such data in my answer to a similar question on Cross Validated | How to prepare/construct features for anomaly detection (network security data)
Since I have posted the original question, I have performed a lot of research on this topic and can now provide my results as an answer.
First of all, in our lab, we develop a SIEM system that utilize |
32,063 | Is the Wilcoxon rank-sum test the right test to see if total donations differ? | If you use wilcox.test() with the argument paired (note that this is lower case, and that R is case sensitive) set to FALSE, you are running a Mann-Whitney $U$-test. This is a test of stochastic dominance. If the distributions were equal, and you picked an observation from each version at random, the observation from version 2 would have a 50%-50% chance of being higher than the observation from version 1. On the other hand, the value drawn from version 2 might have a greater than 50% chance of being greater than (less than) the value from version 1. This is stochastic dominance. Nothing is being said about how much greater or less, only that it is greater or lesser.
That doesn't strike me as a good fit for your objectives. You want the most total money, which can be understood as the largest mean donation times the number of users. It is possible, due to skew, that one version can have the largest mean / total, but that the other version is stochastically greater. (If that were the case, you would want the former version.) Because this is what you ultimately want, a test that is specific to that aspect of the distributions is most appropriate for you.
I recognize that your data are not remotely normal, and thus, the $t$-test (which might be what most people would think of first for comparing two groups), would be inappropriate. Given two continuous, but non-normal groups, most people might likewise automatically go with the Mann-Whitney. In your case, I would go with a permutation test, for the above reason. (I gather this is what you did, if I understood correctly.) A permutation test is valid here, because you randomly assigned users to the two groups; therefore, they are exchangeable.
To perform a permutation test, just shuffle the grouping indicator and calculate means and a difference between the means. Doing this many times will allow you to create a sampling distribution of the difference between the means. You can compare your observed difference to the sampling distribution. For a two-tailed test, take the smaller proportion beyond your difference and multiply it by two. The product is directly interpretable as a $p$-value. Here is a worked example with your data:
A = c(rep(0, 9990), 40,20,20,20,15,10,10,5,5,5)
B = c(rep(0, 9985), 50,20,10,10,10,10,10,10,5,5,5,5,5,5,5)
realized.dif = mean(B)-mean(A); realized.dif # [1] 0.0015
set.seed(6497)
donations = stack(list(A=A, B=B))
values = donations$values
ind = donations$ind
difs = vector(length=1000)
for(i in 1:1000){
ind = sample(ind)
difs[i] = mean(values[ind=="B"])-mean(values[ind=="A"])
}
difs = sort(difs)
mean(difs>=realized.dif) # [1] 0.459 # a 1-tailed test, if Ha: B>A a-priori
mean(difs>=realized.dif)*2 # [1] 0.918 # a 2-tailed test
Regarding the first study question, i.e., 'which version yielded a larger number of donations', while I grant that everybody loves ABBA, you can do this in R as well. I would use a $z$-test of the difference of two proportions. In R, that's prop.test(). Here is an example using your data:
prop.test(rbind(c(10, 9990),
c(15, 9985) ))
# 2-sample test for equality of proportions with continuity correction
#
# data: rbind(c(10, 9990), c(15, 9985))
# X-squared = 0.6408, df = 1, p-value = 0.4234
# alternative hypothesis: two.sided
# 95 percent confidence interval:
# -0.0015793448 0.0005793448
# sample estimates:
# prop 1 prop 2
# 0.0010 0.0015 | Is the Wilcoxon rank-sum test the right test to see if total donations differ? | If you use wilcox.test() with the argument paired (note that this is lower case, and that R is case sensitive) set to FALSE, you are running a Mann-Whitney $U$-test. This is a test of stochastic domi | Is the Wilcoxon rank-sum test the right test to see if total donations differ?
If you use wilcox.test() with the argument paired (note that this is lower case, and that R is case sensitive) set to FALSE, you are running a Mann-Whitney $U$-test. This is a test of stochastic dominance. If the distributions were equal, and you picked an observation from each version at random, the observation from version 2 would have a 50%-50% chance of being higher than the observation from version 1. On the other hand, the value drawn from version 2 might have a greater than 50% chance of being greater than (less than) the value from version 1. This is stochastic dominance. Nothing is being said about how much greater or less, only that it is greater or lesser.
That doesn't strike me as a good fit for your objectives. You want the most total money, which can be understood as the largest mean donation times the number of users. It is possible, due to skew, that one version can have the largest mean / total, but that the other version is stochastically greater. (If that were the case, you would want the former version.) Because this is what you ultimately want, a test that is specific to that aspect of the distributions is most appropriate for you.
I recognize that your data are not remotely normal, and thus, the $t$-test (which might be what most people would think of first for comparing two groups), would be inappropriate. Given two continuous, but non-normal groups, most people might likewise automatically go with the Mann-Whitney. In your case, I would go with a permutation test, for the above reason. (I gather this is what you did, if I understood correctly.) A permutation test is valid here, because you randomly assigned users to the two groups; therefore, they are exchangeable.
To perform a permutation test, just shuffle the grouping indicator and calculate means and a difference between the means. Doing this many times will allow you to create a sampling distribution of the difference between the means. You can compare your observed difference to the sampling distribution. For a two-tailed test, take the smaller proportion beyond your difference and multiply it by two. The product is directly interpretable as a $p$-value. Here is a worked example with your data:
A = c(rep(0, 9990), 40,20,20,20,15,10,10,5,5,5)
B = c(rep(0, 9985), 50,20,10,10,10,10,10,10,5,5,5,5,5,5,5)
realized.dif = mean(B)-mean(A); realized.dif # [1] 0.0015
set.seed(6497)
donations = stack(list(A=A, B=B))
values = donations$values
ind = donations$ind
difs = vector(length=1000)
for(i in 1:1000){
ind = sample(ind)
difs[i] = mean(values[ind=="B"])-mean(values[ind=="A"])
}
difs = sort(difs)
mean(difs>=realized.dif) # [1] 0.459 # a 1-tailed test, if Ha: B>A a-priori
mean(difs>=realized.dif)*2 # [1] 0.918 # a 2-tailed test
Regarding the first study question, i.e., 'which version yielded a larger number of donations', while I grant that everybody loves ABBA, you can do this in R as well. I would use a $z$-test of the difference of two proportions. In R, that's prop.test(). Here is an example using your data:
prop.test(rbind(c(10, 9990),
c(15, 9985) ))
# 2-sample test for equality of proportions with continuity correction
#
# data: rbind(c(10, 9990), c(15, 9985))
# X-squared = 0.6408, df = 1, p-value = 0.4234
# alternative hypothesis: two.sided
# 95 percent confidence interval:
# -0.0015793448 0.0005793448
# sample estimates:
# prop 1 prop 2
# 0.0010 0.0015 | Is the Wilcoxon rank-sum test the right test to see if total donations differ?
If you use wilcox.test() with the argument paired (note that this is lower case, and that R is case sensitive) set to FALSE, you are running a Mann-Whitney $U$-test. This is a test of stochastic domi |
32,064 | Is the Wilcoxon rank-sum test the right test to see if total donations differ? | @gung's answer is correct. But I would add that since your data might be skewed, with a huge right tail, the mean may not be robust and as such it might not be the "right" index for representing the centrality of your distribution. Hence, I would try also with more robust solutions such as medians or truncated means. | Is the Wilcoxon rank-sum test the right test to see if total donations differ? | @gung's answer is correct. But I would add that since your data might be skewed, with a huge right tail, the mean may not be robust and as such it might not be the "right" index for representing the c | Is the Wilcoxon rank-sum test the right test to see if total donations differ?
@gung's answer is correct. But I would add that since your data might be skewed, with a huge right tail, the mean may not be robust and as such it might not be the "right" index for representing the centrality of your distribution. Hence, I would try also with more robust solutions such as medians or truncated means. | Is the Wilcoxon rank-sum test the right test to see if total donations differ?
@gung's answer is correct. But I would add that since your data might be skewed, with a huge right tail, the mean may not be robust and as such it might not be the "right" index for representing the c |
32,065 | If X/Y has the same distribution as Z, is it true that X has the same distribution as YZ? | It can happen. For instance, if $X$, $Y$ and $Z$ are independent Rademacher variables, i.e. they can be 1 or -1 with equal probability. In this case $X/Y$ is also Rademacher, so has the same distribution as $Z$, while $YZ$ is Rademacher so has the same distribution as $X$.
But it won't happen in general. So long as the means exist, necessary (but not sufficient) conditions for $X/Y$ to have the same distribution as $Z$, and for $YZ$ to have the same distribution as $X$, would be:
$$\mathbb{E}(Z) = \mathbb{E}(XY^{-1}) = \mathbb{E}(X)\mathbb{E}(Y^{-1})$$
$$\mathbb{E}(X) = \mathbb{E}(YZ) = \mathbb{E}(Y)\mathbb{E}(Z)$$
The second equalities followed by independence. Substituting gives:
$$\mathbb{E}(Z) = \mathbb{E}(Y) \mathbb{E}(Z) \mathbb{E}(Y^{-1})$$
If $\mathbb{E}(Z) \neq 0$ then $1 = \mathbb{E}(Y) \mathbb{E}(Y^{-1})$, or equivalently, so long as $\mathbb{E}(Y) \neq 0$,
$$\mathbb{E}(Y^{-1}) = \frac{1}{\mathbb{E}(Y)}$$
This is not true in general. For example, let $Y$ be a translated Bernouilli variable which takes values $1$ or $2$ with equal probability, so $\mathbb{E}(Y)=1.5$. Then $Y^{-1}$ takes values $1$ or $0.5$ with equal probability, so $\mathbb{E}(Y^{-1})=0.75 \neq 1.5^{-1}$. (I leave it to the reader's imagination, how dramatic an effect it would have had to use an untranslated Bernouilli variable instead, or one translated only slightly so it is very close to 0 with probability one half. Note that in the Rademacher example there was no problem here because all three expectations were zero, note further that this condition isn't a sufficient one.)
We can explore how this $Y$ fails by constructing a more explicit counterexample. To keep things simple, suppose $X$ is a scaled Bernouilli and takes values $0$ or $2$ with equal probability. Then $X/Y$ is either $0/1$, $0/2$, $2/1$ or $2/2$ with equal probability. It's clear that $P(X/Y=0)=\frac{1}{2}$, $P(X/Y=1)=\frac{1}{4}$ and $P(X/Y=2)=\frac{1}{4}$. Let $Z$ be an independent variable drawn from the same distribution. What is the distribution of $YZ$? Is it the same as the distribution of $X$? We don't even have to work out the full probability distribution to see that it can't be; it suffices to remember $X$ could only be zero or two while $YZ$ can take any value you can obtain from multiplying one of $\{1,2\}$ by one of $\{0,1,2\}$.
If you want a moral for this tale, then try playing around with scaled and translated Bernouilli variables (which includes Rademacher variables). They can be a simple way to construct examples - and counterexamples. It helps having fewer values in the supports so that distributions of various functions of the variables can be easily worked out by hand.
Even more extreme we can consider degenerate variables which only have a single value in their support. If $X$ and $Y$ are degenerate (with $Y\neq 0$) then $Z=X/Y$ will be too, and so the distribution of $YZ$ will match the value of $Z$. Like my Rademacher example, that's a situation showing your conditions can be satisfied. If instead, as @whuber suggests in the comments, we let $X$ be degenerate with $P(X=1)$, but allow $Y$ to vary, then constructing an even simpler counterexample is very easy. If $Y$ can take two finite, non-zero values - $a$ and $b$, say - with positive probability, then $X/Y$, and hence $Z$, can take values $a^{-1}$ and $b^{-1}$. Now $YZ$ therefore has $ab^{-1} \neq 1$ in its support, so can't follow the same distribution as $X$. This is similar to, but simpler than, my argument that the supports couldn't match in my original counterexample. | If X/Y has the same distribution as Z, is it true that X has the same distribution as YZ? | It can happen. For instance, if $X$, $Y$ and $Z$ are independent Rademacher variables, i.e. they can be 1 or -1 with equal probability. In this case $X/Y$ is also Rademacher, so has the same distribut | If X/Y has the same distribution as Z, is it true that X has the same distribution as YZ?
It can happen. For instance, if $X$, $Y$ and $Z$ are independent Rademacher variables, i.e. they can be 1 or -1 with equal probability. In this case $X/Y$ is also Rademacher, so has the same distribution as $Z$, while $YZ$ is Rademacher so has the same distribution as $X$.
But it won't happen in general. So long as the means exist, necessary (but not sufficient) conditions for $X/Y$ to have the same distribution as $Z$, and for $YZ$ to have the same distribution as $X$, would be:
$$\mathbb{E}(Z) = \mathbb{E}(XY^{-1}) = \mathbb{E}(X)\mathbb{E}(Y^{-1})$$
$$\mathbb{E}(X) = \mathbb{E}(YZ) = \mathbb{E}(Y)\mathbb{E}(Z)$$
The second equalities followed by independence. Substituting gives:
$$\mathbb{E}(Z) = \mathbb{E}(Y) \mathbb{E}(Z) \mathbb{E}(Y^{-1})$$
If $\mathbb{E}(Z) \neq 0$ then $1 = \mathbb{E}(Y) \mathbb{E}(Y^{-1})$, or equivalently, so long as $\mathbb{E}(Y) \neq 0$,
$$\mathbb{E}(Y^{-1}) = \frac{1}{\mathbb{E}(Y)}$$
This is not true in general. For example, let $Y$ be a translated Bernouilli variable which takes values $1$ or $2$ with equal probability, so $\mathbb{E}(Y)=1.5$. Then $Y^{-1}$ takes values $1$ or $0.5$ with equal probability, so $\mathbb{E}(Y^{-1})=0.75 \neq 1.5^{-1}$. (I leave it to the reader's imagination, how dramatic an effect it would have had to use an untranslated Bernouilli variable instead, or one translated only slightly so it is very close to 0 with probability one half. Note that in the Rademacher example there was no problem here because all three expectations were zero, note further that this condition isn't a sufficient one.)
We can explore how this $Y$ fails by constructing a more explicit counterexample. To keep things simple, suppose $X$ is a scaled Bernouilli and takes values $0$ or $2$ with equal probability. Then $X/Y$ is either $0/1$, $0/2$, $2/1$ or $2/2$ with equal probability. It's clear that $P(X/Y=0)=\frac{1}{2}$, $P(X/Y=1)=\frac{1}{4}$ and $P(X/Y=2)=\frac{1}{4}$. Let $Z$ be an independent variable drawn from the same distribution. What is the distribution of $YZ$? Is it the same as the distribution of $X$? We don't even have to work out the full probability distribution to see that it can't be; it suffices to remember $X$ could only be zero or two while $YZ$ can take any value you can obtain from multiplying one of $\{1,2\}$ by one of $\{0,1,2\}$.
If you want a moral for this tale, then try playing around with scaled and translated Bernouilli variables (which includes Rademacher variables). They can be a simple way to construct examples - and counterexamples. It helps having fewer values in the supports so that distributions of various functions of the variables can be easily worked out by hand.
Even more extreme we can consider degenerate variables which only have a single value in their support. If $X$ and $Y$ are degenerate (with $Y\neq 0$) then $Z=X/Y$ will be too, and so the distribution of $YZ$ will match the value of $Z$. Like my Rademacher example, that's a situation showing your conditions can be satisfied. If instead, as @whuber suggests in the comments, we let $X$ be degenerate with $P(X=1)$, but allow $Y$ to vary, then constructing an even simpler counterexample is very easy. If $Y$ can take two finite, non-zero values - $a$ and $b$, say - with positive probability, then $X/Y$, and hence $Z$, can take values $a^{-1}$ and $b^{-1}$. Now $YZ$ therefore has $ab^{-1} \neq 1$ in its support, so can't follow the same distribution as $X$. This is similar to, but simpler than, my argument that the supports couldn't match in my original counterexample. | If X/Y has the same distribution as Z, is it true that X has the same distribution as YZ?
It can happen. For instance, if $X$, $Y$ and $Z$ are independent Rademacher variables, i.e. they can be 1 or -1 with equal probability. In this case $X/Y$ is also Rademacher, so has the same distribut |
32,066 | How would you categorize / extract information out of job descriptions? | A potential way to start this is to make use of Python's Natural Language Tool Kit (NLTK) which can be utilized for text and topic analysis but also has useful functions to extract certain words from strings. For instance, you could extract from the job description the words "medical", "hospital", etc. in order to find broad occupations and sectors. Due to the spelling mistakes and quality of the data I don't think it can be done in a fully automated fashion such that you might end up coding the SOCs yourself. Nonetheless, having the broad occupations and sectors in this way already makes the task a lot easier.
If you are interested in natural language processing/text and topic analysis/text mining beyond this, a fairly inexpensive but useful book is by Bird et al. (2009) "Natural Language Processing with Python".
Occupational titles have been linked to salaries by David Autor. He linked data in the Current Population Survey (the data which is used to also produce U.S. unemployment figures) to the SOC titles from which you can also get salaries in each occupation. From these you can easily compute mean salaries in each occupation and you can even have an idea about the variance (within occupational earnings inequality) in each occupation. David makes his data sets available on his data archive at MIT. | How would you categorize / extract information out of job descriptions? | A potential way to start this is to make use of Python's Natural Language Tool Kit (NLTK) which can be utilized for text and topic analysis but also has useful functions to extract certain words from | How would you categorize / extract information out of job descriptions?
A potential way to start this is to make use of Python's Natural Language Tool Kit (NLTK) which can be utilized for text and topic analysis but also has useful functions to extract certain words from strings. For instance, you could extract from the job description the words "medical", "hospital", etc. in order to find broad occupations and sectors. Due to the spelling mistakes and quality of the data I don't think it can be done in a fully automated fashion such that you might end up coding the SOCs yourself. Nonetheless, having the broad occupations and sectors in this way already makes the task a lot easier.
If you are interested in natural language processing/text and topic analysis/text mining beyond this, a fairly inexpensive but useful book is by Bird et al. (2009) "Natural Language Processing with Python".
Occupational titles have been linked to salaries by David Autor. He linked data in the Current Population Survey (the data which is used to also produce U.S. unemployment figures) to the SOC titles from which you can also get salaries in each occupation. From these you can easily compute mean salaries in each occupation and you can even have an idea about the variance (within occupational earnings inequality) in each occupation. David makes his data sets available on his data archive at MIT. | How would you categorize / extract information out of job descriptions?
A potential way to start this is to make use of Python's Natural Language Tool Kit (NLTK) which can be utilized for text and topic analysis but also has useful functions to extract certain words from |
32,067 | How would you categorize / extract information out of job descriptions? | I've had success using Latent Dirichlet Allocation (LDA) to find the latent themes or "topics" in textual data. LDA will create $k$ topics out of terms (words) from your corpus of job descriptions. Each job description is given a probability of containing each of the $k$ topics. For example if you asked LDA to classify a corpus into 3 topics, a job description for a graphic designer might have 80% "photoshop graphic illustrator...", 18% "HTML CSS JS...", and 2% "Java Spring object-oriented...". There's plenty to read about the LDA, just search or start with the Quora question.
My analysis with LDA was in R but there is of course a Python package although I have never employed it in my own work.
You might consider selecting a topic number that corresponds with the number occupations in the SOC. Once you have generated the topics inspect them and see if you can find meaningful links to the SOC and adjust the topic number accordingly until you are satisfied.
To make salary estimates for each job description consider weighting each salary using the topic probabilities. For example if a job description had an 80% probability of being a software developer SOC weight the salary by .80 and the remaining topics likewise. If that creates too much noise just set a cutoff (maybe 20%) and remove the remaining topic weights from the salary estimate.
For misspellings you can always attack it with a spell checker and see how it compares to the results without the tool. Also make sure to employ standard NLP techniques such as punctuation removal and word stemming prior to running LDA. | How would you categorize / extract information out of job descriptions? | I've had success using Latent Dirichlet Allocation (LDA) to find the latent themes or "topics" in textual data. LDA will create $k$ topics out of terms (words) from your corpus of job descriptions. Ea | How would you categorize / extract information out of job descriptions?
I've had success using Latent Dirichlet Allocation (LDA) to find the latent themes or "topics" in textual data. LDA will create $k$ topics out of terms (words) from your corpus of job descriptions. Each job description is given a probability of containing each of the $k$ topics. For example if you asked LDA to classify a corpus into 3 topics, a job description for a graphic designer might have 80% "photoshop graphic illustrator...", 18% "HTML CSS JS...", and 2% "Java Spring object-oriented...". There's plenty to read about the LDA, just search or start with the Quora question.
My analysis with LDA was in R but there is of course a Python package although I have never employed it in my own work.
You might consider selecting a topic number that corresponds with the number occupations in the SOC. Once you have generated the topics inspect them and see if you can find meaningful links to the SOC and adjust the topic number accordingly until you are satisfied.
To make salary estimates for each job description consider weighting each salary using the topic probabilities. For example if a job description had an 80% probability of being a software developer SOC weight the salary by .80 and the remaining topics likewise. If that creates too much noise just set a cutoff (maybe 20%) and remove the remaining topic weights from the salary estimate.
For misspellings you can always attack it with a spell checker and see how it compares to the results without the tool. Also make sure to employ standard NLP techniques such as punctuation removal and word stemming prior to running LDA. | How would you categorize / extract information out of job descriptions?
I've had success using Latent Dirichlet Allocation (LDA) to find the latent themes or "topics" in textual data. LDA will create $k$ topics out of terms (words) from your corpus of job descriptions. Ea |
32,068 | How would you categorize / extract information out of job descriptions? | Those are not so much job descriptions as job titles. If you did have descriptions like this example from the SOC definitions, you could use a topic model as suggested by Chris:
1011 Chief Executives Determine and formulate policies and provide overall direction of companies or private and public sector
organizations within guidelines set up by a board of directors or
similar governing body. Plan, direct, or coordinate operational
activities at the highest level of management with the help of
subordinate executives and staff managers.
In the absence of long-form text, you could use a naive Bayesian classifier (since you have a classification problem) that uses the social network as a feature, since people are likely to work in the same types of jobs as their friends. Another feature could be the string similarity to the Direct Match Title File (I think this database is just what you need), which provides a mapping between job titles and the SOC. | How would you categorize / extract information out of job descriptions? | Those are not so much job descriptions as job titles. If you did have descriptions like this example from the SOC definitions, you could use a topic model as suggested by Chris:
1011 Chief Executives | How would you categorize / extract information out of job descriptions?
Those are not so much job descriptions as job titles. If you did have descriptions like this example from the SOC definitions, you could use a topic model as suggested by Chris:
1011 Chief Executives Determine and formulate policies and provide overall direction of companies or private and public sector
organizations within guidelines set up by a board of directors or
similar governing body. Plan, direct, or coordinate operational
activities at the highest level of management with the help of
subordinate executives and staff managers.
In the absence of long-form text, you could use a naive Bayesian classifier (since you have a classification problem) that uses the social network as a feature, since people are likely to work in the same types of jobs as their friends. Another feature could be the string similarity to the Direct Match Title File (I think this database is just what you need), which provides a mapping between job titles and the SOC. | How would you categorize / extract information out of job descriptions?
Those are not so much job descriptions as job titles. If you did have descriptions like this example from the SOC definitions, you could use a topic model as suggested by Chris:
1011 Chief Executives |
32,069 | What is the difference between R hat and psrf? | $\hat{R}$ and "potential scale reduction factor" refer to the same thing. See Chapter 6 of the Handbook of Markov Chain Monte Carlo, "Inference from Simulations and Monitoring Convergence" by Andrew Gelman and Kenneth Shirley.
In Stan, the number reported is actually split $\hat{R}$; the calculation of $\hat{R}$ is computed with each of the chains split in half. | What is the difference between R hat and psrf? | $\hat{R}$ and "potential scale reduction factor" refer to the same thing. See Chapter 6 of the Handbook of Markov Chain Monte Carlo, "Inference from Simulations and Monitoring Convergence" by Andrew G | What is the difference between R hat and psrf?
$\hat{R}$ and "potential scale reduction factor" refer to the same thing. See Chapter 6 of the Handbook of Markov Chain Monte Carlo, "Inference from Simulations and Monitoring Convergence" by Andrew Gelman and Kenneth Shirley.
In Stan, the number reported is actually split $\hat{R}$; the calculation of $\hat{R}$ is computed with each of the chains split in half. | What is the difference between R hat and psrf?
$\hat{R}$ and "potential scale reduction factor" refer to the same thing. See Chapter 6 of the Handbook of Markov Chain Monte Carlo, "Inference from Simulations and Monitoring Convergence" by Andrew G |
32,070 | Justifying the use of finite population correction | You are correct about the second scenario, for the reason you give, but not about the first scenario. The theory of the finite population correction (fpc) applies only to a random sample without replacement (Lohr (2009) Sec 2.8,pp 51-530. The key word is random. The hallmark of a random sample is that selection is determined by random numbers or the physical equivalent. In your first scenario the 45% of the population who responded were not selected by random numbers. The same would be true if the 45% were part of an even large random sample of the population: response is not governed by random numbers.
Even if you have a sample of a substantial part of the population with (near) 100% response, you should still omit the fpc if the purpose of your study is to develop predictions, estimate odds ratios, or to otherwise test hypotheses or quote p-values. The reasoning is interesting (Cochran, 1977, p.39): For a finite population it is seldom of scientific interest to ask if a null hypothesis (e.g. that two proportions are equal) is exactly true. Except by a very rare chance, it will not be, as one would discover this by enumerating the entire population. This leads to the adoption of a "superpopulation" viewpoint, which is taken by almost all statisticians these days. Your second scenario is a variant of this. See also Deming(1966) pp 247-261 "Distinction between enumerative and analystic studies"; Korn and Graubard (1999), p. 227.
ADDED NOV 26
I should have noted that the finite population correction is a minor concern here. The major problem is the 55% non-response and the subsequent non-response bias. Survey professionals universally agree that it is better to take a smaller manageable sample and to focus on reducing non-response by personalizing the initial contacts and by following-up with non-responders. Post-survey weighting fixes may also help, but will increase standard errors.
In summary, to answer your three questions:
Your interpretation of the first scenario is incorrect.
You really don't need to say anything. If your goal is to describe only the finite population from which you drew the sample, then you can mention that you omit the fpc because the effect is miniscule. Otherwise, when you do hypothesis testing or prediction, you could mention that omit the fpc, but I've never seen anyone do it.
The decision of whether to use the fpc is the assessment you describe in the question.
So the answer is "Yes".
Additional discussion See a related CV discussion here.
References
Cochran, W. G. (1977). Sampling techniques (3rd Ed.). New York: Wiley.
Deming, W. E. (1966). Some theory of sampling. New York: Dover Publications.
Korn, E. L., & Graubard, B. I. (1999). Analysis of health surveys (Wiley series in probability and statistics). New York: Wiley.
Levy, Paul S, and Stanley Lemeshow. 2008. Sampling of populations : methods and applications. Wiley series in survey methodology. Hoboken, N.J: Wiley.
Lohr, Sharon L. 2009. Sampling: Design and Analysis. Boston, MA: Cengage Brooks/Cole. | Justifying the use of finite population correction | You are correct about the second scenario, for the reason you give, but not about the first scenario. The theory of the finite population correction (fpc) applies only to a random sample without repla | Justifying the use of finite population correction
You are correct about the second scenario, for the reason you give, but not about the first scenario. The theory of the finite population correction (fpc) applies only to a random sample without replacement (Lohr (2009) Sec 2.8,pp 51-530. The key word is random. The hallmark of a random sample is that selection is determined by random numbers or the physical equivalent. In your first scenario the 45% of the population who responded were not selected by random numbers. The same would be true if the 45% were part of an even large random sample of the population: response is not governed by random numbers.
Even if you have a sample of a substantial part of the population with (near) 100% response, you should still omit the fpc if the purpose of your study is to develop predictions, estimate odds ratios, or to otherwise test hypotheses or quote p-values. The reasoning is interesting (Cochran, 1977, p.39): For a finite population it is seldom of scientific interest to ask if a null hypothesis (e.g. that two proportions are equal) is exactly true. Except by a very rare chance, it will not be, as one would discover this by enumerating the entire population. This leads to the adoption of a "superpopulation" viewpoint, which is taken by almost all statisticians these days. Your second scenario is a variant of this. See also Deming(1966) pp 247-261 "Distinction between enumerative and analystic studies"; Korn and Graubard (1999), p. 227.
ADDED NOV 26
I should have noted that the finite population correction is a minor concern here. The major problem is the 55% non-response and the subsequent non-response bias. Survey professionals universally agree that it is better to take a smaller manageable sample and to focus on reducing non-response by personalizing the initial contacts and by following-up with non-responders. Post-survey weighting fixes may also help, but will increase standard errors.
In summary, to answer your three questions:
Your interpretation of the first scenario is incorrect.
You really don't need to say anything. If your goal is to describe only the finite population from which you drew the sample, then you can mention that you omit the fpc because the effect is miniscule. Otherwise, when you do hypothesis testing or prediction, you could mention that omit the fpc, but I've never seen anyone do it.
The decision of whether to use the fpc is the assessment you describe in the question.
So the answer is "Yes".
Additional discussion See a related CV discussion here.
References
Cochran, W. G. (1977). Sampling techniques (3rd Ed.). New York: Wiley.
Deming, W. E. (1966). Some theory of sampling. New York: Dover Publications.
Korn, E. L., & Graubard, B. I. (1999). Analysis of health surveys (Wiley series in probability and statistics). New York: Wiley.
Levy, Paul S, and Stanley Lemeshow. 2008. Sampling of populations : methods and applications. Wiley series in survey methodology. Hoboken, N.J: Wiley.
Lohr, Sharon L. 2009. Sampling: Design and Analysis. Boston, MA: Cengage Brooks/Cole. | Justifying the use of finite population correction
You are correct about the second scenario, for the reason you give, but not about the first scenario. The theory of the finite population correction (fpc) applies only to a random sample without repla |
32,071 | Justifying the use of finite population correction | I agree with the accepted answer that it would not be appropriate to utilize the finite population correction. However, I think Rubin's potential outcome framework explains why this would be inappropriate much, much more persuasively than Cochran.
Presumably, by comparing, say worker satisfaction under the old boss and the new boss, the intent is to answer a causal question. What's the average treatment effect of replacing the old boss with the new boss? Rubin says that the best way to answer a question like that is to think about it as a randomized experiment. At a specific point in time, $a_1$, there are two possibilities and two corresponding potential outcomes for each person (unit). One possibility is that the old boss is retained. Then satisfaction is measured at point $a_2$. For each unit, denote this measure as $c_i$. The other possibility is the new boss is hired. Then satisfaction is measured at point $t_2$. Denote this measure as $t_i$.
We want to compare
$$
\frac{1}{N} \sum^N_{i=1} t_i - \frac{1}{N} \sum^N_{i=1} c_i
$$
The problem is that even in a randomized experiment, we can't do that because for each unit, we always only observe either $t_i$ or $c_i$. Thus, questions of causal inference, and this extends beyond randomized experiments, are really questions about missing data.
In a randomized experiment, we have guarantees that difference between the sample mean for the treatment and control group will give us an unbiased estimate of the average treatment effect.
In your example, we're missing the whole $c_i$ vector, so it's more difficult. The key point here though is that even if you every one responds to your survey, you're missing half of the data. There are ways to try to sort of get around this (propensity scores, etc.) so here we'll just assume that you do sort of get around it.
Now you might think we can just go ahead and apply the finite population correction to our estimate of the variance of the difference in means as long as we account for the fact that the real population is $N = N_t + N_c$. However, returning to our grounding example of a randomized experiment, we see that assignment is random but not independent (assuming fixed sizes for the treatment and control group). The last unit assigned can be perfectly predicted by the assignment of the previous units.
That means we have a non-zero covariance term. Letting $W_i$ represent a binary for inclusion (1, 0), we have
$$
Var(\frac{1}{N_t} \sum^N_{i=1} W_i t_i - \frac{1}{N_c} \sum^N_{i=1} (1 - W_i) c_i) = \\ Var(\frac{1}{N_t} \sum^N_{i=1} W_i t_i) + Var(\frac{1}{N_c} \sum^N_{i=1} (1 - W_i) c_i) - 2 \cdot Cov(\frac{1}{N_t} \sum^N_{i=1} W_i t_i, \frac{1}{N_c} \sum^N_{i=1} (1 - W_i)c_i)
$$
The problem is that because we never observe $t_i$ and $c_i$ together, it turns out, we can't estimate the covariance. That forces us to take a conservative approach that approximates dropping the finite population correction.
For more details see my response here.
For a good introduction to this perspective, see Causal Inference by Rubin and Imbens. A recent article by Abadie, Athey, Imbens, Wooldridge that exploits this perspective, "Sampling-based vs. Design-based Uncertainty in
Regression Analysis", recently appeared in Econometrica. Here's a link to the pre-print. | Justifying the use of finite population correction | I agree with the accepted answer that it would not be appropriate to utilize the finite population correction. However, I think Rubin's potential outcome framework explains why this would be inappropr | Justifying the use of finite population correction
I agree with the accepted answer that it would not be appropriate to utilize the finite population correction. However, I think Rubin's potential outcome framework explains why this would be inappropriate much, much more persuasively than Cochran.
Presumably, by comparing, say worker satisfaction under the old boss and the new boss, the intent is to answer a causal question. What's the average treatment effect of replacing the old boss with the new boss? Rubin says that the best way to answer a question like that is to think about it as a randomized experiment. At a specific point in time, $a_1$, there are two possibilities and two corresponding potential outcomes for each person (unit). One possibility is that the old boss is retained. Then satisfaction is measured at point $a_2$. For each unit, denote this measure as $c_i$. The other possibility is the new boss is hired. Then satisfaction is measured at point $t_2$. Denote this measure as $t_i$.
We want to compare
$$
\frac{1}{N} \sum^N_{i=1} t_i - \frac{1}{N} \sum^N_{i=1} c_i
$$
The problem is that even in a randomized experiment, we can't do that because for each unit, we always only observe either $t_i$ or $c_i$. Thus, questions of causal inference, and this extends beyond randomized experiments, are really questions about missing data.
In a randomized experiment, we have guarantees that difference between the sample mean for the treatment and control group will give us an unbiased estimate of the average treatment effect.
In your example, we're missing the whole $c_i$ vector, so it's more difficult. The key point here though is that even if you every one responds to your survey, you're missing half of the data. There are ways to try to sort of get around this (propensity scores, etc.) so here we'll just assume that you do sort of get around it.
Now you might think we can just go ahead and apply the finite population correction to our estimate of the variance of the difference in means as long as we account for the fact that the real population is $N = N_t + N_c$. However, returning to our grounding example of a randomized experiment, we see that assignment is random but not independent (assuming fixed sizes for the treatment and control group). The last unit assigned can be perfectly predicted by the assignment of the previous units.
That means we have a non-zero covariance term. Letting $W_i$ represent a binary for inclusion (1, 0), we have
$$
Var(\frac{1}{N_t} \sum^N_{i=1} W_i t_i - \frac{1}{N_c} \sum^N_{i=1} (1 - W_i) c_i) = \\ Var(\frac{1}{N_t} \sum^N_{i=1} W_i t_i) + Var(\frac{1}{N_c} \sum^N_{i=1} (1 - W_i) c_i) - 2 \cdot Cov(\frac{1}{N_t} \sum^N_{i=1} W_i t_i, \frac{1}{N_c} \sum^N_{i=1} (1 - W_i)c_i)
$$
The problem is that because we never observe $t_i$ and $c_i$ together, it turns out, we can't estimate the covariance. That forces us to take a conservative approach that approximates dropping the finite population correction.
For more details see my response here.
For a good introduction to this perspective, see Causal Inference by Rubin and Imbens. A recent article by Abadie, Athey, Imbens, Wooldridge that exploits this perspective, "Sampling-based vs. Design-based Uncertainty in
Regression Analysis", recently appeared in Econometrica. Here's a link to the pre-print. | Justifying the use of finite population correction
I agree with the accepted answer that it would not be appropriate to utilize the finite population correction. However, I think Rubin's potential outcome framework explains why this would be inappropr |
32,072 | What is the intuition behind the Kappa statistical value in classification | The way it is usually described is the amount of agreement correct by the agreement expected by chance. However, it technically isn't corrected by chance but instead reports if the agreement is greater than by chance. Although the Kappa statistic is widely used, I believe it is most generally applied to predictive models built from unbalanced data (i.e. class distributions not equivalent). You say you understand the mathematics behind the statistic so I will not discuss it here. Let's take a look at an example using R.
# build a starting dataframe, will change shortly
df <- data.frame(act = rep(LETTERS[1:2], each=10), pred = rep(sample(LETTERS[1:2], 20, replace=T)))
# create working frequency table
tab <- table(df)
# A balanced dataset
tab[1,1] <- 45
tab[1,2] <- 5
tab[2,1] <- 5
tab[2,2] <- 45
#truncated output
caret::confusionMatrix(tab)
> caret::confusionMatrix(tab)
Confusion Matrix and Statistics
pred
act A B
A 45 5
B 5 45
Accuracy : 0.9
...
Kappa : 0.8
...
# An unbalanced datasest
tab[1,1] <- 85
tab[1,2] <- 5
tab[2,1] <- 5
tab[2,2] <- 5
caret::confusionMatrix(tab)
> caret::confusionMatrix(tab)
Confusion Matrix and Statistics
pred
act A B
A 85 5
B 5 5
Accuracy : 0.9
...
Kappa : 0.444
...
As you can see, you can have the exact same accuracy with two different datasets but very different Kappa. The idea herein being, with unbalanced data, there is a higher chance you will randomly classify the less common group so this should be accounted for in your evaluation of the model. If you dataset is balanced, you have much more flexibility with your performance metrics. It is important to keep in mind that Kappa is not always the best metric. Some pros and cons of Kappa are reported here. You should always keep in mind other methods like the AUROC (Area under the Receiver Operator Curve) and make the best informed decision for your data. | What is the intuition behind the Kappa statistical value in classification | The way it is usually described is the amount of agreement correct by the agreement expected by chance. However, it technically isn't corrected by chance but instead reports if the agreement is great | What is the intuition behind the Kappa statistical value in classification
The way it is usually described is the amount of agreement correct by the agreement expected by chance. However, it technically isn't corrected by chance but instead reports if the agreement is greater than by chance. Although the Kappa statistic is widely used, I believe it is most generally applied to predictive models built from unbalanced data (i.e. class distributions not equivalent). You say you understand the mathematics behind the statistic so I will not discuss it here. Let's take a look at an example using R.
# build a starting dataframe, will change shortly
df <- data.frame(act = rep(LETTERS[1:2], each=10), pred = rep(sample(LETTERS[1:2], 20, replace=T)))
# create working frequency table
tab <- table(df)
# A balanced dataset
tab[1,1] <- 45
tab[1,2] <- 5
tab[2,1] <- 5
tab[2,2] <- 45
#truncated output
caret::confusionMatrix(tab)
> caret::confusionMatrix(tab)
Confusion Matrix and Statistics
pred
act A B
A 45 5
B 5 45
Accuracy : 0.9
...
Kappa : 0.8
...
# An unbalanced datasest
tab[1,1] <- 85
tab[1,2] <- 5
tab[2,1] <- 5
tab[2,2] <- 5
caret::confusionMatrix(tab)
> caret::confusionMatrix(tab)
Confusion Matrix and Statistics
pred
act A B
A 85 5
B 5 5
Accuracy : 0.9
...
Kappa : 0.444
...
As you can see, you can have the exact same accuracy with two different datasets but very different Kappa. The idea herein being, with unbalanced data, there is a higher chance you will randomly classify the less common group so this should be accounted for in your evaluation of the model. If you dataset is balanced, you have much more flexibility with your performance metrics. It is important to keep in mind that Kappa is not always the best metric. Some pros and cons of Kappa are reported here. You should always keep in mind other methods like the AUROC (Area under the Receiver Operator Curve) and make the best informed decision for your data. | What is the intuition behind the Kappa statistical value in classification
The way it is usually described is the amount of agreement correct by the agreement expected by chance. However, it technically isn't corrected by chance but instead reports if the agreement is great |
32,073 | Why is usually the acceptable probability of type 1 and type 2 errors different? | Neither the 5% type one error rate nor the 80% figure for power are universal. For example, particle physicists tend to use a "5 sigma" criterion that corresponds to a notional type I error rate that is roughly on the order of one in a million. Indeed, I doubt your average physicist has even heard of Cohen.
But one reason why the two error rates you quote should be different would be that the cost of the two error types would not be the same.
As to why the type I error rate is often taken at 5%, part of the reason (some of the historical background for the convention) is discussed here. | Why is usually the acceptable probability of type 1 and type 2 errors different? | Neither the 5% type one error rate nor the 80% figure for power are universal. For example, particle physicists tend to use a "5 sigma" criterion that corresponds to a notional type I error rate that | Why is usually the acceptable probability of type 1 and type 2 errors different?
Neither the 5% type one error rate nor the 80% figure for power are universal. For example, particle physicists tend to use a "5 sigma" criterion that corresponds to a notional type I error rate that is roughly on the order of one in a million. Indeed, I doubt your average physicist has even heard of Cohen.
But one reason why the two error rates you quote should be different would be that the cost of the two error types would not be the same.
As to why the type I error rate is often taken at 5%, part of the reason (some of the historical background for the convention) is discussed here. | Why is usually the acceptable probability of type 1 and type 2 errors different?
Neither the 5% type one error rate nor the 80% figure for power are universal. For example, particle physicists tend to use a "5 sigma" criterion that corresponds to a notional type I error rate that |
32,074 | ks.test and ks.boot - exact p-values and ties | There are two points that are confused. The first one is about words "exact" and "approximate" in a statistical context. The word "exact" means that while calculations are carried out, no simplifications are used. The "approximate" p-value does not mean that the value is rounded to some precision. It means that while calculating it, some simplifications have been used. However, both "exact" and "approximate" calculations give precise numerical values. It is only our confidence that may differ. And now the second point: it is just the way of formatting output that gives you non-precise values. Actually, you are invoking the same output in different ways.
ks.test (black, red, alternative="l")$p.value
ks.test (black, red, alternative="g")$p.value
ks.test (black, red)$p.value
all give you precise (not rounded) values because you are calling the value of variables. In the last case the p-value is so small that it is lower than machine precision, and thus is listed as 0.
But, when you are just calling a function, the function gives you human-readable output. During preparing this output, the p-values are passing through the format.pval() function.
First of all, check the consistency of ks.test (black, red) and ks.test (black, red, alternative="g") - the p-values are the same in the non-precise format.
And now compare
ks.test (black, red, alternative="g")$p.value and
format.pval(ks.test (black, red, alternative="g")$p.value)
Now is it clear how that p-value < 2.2e-16 is produced?
And finally about ks.boot(). It uses bootstrapping. While ks.test() obtains the probability of test statistics from the Kolmogorov distribution (this distribution describes how test statistics are distributed when two samples really are drawn from the same distribution), ks.boot() obtains the probability of test statistics from an empirical distribution, derived under the null hypothesis. That is, the studied two samples are combined together and from this united set two new samples are drawn at random with replacement. These new samples for sure are drawn from the same distribution, and their test statistics is noted. Repeating such procedure many times, we obtain the empirical distribution of test statistics under the null hypothesis. The number of repeats you are doing is in nboots variable in ks.boot() output. You have used default value of 1000. In this way, you have simulated 1000 test statistics values under the null hypothesis. You actual test statistics is greater than all these 1000. That means that p-value at least is equal or lesser than 0.001 - that is ks.boot.p.value. Call ks.boot(red,black,nboots=10000) and you'll obtain ks.boot.p.value=0.0001. To obtain a reasonable p-value with ks.boot() your nboots should have larger (absolute) order than expected p-value do have (i.e. more than $10^{23}$). I recommend you not do this, since it'll hang up your computer or will throw memory exception. Actually, the precise p-values of such small order have no any practical usage. Indeed, they are very sensitive to small changes in data, and thus repeated experiments would result in largely different p-values, so it can be said that the less p-value is - the less confidence to it precise value should be given. | ks.test and ks.boot - exact p-values and ties | There are two points that are confused. The first one is about words "exact" and "approximate" in a statistical context. The word "exact" means that while calculations are carried out, no simplificati | ks.test and ks.boot - exact p-values and ties
There are two points that are confused. The first one is about words "exact" and "approximate" in a statistical context. The word "exact" means that while calculations are carried out, no simplifications are used. The "approximate" p-value does not mean that the value is rounded to some precision. It means that while calculating it, some simplifications have been used. However, both "exact" and "approximate" calculations give precise numerical values. It is only our confidence that may differ. And now the second point: it is just the way of formatting output that gives you non-precise values. Actually, you are invoking the same output in different ways.
ks.test (black, red, alternative="l")$p.value
ks.test (black, red, alternative="g")$p.value
ks.test (black, red)$p.value
all give you precise (not rounded) values because you are calling the value of variables. In the last case the p-value is so small that it is lower than machine precision, and thus is listed as 0.
But, when you are just calling a function, the function gives you human-readable output. During preparing this output, the p-values are passing through the format.pval() function.
First of all, check the consistency of ks.test (black, red) and ks.test (black, red, alternative="g") - the p-values are the same in the non-precise format.
And now compare
ks.test (black, red, alternative="g")$p.value and
format.pval(ks.test (black, red, alternative="g")$p.value)
Now is it clear how that p-value < 2.2e-16 is produced?
And finally about ks.boot(). It uses bootstrapping. While ks.test() obtains the probability of test statistics from the Kolmogorov distribution (this distribution describes how test statistics are distributed when two samples really are drawn from the same distribution), ks.boot() obtains the probability of test statistics from an empirical distribution, derived under the null hypothesis. That is, the studied two samples are combined together and from this united set two new samples are drawn at random with replacement. These new samples for sure are drawn from the same distribution, and their test statistics is noted. Repeating such procedure many times, we obtain the empirical distribution of test statistics under the null hypothesis. The number of repeats you are doing is in nboots variable in ks.boot() output. You have used default value of 1000. In this way, you have simulated 1000 test statistics values under the null hypothesis. You actual test statistics is greater than all these 1000. That means that p-value at least is equal or lesser than 0.001 - that is ks.boot.p.value. Call ks.boot(red,black,nboots=10000) and you'll obtain ks.boot.p.value=0.0001. To obtain a reasonable p-value with ks.boot() your nboots should have larger (absolute) order than expected p-value do have (i.e. more than $10^{23}$). I recommend you not do this, since it'll hang up your computer or will throw memory exception. Actually, the precise p-values of such small order have no any practical usage. Indeed, they are very sensitive to small changes in data, and thus repeated experiments would result in largely different p-values, so it can be said that the less p-value is - the less confidence to it precise value should be given. | ks.test and ks.boot - exact p-values and ties
There are two points that are confused. The first one is about words "exact" and "approximate" in a statistical context. The word "exact" means that while calculations are carried out, no simplificati |
32,075 | ks.test and ks.boot - exact p-values and ties | To add to the confusion, two-samples ks.test will silently resort to approximation when the product of the two sample sizes is larger than 10,000. You may want to consider this github page for an example and a solution. | ks.test and ks.boot - exact p-values and ties | To add to the confusion, two-samples ks.test will silently resort to approximation when the product of the two sample sizes is larger than 10,000. You may want to consider this github page for an exam | ks.test and ks.boot - exact p-values and ties
To add to the confusion, two-samples ks.test will silently resort to approximation when the product of the two sample sizes is larger than 10,000. You may want to consider this github page for an example and a solution. | ks.test and ks.boot - exact p-values and ties
To add to the confusion, two-samples ks.test will silently resort to approximation when the product of the two sample sizes is larger than 10,000. You may want to consider this github page for an exam |
32,076 | Understanding the Rank Probability Score | Equation 7 in Hersbach inspires me to notice that the RPS (as a discrete version of the continuous RPS, or CRPS) is a sum of several Brier quadratic probability scores (BS) evaluated over several probability thresholds. (Hersbach goes on to develop an interpretable decomposition of the CRPS for ensemble forecasts.) That is
\begin{equation}
\mathrm{RPS}=\sum\limits_{i=1}^{r} BS(i),
\end{equation}
where $BS(i)$ is the Brier score for a single forecast of the probability that the outcome of interest is one of the first $i$ (out of $r$ possible) outcomes.
Seeing the RPS as a sum of Brier scores is potentially interesting because the Brier score is a sum three interpretable components (see wikipedia, or page 754 here):
$$BS = reliability - resolution + uncertainty$$
Reliability is a measure of the absence of bias.
Resolution is somewhat analogous to the R-squared in regression (but don't look for an exact analogy since there isn't a clear definition for R-squared for predictions with binary outcomes).
Uncertainty is somewhat analogous to residual standard error in regression.
If you see the RPS as a sum (or mean) of Brier scores and if you like the Brier score decomposition mentioned above, then surely there is a way to write the RPS as a something like
$$RPS = \overline {Rel} - \overline {Res} + \overline {Unc} $$
where the terms on the right-hand-side are the means of the Brier score decomposition components over the $r$ underlying Brier scores.
Thus, in a heuristic sense, I'm guessing that the closest thing you'll get to an "R-squared" with the RPS is an "average BS R-squared" if you take the time to do the decomposition.
For a relatively rigorous discussion of this decomposition for the RPS, see equation (8b) in Candille and Talagrand. | Understanding the Rank Probability Score | Equation 7 in Hersbach inspires me to notice that the RPS (as a discrete version of the continuous RPS, or CRPS) is a sum of several Brier quadratic probability scores (BS) evaluated over several prob | Understanding the Rank Probability Score
Equation 7 in Hersbach inspires me to notice that the RPS (as a discrete version of the continuous RPS, or CRPS) is a sum of several Brier quadratic probability scores (BS) evaluated over several probability thresholds. (Hersbach goes on to develop an interpretable decomposition of the CRPS for ensemble forecasts.) That is
\begin{equation}
\mathrm{RPS}=\sum\limits_{i=1}^{r} BS(i),
\end{equation}
where $BS(i)$ is the Brier score for a single forecast of the probability that the outcome of interest is one of the first $i$ (out of $r$ possible) outcomes.
Seeing the RPS as a sum of Brier scores is potentially interesting because the Brier score is a sum three interpretable components (see wikipedia, or page 754 here):
$$BS = reliability - resolution + uncertainty$$
Reliability is a measure of the absence of bias.
Resolution is somewhat analogous to the R-squared in regression (but don't look for an exact analogy since there isn't a clear definition for R-squared for predictions with binary outcomes).
Uncertainty is somewhat analogous to residual standard error in regression.
If you see the RPS as a sum (or mean) of Brier scores and if you like the Brier score decomposition mentioned above, then surely there is a way to write the RPS as a something like
$$RPS = \overline {Rel} - \overline {Res} + \overline {Unc} $$
where the terms on the right-hand-side are the means of the Brier score decomposition components over the $r$ underlying Brier scores.
Thus, in a heuristic sense, I'm guessing that the closest thing you'll get to an "R-squared" with the RPS is an "average BS R-squared" if you take the time to do the decomposition.
For a relatively rigorous discussion of this decomposition for the RPS, see equation (8b) in Candille and Talagrand. | Understanding the Rank Probability Score
Equation 7 in Hersbach inspires me to notice that the RPS (as a discrete version of the continuous RPS, or CRPS) is a sum of several Brier quadratic probability scores (BS) evaluated over several prob |
32,077 | Understanding the Rank Probability Score | You wrote: "Taking the probability of the three outcomes to be 1/3 gives RPS values of 5/9, 2/9 and 5/9..."
That is not correct. The correct RPS values when all three outcomes are assigned equal weight is {5/18, 1/9, 5/18}. You forgot to divide by 2. | Understanding the Rank Probability Score | You wrote: "Taking the probability of the three outcomes to be 1/3 gives RPS values of 5/9, 2/9 and 5/9..."
That is not correct. The correct RPS values when all three outcomes are assigned equal weig | Understanding the Rank Probability Score
You wrote: "Taking the probability of the three outcomes to be 1/3 gives RPS values of 5/9, 2/9 and 5/9..."
That is not correct. The correct RPS values when all three outcomes are assigned equal weight is {5/18, 1/9, 5/18}. You forgot to divide by 2. | Understanding the Rank Probability Score
You wrote: "Taking the probability of the three outcomes to be 1/3 gives RPS values of 5/9, 2/9 and 5/9..."
That is not correct. The correct RPS values when all three outcomes are assigned equal weig |
32,078 | Conditional logit model and price elasticities | To estimate the matrix of own- and cross-price elasticities it is more convenient to use the asclogit command in Stata. Let's use the example in Cameron and Trivedi (2009) to show you the whole process to get this matrix. The data is on individual choices of whether to fish from the beach, the pier, a private boat or a chartered boat. They have three variables:
income is each individual's income
p is the price of each fishing alternative
q is the quantity of fish that an individual can obtain from each fishing alternative
Note that income is individual specific (a consumer characteristic) and p and q are choice specific (the product characteristics). Now let's first estimate the choice model and then obtain the matrix of own- and cross-price elasticities.
Obtain the data set and prepare it for the regression:
net from http://www.stata-press.com/data/musr
net install musr
net get musr
use mus15data.dta
reshape long d p q, i(id) j(fishmode beach pier private charter) string
Run the alternative specific clogit (asclogit) model:
asclogit d p q, case(id) alternatives(fishmode) casevar(income) basealternative(beach) nolog
Alternative-specific conditional logit Number of obs = 4728
Case variable: id Number of cases = 1182
Alternative variable: fishmode Alts per case: min = 4
avg = 4.0
max = 4
Wald chi2(5) = 252.98
Log likelihood = -1215.1376 Prob > chi2 = 0.0000
------------------------------------------------------------------------------
d | Coef. Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
fishmode |
p | -.0251166 .0017317 -14.50 0.000 -.0285106 -.0217225
q | .357782 .1097733 3.26 0.001 .1426302 .5729337
-------------+----------------------------------------------------------------
beach | (base alternative)
-------------+----------------------------------------------------------------
charter |
income | -.0332917 .0503409 -0.66 0.508 -.131958 .0653745
_cons | 1.694366 .2240506 7.56 0.000 1.255235 2.133497
-------------+----------------------------------------------------------------
pier |
income | -.1275771 .0506395 -2.52 0.012 -.2268288 -.0283255
_cons | .7779593 .2204939 3.53 0.000 .3457992 1.210119
-------------+----------------------------------------------------------------
private |
income | .0894398 .0500671 1.79 0.074 -.0086898 .1875694
_cons | .5272788 .2227927 2.37 0.018 .0906132 .9639444
------------------------------------------------------------------------------
A negative coefficient for the price means that if the price of one fishing choice increases, then the demand for this choice decreases and the demand for the other choices increases. Conversely, if the quantity of fish caught increases in one choice, the demand for this choice increases and decreases for the other choices.
Now the own- and cross price elasticities are
$$
\begin{align}
\frac{\partial p_{ij}}{\partial x_{rik}} &= p_{ij}(1-p_{ij})\beta_r, \qquad j=k \quad\text{(own-price elasticity)} \newline
\frac{\partial p_{ij}}{\partial x_{rik}} &= -p_{ij}p_{ik}\beta_r, \quad \quad \quad j \neq k \quad \text{(cross-price elasticity)}
\end{align}
$$
for the alternative choice $r$ (relative to the baseline choice; here the baseline is "beach").
The own- and cross-price elasticities are easily estimate as:
estat mfx, varlist(p)
Pr(choice = beach|1 selected) = .05248806
-------------------------------------------------------------------------------
variable | dp/dx Std. Err. z P>|z| [ 95% C.I. ] X
-------------+-----------------------------------------------------------------
p |
beach | -.001249 .000121 -10.29 0.000 -.001487 -.001011 103.42
charter | .000609 .000061 9.97 0.000 .000489 .000729 84.379
pier | .000087 .000016 5.42 0.000 .000055 .000118 103.42
private | .000553 .000056 9.88 0.000 .000443 .000663 55.257
-------------------------------------------------------------------------------
Pr(choice = charter|1 selected) = .46206853
-------------------------------------------------------------------------------
variable | dp/dx Std. Err. z P>|z| [ 95% C.I. ] X
-------------+-----------------------------------------------------------------
p |
beach | .000609 .000061 9.97 0.000 .000489 .000729 103.42
charter | -.006243 .000441 -14.15 0.000 -.007108 -.005378 84.379
pier | .000764 .000071 10.69 0.000 .000624 .000904 103.42
private | .00487 .000452 10.77 0.000 .003983 .005756 55.257
-------------------------------------------------------------------------------
Pr(choice = pier|1 selected) = .06584968
-------------------------------------------------------------------------------
variable | dp/dx Std. Err. z P>|z| [ 95% C.I. ] X
-------------+-----------------------------------------------------------------
p |
beach | .000087 .000016 5.42 0.000 .000055 .000118 103.42
charter | .000764 .000071 10.69 0.000 .000624 .000904 84.379
pier | -.001545 .000138 -11.16 0.000 -.001816 -.001274 103.42
private | .000694 .000066 10.58 0.000 .000565 .000822 55.257
-------------------------------------------------------------------------------
Pr(choice = private|1 selected) = .41959373
-------------------------------------------------------------------------------
variable | dp/dx Std. Err. z P>|z| [ 95% C.I. ] X
-------------+-----------------------------------------------------------------
p |
beach | .000553 .000056 9.88 0.000 .000443 .000663 103.42
charter | .00487 .000452 10.77 0.000 .003983 .005756 84.379
pier | .000694 .000066 10.58 0.000 .000565 .000822 103.42
private | -.006117 .000444 -13.77 0.000 -.006987 -.005246 55.257
-------------------------------------------------------------------------------
All the own-price elasticities are negative and the cross-price elasticities are positive which makes sense. The own-price elasticity of -.001249 means that a 1 Dollar increase from the mean of p (price) of fishing at the beach reduces the probability that beach fishing is chosen by 0.001249 for an individual with mean income and mean q (fish caught).
So all elasticities are expressed relative to the mean values of income, p, and q.
The cross-price elasticity .000609 tells you that if the price for fishing from a charter boat increases by 1 Dollar, the probability that beach fishing is chosen increases by .000609. The result is not in matrix format but you can easily take each dp/dx block from the results (each of which is a column for your final matrix) and put them together as a matrix of own- and cross-price elasticities where the own-price elasticities are on the principal diagonal and the cross-price elasticities are off diagonal like this:
beach charter pier private
------------------------------------------------
beach | -.001249 .000609 .000087 .000553
charter | .000609 -.006243 .000764 .00487
pier | .000087 .000764 -.001545 .000694
private | .000553 .00487 .000694 -.006117
The fishing choice example seems trivial but it should now be straightforward for you to apply your own demand estimation problem to the code provided. For more information on estimating these price elasticities or the asclogit command have a look at Cameron and Trivedi (2009) "Microeconometrics Using Stata". | Conditional logit model and price elasticities | To estimate the matrix of own- and cross-price elasticities it is more convenient to use the asclogit command in Stata. Let's use the example in Cameron and Trivedi (2009) to show you the whole proces | Conditional logit model and price elasticities
To estimate the matrix of own- and cross-price elasticities it is more convenient to use the asclogit command in Stata. Let's use the example in Cameron and Trivedi (2009) to show you the whole process to get this matrix. The data is on individual choices of whether to fish from the beach, the pier, a private boat or a chartered boat. They have three variables:
income is each individual's income
p is the price of each fishing alternative
q is the quantity of fish that an individual can obtain from each fishing alternative
Note that income is individual specific (a consumer characteristic) and p and q are choice specific (the product characteristics). Now let's first estimate the choice model and then obtain the matrix of own- and cross-price elasticities.
Obtain the data set and prepare it for the regression:
net from http://www.stata-press.com/data/musr
net install musr
net get musr
use mus15data.dta
reshape long d p q, i(id) j(fishmode beach pier private charter) string
Run the alternative specific clogit (asclogit) model:
asclogit d p q, case(id) alternatives(fishmode) casevar(income) basealternative(beach) nolog
Alternative-specific conditional logit Number of obs = 4728
Case variable: id Number of cases = 1182
Alternative variable: fishmode Alts per case: min = 4
avg = 4.0
max = 4
Wald chi2(5) = 252.98
Log likelihood = -1215.1376 Prob > chi2 = 0.0000
------------------------------------------------------------------------------
d | Coef. Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
fishmode |
p | -.0251166 .0017317 -14.50 0.000 -.0285106 -.0217225
q | .357782 .1097733 3.26 0.001 .1426302 .5729337
-------------+----------------------------------------------------------------
beach | (base alternative)
-------------+----------------------------------------------------------------
charter |
income | -.0332917 .0503409 -0.66 0.508 -.131958 .0653745
_cons | 1.694366 .2240506 7.56 0.000 1.255235 2.133497
-------------+----------------------------------------------------------------
pier |
income | -.1275771 .0506395 -2.52 0.012 -.2268288 -.0283255
_cons | .7779593 .2204939 3.53 0.000 .3457992 1.210119
-------------+----------------------------------------------------------------
private |
income | .0894398 .0500671 1.79 0.074 -.0086898 .1875694
_cons | .5272788 .2227927 2.37 0.018 .0906132 .9639444
------------------------------------------------------------------------------
A negative coefficient for the price means that if the price of one fishing choice increases, then the demand for this choice decreases and the demand for the other choices increases. Conversely, if the quantity of fish caught increases in one choice, the demand for this choice increases and decreases for the other choices.
Now the own- and cross price elasticities are
$$
\begin{align}
\frac{\partial p_{ij}}{\partial x_{rik}} &= p_{ij}(1-p_{ij})\beta_r, \qquad j=k \quad\text{(own-price elasticity)} \newline
\frac{\partial p_{ij}}{\partial x_{rik}} &= -p_{ij}p_{ik}\beta_r, \quad \quad \quad j \neq k \quad \text{(cross-price elasticity)}
\end{align}
$$
for the alternative choice $r$ (relative to the baseline choice; here the baseline is "beach").
The own- and cross-price elasticities are easily estimate as:
estat mfx, varlist(p)
Pr(choice = beach|1 selected) = .05248806
-------------------------------------------------------------------------------
variable | dp/dx Std. Err. z P>|z| [ 95% C.I. ] X
-------------+-----------------------------------------------------------------
p |
beach | -.001249 .000121 -10.29 0.000 -.001487 -.001011 103.42
charter | .000609 .000061 9.97 0.000 .000489 .000729 84.379
pier | .000087 .000016 5.42 0.000 .000055 .000118 103.42
private | .000553 .000056 9.88 0.000 .000443 .000663 55.257
-------------------------------------------------------------------------------
Pr(choice = charter|1 selected) = .46206853
-------------------------------------------------------------------------------
variable | dp/dx Std. Err. z P>|z| [ 95% C.I. ] X
-------------+-----------------------------------------------------------------
p |
beach | .000609 .000061 9.97 0.000 .000489 .000729 103.42
charter | -.006243 .000441 -14.15 0.000 -.007108 -.005378 84.379
pier | .000764 .000071 10.69 0.000 .000624 .000904 103.42
private | .00487 .000452 10.77 0.000 .003983 .005756 55.257
-------------------------------------------------------------------------------
Pr(choice = pier|1 selected) = .06584968
-------------------------------------------------------------------------------
variable | dp/dx Std. Err. z P>|z| [ 95% C.I. ] X
-------------+-----------------------------------------------------------------
p |
beach | .000087 .000016 5.42 0.000 .000055 .000118 103.42
charter | .000764 .000071 10.69 0.000 .000624 .000904 84.379
pier | -.001545 .000138 -11.16 0.000 -.001816 -.001274 103.42
private | .000694 .000066 10.58 0.000 .000565 .000822 55.257
-------------------------------------------------------------------------------
Pr(choice = private|1 selected) = .41959373
-------------------------------------------------------------------------------
variable | dp/dx Std. Err. z P>|z| [ 95% C.I. ] X
-------------+-----------------------------------------------------------------
p |
beach | .000553 .000056 9.88 0.000 .000443 .000663 103.42
charter | .00487 .000452 10.77 0.000 .003983 .005756 84.379
pier | .000694 .000066 10.58 0.000 .000565 .000822 103.42
private | -.006117 .000444 -13.77 0.000 -.006987 -.005246 55.257
-------------------------------------------------------------------------------
All the own-price elasticities are negative and the cross-price elasticities are positive which makes sense. The own-price elasticity of -.001249 means that a 1 Dollar increase from the mean of p (price) of fishing at the beach reduces the probability that beach fishing is chosen by 0.001249 for an individual with mean income and mean q (fish caught).
So all elasticities are expressed relative to the mean values of income, p, and q.
The cross-price elasticity .000609 tells you that if the price for fishing from a charter boat increases by 1 Dollar, the probability that beach fishing is chosen increases by .000609. The result is not in matrix format but you can easily take each dp/dx block from the results (each of which is a column for your final matrix) and put them together as a matrix of own- and cross-price elasticities where the own-price elasticities are on the principal diagonal and the cross-price elasticities are off diagonal like this:
beach charter pier private
------------------------------------------------
beach | -.001249 .000609 .000087 .000553
charter | .000609 -.006243 .000764 .00487
pier | .000087 .000764 -.001545 .000694
private | .000553 .00487 .000694 -.006117
The fishing choice example seems trivial but it should now be straightforward for you to apply your own demand estimation problem to the code provided. For more information on estimating these price elasticities or the asclogit command have a look at Cameron and Trivedi (2009) "Microeconometrics Using Stata". | Conditional logit model and price elasticities
To estimate the matrix of own- and cross-price elasticities it is more convenient to use the asclogit command in Stata. Let's use the example in Cameron and Trivedi (2009) to show you the whole proces |
32,079 | Conditional logit model and price elasticities | If elasticity is the changes in probability as a result of 1% change in an independent variable, then first you have to:
1- Calculate probability of model, in stata predict, p1
2-Increase interested variable by 1%, in stata: var*1.01
3-Again calculate probability, predict, p2
4-The differences between two probabilities are elasticity. E=average(p2-p1) | Conditional logit model and price elasticities | If elasticity is the changes in probability as a result of 1% change in an independent variable, then first you have to:
1- Calculate probability of model, in stata predict, p1
2-Increase interested v | Conditional logit model and price elasticities
If elasticity is the changes in probability as a result of 1% change in an independent variable, then first you have to:
1- Calculate probability of model, in stata predict, p1
2-Increase interested variable by 1%, in stata: var*1.01
3-Again calculate probability, predict, p2
4-The differences between two probabilities are elasticity. E=average(p2-p1) | Conditional logit model and price elasticities
If elasticity is the changes in probability as a result of 1% change in an independent variable, then first you have to:
1- Calculate probability of model, in stata predict, p1
2-Increase interested v |
32,080 | Conditional logit model and price elasticities | The equations in above answer are the marginal effect, not the elasticity.
Please check a seminal book by Prof. KE, Train.
See pp.57--60 in https://eml.berkeley.edu/books/choice2nd/Ch03_p34-75.pdf. | Conditional logit model and price elasticities | The equations in above answer are the marginal effect, not the elasticity.
Please check a seminal book by Prof. KE, Train.
See pp.57--60 in https://eml.berkeley.edu/books/choice2nd/Ch03_p34-75.pdf. | Conditional logit model and price elasticities
The equations in above answer are the marginal effect, not the elasticity.
Please check a seminal book by Prof. KE, Train.
See pp.57--60 in https://eml.berkeley.edu/books/choice2nd/Ch03_p34-75.pdf. | Conditional logit model and price elasticities
The equations in above answer are the marginal effect, not the elasticity.
Please check a seminal book by Prof. KE, Train.
See pp.57--60 in https://eml.berkeley.edu/books/choice2nd/Ch03_p34-75.pdf. |
32,081 | Understanding the output of SVD when used for PCA [duplicate] | I think the first thing to remember is that given a matrix $A$ is $A = U \Sigma V^T$ (singular value decomposition) that decomposition is the same as $A = S \Lambda S^{-1}$ (eigenvalue decomposition) if $A$ is a positive (semi) definite symmetric matrix, ie. $ A = Q \Lambda Q^T$. Having said that and going back to your first question: Yeap, it is plausible that the singular values are numerically the same as the eigenvalues. Generally speaking, as shown below and noted by @amoeba, the singular values are the square roots of the non-zero eigenvalues of $A^TA$.
Coming to your second question: Assuming $A_{m \times n} = U \Sigma V^T$, the eigenvector you are looking for are in $V$ where as $U$ and $V$ are unitary matrices: $V^T V = I_n$ and $U^T U = I_m$. I think this point also answers your third question. To make this more clear: $A = U \Sigma V^T \rightarrow A^T A = V \Sigma^T U^T U\Sigma V^T \rightarrow V \Sigma^2 V^T$ because $\Sigma^T = \Sigma$ and $U^T U = I$. So $\Sigma^2$ = $\Lambda$. (Be carefully you most probably need to use a normalizing factor $\frac{1}{n-1}$ to achieve this equality.)
Regarding your final point: I usually work on the $m > n$ domain so the eigen-decomposition of the covariance function is more efficient; so that takes care of the centring immediately. Having said that: Yes, your intuition is correct; no, if you are looking to use $SVD$ to calculate principal components you do not need to centre your data first. There is a nice discussion of this topic in the following thread: When should you center your data & when should you standardize?
My first references regarding $SVD$ and its connection to eigen-decomposition are G.Strang's Introduction to Linear Algebra, Chapt. 6 Sect. 7 and I.T. Jolliffe's Principal Component Analysis, Chapt. 3 Sect. 5. Both are usually easily available as worn library copies and should serve as a good introduction if you wish to visit more advanced texts latter on. | Understanding the output of SVD when used for PCA [duplicate] | I think the first thing to remember is that given a matrix $A$ is $A = U \Sigma V^T$ (singular value decomposition) that decomposition is the same as $A = S \Lambda S^{-1}$ (eigenvalue decomposition) | Understanding the output of SVD when used for PCA [duplicate]
I think the first thing to remember is that given a matrix $A$ is $A = U \Sigma V^T$ (singular value decomposition) that decomposition is the same as $A = S \Lambda S^{-1}$ (eigenvalue decomposition) if $A$ is a positive (semi) definite symmetric matrix, ie. $ A = Q \Lambda Q^T$. Having said that and going back to your first question: Yeap, it is plausible that the singular values are numerically the same as the eigenvalues. Generally speaking, as shown below and noted by @amoeba, the singular values are the square roots of the non-zero eigenvalues of $A^TA$.
Coming to your second question: Assuming $A_{m \times n} = U \Sigma V^T$, the eigenvector you are looking for are in $V$ where as $U$ and $V$ are unitary matrices: $V^T V = I_n$ and $U^T U = I_m$. I think this point also answers your third question. To make this more clear: $A = U \Sigma V^T \rightarrow A^T A = V \Sigma^T U^T U\Sigma V^T \rightarrow V \Sigma^2 V^T$ because $\Sigma^T = \Sigma$ and $U^T U = I$. So $\Sigma^2$ = $\Lambda$. (Be carefully you most probably need to use a normalizing factor $\frac{1}{n-1}$ to achieve this equality.)
Regarding your final point: I usually work on the $m > n$ domain so the eigen-decomposition of the covariance function is more efficient; so that takes care of the centring immediately. Having said that: Yes, your intuition is correct; no, if you are looking to use $SVD$ to calculate principal components you do not need to centre your data first. There is a nice discussion of this topic in the following thread: When should you center your data & when should you standardize?
My first references regarding $SVD$ and its connection to eigen-decomposition are G.Strang's Introduction to Linear Algebra, Chapt. 6 Sect. 7 and I.T. Jolliffe's Principal Component Analysis, Chapt. 3 Sect. 5. Both are usually easily available as worn library copies and should serve as a good introduction if you wish to visit more advanced texts latter on. | Understanding the output of SVD when used for PCA [duplicate]
I think the first thing to remember is that given a matrix $A$ is $A = U \Sigma V^T$ (singular value decomposition) that decomposition is the same as $A = S \Lambda S^{-1}$ (eigenvalue decomposition) |
32,082 | Understanding the output of SVD when used for PCA [duplicate] | The answers to your questions are as follows:
No, this is incorrect: singular values of the data matrix (your $s$) are equal to the square roots of the eigenvalues of the covariance matrix, up to a scaling factor $\sqrt{N-1}$ where $N$ is the number of data points.
Eigenvectors of the covariance (NB: covariance! not correlation) matrix are given by the columns of $U$.
Almost correct: columns of $V$ are principal components, i.e. projections on the principle axes, but scaled to unit norm! Principal components themselves are given by columns of $V$, each multiplied by the respective singular value. | Understanding the output of SVD when used for PCA [duplicate] | The answers to your questions are as follows:
No, this is incorrect: singular values of the data matrix (your $s$) are equal to the square roots of the eigenvalues of the covariance matrix, up to a s | Understanding the output of SVD when used for PCA [duplicate]
The answers to your questions are as follows:
No, this is incorrect: singular values of the data matrix (your $s$) are equal to the square roots of the eigenvalues of the covariance matrix, up to a scaling factor $\sqrt{N-1}$ where $N$ is the number of data points.
Eigenvectors of the covariance (NB: covariance! not correlation) matrix are given by the columns of $U$.
Almost correct: columns of $V$ are principal components, i.e. projections on the principle axes, but scaled to unit norm! Principal components themselves are given by columns of $V$, each multiplied by the respective singular value. | Understanding the output of SVD when used for PCA [duplicate]
The answers to your questions are as follows:
No, this is incorrect: singular values of the data matrix (your $s$) are equal to the square roots of the eigenvalues of the covariance matrix, up to a s |
32,083 | Understanding the output of SVD when used for PCA [duplicate] | The two functions linked below compute the PCA using either np.linalg.eig or np.linalg.svd. It should help you get there for going between the two. There's a larger PCA class in that module that you might be interested in. I'd like to hear some feedback on the PCA class if you do end up using it. I'm still adding features before we merge that in.
You can see the PR here. It won't let me post a deep link for some reason, so look for def _pca_svd and def _pca_eig. | Understanding the output of SVD when used for PCA [duplicate] | The two functions linked below compute the PCA using either np.linalg.eig or np.linalg.svd. It should help you get there for going between the two. There's a larger PCA class in that module that you m | Understanding the output of SVD when used for PCA [duplicate]
The two functions linked below compute the PCA using either np.linalg.eig or np.linalg.svd. It should help you get there for going between the two. There's a larger PCA class in that module that you might be interested in. I'd like to hear some feedback on the PCA class if you do end up using it. I'm still adding features before we merge that in.
You can see the PR here. It won't let me post a deep link for some reason, so look for def _pca_svd and def _pca_eig. | Understanding the output of SVD when used for PCA [duplicate]
The two functions linked below compute the PCA using either np.linalg.eig or np.linalg.svd. It should help you get there for going between the two. There's a larger PCA class in that module that you m |
32,084 | Switchpoint detection with probabilistic programming (pymc) | SeanEaster has some good advice. Bayes factor can be difficult to compute, but there are some good blog posts specifically for Bayes factor in PyMC2.
A closly related question is goodness-of-fit of a model. A fair method for this is just inspection - posteriors can give us evidence of goodness-of-fit. Like quoted:
"Had no change occurred, or had the change been gradual over time, the posterior distribution of $\tau$ would have been more spread out"
This is true. The posterior is quite peaked near time 45. As you say > 50% of the mass is at 45, whereas if there was no switch point the mass should (theoretically) be closer to 1/80 = 1.125% at time 45.
What you are aiming to do is faithfully reconstruct the observed data set, given your model. In Chapter 2, their are simulations of generating fake data. If your observed data looks wildly different from your artificial data, then likely your model is not the correct fit.
I apologize for the non-rigourous answer, but really it's a major difficulty that I haven't efficiently overcome. | Switchpoint detection with probabilistic programming (pymc) | SeanEaster has some good advice. Bayes factor can be difficult to compute, but there are some good blog posts specifically for Bayes factor in PyMC2.
A closly related question is goodness-of-fit of a | Switchpoint detection with probabilistic programming (pymc)
SeanEaster has some good advice. Bayes factor can be difficult to compute, but there are some good blog posts specifically for Bayes factor in PyMC2.
A closly related question is goodness-of-fit of a model. A fair method for this is just inspection - posteriors can give us evidence of goodness-of-fit. Like quoted:
"Had no change occurred, or had the change been gradual over time, the posterior distribution of $\tau$ would have been more spread out"
This is true. The posterior is quite peaked near time 45. As you say > 50% of the mass is at 45, whereas if there was no switch point the mass should (theoretically) be closer to 1/80 = 1.125% at time 45.
What you are aiming to do is faithfully reconstruct the observed data set, given your model. In Chapter 2, their are simulations of generating fake data. If your observed data looks wildly different from your artificial data, then likely your model is not the correct fit.
I apologize for the non-rigourous answer, but really it's a major difficulty that I haven't efficiently overcome. | Switchpoint detection with probabilistic programming (pymc)
SeanEaster has some good advice. Bayes factor can be difficult to compute, but there are some good blog posts specifically for Bayes factor in PyMC2.
A closly related question is goodness-of-fit of a |
32,085 | Switchpoint detection with probabilistic programming (pymc) | That's more of a model comparison question: The interest is in whether a model without a switchpoint better explains the data than a model with a switchpoint. One approach to answer that question is to compute the Bayes factor of models with and without a switchpoint. In short, the Bayes factor is the ratio of probabilities of the data under both models:
$K = \frac{\Pr(D|M_1)}{\Pr(D|M_2)} =\frac{\int\Pr(\theta_1|M_1)\Pr(D|\theta_1,M_1)\,d\theta_1}{\int \Pr(\theta_2|M_2)\Pr(D|\theta_2,M_2)\,d\theta_2}$
If $M_1$ is the model using a switchpoint, and $M_2$ is the model without, then a high value for $K$ can be interpreted as strongly favoring the switchpoint model. (The wikipedia article linked above gives guidelines for what K values are noteworthy.)
Also note that in an MCMC context the above integrals would be replaced with sums of parameter values from the MCMC chains. A more thorough treatment of Bayes factors, with examples, is available here.
To the question of computing the probability of a switchpoint, that's equivalent to solving for $P(M_1|D)$. If you assume equal priors across the two models, then the posterior odds of the models are equivalent to the Bayes factor. (See slide 5 here.) Then it's just a matter of solving for $P(M_1|D)$ using the Bayes factor and the requirement that $\sum\limits_{i=1}^n P(M_i|D) = 1$ for n (exclusive) model events under consideration. | Switchpoint detection with probabilistic programming (pymc) | That's more of a model comparison question: The interest is in whether a model without a switchpoint better explains the data than a model with a switchpoint. One approach to answer that question is t | Switchpoint detection with probabilistic programming (pymc)
That's more of a model comparison question: The interest is in whether a model without a switchpoint better explains the data than a model with a switchpoint. One approach to answer that question is to compute the Bayes factor of models with and without a switchpoint. In short, the Bayes factor is the ratio of probabilities of the data under both models:
$K = \frac{\Pr(D|M_1)}{\Pr(D|M_2)} =\frac{\int\Pr(\theta_1|M_1)\Pr(D|\theta_1,M_1)\,d\theta_1}{\int \Pr(\theta_2|M_2)\Pr(D|\theta_2,M_2)\,d\theta_2}$
If $M_1$ is the model using a switchpoint, and $M_2$ is the model without, then a high value for $K$ can be interpreted as strongly favoring the switchpoint model. (The wikipedia article linked above gives guidelines for what K values are noteworthy.)
Also note that in an MCMC context the above integrals would be replaced with sums of parameter values from the MCMC chains. A more thorough treatment of Bayes factors, with examples, is available here.
To the question of computing the probability of a switchpoint, that's equivalent to solving for $P(M_1|D)$. If you assume equal priors across the two models, then the posterior odds of the models are equivalent to the Bayes factor. (See slide 5 here.) Then it's just a matter of solving for $P(M_1|D)$ using the Bayes factor and the requirement that $\sum\limits_{i=1}^n P(M_i|D) = 1$ for n (exclusive) model events under consideration. | Switchpoint detection with probabilistic programming (pymc)
That's more of a model comparison question: The interest is in whether a model without a switchpoint better explains the data than a model with a switchpoint. One approach to answer that question is t |
32,086 | Poisson vs Binomial for rare events | More typically, the Poisson is used to approximate the binomial for situations when $p$ is small but $n$ is "large enough" for the approximation to be reasonable rather than the binomial being used to approximate the Poisson.
With large $n$, Poisson probabilities are easier to calculate. Further, the binomial requires a table for each $n,p$ combination, while the Poisson only requires one for each $\lambda$.
Another advantage of using the Poisson: when looking at the distribution of the sum of two (or more) binomials with different $p$ -- each of which is well approximated by a Poisson -- the sum won't be binomial, but will still be approximately Poisson.
You could sometimes use a binomial to approximate a Poisson, but there would usually be little reason to do so; generally either the Poisson is such that it would be at least as convenient to use the Poisson, or a normal approximation will suffice for both. | Poisson vs Binomial for rare events | More typically, the Poisson is used to approximate the binomial for situations when $p$ is small but $n$ is "large enough" for the approximation to be reasonable rather than the binomial being used to | Poisson vs Binomial for rare events
More typically, the Poisson is used to approximate the binomial for situations when $p$ is small but $n$ is "large enough" for the approximation to be reasonable rather than the binomial being used to approximate the Poisson.
With large $n$, Poisson probabilities are easier to calculate. Further, the binomial requires a table for each $n,p$ combination, while the Poisson only requires one for each $\lambda$.
Another advantage of using the Poisson: when looking at the distribution of the sum of two (or more) binomials with different $p$ -- each of which is well approximated by a Poisson -- the sum won't be binomial, but will still be approximately Poisson.
You could sometimes use a binomial to approximate a Poisson, but there would usually be little reason to do so; generally either the Poisson is such that it would be at least as convenient to use the Poisson, or a normal approximation will suffice for both. | Poisson vs Binomial for rare events
More typically, the Poisson is used to approximate the binomial for situations when $p$ is small but $n$ is "large enough" for the approximation to be reasonable rather than the binomial being used to |
32,087 | CLT can be used for weighted sum of different Bernoulli variables? | Either the Lyapunov CLT or the Lindeberg CLT will be what you seek.
In each case let $X_i\,=\,w_i\,z_i$ and apply the theorems as given there to the $X_i$.
In a great many cases of the kind you suggest (and likely all that you care about), checking Lyapunov's condition should be sufficient.
However, unless you have some weird edge case, I think Lindeberg's should work in all cases of the kind you need. | CLT can be used for weighted sum of different Bernoulli variables? | Either the Lyapunov CLT or the Lindeberg CLT will be what you seek.
In each case let $X_i\,=\,w_i\,z_i$ and apply the theorems as given there to the $X_i$.
In a great many cases of the kind you sugges | CLT can be used for weighted sum of different Bernoulli variables?
Either the Lyapunov CLT or the Lindeberg CLT will be what you seek.
In each case let $X_i\,=\,w_i\,z_i$ and apply the theorems as given there to the $X_i$.
In a great many cases of the kind you suggest (and likely all that you care about), checking Lyapunov's condition should be sufficient.
However, unless you have some weird edge case, I think Lindeberg's should work in all cases of the kind you need. | CLT can be used for weighted sum of different Bernoulli variables?
Either the Lyapunov CLT or the Lindeberg CLT will be what you seek.
In each case let $X_i\,=\,w_i\,z_i$ and apply the theorems as given there to the $X_i$.
In a great many cases of the kind you sugges |
32,088 | Does RandomForest ignore spatial independence? | It has no problem with spatial autocorrelation of your response or explanatory variables. It's a totally non-parametric technique. I have used it for the interpolation of structural diversity variables across my country based on in situ data from a regular grid and introducing the coordinates as covariables even produces better predictions. This is because Random Forest is based on a divide and conquer approach (classification and regression trees), meaning it separates your feature space into disjoint subsets where simpler models (by default a simple average in the case of regression) can produce good predictions. Introducing the coordinates as variables, in my case, exploits spatial autocorrelation as it makes sense that certain geographic subsets of the country behave homogeneously. | Does RandomForest ignore spatial independence? | It has no problem with spatial autocorrelation of your response or explanatory variables. It's a totally non-parametric technique. I have used it for the interpolation of structural diversity variable | Does RandomForest ignore spatial independence?
It has no problem with spatial autocorrelation of your response or explanatory variables. It's a totally non-parametric technique. I have used it for the interpolation of structural diversity variables across my country based on in situ data from a regular grid and introducing the coordinates as covariables even produces better predictions. This is because Random Forest is based on a divide and conquer approach (classification and regression trees), meaning it separates your feature space into disjoint subsets where simpler models (by default a simple average in the case of regression) can produce good predictions. Introducing the coordinates as variables, in my case, exploits spatial autocorrelation as it makes sense that certain geographic subsets of the country behave homogeneously. | Does RandomForest ignore spatial independence?
It has no problem with spatial autocorrelation of your response or explanatory variables. It's a totally non-parametric technique. I have used it for the interpolation of structural diversity variable |
32,089 | Why would scaling features decrease SVM performance? | The problem is that you used the default parameter values in both cases. Apparently, the default values happened to be better for your data set before scaling (this is a coincidence).
When using SVM, the parameters $c$ and $\gamma$ play a crucial role and it is your task to find the best values. Your intuition is correct: the optimal performance is better when all features are scaled properly (or at least 99.99% of the time). Unfortunately, neither of your settings had optimal parameters which led to a result that seemed to reject your intuition.
Searching the optimal values for $c$ and $\gamma$ is typically done via a grid search (e.g. search a set of $<c,\gamma>$ combinations). You can estimate the performance of an SVM for a given set of parameters using cross-validation.
In pseudo-code, the general idea is this:
for c in {set of possible c values}
for gamma in {set of possible gamma values}
perform k-fold cross-validation to find accuracy
end
end
train svm model on full training set with best c,gamma-pair
You can find a good beginner's tutorial here. | Why would scaling features decrease SVM performance? | The problem is that you used the default parameter values in both cases. Apparently, the default values happened to be better for your data set before scaling (this is a coincidence).
When using SVM, | Why would scaling features decrease SVM performance?
The problem is that you used the default parameter values in both cases. Apparently, the default values happened to be better for your data set before scaling (this is a coincidence).
When using SVM, the parameters $c$ and $\gamma$ play a crucial role and it is your task to find the best values. Your intuition is correct: the optimal performance is better when all features are scaled properly (or at least 99.99% of the time). Unfortunately, neither of your settings had optimal parameters which led to a result that seemed to reject your intuition.
Searching the optimal values for $c$ and $\gamma$ is typically done via a grid search (e.g. search a set of $<c,\gamma>$ combinations). You can estimate the performance of an SVM for a given set of parameters using cross-validation.
In pseudo-code, the general idea is this:
for c in {set of possible c values}
for gamma in {set of possible gamma values}
perform k-fold cross-validation to find accuracy
end
end
train svm model on full training set with best c,gamma-pair
You can find a good beginner's tutorial here. | Why would scaling features decrease SVM performance?
The problem is that you used the default parameter values in both cases. Apparently, the default values happened to be better for your data set before scaling (this is a coincidence).
When using SVM, |
32,090 | How to test whether the variance of two distributions is different if the distributions are not normal | Are these distributions of something over time? Counts, perhaps? (If so then you might need something quite different from the discussions here so far)
What you describe doesn't sound like it would be very well picked up as a difference in variance of the distributions.
It sounds like you're describing something vaguely like this (ignore the numbers on the axes, it's just to give a sense of the general kind of pattern you seem to be describing):
If that's right, then consider:
While the width of each peak about the local centers is narrower for the blue curve, the variance of the red and blue distributions overall hardly differs.
If you identify the modes and antimodes beforehand, you could then measure the local variability. | How to test whether the variance of two distributions is different if the distributions are not norm | Are these distributions of something over time? Counts, perhaps? (If so then you might need something quite different from the discussions here so far)
What you describe doesn't sound like it would be | How to test whether the variance of two distributions is different if the distributions are not normal
Are these distributions of something over time? Counts, perhaps? (If so then you might need something quite different from the discussions here so far)
What you describe doesn't sound like it would be very well picked up as a difference in variance of the distributions.
It sounds like you're describing something vaguely like this (ignore the numbers on the axes, it's just to give a sense of the general kind of pattern you seem to be describing):
If that's right, then consider:
While the width of each peak about the local centers is narrower for the blue curve, the variance of the red and blue distributions overall hardly differs.
If you identify the modes and antimodes beforehand, you could then measure the local variability. | How to test whether the variance of two distributions is different if the distributions are not norm
Are these distributions of something over time? Counts, perhaps? (If so then you might need something quite different from the discussions here so far)
What you describe doesn't sound like it would be |
32,091 | How to test whether the variance of two distributions is different if the distributions are not normal | First of all, I think that you should look at the seasonal distributions separately, since the bimodal distribution is likely to be the outcome of two fairly separate processes. The two distributions might be controlled by different mechanisms, so that e.g. winter distributions could be more sensitive to yearly climate. If you want to look at population differences and reasons for these I think it is therefore more useful to study the seasonal distributions separately.
As for a test, you could try Levine's test (basically a test of homoscedasticity), which is used to compare variances between groups. Bartlett's test is an alternative, but Levene's test is supposed to be more robust to non-normality (especially when using the median for testing). In R the Levene's and Bartlett's tests are found in library(car). | How to test whether the variance of two distributions is different if the distributions are not norm | First of all, I think that you should look at the seasonal distributions separately, since the bimodal distribution is likely to be the outcome of two fairly separate processes. The two distributions | How to test whether the variance of two distributions is different if the distributions are not normal
First of all, I think that you should look at the seasonal distributions separately, since the bimodal distribution is likely to be the outcome of two fairly separate processes. The two distributions might be controlled by different mechanisms, so that e.g. winter distributions could be more sensitive to yearly climate. If you want to look at population differences and reasons for these I think it is therefore more useful to study the seasonal distributions separately.
As for a test, you could try Levine's test (basically a test of homoscedasticity), which is used to compare variances between groups. Bartlett's test is an alternative, but Levene's test is supposed to be more robust to non-normality (especially when using the median for testing). In R the Levene's and Bartlett's tests are found in library(car). | How to test whether the variance of two distributions is different if the distributions are not norm
First of all, I think that you should look at the seasonal distributions separately, since the bimodal distribution is likely to be the outcome of two fairly separate processes. The two distributions |
32,092 | How to test whether the variance of two distributions is different if the distributions are not normal | I agree with what others have said -- namely that "variance" is probably the wrong word to use (seeing as the function you are considering isn't a probability distribution but a time-series).
I think you may want to approach this problem from a different perspective -- just fit the two time series with LOWESS curves. You can calculate 95% confidence intervals and qualitatively comment on their shapes. I'm not sure you need to do anything more fancy than this.
I've written some MATLAB code below to illustrate what I'm saying. I'm in a bit of a rush but can provide clarifications soon. Much of what I did can be taken directly from here: http://blogs.mathworks.com/loren/2011/01/13/data-driven-fitting/
%% Generate Example data
npts = 200;
x = linspace(1,100,npts)';
y1 = (1e3*exp(-(x-25).^2/20) + 5e2*exp(-(x-65).^2/40));
y1_noisy = 50*randn(npts,1) + y1;
y2 = (1e3*exp(-(x-25).^2/60) + 5e2*exp(-(x-65).^2/100));
y2_noisy = 50*randn(npts,1) + y2;
figure; hold on
plot(x,y1_noisy,'ob')
plot(x,y2_noisy,'or')
title('raw data'); ylabel('count'); xlabel('time')
legend('y1','y2')
You may want to normalize the two time-series to compare their relative trends rather than their absolute levels.
%% Normalize data sets
figure; hold on
Y1 = y1_noisy./norm(y1_noisy);
Y2 = y2_noisy./norm(y2_noisy);
plot(x,Y1,'ob')
plot(x,Y2,'or')
title('normalized data'); ylabel('normalized count'); xlabel('time')
legend('Y1','Y2')
Now make LOWESS fits...
%% Make figure with lowess fits
figure; hold on
plot(x,Y1,'o','Color',[0.5 0.5 1])
plot(x,Y2,'o','Color',[1 0.5 0.5])
plot(x,mylowess([x,Y1],x,0.15),'-b','LineWidth',2)
plot(x,mylowess([x,Y2],x,0.15),'-r','LineWidth',2)
title('fit data'); ylabel('normalized count'); xlabel('time')
Finally, you can create 95% confidence bands as follows:
%% Use Bootstrapping to determine 95% confidence bands
figure; hold on
plot(x,Y1,'o','Color',[0.75 0.75 1])
plot(x,Y2,'o','Color',[1 0.75 0.75])
f = @(xy) mylowess(xy,x,0.15);
yboot_1 = bootstrp(1000,f,[x,Y1])';
yboot_2 = bootstrp(1000,f,[x,Y2])';
meanloess(:,1) = mean(yboot_1,2);
meanloess(:,2) = mean(yboot_2,2);
upper(:,1) = quantile(yboot_1,0.975,2);
upper(:,2) = quantile(yboot_2,0.975,2);
lower(:,1) = quantile(yboot_1,0.025,2);
lower(:,2) = quantile(yboot_2,0.025,2);
plot(x,meanloess(:,1),'-b','LineWidth',2);
plot(x,meanloess(:,2),'-r','LineWidth',2);
plot(x,upper(:,1),':b');
plot(x,upper(:,2),':r');
plot(x,lower(:,1),':b');
plot(x,lower(:,2),':r');
title('fit data -- with confidence bands'); ylabel('normalized count'); xlabel('time')
Now you can interpret the final figure as you wish, and you have the LOWESS fits to back up your hypothesis that the peaks in the red curve are actually broader than the blue curve. If you have a better idea of what the function is you could do non-linear regression instead.
Edit: Based on some helpful comments below, I am adding some more details about estimating peak widths explicitly. First, you need to come up with some definition for what you are considering a "peak" to be in the first place. Perhaps any bump that rises above some threshold (something like 0.05 in the plots I made above). The basic principle is that you should find a way from separating "real" or "notable" peaks from noise.
Then, for each peak, you can measure its width in a couple of ways. As I mentioned in the comments below, I think it is reasonable to look at the "half-max-width" but you could also look at the total time the peak stands above your threshold. Ideally, you should use several different measures of peak width and report how consistent your results were given these choices.
Whatever your metric(s) of choice, you can use bootstrapping to calculate a confidence interval for each peak in each trace.
f = @(xy) mylowess(xy,x,0.15);
N_boot = 1000;
yboot_1 = bootstrp(N_boot,f,[x,Y1])';
yboot_2 = bootstrp(N_boot,f,[x,Y2])';
This code creates 1000 bootstrapped fits for the blue and red traces in the plots above. One detail that I will gloss over is the choice of the smoothing factor 0.15 -- you can choose this parameter such that it minimizes cross validation error (see the link I posted). Now all you have to do is write a function that isolates the peaks and estimates their width:
function [t_peaks,heights,widths] = getPeaks(t,Y)
%% Computes a list of times, heights, and widths, for each peak in a time series Y
%% (column vector) with associated time points t (column vector).
% The implementation of this function will be problem-specific...
Then you run this code on the 1000 curves for each dataset and calculate the 2.5th and 97.5th percentiles for the width of each peak. I'll illustrate this on the Y1 time series - you would do the same for the the Y2 time series or any other data set of interest.
N_peaks = 2; % two peaks in example data
t_peaks = nan(N_boot,N_peaks);
heights = nan(N_boot,N_peaks);
widths = nan(N_boot,N_peaks);
for aa = 1:N_boot
[t_peaks(aa,:),heights(aa,:),widths(aa,:)] = getPeaks(x,yboot_1(:,aa));
end
quantile(widths(:,1),[0.025 0.975]) % confidence interval for the width of first peak
quantile(widths(:,2),[0.025 0.975]) % same for second peak width
If you desire, you can perform hypothesis tests rather than calculating confidence intervals. Note that the code above is simplistic - it assumes each bootstrapped lowess curve will have 2 peaks. This assumption may not always hold, so be careful. I'm just trying to illustrate the approach I would take.
Note: the "mylowess" function is given in the link I posted above. This is what it looks like...
function ys=mylowess(xy,xs,span)
%MYLOWESS Lowess smoothing, preserving x values
% YS=MYLOWESS(XY,XS) returns the smoothed version of the x/y data in the
% two-column matrix XY, but evaluates the smooth at XS and returns the
% smoothed values in YS. Any values outside the range of XY are taken to
% be equal to the closest values.
if nargin<3 || isempty(span)
span = .3;
end
% Sort and get smoothed version of xy data
xy = sortrows(xy);
x1 = xy(:,1);
y1 = xy(:,2);
ys1 = smooth(x1,y1,span,'loess');
% Remove repeats so we can interpolate
t = diff(x1)==0;
x1(t)=[]; ys1(t) = [];
% Interpolate to evaluate this at the xs values
ys = interp1(x1,ys1,xs,'linear',NaN);
% Some of the original points may have x values outside the range of the
% resampled data. Those are now NaN because we could not interpolate them.
% Replace NaN by the closest smoothed value. This amounts to extending the
% smooth curve using a horizontal line.
if any(isnan(ys))
ys(xs<x1(1)) = ys1(1);
ys(xs>x1(end)) = ys1(end);
end | How to test whether the variance of two distributions is different if the distributions are not norm | I agree with what others have said -- namely that "variance" is probably the wrong word to use (seeing as the function you are considering isn't a probability distribution but a time-series).
I think | How to test whether the variance of two distributions is different if the distributions are not normal
I agree with what others have said -- namely that "variance" is probably the wrong word to use (seeing as the function you are considering isn't a probability distribution but a time-series).
I think you may want to approach this problem from a different perspective -- just fit the two time series with LOWESS curves. You can calculate 95% confidence intervals and qualitatively comment on their shapes. I'm not sure you need to do anything more fancy than this.
I've written some MATLAB code below to illustrate what I'm saying. I'm in a bit of a rush but can provide clarifications soon. Much of what I did can be taken directly from here: http://blogs.mathworks.com/loren/2011/01/13/data-driven-fitting/
%% Generate Example data
npts = 200;
x = linspace(1,100,npts)';
y1 = (1e3*exp(-(x-25).^2/20) + 5e2*exp(-(x-65).^2/40));
y1_noisy = 50*randn(npts,1) + y1;
y2 = (1e3*exp(-(x-25).^2/60) + 5e2*exp(-(x-65).^2/100));
y2_noisy = 50*randn(npts,1) + y2;
figure; hold on
plot(x,y1_noisy,'ob')
plot(x,y2_noisy,'or')
title('raw data'); ylabel('count'); xlabel('time')
legend('y1','y2')
You may want to normalize the two time-series to compare their relative trends rather than their absolute levels.
%% Normalize data sets
figure; hold on
Y1 = y1_noisy./norm(y1_noisy);
Y2 = y2_noisy./norm(y2_noisy);
plot(x,Y1,'ob')
plot(x,Y2,'or')
title('normalized data'); ylabel('normalized count'); xlabel('time')
legend('Y1','Y2')
Now make LOWESS fits...
%% Make figure with lowess fits
figure; hold on
plot(x,Y1,'o','Color',[0.5 0.5 1])
plot(x,Y2,'o','Color',[1 0.5 0.5])
plot(x,mylowess([x,Y1],x,0.15),'-b','LineWidth',2)
plot(x,mylowess([x,Y2],x,0.15),'-r','LineWidth',2)
title('fit data'); ylabel('normalized count'); xlabel('time')
Finally, you can create 95% confidence bands as follows:
%% Use Bootstrapping to determine 95% confidence bands
figure; hold on
plot(x,Y1,'o','Color',[0.75 0.75 1])
plot(x,Y2,'o','Color',[1 0.75 0.75])
f = @(xy) mylowess(xy,x,0.15);
yboot_1 = bootstrp(1000,f,[x,Y1])';
yboot_2 = bootstrp(1000,f,[x,Y2])';
meanloess(:,1) = mean(yboot_1,2);
meanloess(:,2) = mean(yboot_2,2);
upper(:,1) = quantile(yboot_1,0.975,2);
upper(:,2) = quantile(yboot_2,0.975,2);
lower(:,1) = quantile(yboot_1,0.025,2);
lower(:,2) = quantile(yboot_2,0.025,2);
plot(x,meanloess(:,1),'-b','LineWidth',2);
plot(x,meanloess(:,2),'-r','LineWidth',2);
plot(x,upper(:,1),':b');
plot(x,upper(:,2),':r');
plot(x,lower(:,1),':b');
plot(x,lower(:,2),':r');
title('fit data -- with confidence bands'); ylabel('normalized count'); xlabel('time')
Now you can interpret the final figure as you wish, and you have the LOWESS fits to back up your hypothesis that the peaks in the red curve are actually broader than the blue curve. If you have a better idea of what the function is you could do non-linear regression instead.
Edit: Based on some helpful comments below, I am adding some more details about estimating peak widths explicitly. First, you need to come up with some definition for what you are considering a "peak" to be in the first place. Perhaps any bump that rises above some threshold (something like 0.05 in the plots I made above). The basic principle is that you should find a way from separating "real" or "notable" peaks from noise.
Then, for each peak, you can measure its width in a couple of ways. As I mentioned in the comments below, I think it is reasonable to look at the "half-max-width" but you could also look at the total time the peak stands above your threshold. Ideally, you should use several different measures of peak width and report how consistent your results were given these choices.
Whatever your metric(s) of choice, you can use bootstrapping to calculate a confidence interval for each peak in each trace.
f = @(xy) mylowess(xy,x,0.15);
N_boot = 1000;
yboot_1 = bootstrp(N_boot,f,[x,Y1])';
yboot_2 = bootstrp(N_boot,f,[x,Y2])';
This code creates 1000 bootstrapped fits for the blue and red traces in the plots above. One detail that I will gloss over is the choice of the smoothing factor 0.15 -- you can choose this parameter such that it minimizes cross validation error (see the link I posted). Now all you have to do is write a function that isolates the peaks and estimates their width:
function [t_peaks,heights,widths] = getPeaks(t,Y)
%% Computes a list of times, heights, and widths, for each peak in a time series Y
%% (column vector) with associated time points t (column vector).
% The implementation of this function will be problem-specific...
Then you run this code on the 1000 curves for each dataset and calculate the 2.5th and 97.5th percentiles for the width of each peak. I'll illustrate this on the Y1 time series - you would do the same for the the Y2 time series or any other data set of interest.
N_peaks = 2; % two peaks in example data
t_peaks = nan(N_boot,N_peaks);
heights = nan(N_boot,N_peaks);
widths = nan(N_boot,N_peaks);
for aa = 1:N_boot
[t_peaks(aa,:),heights(aa,:),widths(aa,:)] = getPeaks(x,yboot_1(:,aa));
end
quantile(widths(:,1),[0.025 0.975]) % confidence interval for the width of first peak
quantile(widths(:,2),[0.025 0.975]) % same for second peak width
If you desire, you can perform hypothesis tests rather than calculating confidence intervals. Note that the code above is simplistic - it assumes each bootstrapped lowess curve will have 2 peaks. This assumption may not always hold, so be careful. I'm just trying to illustrate the approach I would take.
Note: the "mylowess" function is given in the link I posted above. This is what it looks like...
function ys=mylowess(xy,xs,span)
%MYLOWESS Lowess smoothing, preserving x values
% YS=MYLOWESS(XY,XS) returns the smoothed version of the x/y data in the
% two-column matrix XY, but evaluates the smooth at XS and returns the
% smoothed values in YS. Any values outside the range of XY are taken to
% be equal to the closest values.
if nargin<3 || isempty(span)
span = .3;
end
% Sort and get smoothed version of xy data
xy = sortrows(xy);
x1 = xy(:,1);
y1 = xy(:,2);
ys1 = smooth(x1,y1,span,'loess');
% Remove repeats so we can interpolate
t = diff(x1)==0;
x1(t)=[]; ys1(t) = [];
% Interpolate to evaluate this at the xs values
ys = interp1(x1,ys1,xs,'linear',NaN);
% Some of the original points may have x values outside the range of the
% resampled data. Those are now NaN because we could not interpolate them.
% Replace NaN by the closest smoothed value. This amounts to extending the
% smooth curve using a horizontal line.
if any(isnan(ys))
ys(xs<x1(1)) = ys1(1);
ys(xs>x1(end)) = ys1(end);
end | How to test whether the variance of two distributions is different if the distributions are not norm
I agree with what others have said -- namely that "variance" is probably the wrong word to use (seeing as the function you are considering isn't a probability distribution but a time-series).
I think |
32,093 | Examples for One class SVM in R | The Chapter 9 lab exercise of An Introduction to Statistical Learning provides a working example of using an SVM for binary classification, and it does indeed use the e1071 library. By permission of the publisher, a PDF version of the book is available for free download. | Examples for One class SVM in R | The Chapter 9 lab exercise of An Introduction to Statistical Learning provides a working example of using an SVM for binary classification, and it does indeed use the e1071 library. By permission of t | Examples for One class SVM in R
The Chapter 9 lab exercise of An Introduction to Statistical Learning provides a working example of using an SVM for binary classification, and it does indeed use the e1071 library. By permission of the publisher, a PDF version of the book is available for free download. | Examples for One class SVM in R
The Chapter 9 lab exercise of An Introduction to Statistical Learning provides a working example of using an SVM for binary classification, and it does indeed use the e1071 library. By permission of t |
32,094 | Examples for One class SVM in R | I am providing rectified version of above code. Your 'trainpredictors' selection is wrong because u selected from iris instead of 'trainPositive' but index u selected from 'trainPositive'. Accuracy: train=78.125 test= 91.53
library(e1071)
library(caret)
library(NLP)
library(tm)
data(iris)
iris$SpeciesClass[iris$Species=="versicolor"] <- "TRUE"
iris$SpeciesClass[iris$Species!="versicolor"] <- "FALSE"
trainPositive<-subset(iris,SpeciesClass=="TRUE")
testnegative<-subset(iris,SpeciesClass=="FALSE")
inTrain<-createDataPartition(1:nrow(trainPositive),p=0.6,list=FALSE)
trainpredictors<-trainPositive[inTrain,1:4]
trainLabels<-trainPositive[inTrain,6]
testPositive<-trainPositive[-inTrain,]
testPosNeg<-rbind(testPositive,testnegative)
testpredictors<-testPosNeg[,1:4]
testLabels<-testPosNeg[,6]
svm.model<-svm(trainpredictors,y=NULL,
type='one-classification',
nu=0.10,
scale=TRUE,
kernel="radial")
svm.predtrain<-predict(svm.model,trainpredictors)
svm.predtest<-predict(svm.model,testpredictors)
confTrain<-table(Predicted=svm.predtrain,Reference=trainLabels)
confTest<-table(Predicted=svm.predtest,Reference=testLabels)
confusionMatrix(confTest,positive='TRUE')
print(confTrain)
print(confTest) | Examples for One class SVM in R | I am providing rectified version of above code. Your 'trainpredictors' selection is wrong because u selected from iris instead of 'trainPositive' but index u selected from 'trainPositive'. Accuracy: t | Examples for One class SVM in R
I am providing rectified version of above code. Your 'trainpredictors' selection is wrong because u selected from iris instead of 'trainPositive' but index u selected from 'trainPositive'. Accuracy: train=78.125 test= 91.53
library(e1071)
library(caret)
library(NLP)
library(tm)
data(iris)
iris$SpeciesClass[iris$Species=="versicolor"] <- "TRUE"
iris$SpeciesClass[iris$Species!="versicolor"] <- "FALSE"
trainPositive<-subset(iris,SpeciesClass=="TRUE")
testnegative<-subset(iris,SpeciesClass=="FALSE")
inTrain<-createDataPartition(1:nrow(trainPositive),p=0.6,list=FALSE)
trainpredictors<-trainPositive[inTrain,1:4]
trainLabels<-trainPositive[inTrain,6]
testPositive<-trainPositive[-inTrain,]
testPosNeg<-rbind(testPositive,testnegative)
testpredictors<-testPosNeg[,1:4]
testLabels<-testPosNeg[,6]
svm.model<-svm(trainpredictors,y=NULL,
type='one-classification',
nu=0.10,
scale=TRUE,
kernel="radial")
svm.predtrain<-predict(svm.model,trainpredictors)
svm.predtest<-predict(svm.model,testpredictors)
confTrain<-table(Predicted=svm.predtrain,Reference=trainLabels)
confTest<-table(Predicted=svm.predtest,Reference=testLabels)
confusionMatrix(confTest,positive='TRUE')
print(confTrain)
print(confTest) | Examples for One class SVM in R
I am providing rectified version of above code. Your 'trainpredictors' selection is wrong because u selected from iris instead of 'trainPositive' but index u selected from 'trainPositive'. Accuracy: t |
32,095 | Differences between clustering and segmentation | What is the difference between segmenting and clustering?
First, let us define the two terms:
Segmentation partitioning of some whole, some object, into parts vased on similarity and contiguity. See Wikipedia which gives as an example Segmentation (biology), the division of body plans into a series of repetitive segments and also Oxford.
Clustering Wikipedia says the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar (in some sense) to each other than to those in other groups (clusters).
This is, in some sense, closely associated. If we consider some whole ABC as consisting of many atoms, like a market consisting of customers, or a body consisting of body parts, we can say that we segment ABC but cluster the atoms. But it seems that segmentation is more used when there is some concept of (spatial) contiguity of the atoms within the whole.
There seems to be confusion of this usage. On this site customer segmentation is often used, it should be market segmentation. The customers are not segmented (hopefully!), they are clustered. Wikipedia got it right.
Use in connection with time series With multiple (parallel) time series, we can cluster the series into groups of similar series, while segmentation typically refers to partitioning a single series in similar, contiguous, parts. See the tag timeseries-segmentation and this list of posts about time series clustering. That points to a connection to change-point-detection. See Wikipedia.
On this site there are many posts on image-segmentation. | Differences between clustering and segmentation | What is the difference between segmenting and clustering?
First, let us define the two terms:
Segmentation partitioning of some whole, some object, into parts vased on similarity and contiguity. See | Differences between clustering and segmentation
What is the difference between segmenting and clustering?
First, let us define the two terms:
Segmentation partitioning of some whole, some object, into parts vased on similarity and contiguity. See Wikipedia which gives as an example Segmentation (biology), the division of body plans into a series of repetitive segments and also Oxford.
Clustering Wikipedia says the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar (in some sense) to each other than to those in other groups (clusters).
This is, in some sense, closely associated. If we consider some whole ABC as consisting of many atoms, like a market consisting of customers, or a body consisting of body parts, we can say that we segment ABC but cluster the atoms. But it seems that segmentation is more used when there is some concept of (spatial) contiguity of the atoms within the whole.
There seems to be confusion of this usage. On this site customer segmentation is often used, it should be market segmentation. The customers are not segmented (hopefully!), they are clustered. Wikipedia got it right.
Use in connection with time series With multiple (parallel) time series, we can cluster the series into groups of similar series, while segmentation typically refers to partitioning a single series in similar, contiguous, parts. See the tag timeseries-segmentation and this list of posts about time series clustering. That points to a connection to change-point-detection. See Wikipedia.
On this site there are many posts on image-segmentation. | Differences between clustering and segmentation
What is the difference between segmenting and clustering?
First, let us define the two terms:
Segmentation partitioning of some whole, some object, into parts vased on similarity and contiguity. See |
32,096 | Differences between clustering and segmentation | Segmentation vs. Clustering
In control system engineering, the ideas of controllability and measurability are, through the Cayley-Hamilton theorem, two faces of the same phenomena. One implies the other.
Segmentation and clustering are two faces of the same coin, too. The line of equal probability of cluster membership is the segmentation boundary. This is a deep topic and discussions about convergence, nature of space, and appropriate basis functions are beyond the scope of this answer.
Retaining Temporal In formation
If I were doing this, then I would augment each temporal membership with cluster membership. I would use both cluster index and cluster Mahalanobis distance. So if you took one measurement at each instant, then clustered the data, your augmented time-series would have three values at each instant - cluster index, Mahalanobis distance (useful), and the measurement itself.
Algorithms
I have not done much with time-series as a formalism, so this is all hands-on. When I have temporal data and I want to cluster, I just use the time-measurement as another measurement.
This means that if you had one measurement per instant, then you have a 2d walk, of sorts, where time is strictly increasing. You can throw away the time and cluster in measurement only. (Here is a link to lots of appropriate approaches: AutonLab) You can look at both. You can transform to lagged coordinates, or time-difference coordinates and think in terms of velocities, accelerations or such. The classic drunkards walk is 2d-random, and is a diffusion process. Being able to contrive your data as such a walk opens up those analysis tools for use. (link,link, link, link) Diffusion is studied in many disciplines including genetics, mathematics, materials science, epidemiology, and computer science.
There is no perfect "pepsi" - no silver bullet that solves all problems with ease. There are many good "pepsis", tools in the toolbox for which some will outperform others in particular areas. K-means, Gaussian Mixtures, Radial Basis Function Neural Networks, Support Vector Machines, even Q-learning lookups - these might have use for you.
Without a clearer description of the nature of the data, of what you are looking to cluster, it is harder to say which tool to use. If I don't know whether it is a nail or a bolt - I can't say "try to use a wrench" or "try to use a hammer". I hope that you find a tool that works for you.
Best of Luck. | Differences between clustering and segmentation | Segmentation vs. Clustering
In control system engineering, the ideas of controllability and measurability are, through the Cayley-Hamilton theorem, two faces of the same phenomena. One implies the ot | Differences between clustering and segmentation
Segmentation vs. Clustering
In control system engineering, the ideas of controllability and measurability are, through the Cayley-Hamilton theorem, two faces of the same phenomena. One implies the other.
Segmentation and clustering are two faces of the same coin, too. The line of equal probability of cluster membership is the segmentation boundary. This is a deep topic and discussions about convergence, nature of space, and appropriate basis functions are beyond the scope of this answer.
Retaining Temporal In formation
If I were doing this, then I would augment each temporal membership with cluster membership. I would use both cluster index and cluster Mahalanobis distance. So if you took one measurement at each instant, then clustered the data, your augmented time-series would have three values at each instant - cluster index, Mahalanobis distance (useful), and the measurement itself.
Algorithms
I have not done much with time-series as a formalism, so this is all hands-on. When I have temporal data and I want to cluster, I just use the time-measurement as another measurement.
This means that if you had one measurement per instant, then you have a 2d walk, of sorts, where time is strictly increasing. You can throw away the time and cluster in measurement only. (Here is a link to lots of appropriate approaches: AutonLab) You can look at both. You can transform to lagged coordinates, or time-difference coordinates and think in terms of velocities, accelerations or such. The classic drunkards walk is 2d-random, and is a diffusion process. Being able to contrive your data as such a walk opens up those analysis tools for use. (link,link, link, link) Diffusion is studied in many disciplines including genetics, mathematics, materials science, epidemiology, and computer science.
There is no perfect "pepsi" - no silver bullet that solves all problems with ease. There are many good "pepsis", tools in the toolbox for which some will outperform others in particular areas. K-means, Gaussian Mixtures, Radial Basis Function Neural Networks, Support Vector Machines, even Q-learning lookups - these might have use for you.
Without a clearer description of the nature of the data, of what you are looking to cluster, it is harder to say which tool to use. If I don't know whether it is a nail or a bolt - I can't say "try to use a wrench" or "try to use a hammer". I hope that you find a tool that works for you.
Best of Luck. | Differences between clustering and segmentation
Segmentation vs. Clustering
In control system engineering, the ideas of controllability and measurability are, through the Cayley-Hamilton theorem, two faces of the same phenomena. One implies the ot |
32,097 | Differences between clustering and segmentation | I think that, in general, the difference is in that clustering does not imply any prior knowledge about groups, whereas segmentation in many cases implies prior knowledge about groups, including their number and names (often used in business, for example, customer segmentation). | Differences between clustering and segmentation | I think that, in general, the difference is in that clustering does not imply any prior knowledge about groups, whereas segmentation in many cases implies prior knowledge about groups, including their | Differences between clustering and segmentation
I think that, in general, the difference is in that clustering does not imply any prior knowledge about groups, whereas segmentation in many cases implies prior knowledge about groups, including their number and names (often used in business, for example, customer segmentation). | Differences between clustering and segmentation
I think that, in general, the difference is in that clustering does not imply any prior knowledge about groups, whereas segmentation in many cases implies prior knowledge about groups, including their |
32,098 | Dealing with good performance on training and validation data, but very bad performance on testing data | While this sounds somewhat like overfitting, I think it's actually more likely that you've got some kind of "bug" in your code or your process. I would start by verifying that your test set isn't somehow systematically different from the training/validation set. Suppose your data is sorted by date (or whatever). If you used the first 50% for training, the next 25% for validation, and the rest for testing, you may have accidentally stratified your data in a way that makes the training data somewhat representative of the validation data, but less so for the testing data. This is fairly easy to do by accident.
You should also ensure you're not "double-dipping" in the validation data somehow, which sometimes happens accidentally.
Alternately, CV's own @Frank Harrell has reported that a single train/test split is often too variable to provide useful information on a system's performance (maybe he can weigh in with a citation or some data). You might consider doing something like cross-validation or bootstrapping, which would let you measure both the mean and variance of your accuracy measure.
Unlike Mikera, I don't think the problem is your scoring mechanism. That said, I can't imagine a situation where your $R^2_{training} < R^2_{validation}$, so I'd suggest scoring using the validation data alone.
More generally, I think $R^2$ or something like it is a reasonable choice for measuring the performance of a continuous-output model, assuming you're aware of its potential caveats. Depending on exactly what you're doing, you may also want to look at the maximum or worst-case error too. If you are somehow discretizing your output (logistic regression, some external thresholds), then looking at precision/recall/AUC might be a better idea. | Dealing with good performance on training and validation data, but very bad performance on testing d | While this sounds somewhat like overfitting, I think it's actually more likely that you've got some kind of "bug" in your code or your process. I would start by verifying that your test set isn't some | Dealing with good performance on training and validation data, but very bad performance on testing data
While this sounds somewhat like overfitting, I think it's actually more likely that you've got some kind of "bug" in your code or your process. I would start by verifying that your test set isn't somehow systematically different from the training/validation set. Suppose your data is sorted by date (or whatever). If you used the first 50% for training, the next 25% for validation, and the rest for testing, you may have accidentally stratified your data in a way that makes the training data somewhat representative of the validation data, but less so for the testing data. This is fairly easy to do by accident.
You should also ensure you're not "double-dipping" in the validation data somehow, which sometimes happens accidentally.
Alternately, CV's own @Frank Harrell has reported that a single train/test split is often too variable to provide useful information on a system's performance (maybe he can weigh in with a citation or some data). You might consider doing something like cross-validation or bootstrapping, which would let you measure both the mean and variance of your accuracy measure.
Unlike Mikera, I don't think the problem is your scoring mechanism. That said, I can't imagine a situation where your $R^2_{training} < R^2_{validation}$, so I'd suggest scoring using the validation data alone.
More generally, I think $R^2$ or something like it is a reasonable choice for measuring the performance of a continuous-output model, assuming you're aware of its potential caveats. Depending on exactly what you're doing, you may also want to look at the maximum or worst-case error too. If you are somehow discretizing your output (logistic regression, some external thresholds), then looking at precision/recall/AUC might be a better idea. | Dealing with good performance on training and validation data, but very bad performance on testing d
While this sounds somewhat like overfitting, I think it's actually more likely that you've got some kind of "bug" in your code or your process. I would start by verifying that your test set isn't some |
32,099 | Dealing with good performance on training and validation data, but very bad performance on testing data | You are overfitting because you are using min(training r-square,validation r-square) data to produce a score, which is in turn being used to drive model selection. Because your training r-square is likely to be equal or lower (you just ran a regression on it, after all), this is roughly equivalent to doing model selection on the r-square of the training data.
This has the effect of fitting too tightly to the training data, and ignoring the validation data.
If you used just validation r-square then you should get a better result. | Dealing with good performance on training and validation data, but very bad performance on testing d | You are overfitting because you are using min(training r-square,validation r-square) data to produce a score, which is in turn being used to drive model selection. Because your training r-square is li | Dealing with good performance on training and validation data, but very bad performance on testing data
You are overfitting because you are using min(training r-square,validation r-square) data to produce a score, which is in turn being used to drive model selection. Because your training r-square is likely to be equal or lower (you just ran a regression on it, after all), this is roughly equivalent to doing model selection on the r-square of the training data.
This has the effect of fitting too tightly to the training data, and ignoring the validation data.
If you used just validation r-square then you should get a better result. | Dealing with good performance on training and validation data, but very bad performance on testing d
You are overfitting because you are using min(training r-square,validation r-square) data to produce a score, which is in turn being used to drive model selection. Because your training r-square is li |
32,100 | Why computing the variance of the extracted random effect (using ranef) is not the same as the output from lme? | VarCorr() here provides the variance estimate of the random intercept by REML, but sd(ranef(fit1)[[1]]) shows the standard deviation of the empirical Bayesian estimates of the random intercept. In other words, say we have parameter $\sigma$, VarCorr() gives us the estimate $\hat \sigma$; we can generate a random sample based on $\hat \sigma$, and then calculate the standard deviation of the random sample by sd().
The two would be different since the result by sd() is an estimate of the result by VarCorr(). The similarity depends on the data set, and the two are similar when tested with the Orthodont example in lme().
> summary(fit1 <- lme(distance ~ age, random = ~1 | Subject, data=Orthodont))
Random effects:
Formula: ~1 | Subject
(Intercept) Residual
StdDev: 2.114724 1.431592
> sd(ranef(fit1)[[1]])
[1] 2.003087 | Why computing the variance of the extracted random effect (using ranef) is not the same as the outpu | VarCorr() here provides the variance estimate of the random intercept by REML, but sd(ranef(fit1)[[1]]) shows the standard deviation of the empirical Bayesian estimates of the random intercept. In oth | Why computing the variance of the extracted random effect (using ranef) is not the same as the output from lme?
VarCorr() here provides the variance estimate of the random intercept by REML, but sd(ranef(fit1)[[1]]) shows the standard deviation of the empirical Bayesian estimates of the random intercept. In other words, say we have parameter $\sigma$, VarCorr() gives us the estimate $\hat \sigma$; we can generate a random sample based on $\hat \sigma$, and then calculate the standard deviation of the random sample by sd().
The two would be different since the result by sd() is an estimate of the result by VarCorr(). The similarity depends on the data set, and the two are similar when tested with the Orthodont example in lme().
> summary(fit1 <- lme(distance ~ age, random = ~1 | Subject, data=Orthodont))
Random effects:
Formula: ~1 | Subject
(Intercept) Residual
StdDev: 2.114724 1.431592
> sd(ranef(fit1)[[1]])
[1] 2.003087 | Why computing the variance of the extracted random effect (using ranef) is not the same as the outpu
VarCorr() here provides the variance estimate of the random intercept by REML, but sd(ranef(fit1)[[1]]) shows the standard deviation of the empirical Bayesian estimates of the random intercept. In oth |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.