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
47,101
General hints regarding the use of the binomial distribution in conditional probabilty problems
In this response I will limit myself to the general question of when to use the binomial. The binomial arises naturally as the count of successes in a sequence of independent Bernoulli trials with constant success probability $p$. It's useful to keep the conditions in mind (both for Bernoulli trials and the independent and constant $p$ of the sequence of them) and see whether that might be more-or-less plausible. [Often the model is a reasonable approximation when the conditions don't quite hold.] For example if you have a population with some fraction having some attribute and you sample it at random with replacement, the count of the number having the attribute in your sample would be an obvious candidate for using a binomial. If you instead sample without replacement but the population is very very large compared to your sample (making the effect on $p$ at trial $i$ and the dependence negligible) then you could use the binomial as an approximation.
General hints regarding the use of the binomial distribution in conditional probabilty problems
In this response I will limit myself to the general question of when to use the binomial. The binomial arises naturally as the count of successes in a sequence of independent Bernoulli trials with con
General hints regarding the use of the binomial distribution in conditional probabilty problems In this response I will limit myself to the general question of when to use the binomial. The binomial arises naturally as the count of successes in a sequence of independent Bernoulli trials with constant success probability $p$. It's useful to keep the conditions in mind (both for Bernoulli trials and the independent and constant $p$ of the sequence of them) and see whether that might be more-or-less plausible. [Often the model is a reasonable approximation when the conditions don't quite hold.] For example if you have a population with some fraction having some attribute and you sample it at random with replacement, the count of the number having the attribute in your sample would be an obvious candidate for using a binomial. If you instead sample without replacement but the population is very very large compared to your sample (making the effect on $p$ at trial $i$ and the dependence negligible) then you could use the binomial as an approximation.
General hints regarding the use of the binomial distribution in conditional probabilty problems In this response I will limit myself to the general question of when to use the binomial. The binomial arises naturally as the count of successes in a sequence of independent Bernoulli trials with con
47,102
Bayesian and Frequentist linear regressions: different results
I think the frequentist linear regression results are going to be anticonservative in this case. We know those results are wrong (in the sense of an inadequate control of type 1 error) because the model assumptions are not met. The correct frequentist inference would be obtained by using sandwich standard errors. See the sandwich package and lmtest to obtain "wider" CIs that account for the heteroscedasticity. See my post here for a how-to on doing this in R. I wouldn't be surprised if the uncertainty and confidence intervals are very similar. To handle repeated measures, use a gee. The posterior densities for the regression parameters and the residual standard error should reflect the heteroscedasticity. In particular, the posterior for the residual standard error should appear trimodal, one "peak" for each group. Look at a density smoothed distribution of the posterior density (excluding burn-in). This means that the posterior density is accurately reflecting a mixture-inverse-gamma distribution and the beliefs should be updated correctly. I'm not sure how one would go about obtaining approximate frequentist inference in this case of model misspecification.
Bayesian and Frequentist linear regressions: different results
I think the frequentist linear regression results are going to be anticonservative in this case. We know those results are wrong (in the sense of an inadequate control of type 1 error) because the mod
Bayesian and Frequentist linear regressions: different results I think the frequentist linear regression results are going to be anticonservative in this case. We know those results are wrong (in the sense of an inadequate control of type 1 error) because the model assumptions are not met. The correct frequentist inference would be obtained by using sandwich standard errors. See the sandwich package and lmtest to obtain "wider" CIs that account for the heteroscedasticity. See my post here for a how-to on doing this in R. I wouldn't be surprised if the uncertainty and confidence intervals are very similar. To handle repeated measures, use a gee. The posterior densities for the regression parameters and the residual standard error should reflect the heteroscedasticity. In particular, the posterior for the residual standard error should appear trimodal, one "peak" for each group. Look at a density smoothed distribution of the posterior density (excluding burn-in). This means that the posterior density is accurately reflecting a mixture-inverse-gamma distribution and the beliefs should be updated correctly. I'm not sure how one would go about obtaining approximate frequentist inference in this case of model misspecification.
Bayesian and Frequentist linear regressions: different results I think the frequentist linear regression results are going to be anticonservative in this case. We know those results are wrong (in the sense of an inadequate control of type 1 error) because the mod
47,103
Bayesian and Frequentist linear regressions: different results
So there are a couple of issues here. As correctly pointed out above, you have calculation issues with the errors in the Frequentist model. But you also have another issue, it appears you may be interpreting the Bayesian interval incorrectly. That the interval contains zero is very important in Frequentist models but doesn't mean the same thing in Bayesian models. The Frequentist hypothesis test is $\Pr(data|\beta=0)$. The Bayesian test cannot be $\Pr(\beta=0|data)$ because it is a continuous variable. The $\Pr(\beta=0)=0$ because it is a countable point in a continuum, so it has zero measure. Instead, there needs to be an hypothesized region so that you are actually looking at $\Pr(-\epsilon\le{0}\le\epsilon)<.95$. The interval you are displaying is around the parameter estimate and not around zero. Let us imagine that the interval you saw was $(-.05,7)$. This includes zero, but it also includes $-.04$. It could be $-.04$. It could also be $.01$. Let us assume the posterior is denser at $.01$ than $0$. This implies that while zero is a possible solution, it is less likely than $.01$. The Bayesian interval does not say there is a 95% chance the solution may be zero. It says that there is a 95% chance the true value is inside the interval. This substantially differs from the Frequentist interval. The Frequentist interval implies that if you were to repeat the experiment an infinite number of times with an infinitely large population, at least 95% of the intervals created would contain the true value of the parameter. It says nothing at all about this current data set. So the Frequentist interval that included zero, because the null is that it is zero, would imply that you cannot reject the null and therefore should behave as if it is zero. (Using Frequentist decision theory instead of Frequentist inference which could differ in interpretation.) A second issue is how Bayesian and Frequentist tools handle assumptions violations. Frequentist methods, if correctly specified, are optimal methods ex ante. That is they are optimal prior to seeing the data. They may be a terrible method for the particular set of data you have, but on average you cannot do better. This is because they average over the sample space given the null that all slopes are equal to zero. They condition on the null hypothesis; and as such, can become fragile when there is a violation. Some things, like a $\chi^2$ test can handle substantial departures, other things cannot. Bayesian methods, if correctly specified, are optimal methods ex post. They optimally extract information from the specific data set, without making a statement of how they would have performed under another set. It could have poor Frequentist properties. This is because they average over the parameter space, but condition on the data itself and not the model. You actually did not perform a Bayesian hypothesis test. A proper Bayesian test would have considered model selection. The Bayesian equivalent of the "no effect" hypothesis, where $\beta_1=\beta_2=0$ isn't to see if the intervals contain zero, but to run separate regressions for all combinations of possible variables. If the best regression excludes variable B, then variable B has a stated probability of having no effect. Because the Bayesian method is averaging over the parameter space, it is averaging over all possible values for $\sigma^2$. It is sort of creating a composite variance. The issue here isn't so much the estimator as the probabilities. Bayesian probabilities are affirmative probabilities and not conditioned on a null. It becomes an interpretation problem because you have incorrectly specified the model and so incorrectly specified the construction of the probability statements. In the case of heteroskedasticity, the Bayesian solution is to run two classes of regression, one with homoskedasticity and one with heteroskedasticity, though you must specify in the likelihood function how that heteroskedasticity is created. For example, if the heteroskedasticity were a function of time, then the variance would have to be a function of time. With Frequentist methods there is no concern with why heteroskedasticity is present, only if it is or it is not. "Why" is not a Frequentist issue.
Bayesian and Frequentist linear regressions: different results
So there are a couple of issues here. As correctly pointed out above, you have calculation issues with the errors in the Frequentist model. But you also have another issue, it appears you may be int
Bayesian and Frequentist linear regressions: different results So there are a couple of issues here. As correctly pointed out above, you have calculation issues with the errors in the Frequentist model. But you also have another issue, it appears you may be interpreting the Bayesian interval incorrectly. That the interval contains zero is very important in Frequentist models but doesn't mean the same thing in Bayesian models. The Frequentist hypothesis test is $\Pr(data|\beta=0)$. The Bayesian test cannot be $\Pr(\beta=0|data)$ because it is a continuous variable. The $\Pr(\beta=0)=0$ because it is a countable point in a continuum, so it has zero measure. Instead, there needs to be an hypothesized region so that you are actually looking at $\Pr(-\epsilon\le{0}\le\epsilon)<.95$. The interval you are displaying is around the parameter estimate and not around zero. Let us imagine that the interval you saw was $(-.05,7)$. This includes zero, but it also includes $-.04$. It could be $-.04$. It could also be $.01$. Let us assume the posterior is denser at $.01$ than $0$. This implies that while zero is a possible solution, it is less likely than $.01$. The Bayesian interval does not say there is a 95% chance the solution may be zero. It says that there is a 95% chance the true value is inside the interval. This substantially differs from the Frequentist interval. The Frequentist interval implies that if you were to repeat the experiment an infinite number of times with an infinitely large population, at least 95% of the intervals created would contain the true value of the parameter. It says nothing at all about this current data set. So the Frequentist interval that included zero, because the null is that it is zero, would imply that you cannot reject the null and therefore should behave as if it is zero. (Using Frequentist decision theory instead of Frequentist inference which could differ in interpretation.) A second issue is how Bayesian and Frequentist tools handle assumptions violations. Frequentist methods, if correctly specified, are optimal methods ex ante. That is they are optimal prior to seeing the data. They may be a terrible method for the particular set of data you have, but on average you cannot do better. This is because they average over the sample space given the null that all slopes are equal to zero. They condition on the null hypothesis; and as such, can become fragile when there is a violation. Some things, like a $\chi^2$ test can handle substantial departures, other things cannot. Bayesian methods, if correctly specified, are optimal methods ex post. They optimally extract information from the specific data set, without making a statement of how they would have performed under another set. It could have poor Frequentist properties. This is because they average over the parameter space, but condition on the data itself and not the model. You actually did not perform a Bayesian hypothesis test. A proper Bayesian test would have considered model selection. The Bayesian equivalent of the "no effect" hypothesis, where $\beta_1=\beta_2=0$ isn't to see if the intervals contain zero, but to run separate regressions for all combinations of possible variables. If the best regression excludes variable B, then variable B has a stated probability of having no effect. Because the Bayesian method is averaging over the parameter space, it is averaging over all possible values for $\sigma^2$. It is sort of creating a composite variance. The issue here isn't so much the estimator as the probabilities. Bayesian probabilities are affirmative probabilities and not conditioned on a null. It becomes an interpretation problem because you have incorrectly specified the model and so incorrectly specified the construction of the probability statements. In the case of heteroskedasticity, the Bayesian solution is to run two classes of regression, one with homoskedasticity and one with heteroskedasticity, though you must specify in the likelihood function how that heteroskedasticity is created. For example, if the heteroskedasticity were a function of time, then the variance would have to be a function of time. With Frequentist methods there is no concern with why heteroskedasticity is present, only if it is or it is not. "Why" is not a Frequentist issue.
Bayesian and Frequentist linear regressions: different results So there are a couple of issues here. As correctly pointed out above, you have calculation issues with the errors in the Frequentist model. But you also have another issue, it appears you may be int
47,104
Is there an opposite to Clustering or "Anti-"Clustering?
Based on the poster's response in one of the answers, I will rephrase the problem statement because it can be solved using an R package that I wrote: The task is to partition a set of elements into K groups such that the distances between clusters is minimized and the distance within clusters is maximized. This is mathematically the opposite of clustering and has indeed been called anticlustering; there are some rarely-cited papers on this approach (Späth 1986; Valev 1998). Generally, anticlustering leads to clusters that are similar to each other. If you are using R, you can use my package anticlust to tackle the anticlustering problem. For example, use the following code to create three similar sets of plants in the classical iris data set: library(anticlust) data(iris) ## Maximize the k-means criterion anticlusters <- anticlustering( iris[, -5], K = 3, objective = "variance" ) ## Compare feature means by anticluster by(iris[, -5], anticlusters, function(x) round(colMeans(x), 2)) #> anticlusters: 1 #> Sepal.Length Sepal.Width Petal.Length Petal.Width #> 5.84 3.06 3.76 1.20 #> --------------------------------------------------------------------------------------- #> anticlusters: 2 #> Sepal.Length Sepal.Width Petal.Length Petal.Width #> 5.84 3.06 3.76 1.20 #> --------------------------------------------------------------------------------------- #> anticlusters: 3 #> Sepal.Length Sepal.Width Petal.Length Petal.Width #> 5.84 3.06 3.76 1.20 My package can maximize two clustering objectives: (a) the classical k-means objective, leading to similar feature means; (b) the cluster editing objective, which is the sum of the pairwise distances within clusters. In the package, you can vary the parameter objective between "variance" (k-means) or "distance" (cluster editing). The Github page and the package docs contains some more information on the methods and algorithms used in the package. Späth, H. (1986). Anticlustering: Maximizing the variance criterion. Control and Cybernetics, 15(2), 213–218. Valev, V. (1998). Set partition principles revisited. In Joint IAPR international workshops on statistical techniques in pattern recognition (SPR) and structural and syntactic pattern recognition (SSPR) (pp. 875– 881).
Is there an opposite to Clustering or "Anti-"Clustering?
Based on the poster's response in one of the answers, I will rephrase the problem statement because it can be solved using an R package that I wrote: The task is to partition a set of elements into K
Is there an opposite to Clustering or "Anti-"Clustering? Based on the poster's response in one of the answers, I will rephrase the problem statement because it can be solved using an R package that I wrote: The task is to partition a set of elements into K groups such that the distances between clusters is minimized and the distance within clusters is maximized. This is mathematically the opposite of clustering and has indeed been called anticlustering; there are some rarely-cited papers on this approach (Späth 1986; Valev 1998). Generally, anticlustering leads to clusters that are similar to each other. If you are using R, you can use my package anticlust to tackle the anticlustering problem. For example, use the following code to create three similar sets of plants in the classical iris data set: library(anticlust) data(iris) ## Maximize the k-means criterion anticlusters <- anticlustering( iris[, -5], K = 3, objective = "variance" ) ## Compare feature means by anticluster by(iris[, -5], anticlusters, function(x) round(colMeans(x), 2)) #> anticlusters: 1 #> Sepal.Length Sepal.Width Petal.Length Petal.Width #> 5.84 3.06 3.76 1.20 #> --------------------------------------------------------------------------------------- #> anticlusters: 2 #> Sepal.Length Sepal.Width Petal.Length Petal.Width #> 5.84 3.06 3.76 1.20 #> --------------------------------------------------------------------------------------- #> anticlusters: 3 #> Sepal.Length Sepal.Width Petal.Length Petal.Width #> 5.84 3.06 3.76 1.20 My package can maximize two clustering objectives: (a) the classical k-means objective, leading to similar feature means; (b) the cluster editing objective, which is the sum of the pairwise distances within clusters. In the package, you can vary the parameter objective between "variance" (k-means) or "distance" (cluster editing). The Github page and the package docs contains some more information on the methods and algorithms used in the package. Späth, H. (1986). Anticlustering: Maximizing the variance criterion. Control and Cybernetics, 15(2), 213–218. Valev, V. (1998). Set partition principles revisited. In Joint IAPR international workshops on statistical techniques in pattern recognition (SPR) and structural and syntactic pattern recognition (SSPR) (pp. 875– 881).
Is there an opposite to Clustering or "Anti-"Clustering? Based on the poster's response in one of the answers, I will rephrase the problem statement because it can be solved using an R package that I wrote: The task is to partition a set of elements into K
47,105
Is there an opposite to Clustering or "Anti-"Clustering?
There are several related domains: Outlier detection: find unusual points, rather than typical representatives as in clustering. Stratified sampling. Choose a random sample such that the samples correspond to different classes. For larger sets, so that the class distribution matches. Archetypal analysis. Summarize data not by 'average' cluster representatives, but rather by extreme observations that "bound" the clusters. But you'll certainly need to become more explicit about the formal requirements that you have, some vague intuition is not enough. Maybe you still want clustering - kmeans tries to minimize the within-cluster variance, which implies that it maximizes the between cluster sum of squares. So in a good kmeans clustering, the typical squared deviation of two objects not in the same cluster is maximized; the clustering does divide the data into partitions that are "as dissimilar as possible".
Is there an opposite to Clustering or "Anti-"Clustering?
There are several related domains: Outlier detection: find unusual points, rather than typical representatives as in clustering. Stratified sampling. Choose a random sample such that the samples corr
Is there an opposite to Clustering or "Anti-"Clustering? There are several related domains: Outlier detection: find unusual points, rather than typical representatives as in clustering. Stratified sampling. Choose a random sample such that the samples correspond to different classes. For larger sets, so that the class distribution matches. Archetypal analysis. Summarize data not by 'average' cluster representatives, but rather by extreme observations that "bound" the clusters. But you'll certainly need to become more explicit about the formal requirements that you have, some vague intuition is not enough. Maybe you still want clustering - kmeans tries to minimize the within-cluster variance, which implies that it maximizes the between cluster sum of squares. So in a good kmeans clustering, the typical squared deviation of two objects not in the same cluster is maximized; the clustering does divide the data into partitions that are "as dissimilar as possible".
Is there an opposite to Clustering or "Anti-"Clustering? There are several related domains: Outlier detection: find unusual points, rather than typical representatives as in clustering. Stratified sampling. Choose a random sample such that the samples corr
47,106
Is there an opposite to Clustering or "Anti-"Clustering?
It's still clustering that you want, because you're trying to split the data into subsets, which is clustering. If you clustering algorithm is based on a distance measure, then simple negative of that measure or inverse should accomplish subsetting you request. Some algorithms rely on the distance measure being positive, in this case the inverse should work. You could soften the inverse with a fractional power function, of course.
Is there an opposite to Clustering or "Anti-"Clustering?
It's still clustering that you want, because you're trying to split the data into subsets, which is clustering. If you clustering algorithm is based on a distance measure, then simple negative of that
Is there an opposite to Clustering or "Anti-"Clustering? It's still clustering that you want, because you're trying to split the data into subsets, which is clustering. If you clustering algorithm is based on a distance measure, then simple negative of that measure or inverse should accomplish subsetting you request. Some algorithms rely on the distance measure being positive, in this case the inverse should work. You could soften the inverse with a fractional power function, of course.
Is there an opposite to Clustering or "Anti-"Clustering? It's still clustering that you want, because you're trying to split the data into subsets, which is clustering. If you clustering algorithm is based on a distance measure, then simple negative of that
47,107
Is there an opposite to Clustering or "Anti-"Clustering?
Building on the useful comments & answers by Nick Cox and others here: DBSCAN is a clustering algorithm that also identifies points that do not belong well to any particular cluster, and treats them as 'noise'. This might be one way to achieve what you are after, since it identifies points that are distant enough from clusters to make grouping them together questionable.
Is there an opposite to Clustering or "Anti-"Clustering?
Building on the useful comments & answers by Nick Cox and others here: DBSCAN is a clustering algorithm that also identifies points that do not belong well to any particular cluster, and treats them
Is there an opposite to Clustering or "Anti-"Clustering? Building on the useful comments & answers by Nick Cox and others here: DBSCAN is a clustering algorithm that also identifies points that do not belong well to any particular cluster, and treats them as 'noise'. This might be one way to achieve what you are after, since it identifies points that are distant enough from clusters to make grouping them together questionable.
Is there an opposite to Clustering or "Anti-"Clustering? Building on the useful comments & answers by Nick Cox and others here: DBSCAN is a clustering algorithm that also identifies points that do not belong well to any particular cluster, and treats them
47,108
Is there an opposite to Clustering or "Anti-"Clustering?
We have been working on unclusters (and anti-clusters and noclusters) and we have a few definitions that we have been exploring. the holes between clusters that illustrate where points can not exist. the density of points on the periphery of a cluster. the density of clusters (as compared to the density of points in the clusters) the specificity of the centroid in any given cluster... how much can you move the centroid yet still keep the cluster reasonably intact. the potential overlap between clusters (coclusters) - we even thought there should be a complex cluster with a real and imaginary components to handle overlapping densities. k-means is certainly a useful approach, but there seems to be some underlying meaning to these "unclusters"... and we have started to try to model these unclusters so that we can learn optimal numbers of clusters and start with 'better' centroid estimates. It sounds like you are exploring the density aspect to help with cluster separation and overlap. Certainly a very interesting topic and one that warrants more thought.
Is there an opposite to Clustering or "Anti-"Clustering?
We have been working on unclusters (and anti-clusters and noclusters) and we have a few definitions that we have been exploring. the holes between clusters that illustrate where points can not exist
Is there an opposite to Clustering or "Anti-"Clustering? We have been working on unclusters (and anti-clusters and noclusters) and we have a few definitions that we have been exploring. the holes between clusters that illustrate where points can not exist. the density of points on the periphery of a cluster. the density of clusters (as compared to the density of points in the clusters) the specificity of the centroid in any given cluster... how much can you move the centroid yet still keep the cluster reasonably intact. the potential overlap between clusters (coclusters) - we even thought there should be a complex cluster with a real and imaginary components to handle overlapping densities. k-means is certainly a useful approach, but there seems to be some underlying meaning to these "unclusters"... and we have started to try to model these unclusters so that we can learn optimal numbers of clusters and start with 'better' centroid estimates. It sounds like you are exploring the density aspect to help with cluster separation and overlap. Certainly a very interesting topic and one that warrants more thought.
Is there an opposite to Clustering or "Anti-"Clustering? We have been working on unclusters (and anti-clusters and noclusters) and we have a few definitions that we have been exploring. the holes between clusters that illustrate where points can not exist
47,109
Understanding simulation in the secretary problem
Why Simulate? Quick research into the problem will reveal that the optimal algorithm to solve this problem is to rank the first $\frac{1}{e}$ applicants, not hire them, and then choose the first candidate who is better than your previous ones. For example, if there are ten candidates each with unique rankings, you might observe the following sequence. $$2 \quad 3 \quad 6 \quad 5 \quad 4 \quad 8 \quad 9 \quad 10 \quad 1 \quad 7$$ We observe that in the first $\lfloor \frac{1}{e} \rfloor$ candidates, or first 3 candidates, the max score was a six. So, we check the fourth candidate and observe a 5, so we don't hire. Then we observe a 4, so we don't hire. Then we observe a 9, so he hire them and halt the interview process. In this case, we didn't select the optimal candidate, but we were close. But what if we don't know this algorithm and we want to determine which $k$ is best? It isn't immediately intuitive that $k \approx \frac{1}{e}$ is the best number of candidates to skip and so simulating can assist us in finding for which $k$ our probabilility of picking the best candidate is maximized. In the general case, simulations aid in intuition. If we can guess an optimal solution, or perhaps even prove an optimal solution through mathematics, then simulation helps to verify our results. How would you simulate? This is perhaps my favorite part. I will be using R to write this simulation and go through the steps on how to do this simulation. We will start with a single simulation for arbitrary $k$, where we want to create 1000 candidates each with distinct rankings. x <- sample(1:1000, 1000) Now that we have our sample, we want to find the best candidate among the first $k$ candidates, which can be done with init_best <- max(x[1:k]) Next, we begin by looping through the remaining candidates until we find one who is better than the best of our first $k$ candidates. Note that we only simuluate up to $n-1$ candidates for $k$, because it doesn't make sense to skip every candidate as that always results in no hire. for (i in (k+1):999) { if (x[i] > init_best) { candidate_score <- x[i] candidate_num <- i break } } So, from here, we have recorded the candidates score. We can quickly verify if this candidate is the best candidate by checking if their ranking is the max ranking. Since we have 1000 candidates, we do this with if (candidate_score == 1000) success = success + 1 That is, we record that we successfully chose the best candidate and increment some value that keeps track of that. Using these, we can write a few loops to run this simulation several times which is shown below sims <- 10000 p <- c() p[1] <- 0 cand_ave <- c() cand_ave[1] <- 0 for (k in 2:999) { success <- 0 for (n in 1:sims) { x <- sample(1:1000, 1000) init_best <- max(x[1:k]) candidate_score = -1 for (i in (k+1):1000) { if (x[i] > init_best) { candidate_score <- x[i] break } } if (candidate_score == 1000) success <- success + 1 } p[k] <- success/sims cat(k, " complete \n") } plot(1:999, p, type = "l", xlab = "Candidates Skipped", ylab = "Probability of selecting Best Candidate", main = "The Secretary Problem") So, we create a collection of probabilities so that later on, we can plot these values. We also initialize candidate_score at -1 before each loop so as to signify the case where we end up not hiring anyone. After running this simulation 10000 times for each $k$, the results are as follows Within this simulation, we find that the $k$ value(s) that maximizes $p$ is $k = 332$ or $k = 374$ with $p = .3789$. We know that the asymptotic $k_n^*$ and $p_n^*$ values are $\dfrac{n}{e}$ and $\dfrac{1}{e}$ respectively and these results are fairly close to those values which would be in this case $$k_{1000} \approx 369 \quad \quad p_{1000} \approx .369$$ So the simulation approximately confirms the asymptotic values.
Understanding simulation in the secretary problem
Why Simulate? Quick research into the problem will reveal that the optimal algorithm to solve this problem is to rank the first $\frac{1}{e}$ applicants, not hire them, and then choose the first candi
Understanding simulation in the secretary problem Why Simulate? Quick research into the problem will reveal that the optimal algorithm to solve this problem is to rank the first $\frac{1}{e}$ applicants, not hire them, and then choose the first candidate who is better than your previous ones. For example, if there are ten candidates each with unique rankings, you might observe the following sequence. $$2 \quad 3 \quad 6 \quad 5 \quad 4 \quad 8 \quad 9 \quad 10 \quad 1 \quad 7$$ We observe that in the first $\lfloor \frac{1}{e} \rfloor$ candidates, or first 3 candidates, the max score was a six. So, we check the fourth candidate and observe a 5, so we don't hire. Then we observe a 4, so we don't hire. Then we observe a 9, so he hire them and halt the interview process. In this case, we didn't select the optimal candidate, but we were close. But what if we don't know this algorithm and we want to determine which $k$ is best? It isn't immediately intuitive that $k \approx \frac{1}{e}$ is the best number of candidates to skip and so simulating can assist us in finding for which $k$ our probabilility of picking the best candidate is maximized. In the general case, simulations aid in intuition. If we can guess an optimal solution, or perhaps even prove an optimal solution through mathematics, then simulation helps to verify our results. How would you simulate? This is perhaps my favorite part. I will be using R to write this simulation and go through the steps on how to do this simulation. We will start with a single simulation for arbitrary $k$, where we want to create 1000 candidates each with distinct rankings. x <- sample(1:1000, 1000) Now that we have our sample, we want to find the best candidate among the first $k$ candidates, which can be done with init_best <- max(x[1:k]) Next, we begin by looping through the remaining candidates until we find one who is better than the best of our first $k$ candidates. Note that we only simuluate up to $n-1$ candidates for $k$, because it doesn't make sense to skip every candidate as that always results in no hire. for (i in (k+1):999) { if (x[i] > init_best) { candidate_score <- x[i] candidate_num <- i break } } So, from here, we have recorded the candidates score. We can quickly verify if this candidate is the best candidate by checking if their ranking is the max ranking. Since we have 1000 candidates, we do this with if (candidate_score == 1000) success = success + 1 That is, we record that we successfully chose the best candidate and increment some value that keeps track of that. Using these, we can write a few loops to run this simulation several times which is shown below sims <- 10000 p <- c() p[1] <- 0 cand_ave <- c() cand_ave[1] <- 0 for (k in 2:999) { success <- 0 for (n in 1:sims) { x <- sample(1:1000, 1000) init_best <- max(x[1:k]) candidate_score = -1 for (i in (k+1):1000) { if (x[i] > init_best) { candidate_score <- x[i] break } } if (candidate_score == 1000) success <- success + 1 } p[k] <- success/sims cat(k, " complete \n") } plot(1:999, p, type = "l", xlab = "Candidates Skipped", ylab = "Probability of selecting Best Candidate", main = "The Secretary Problem") So, we create a collection of probabilities so that later on, we can plot these values. We also initialize candidate_score at -1 before each loop so as to signify the case where we end up not hiring anyone. After running this simulation 10000 times for each $k$, the results are as follows Within this simulation, we find that the $k$ value(s) that maximizes $p$ is $k = 332$ or $k = 374$ with $p = .3789$. We know that the asymptotic $k_n^*$ and $p_n^*$ values are $\dfrac{n}{e}$ and $\dfrac{1}{e}$ respectively and these results are fairly close to those values which would be in this case $$k_{1000} \approx 369 \quad \quad p_{1000} \approx .369$$ So the simulation approximately confirms the asymptotic values.
Understanding simulation in the secretary problem Why Simulate? Quick research into the problem will reveal that the optimal algorithm to solve this problem is to rank the first $\frac{1}{e}$ applicants, not hire them, and then choose the first candi
47,110
Understanding simulation in the secretary problem
You can use your derivations to deduce the asymptotics of $k_n^*$ for large $n$. However, for smaller $n$, it's not trivial to derive the maximal $r$. You'll end up with a $n$'th degree polynomial in $r$, which is nasty to optimize over integers $r$, and may have surprising behavior for smaller $n$. Explicitely, for large $n$, and $r=cn$, $$P(k)\approx \frac{cn-1}{n}(\ln n - \ln (cn))\approx -c\ln(c),$$ so taking derivatives gives $\ln(c)=-1$, or $c=1/e$, which can be verified to give the maximum (e.g. second derivative test). Thus $k^*_n\approx n/e$.
Understanding simulation in the secretary problem
You can use your derivations to deduce the asymptotics of $k_n^*$ for large $n$. However, for smaller $n$, it's not trivial to derive the maximal $r$. You'll end up with a $n$'th degree polynomial in
Understanding simulation in the secretary problem You can use your derivations to deduce the asymptotics of $k_n^*$ for large $n$. However, for smaller $n$, it's not trivial to derive the maximal $r$. You'll end up with a $n$'th degree polynomial in $r$, which is nasty to optimize over integers $r$, and may have surprising behavior for smaller $n$. Explicitely, for large $n$, and $r=cn$, $$P(k)\approx \frac{cn-1}{n}(\ln n - \ln (cn))\approx -c\ln(c),$$ so taking derivatives gives $\ln(c)=-1$, or $c=1/e$, which can be verified to give the maximum (e.g. second derivative test). Thus $k^*_n\approx n/e$.
Understanding simulation in the secretary problem You can use your derivations to deduce the asymptotics of $k_n^*$ for large $n$. However, for smaller $n$, it's not trivial to derive the maximal $r$. You'll end up with a $n$'th degree polynomial in
47,111
Inference and predictive models
I see two somewhat unrelated questions in this question. Is it possible to draw reliable inference about individual coefficients in predictive models, especially if we have a large number of predictors and use some form of variable selection and/or regularization? Can the coefficients in a predictive model be interpreted causally? My short answer to the first question is yes, that's possible, but it's not straightforward to do correctly, and it's the subject of intense current research. To the second question I find that the safe answer is no, the coefficients in a predictive model don't generally have a causal interpretation. This point should be made very clear to collaborators/clients, who may not have a strong training in causal models. Inference Emmanuel Candes gave the 2017 Wald Lectures at the Joint Statistical Meetings entitled What's happening in Selective Inference?, which offers a great starting point for learning what the challenges are, and what the status is. A main challenge, especially when the number of predictors is large, is how to compute and report uncertainty correctly, when the model/predictors have been selected by the data. Candes explains at length his contributions (mostly with Rina Barber) on the knockoff filter, which is a very nice idea for controlling the false discovery rate of selected predictors. Another question is how to reliably compute confidence intervals for the coefficients. Candes touches upon this in his talk, but see the paper Exact post-selection inference, with application to the lasso by Lee at al. for more details, and see also the paper Valid post-selection inference by Berk et al. The R package Selective Inference implements these ideas. Another relevant R package to consider is hdi, see also the paper High-Dimensional Inference: Confidence Intervals, p-Values and R-Software hdi by Dezeure et al. Note that there is a non-trivial discussion in selective inference about what the target parameter actually is! Is it the (theoretical) coefficient in the model with the selected predictors, or is it the coefficient in the model with all predictors included? Read the paper by Berk et al. for some discussion on this difference. I would typically investigate uncertainty of reported coefficients and selected predictors via simulations/bootstrapping (remembering to include the full variable selection procedure within the bootstrapping), but it may actually require some work to make sure that e.g. bootstrapped confidence intervals are appropriate, see Bootstrapping Lasso Estimators by Chatterjee and Lahiri. I should say that the challenges discussed above are fundamentally frequentistic of nature. See e.g. Gelman's post Bayesian inference completely solves the multiple comparisons problem for a more Bayesian perspective. Causality Regression models have been used in econometrics and epidemiology, to mention some areas, to estimate causal effects from observational data. This, I find, has historically not always been done with a crystal clear discussion of what actually constitutes a causal effect. Causality has been thought justified by appealing to "no unmeasured confounders" and other similar properties of the setup, in an attempt to argue that the regressors included are precisely those that are needed to justify a causal interpretation of estimated coefficients. But often without a clear conceptual or mathematical framework for defining causality and causal effects. The history of how Simpson's paradox has been treated in the statistical literature illustrates the problems as described by Pearl in his paper Understanding Simpson’s Paradox. What is crystal clear to me is that causality is a concept beyond a probabilistic model, and this can be formalized using frameworks such as counterfactuals, structural equation models or graphical models (DAGs). These are not unrelated frameworks, but offer slightly different concepts and languages to introduce the fundamental parameters of interest: the causal effects. In some situations it might be possible to interpret coefficients from a predictive (regression) model as causal effects, but I would say it's unlikely to be the case if the model is optimized for purely predictive performance from a vast number of potential predictors using observational data. The forthcoming Causal Inference Book by Hernan and Robins is a great place to learn about the causal models. Part II of the book deals specifically with the use of models for causal inference. Causal effects can sometimes be estimated using predictive models, but it may require some ingenuity. Inverse probability weighting relies on a predictive model of probability weights, as Hernan and Robins describe. The recent paper Causal inference by using invariant prediction: identification and confidence intervals by Peters, Bühlmann and Meinshausen relies on the causal model being invariant under different (unspecified) interventions, whereas non-causal associations are not. In any case, I would strongly advice against careless interpretations of (regression) coefficients as causal effects. If causal effects are of interest, this should be taken seriously, and appropriate methods should be employed to estimate the effects of interest.
Inference and predictive models
I see two somewhat unrelated questions in this question. Is it possible to draw reliable inference about individual coefficients in predictive models, especially if we have a large number of predicto
Inference and predictive models I see two somewhat unrelated questions in this question. Is it possible to draw reliable inference about individual coefficients in predictive models, especially if we have a large number of predictors and use some form of variable selection and/or regularization? Can the coefficients in a predictive model be interpreted causally? My short answer to the first question is yes, that's possible, but it's not straightforward to do correctly, and it's the subject of intense current research. To the second question I find that the safe answer is no, the coefficients in a predictive model don't generally have a causal interpretation. This point should be made very clear to collaborators/clients, who may not have a strong training in causal models. Inference Emmanuel Candes gave the 2017 Wald Lectures at the Joint Statistical Meetings entitled What's happening in Selective Inference?, which offers a great starting point for learning what the challenges are, and what the status is. A main challenge, especially when the number of predictors is large, is how to compute and report uncertainty correctly, when the model/predictors have been selected by the data. Candes explains at length his contributions (mostly with Rina Barber) on the knockoff filter, which is a very nice idea for controlling the false discovery rate of selected predictors. Another question is how to reliably compute confidence intervals for the coefficients. Candes touches upon this in his talk, but see the paper Exact post-selection inference, with application to the lasso by Lee at al. for more details, and see also the paper Valid post-selection inference by Berk et al. The R package Selective Inference implements these ideas. Another relevant R package to consider is hdi, see also the paper High-Dimensional Inference: Confidence Intervals, p-Values and R-Software hdi by Dezeure et al. Note that there is a non-trivial discussion in selective inference about what the target parameter actually is! Is it the (theoretical) coefficient in the model with the selected predictors, or is it the coefficient in the model with all predictors included? Read the paper by Berk et al. for some discussion on this difference. I would typically investigate uncertainty of reported coefficients and selected predictors via simulations/bootstrapping (remembering to include the full variable selection procedure within the bootstrapping), but it may actually require some work to make sure that e.g. bootstrapped confidence intervals are appropriate, see Bootstrapping Lasso Estimators by Chatterjee and Lahiri. I should say that the challenges discussed above are fundamentally frequentistic of nature. See e.g. Gelman's post Bayesian inference completely solves the multiple comparisons problem for a more Bayesian perspective. Causality Regression models have been used in econometrics and epidemiology, to mention some areas, to estimate causal effects from observational data. This, I find, has historically not always been done with a crystal clear discussion of what actually constitutes a causal effect. Causality has been thought justified by appealing to "no unmeasured confounders" and other similar properties of the setup, in an attempt to argue that the regressors included are precisely those that are needed to justify a causal interpretation of estimated coefficients. But often without a clear conceptual or mathematical framework for defining causality and causal effects. The history of how Simpson's paradox has been treated in the statistical literature illustrates the problems as described by Pearl in his paper Understanding Simpson’s Paradox. What is crystal clear to me is that causality is a concept beyond a probabilistic model, and this can be formalized using frameworks such as counterfactuals, structural equation models or graphical models (DAGs). These are not unrelated frameworks, but offer slightly different concepts and languages to introduce the fundamental parameters of interest: the causal effects. In some situations it might be possible to interpret coefficients from a predictive (regression) model as causal effects, but I would say it's unlikely to be the case if the model is optimized for purely predictive performance from a vast number of potential predictors using observational data. The forthcoming Causal Inference Book by Hernan and Robins is a great place to learn about the causal models. Part II of the book deals specifically with the use of models for causal inference. Causal effects can sometimes be estimated using predictive models, but it may require some ingenuity. Inverse probability weighting relies on a predictive model of probability weights, as Hernan and Robins describe. The recent paper Causal inference by using invariant prediction: identification and confidence intervals by Peters, Bühlmann and Meinshausen relies on the causal model being invariant under different (unspecified) interventions, whereas non-causal associations are not. In any case, I would strongly advice against careless interpretations of (regression) coefficients as causal effects. If causal effects are of interest, this should be taken seriously, and appropriate methods should be employed to estimate the effects of interest.
Inference and predictive models I see two somewhat unrelated questions in this question. Is it possible to draw reliable inference about individual coefficients in predictive models, especially if we have a large number of predicto
47,112
Inference and predictive models
Frank Harrell, in his 'Regression Modeling Strategies' (2015) offers a range of possible modeling strategies (section 4.12, if you are able to obtain a copy), some of which may be considered facetious ('develop a black box model that performs poorly and is difficult to interpret'), but he then goes on to develop a strategy for regression models which provide accurate predictions, and then discusses how this model may be improved to allow accurate effect estimation, commenting 'estimation of effects for these models must involve accurate prediction of overall response values'. Effectively it seems doubtful that you can have an accurate estimate of the value of a predictor's effect size if you don't have a model that accurately predicts your target. Harrell points out some useful considerations needed to ensure that a model providing good accuracy can provide good estimates of predictor effects. For example, one is strict attention to interaction effects. Another is the role of imputation for missing data, especially if a variable whose effect size is a high priority has many missing values e.g. it might be sensible to impute the missing values if model accuracy is the only goal, but not sensible if estimating that particular effect is the goal. At the same time, the above implies that it is possible to achieve a level of accuracy with respect to the target without having achieved accurate estimates of each predictor's effect. You also mention causal analysis, and one of the commenters rightly observes that you can achieve accurate estimates of correlations without accurately understanding causal relationships. Overall, it begins to look like a hierarchy, where a strong predictive model forms the foundation for accurate estimation of predictor effects, and accurate predictor estimates of predictor effects could then be the beginning of an analysis of causation. Then the answer to your main question is 'yes, it is legitimate to use the coefficients from a predictive model for inference, under the condition that the model has been analysed carefully to ensure the legitimacy of the effects estimates'.
Inference and predictive models
Frank Harrell, in his 'Regression Modeling Strategies' (2015) offers a range of possible modeling strategies (section 4.12, if you are able to obtain a copy), some of which may be considered facetious
Inference and predictive models Frank Harrell, in his 'Regression Modeling Strategies' (2015) offers a range of possible modeling strategies (section 4.12, if you are able to obtain a copy), some of which may be considered facetious ('develop a black box model that performs poorly and is difficult to interpret'), but he then goes on to develop a strategy for regression models which provide accurate predictions, and then discusses how this model may be improved to allow accurate effect estimation, commenting 'estimation of effects for these models must involve accurate prediction of overall response values'. Effectively it seems doubtful that you can have an accurate estimate of the value of a predictor's effect size if you don't have a model that accurately predicts your target. Harrell points out some useful considerations needed to ensure that a model providing good accuracy can provide good estimates of predictor effects. For example, one is strict attention to interaction effects. Another is the role of imputation for missing data, especially if a variable whose effect size is a high priority has many missing values e.g. it might be sensible to impute the missing values if model accuracy is the only goal, but not sensible if estimating that particular effect is the goal. At the same time, the above implies that it is possible to achieve a level of accuracy with respect to the target without having achieved accurate estimates of each predictor's effect. You also mention causal analysis, and one of the commenters rightly observes that you can achieve accurate estimates of correlations without accurately understanding causal relationships. Overall, it begins to look like a hierarchy, where a strong predictive model forms the foundation for accurate estimation of predictor effects, and accurate predictor estimates of predictor effects could then be the beginning of an analysis of causation. Then the answer to your main question is 'yes, it is legitimate to use the coefficients from a predictive model for inference, under the condition that the model has been analysed carefully to ensure the legitimacy of the effects estimates'.
Inference and predictive models Frank Harrell, in his 'Regression Modeling Strategies' (2015) offers a range of possible modeling strategies (section 4.12, if you are able to obtain a copy), some of which may be considered facetious
47,113
When I normalize the standardized values of data, why do I get the same values as just normalizing?
The easy answer is that standardization and normalization are linear transformations of the data and any line is determined by two distinct points on it. Since columns 3 and 4 are constructed to include the points $(\min(\text{data}), 0)$ and $(\max(\text{data}), 1)$ (namely, $(2,0)$ and $(95, 1)$), they must result from identical transformations. The algebraically rigorous answer manipulates the formulas. Recall that standardization of data $\mathbf{x} = x_1, x_2, \ldots, x_n$ replaces each $x_i$ with $$y_i = \frac{x_i - \bar x}{s_x}$$ where $\bar x$ usually is the (arithmetic) mean of the data and $s_x$ often is a standard deviation of the data. (Generally, $\bar x$ may be any estimate of a central value and $s_x$ may be any estimate of the spread, but such generality is usually not intended.) On the other hand, normalization replaces each $x_i$ with $$z_i = \frac{x_i - \min(\mathbf{x})}{\max(\mathbf x) - \min(\mathbf x)}.$$ But since $s_x \gt 0$, division by $s_x$ is an increasing function. Subtracting any constant like $\bar x$ similarly is an increasing function. Therefore the extremes of $\mathbf x$ correspond to the extremes of $\mathbf y$. Consequently, normalization of $\mathbf y = y_1, y_2, \ldots,y_n$ produces $$\eqalign{ z_i^\prime &= \frac{y_i - \min(\mathbf{y})}{\max(\mathbf y) - \min(\mathbf y)} \\ &= \frac{\frac{x_i - \bar x}{s_x} - \min_j(\frac{x_j - \bar x}{s_x})}{\max_j(\frac{x_j - \bar x}{s_x}) - \min_j(\frac{x_j - \bar x}{s_x})} \\ &= \frac{{x_i - \bar x} - \min_j({x_j - \bar x})}{\max_j({x_j - \bar x}) - \min_j({x_j - \bar x})} \\ &= \frac{x_i - \min(\mathbf{x})}{\max(\mathbf x) - \min(\mathbf x)} \\ &= z_i. }$$
When I normalize the standardized values of data, why do I get the same values as just normalizing?
The easy answer is that standardization and normalization are linear transformations of the data and any line is determined by two distinct points on it. Since columns 3 and 4 are constructed to incl
When I normalize the standardized values of data, why do I get the same values as just normalizing? The easy answer is that standardization and normalization are linear transformations of the data and any line is determined by two distinct points on it. Since columns 3 and 4 are constructed to include the points $(\min(\text{data}), 0)$ and $(\max(\text{data}), 1)$ (namely, $(2,0)$ and $(95, 1)$), they must result from identical transformations. The algebraically rigorous answer manipulates the formulas. Recall that standardization of data $\mathbf{x} = x_1, x_2, \ldots, x_n$ replaces each $x_i$ with $$y_i = \frac{x_i - \bar x}{s_x}$$ where $\bar x$ usually is the (arithmetic) mean of the data and $s_x$ often is a standard deviation of the data. (Generally, $\bar x$ may be any estimate of a central value and $s_x$ may be any estimate of the spread, but such generality is usually not intended.) On the other hand, normalization replaces each $x_i$ with $$z_i = \frac{x_i - \min(\mathbf{x})}{\max(\mathbf x) - \min(\mathbf x)}.$$ But since $s_x \gt 0$, division by $s_x$ is an increasing function. Subtracting any constant like $\bar x$ similarly is an increasing function. Therefore the extremes of $\mathbf x$ correspond to the extremes of $\mathbf y$. Consequently, normalization of $\mathbf y = y_1, y_2, \ldots,y_n$ produces $$\eqalign{ z_i^\prime &= \frac{y_i - \min(\mathbf{y})}{\max(\mathbf y) - \min(\mathbf y)} \\ &= \frac{\frac{x_i - \bar x}{s_x} - \min_j(\frac{x_j - \bar x}{s_x})}{\max_j(\frac{x_j - \bar x}{s_x}) - \min_j(\frac{x_j - \bar x}{s_x})} \\ &= \frac{{x_i - \bar x} - \min_j({x_j - \bar x})}{\max_j({x_j - \bar x}) - \min_j({x_j - \bar x})} \\ &= \frac{x_i - \min(\mathbf{x})}{\max(\mathbf x) - \min(\mathbf x)} \\ &= z_i. }$$
When I normalize the standardized values of data, why do I get the same values as just normalizing? The easy answer is that standardization and normalization are linear transformations of the data and any line is determined by two distinct points on it. Since columns 3 and 4 are constructed to incl
47,114
Machine learning algorithms as matrix factorization
Generalized Low Rank Models paper deals with exactly this. From the abstract: This framework encompasses many well known techniques in data analysis, such as nonnegative matrix factorization, matrix completion, sparse and robust PCA, k-means, k-SVD, and maximum margin matrix factorization.
Machine learning algorithms as matrix factorization
Generalized Low Rank Models paper deals with exactly this. From the abstract: This framework encompasses many well known techniques in data analysis, such as nonnegative matrix factorization, ma
Machine learning algorithms as matrix factorization Generalized Low Rank Models paper deals with exactly this. From the abstract: This framework encompasses many well known techniques in data analysis, such as nonnegative matrix factorization, matrix completion, sparse and robust PCA, k-means, k-SVD, and maximum margin matrix factorization.
Machine learning algorithms as matrix factorization Generalized Low Rank Models paper deals with exactly this. From the abstract: This framework encompasses many well known techniques in data analysis, such as nonnegative matrix factorization, ma
47,115
How to estimate the Poisson distribution with one event occurrence?
I would treat this as one observation of, assuming you started at midnight on Dec. 31, 2000, 4 years, and another observation censored at 12.956 years. In the case of the exponential distribution, this is a pretty easy problem to solve: $$p(x_1, x_2 | \lambda) = \left(\frac{1}{\lambda}e^{-x_1/\lambda}\right)\left(e^{-c_2/\lambda}\right)$$ where the first term is the probability of observing $x_1$ and the second the probability of observing $x_2 > c_2$, with $c_2$ being the censoring point of 12.956 years. Taking the log and setting the derivative equal to zero gives us: $$\hat{\lambda} = \frac{1}{x_1 + c_2}$$ which gives us roughly $1/18$ years, as we are at the end of 2017 instead of the beginning. This is just working through a specific case of the general result that the MLE for a censored Exponential distribution is equal to the sum of the total observed times, regardless of whether they were censored, divided by the total number of observed arrivals. The conclusion: the two approaches will give the same result. Edit in response to comments: The Poisson and Exponential-based estimators will always give the same answer. In the case of the Poisson, you have $n$ events observed over the time period $T$ giving an estimate of $T/n$. In the case of the Exponential, your total observed time is $T$, and you have $n+1$ observations, with the last one being censored by the end of the observation period, so the estimate is $n/T$.
How to estimate the Poisson distribution with one event occurrence?
I would treat this as one observation of, assuming you started at midnight on Dec. 31, 2000, 4 years, and another observation censored at 12.956 years. In the case of the exponential distribution, t
How to estimate the Poisson distribution with one event occurrence? I would treat this as one observation of, assuming you started at midnight on Dec. 31, 2000, 4 years, and another observation censored at 12.956 years. In the case of the exponential distribution, this is a pretty easy problem to solve: $$p(x_1, x_2 | \lambda) = \left(\frac{1}{\lambda}e^{-x_1/\lambda}\right)\left(e^{-c_2/\lambda}\right)$$ where the first term is the probability of observing $x_1$ and the second the probability of observing $x_2 > c_2$, with $c_2$ being the censoring point of 12.956 years. Taking the log and setting the derivative equal to zero gives us: $$\hat{\lambda} = \frac{1}{x_1 + c_2}$$ which gives us roughly $1/18$ years, as we are at the end of 2017 instead of the beginning. This is just working through a specific case of the general result that the MLE for a censored Exponential distribution is equal to the sum of the total observed times, regardless of whether they were censored, divided by the total number of observed arrivals. The conclusion: the two approaches will give the same result. Edit in response to comments: The Poisson and Exponential-based estimators will always give the same answer. In the case of the Poisson, you have $n$ events observed over the time period $T$ giving an estimate of $T/n$. In the case of the Exponential, your total observed time is $T$, and you have $n+1$ observations, with the last one being censored by the end of the observation period, so the estimate is $n/T$.
How to estimate the Poisson distribution with one event occurrence? I would treat this as one observation of, assuming you started at midnight on Dec. 31, 2000, 4 years, and another observation censored at 12.956 years. In the case of the exponential distribution, t
47,116
How to estimate the Poisson distribution with one event occurrence?
Looking more closely at your simulation, I can see a bit more clearly what you're doing. You've set up a data generating process with a random intensity taking a gamma distribution for each gamma intensity, there's a Poisson realization, you then turn to estimate the Poisson rate among a subsample with non-zero counts. This is a bit different than how I envisioned the date problem because you have data from a sample, some of which are deliberately excluded, and this sample has important heterogeneity. There's a couple things to address here: If you did not have a random input to the Poisson process, the correct probability model for the observed data is a zero-truncated Poisson distribution. https://en.wikipedia.org/wiki/Zero-truncated_Poisson_distribution. Note that a method of moments estimator for the intensity could be solved numerically (no tractable analytic solution) \begin{equation} 0 = \bar{Y} - \lambda \exp(\lambda) / (\exp(\lambda) - 1) \end{equation} set.seed(123) ns <- 10000 zcpois <- function(y) uniroot(function(x) mean(y) - x*exp(x)/(exp(x)-1), c(1e-8, max(y))) y <- rpois(ns, 0.7) zcpois(y[y!=0]) ## very precise MoM > zcpois(y[y!=0])$root [1] 0.6950045 You can also use maximum likelihood recalling the likelihood for a truncated RV: $P(Y=y | Y>0) = P(Y=y)/P(Y>0)$. y0 <- y[y!=0] negloglik <- function(lambda, y) { -sum(dpois(x=y, lambda=lambda, log=T) - ppois(q=0, lambda=lambda, lower.tail=F, log=T)) } lseq <- seq(from=0.001, to=2, by=0.001) nll <- sapply(lseq, negloglik, y=y0) plot(lseq, nll, type='l') i <- which.min(nll) abline(v=lseq[i]) text(lseq[i], max(nll), paste('MLE:', lseq[i]), pos=4, xpd=T) However, it's important to consider the Poisson/Gamma mixture and the impact on the resulting probability model. The mixture model does not follow a zero-truncated Poisson distribution. The underlying Poisson process (without omission of 0 counts) would follow an overdispersed Poisson process. lambdas <- rgamma(ns, 1, 18) ## rate parametrization counts <- rpois(ns, lambdas) nzcounts <- counts[counts!=0] > zcpois(nzcounts)$root [1] 0.1311875 > mean(lambdas) [1] 0.05573894 A Bayesian model whose likelihood follows a zero-truncated Poisson model and whose intensity follows a gamma distribution with a non-informative shape and scale parameter would enable you to estimate the posterior distribution, whose posterior modes would give you good estimates of the input parameters to the gamma distribution. A frequentist approach would invoke the EM algorithm.
How to estimate the Poisson distribution with one event occurrence?
Looking more closely at your simulation, I can see a bit more clearly what you're doing. You've set up a data generating process with a random intensity taking a gamma distribution for each gamma inte
How to estimate the Poisson distribution with one event occurrence? Looking more closely at your simulation, I can see a bit more clearly what you're doing. You've set up a data generating process with a random intensity taking a gamma distribution for each gamma intensity, there's a Poisson realization, you then turn to estimate the Poisson rate among a subsample with non-zero counts. This is a bit different than how I envisioned the date problem because you have data from a sample, some of which are deliberately excluded, and this sample has important heterogeneity. There's a couple things to address here: If you did not have a random input to the Poisson process, the correct probability model for the observed data is a zero-truncated Poisson distribution. https://en.wikipedia.org/wiki/Zero-truncated_Poisson_distribution. Note that a method of moments estimator for the intensity could be solved numerically (no tractable analytic solution) \begin{equation} 0 = \bar{Y} - \lambda \exp(\lambda) / (\exp(\lambda) - 1) \end{equation} set.seed(123) ns <- 10000 zcpois <- function(y) uniroot(function(x) mean(y) - x*exp(x)/(exp(x)-1), c(1e-8, max(y))) y <- rpois(ns, 0.7) zcpois(y[y!=0]) ## very precise MoM > zcpois(y[y!=0])$root [1] 0.6950045 You can also use maximum likelihood recalling the likelihood for a truncated RV: $P(Y=y | Y>0) = P(Y=y)/P(Y>0)$. y0 <- y[y!=0] negloglik <- function(lambda, y) { -sum(dpois(x=y, lambda=lambda, log=T) - ppois(q=0, lambda=lambda, lower.tail=F, log=T)) } lseq <- seq(from=0.001, to=2, by=0.001) nll <- sapply(lseq, negloglik, y=y0) plot(lseq, nll, type='l') i <- which.min(nll) abline(v=lseq[i]) text(lseq[i], max(nll), paste('MLE:', lseq[i]), pos=4, xpd=T) However, it's important to consider the Poisson/Gamma mixture and the impact on the resulting probability model. The mixture model does not follow a zero-truncated Poisson distribution. The underlying Poisson process (without omission of 0 counts) would follow an overdispersed Poisson process. lambdas <- rgamma(ns, 1, 18) ## rate parametrization counts <- rpois(ns, lambdas) nzcounts <- counts[counts!=0] > zcpois(nzcounts)$root [1] 0.1311875 > mean(lambdas) [1] 0.05573894 A Bayesian model whose likelihood follows a zero-truncated Poisson model and whose intensity follows a gamma distribution with a non-informative shape and scale parameter would enable you to estimate the posterior distribution, whose posterior modes would give you good estimates of the input parameters to the gamma distribution. A frequentist approach would invoke the EM algorithm.
How to estimate the Poisson distribution with one event occurrence? Looking more closely at your simulation, I can see a bit more clearly what you're doing. You've set up a data generating process with a random intensity taking a gamma distribution for each gamma inte
47,117
Alternative to Chi-squared test to check if categorical distribution in two sets are the same
Tests for equivalence test the null hypothesis that quantities are different by a threshold of relevance—the smallest value that researchers, or regulators in the case of, for example, the FDA, consider to be meaningful—and rejection of this null hypothesis is to conclude that the quantities are equivalent within the bounds of the relevance threshold.1 One form of equivalence tests is the two one-sided tests (TOST) approach, where (typically) two one-sided t or z tests are constructed around the relevance threshold in the upper and lower directions… rejecting both one-sided tests implies that the true value ought to be inferred to lying within the equivalence range. However, TOST, why relatively straightforward to compute, and widely used, ignores an accurate accounting of power to reject by ignoring the non-centrality parameters that come into play in their test statistics. By contrast uniformly most powerful (UMP) tests for equivalence account for such, and provide optimal statistical power to reject equivalence null hypotheses. Chapter 9, section 9.2 of Welleck's Testing Statistical Hypotheses Of Equivalence And Noninferiority, Second Edition provides a uniformly most powerful test for equivalence for contingency table $\chi^{2}$ tests (or, test for 'collapsability' as the contingency table equivalence testing literature has it). The math for constructing the UMP contingency table test statistic is a tad hairy (by which I mean I haven't learned it yet :), but Welleck includes an R macro for the test and an example application. Finally, I will note that only testing for difference, or only testing for equivalence implies—without explicit a priori power analysis and justification of minimum relevant effect size—committing to confirmation bias by privileging the direction of evidence/burden of proof. A savvy way to counter that commitment in a frequentist analytic context is to conduct both tests for relevance and tests for equivalence, and draw conclusions accordingly (see the [tost] tag info page for more details on this point). 1 Relevance thresholds can be asymmetric: closer to 'no difference' in one direction than the other.
Alternative to Chi-squared test to check if categorical distribution in two sets are the same
Tests for equivalence test the null hypothesis that quantities are different by a threshold of relevance—the smallest value that researchers, or regulators in the case of, for example, the FDA, consid
Alternative to Chi-squared test to check if categorical distribution in two sets are the same Tests for equivalence test the null hypothesis that quantities are different by a threshold of relevance—the smallest value that researchers, or regulators in the case of, for example, the FDA, consider to be meaningful—and rejection of this null hypothesis is to conclude that the quantities are equivalent within the bounds of the relevance threshold.1 One form of equivalence tests is the two one-sided tests (TOST) approach, where (typically) two one-sided t or z tests are constructed around the relevance threshold in the upper and lower directions… rejecting both one-sided tests implies that the true value ought to be inferred to lying within the equivalence range. However, TOST, why relatively straightforward to compute, and widely used, ignores an accurate accounting of power to reject by ignoring the non-centrality parameters that come into play in their test statistics. By contrast uniformly most powerful (UMP) tests for equivalence account for such, and provide optimal statistical power to reject equivalence null hypotheses. Chapter 9, section 9.2 of Welleck's Testing Statistical Hypotheses Of Equivalence And Noninferiority, Second Edition provides a uniformly most powerful test for equivalence for contingency table $\chi^{2}$ tests (or, test for 'collapsability' as the contingency table equivalence testing literature has it). The math for constructing the UMP contingency table test statistic is a tad hairy (by which I mean I haven't learned it yet :), but Welleck includes an R macro for the test and an example application. Finally, I will note that only testing for difference, or only testing for equivalence implies—without explicit a priori power analysis and justification of minimum relevant effect size—committing to confirmation bias by privileging the direction of evidence/burden of proof. A savvy way to counter that commitment in a frequentist analytic context is to conduct both tests for relevance and tests for equivalence, and draw conclusions accordingly (see the [tost] tag info page for more details on this point). 1 Relevance thresholds can be asymmetric: closer to 'no difference' in one direction than the other.
Alternative to Chi-squared test to check if categorical distribution in two sets are the same Tests for equivalence test the null hypothesis that quantities are different by a threshold of relevance—the smallest value that researchers, or regulators in the case of, for example, the FDA, consid
47,118
Alternative to Chi-squared test to check if categorical distribution in two sets are the same
I think identifying an appropriate threshold that indicates a meaningful rather than simply a statistically significant difference between your two samples would be a valuable step as described, in part, by @Alexis's answer. I would like to propose an alternative approach of sorts, though, one based on simulation. The logic here is that you can create a range of plausible sample counts based on your larger dataset, and then determine whether your observed counts for the smaller dataset generally fall inside or outside those plausible ranges. Using your counts from your larger sample to represent something closer to your population counts then, you can generate a sufficiently large number of random samples from said (pseudo)population of the same size as your smaller sample. I will illustrate using R, and with a much smaller set of categorical data: > #Observed frequencies in the larger sample: > lambdas<-c(2500,30000,25000,17000,18750,19200, 2000, 2500, 950, 750) > N<-sum(lambdas) > #Total "psuedo"-population size > N [1] 118650 > > #Probabilities for each category (based on "pseudo"-population) > p<-lambdas/N > p [1] 0.021070375 0.252844501 0.210703751 0.143278550 0.158027813 0.161820480 [7] 0.016856300 0.021070375 0.008006743 0.006321113 > > #Sample size for smaller data set > N2<-2500 > > #Category names > cat.names<-paste('cat', sep='_', letters[1:length(p)]) > > #Simulate category counts > n.sims<-10000 > sim.counts<-data.frame() > for(i in 1:n.sims){ + temp<-as.vector(table(sample(cat.names, size=N2, prob=p, replace=T))) + sim.counts<-rbind(sim.counts, temp) + } > > colnames(sim.counts)<-cat.names > head(sim.counts) cat_a cat_b cat_c cat_d cat_e cat_f cat_g cat_h cat_i cat_j 1 46 576 535 348 453 400 50 49 28 15 2 46 603 537 338 421 426 38 50 25 16 3 50 633 495 350 391 450 46 46 22 17 4 60 606 521 344 440 397 50 50 18 14 5 42 630 539 381 386 398 34 58 19 13 6 48 663 514 356 398 380 40 62 22 17 > > #create empty vectors to hold upper and lower percentile values > LB.95<-vector() > UB.95<-vector() > #calculate 95% interval > for(i in 1:length(p)){ + LB.95[i]<-quantile(sim.counts[,i], .025) + UB.95[i]<-quantile(sim.counts[,i], .975) + } > > cbind(cat.names, LB.95, UB.95) cat.names LB.95 UB.95 [1,] "cat_a" "39" "67" [2,] "cat_b" "590" "675" [3,] "cat_c" "487" "566" [4,] "cat_d" "324" "392" [5,] "cat_e" "360" "431" [6,] "cat_f" "369" "442" [7,] "cat_g" "30" "55" [8,] "cat_h" "39" "67" [9,] "cat_i" "12" "30" [10,] "cat_j" "9" "24" Now the biggest caveat here is that I am treating estimates from my larger sample ($N$ = 118,650) as if they were parameters from the population. In some ways this simulation then is something of a poor man's Bayesian approach to resolving the problem, where I ignore my uncertainty about the the true parameters based on the large initial sample. One could certainly take a more fully Bayesian approach to this problem, and I am sure there are a number of advocates in the applied statistics community who would see this question as extremely well-suited to Bayesian techniques. The caveat noted, how do you use this analysis? Well, you can take an obtained sample of size N2 (in my case $N_2$ = 2500), calculate your counts for each category, and determine whether those counts fall within a pre-identified interval based on the simulations (I chose a 95% confidence interval - displayed in the final table). Note that this approach will not have the nice, clean decision-making rules often relied upon within a hypothesis-testing framework, and depending on your final audience, this may be a non-trivial concern. However, you can answer (perhaps more meaningfully even) whether obtained counts from a smaller sample fall within a likely range of values if the parameters for the population from which that sample was drawn are equivalent to a MUCH larger (presumably previously obtained) comparison sample.
Alternative to Chi-squared test to check if categorical distribution in two sets are the same
I think identifying an appropriate threshold that indicates a meaningful rather than simply a statistically significant difference between your two samples would be a valuable step as described, in pa
Alternative to Chi-squared test to check if categorical distribution in two sets are the same I think identifying an appropriate threshold that indicates a meaningful rather than simply a statistically significant difference between your two samples would be a valuable step as described, in part, by @Alexis's answer. I would like to propose an alternative approach of sorts, though, one based on simulation. The logic here is that you can create a range of plausible sample counts based on your larger dataset, and then determine whether your observed counts for the smaller dataset generally fall inside or outside those plausible ranges. Using your counts from your larger sample to represent something closer to your population counts then, you can generate a sufficiently large number of random samples from said (pseudo)population of the same size as your smaller sample. I will illustrate using R, and with a much smaller set of categorical data: > #Observed frequencies in the larger sample: > lambdas<-c(2500,30000,25000,17000,18750,19200, 2000, 2500, 950, 750) > N<-sum(lambdas) > #Total "psuedo"-population size > N [1] 118650 > > #Probabilities for each category (based on "pseudo"-population) > p<-lambdas/N > p [1] 0.021070375 0.252844501 0.210703751 0.143278550 0.158027813 0.161820480 [7] 0.016856300 0.021070375 0.008006743 0.006321113 > > #Sample size for smaller data set > N2<-2500 > > #Category names > cat.names<-paste('cat', sep='_', letters[1:length(p)]) > > #Simulate category counts > n.sims<-10000 > sim.counts<-data.frame() > for(i in 1:n.sims){ + temp<-as.vector(table(sample(cat.names, size=N2, prob=p, replace=T))) + sim.counts<-rbind(sim.counts, temp) + } > > colnames(sim.counts)<-cat.names > head(sim.counts) cat_a cat_b cat_c cat_d cat_e cat_f cat_g cat_h cat_i cat_j 1 46 576 535 348 453 400 50 49 28 15 2 46 603 537 338 421 426 38 50 25 16 3 50 633 495 350 391 450 46 46 22 17 4 60 606 521 344 440 397 50 50 18 14 5 42 630 539 381 386 398 34 58 19 13 6 48 663 514 356 398 380 40 62 22 17 > > #create empty vectors to hold upper and lower percentile values > LB.95<-vector() > UB.95<-vector() > #calculate 95% interval > for(i in 1:length(p)){ + LB.95[i]<-quantile(sim.counts[,i], .025) + UB.95[i]<-quantile(sim.counts[,i], .975) + } > > cbind(cat.names, LB.95, UB.95) cat.names LB.95 UB.95 [1,] "cat_a" "39" "67" [2,] "cat_b" "590" "675" [3,] "cat_c" "487" "566" [4,] "cat_d" "324" "392" [5,] "cat_e" "360" "431" [6,] "cat_f" "369" "442" [7,] "cat_g" "30" "55" [8,] "cat_h" "39" "67" [9,] "cat_i" "12" "30" [10,] "cat_j" "9" "24" Now the biggest caveat here is that I am treating estimates from my larger sample ($N$ = 118,650) as if they were parameters from the population. In some ways this simulation then is something of a poor man's Bayesian approach to resolving the problem, where I ignore my uncertainty about the the true parameters based on the large initial sample. One could certainly take a more fully Bayesian approach to this problem, and I am sure there are a number of advocates in the applied statistics community who would see this question as extremely well-suited to Bayesian techniques. The caveat noted, how do you use this analysis? Well, you can take an obtained sample of size N2 (in my case $N_2$ = 2500), calculate your counts for each category, and determine whether those counts fall within a pre-identified interval based on the simulations (I chose a 95% confidence interval - displayed in the final table). Note that this approach will not have the nice, clean decision-making rules often relied upon within a hypothesis-testing framework, and depending on your final audience, this may be a non-trivial concern. However, you can answer (perhaps more meaningfully even) whether obtained counts from a smaller sample fall within a likely range of values if the parameters for the population from which that sample was drawn are equivalent to a MUCH larger (presumably previously obtained) comparison sample.
Alternative to Chi-squared test to check if categorical distribution in two sets are the same I think identifying an appropriate threshold that indicates a meaningful rather than simply a statistically significant difference between your two samples would be a valuable step as described, in pa
47,119
When is likelihood also a probability distribution?
The likelihood is a two variables function $L(\theta,x)$. For fixed $\theta$, this function can be seen as a function of $x$, and this is a distribution: the distribution of $x$ for this fixed $\theta$. For fixed $x$, this function can be seen as a function of $\theta$, and this should not be thought as a distribution. Most often it is not formally a distribution since it does no sum to 1. Sometimes it may formally be a distribution and sum to 1 (see Xi'an answer), but it can be thought as an "accident". Actually, when using the word "likelihood" we most often implicitly mean that we look at it as a function of $\theta$ for fixed $x$, thus it makes sense saying the likelihood is not a distribution. Bayesian inference is a useful way however to understand that in spite of not being a distribution it is related to a distribution. In Bayesian inference the distribution of $\theta$ for fixed $x$, known as the posterior, is : $$p(\theta|x)=p(\theta)L(\theta,x)c(x)$$ where: $p(\theta)$ is the prior $L(\theta,x)$ is the likelihood $c(x)$ is a normalization constant (that is not very important) The likelihood can be thought as the distribution of $\theta$ for fixed $x$ (actually proportional to it) for the special case where the prior is uniform (constant). Generally, the likelihood is not the posterior, but the function by which you multiply the prior to get the the posterior. It plays a key role in defining a distribution (the posterior) while not being a distribution.
When is likelihood also a probability distribution?
The likelihood is a two variables function $L(\theta,x)$. For fixed $\theta$, this function can be seen as a function of $x$, and this is a distribution: the distribution of $x$ for this fixed $\theta
When is likelihood also a probability distribution? The likelihood is a two variables function $L(\theta,x)$. For fixed $\theta$, this function can be seen as a function of $x$, and this is a distribution: the distribution of $x$ for this fixed $\theta$. For fixed $x$, this function can be seen as a function of $\theta$, and this should not be thought as a distribution. Most often it is not formally a distribution since it does no sum to 1. Sometimes it may formally be a distribution and sum to 1 (see Xi'an answer), but it can be thought as an "accident". Actually, when using the word "likelihood" we most often implicitly mean that we look at it as a function of $\theta$ for fixed $x$, thus it makes sense saying the likelihood is not a distribution. Bayesian inference is a useful way however to understand that in spite of not being a distribution it is related to a distribution. In Bayesian inference the distribution of $\theta$ for fixed $x$, known as the posterior, is : $$p(\theta|x)=p(\theta)L(\theta,x)c(x)$$ where: $p(\theta)$ is the prior $L(\theta,x)$ is the likelihood $c(x)$ is a normalization constant (that is not very important) The likelihood can be thought as the distribution of $\theta$ for fixed $x$ (actually proportional to it) for the special case where the prior is uniform (constant). Generally, the likelihood is not the posterior, but the function by which you multiply the prior to get the the posterior. It plays a key role in defining a distribution (the posterior) while not being a distribution.
When is likelihood also a probability distribution? The likelihood is a two variables function $L(\theta,x)$. For fixed $\theta$, this function can be seen as a function of $x$, and this is a distribution: the distribution of $x$ for this fixed $\theta
47,120
When is likelihood also a probability distribution?
On the generic and general distinction between likelihood and probability density, check this question on CV as it has fairly detailed and useful answers. Plus this other question on mathoverflow. For the likelihood $\ell(\theta|x)$ to be a probability distribution, or more precisely the density of a probability distribution, it need satisfy$$\int_\Theta \ell(\theta|x)\text{d}\theta=1\quad\forall x\in\mathcal{X}\qquad\qquad(1)$$on top of satisfying$$\int_\Theta \ell(\theta|x)\text{d}x=1\quad\forall\theta\in\Theta\qquad\qquad(2)$$This is a situation that occurs when $x$ and $\theta$ are interchangeable as in location families$$\ell(\theta|x)=f(x-\theta)\qquad x,\theta\in\mathcal{X}=\Theta$$ but not in scale families$$\ell(\theta|x)=g(x/\theta)/\theta\qquad x,\theta>0$$due to the normalisation factor $1/\theta$. However, and this is central to my answer that the question does not have a generic meaning, a change of variable from $(x,\theta)$ to $$(y,\xi)=(\log x,\log \theta)$$turns the scale family into a location family, for which the property holds. This highlights that the major issue that property (1) heavily depends on the choice of the parameterisation $\theta$ of the distribution of $X$: likelihoods are invariant by reparameterisation and thus do not include a Jacobian for the change of variables, as probability densities do. Hence, if (1) holds for a parameterisation $\theta$ it will a.s. not hold for another parameterisation $\xi=h(\theta)$. A new question is thus whether there could exist a parameterisation for which (1) happens but this is unlikely, especially when considering the dependence of $\ell(\theta|x)$ on the size of the sample $x$. For exponential families, this would essentially correspond to the existence of a function equal to its Laplace transform. Although this brings another difficulty with the phrasing of the question, which does not specify the dominating measures on $\mathcal{X}$ and $\Theta$: if those are free (and they should be in the case of $\Theta$ outside of a Bayesian setting) then there are more chances of a positive answer.
When is likelihood also a probability distribution?
On the generic and general distinction between likelihood and probability density, check this question on CV as it has fairly detailed and useful answers. Plus this other question on mathoverflow. For
When is likelihood also a probability distribution? On the generic and general distinction between likelihood and probability density, check this question on CV as it has fairly detailed and useful answers. Plus this other question on mathoverflow. For the likelihood $\ell(\theta|x)$ to be a probability distribution, or more precisely the density of a probability distribution, it need satisfy$$\int_\Theta \ell(\theta|x)\text{d}\theta=1\quad\forall x\in\mathcal{X}\qquad\qquad(1)$$on top of satisfying$$\int_\Theta \ell(\theta|x)\text{d}x=1\quad\forall\theta\in\Theta\qquad\qquad(2)$$This is a situation that occurs when $x$ and $\theta$ are interchangeable as in location families$$\ell(\theta|x)=f(x-\theta)\qquad x,\theta\in\mathcal{X}=\Theta$$ but not in scale families$$\ell(\theta|x)=g(x/\theta)/\theta\qquad x,\theta>0$$due to the normalisation factor $1/\theta$. However, and this is central to my answer that the question does not have a generic meaning, a change of variable from $(x,\theta)$ to $$(y,\xi)=(\log x,\log \theta)$$turns the scale family into a location family, for which the property holds. This highlights that the major issue that property (1) heavily depends on the choice of the parameterisation $\theta$ of the distribution of $X$: likelihoods are invariant by reparameterisation and thus do not include a Jacobian for the change of variables, as probability densities do. Hence, if (1) holds for a parameterisation $\theta$ it will a.s. not hold for another parameterisation $\xi=h(\theta)$. A new question is thus whether there could exist a parameterisation for which (1) happens but this is unlikely, especially when considering the dependence of $\ell(\theta|x)$ on the size of the sample $x$. For exponential families, this would essentially correspond to the existence of a function equal to its Laplace transform. Although this brings another difficulty with the phrasing of the question, which does not specify the dominating measures on $\mathcal{X}$ and $\Theta$: if those are free (and they should be in the case of $\Theta$ outside of a Bayesian setting) then there are more chances of a positive answer.
When is likelihood also a probability distribution? On the generic and general distinction between likelihood and probability density, check this question on CV as it has fairly detailed and useful answers. Plus this other question on mathoverflow. For
47,121
Hyper-parameter estimation for Beta-Binomial Empirical Bayes
The hierarchical model You don't actually even need the marginal probability mass function $m()$, you actually only need the marginal moments of $Y$. In this tutorial, Casella (1992) is assuming the following hierarchical model for a response count $Y$: $$Y|p\sim\mbox{bin}(n,p)$$ and $$p \sim \mbox{Beta}(\lambda,\lambda)$$ with $n=50$. Moments of the prior distribution The Beta distribution usually has two parameters, $\alpha$ and $\beta$ say, and the mean is $\alpha/(\alpha+\beta)$. The variance is slightly more complicated, see the Wikipedia article on the Beta distribution. In this case, both parameters are the same, $\alpha=\beta=\lambda$, so the prior distribution for $p$ is symmetric with mean 1/2. The hyper-parameter $\lambda$ affects the variance of the prior distribution around 1/2, with larger values of $\lambda$ corresponding to smaller variances. In other words, $\lambda$ determines the precision (and hence the informativeness) of the prior. Specifically, the mean and variance of the prior distribution are $E(p)=1/2$ and $\mbox{var}(p)=1/\{4(2\lambda+1)\}$. It will also be convenient later to note that $$E[p(1-p)]=\frac12-\frac14-\frac1{4(2\lambda+1)}=\frac{\lambda}{2(2\lambda+1)}$$ Marginal moments for $Y$ Now we can obtain the marginal moments of $Y$. It is a characteristic of empirical Bayes that it uses the marginal distribution for marginal moments to estimate the unknown parameters in the prior. The marginal mean of $Y$ is obviously $$E(Y)=E_p(np)=n/2$$ The marginal variance of $Y$ is most easily obtained by the law of total variance: \begin{eqnarray}\mbox{var}(Y)&=&E_p \mbox{var}(Y|p) + \mbox{var}_p E(Y|p)\\ &=&E_p[ np(1-p)] + \mbox{var}_p[np]\\ &=&\frac{n\lambda}{2(2\lambda+1)}+\frac{n^2}{4(2\lambda+1)}\\ &=&\frac{n}{4}\frac{2\lambda+n}{2\lambda+1} \end{eqnarray} It might not be obvious, but var($Y$) is a decreasing function of $\lambda$. It has a maximum value of $n^2/4$ for $\lambda=0$ and a minimum value of $n/4$ for $\lambda=\infty$. Hyper-parameter estimation We can use the observed variance of $Y$ to estimate $\lambda$. Suppose we observe y-values 35 and 27. The sample variance of these two values is 32. Equating $$\mbox{var}(Y)=\frac{n}{4}\frac{2\lambda+n}{2\lambda+1}=32$$ and solving for $\lambda$ gives $\hat\lambda=$15.205. Posterior Inference Now that we have estimated the hyper-parameter $\hat\lambda$, we can now proceed with Bayesian posterior inference. Given an observation $Y=y_i$, we have two possible estimators of the corresponding $p_i$. The usual maximum likelihood estimator (MLE) is $\hat p_i=y_i/n$, but we also have the prior estimate $p_0=1/2$ predicted by the prior distribution. How should we combine these two estimators? The precision of the MLE is determined by $n$ and the precision of the prior is determined by $2\lambda$, so we weight the two estimators accordingly. The posterior estimator for $p_i$ is the weighted average of the two estimators $$E(p_i|y_i,\lambda)=w_0 p_0 + w_1 \hat{p}_i$$ with weights equal to the relative precisions $$w_0=\frac{2\lambda}{2\lambda+n}$$ and $$w_1=\frac{n}{2\lambda+n}$$ This gives $$E(p_i|y_i,\lambda)=\frac{y_i+\lambda}{n+2 \lambda}$$ and we just plug-in $\lambda=\hat\lambda$. Another way to interpret the prior estimator is like this. It is as if we observed another $n=2\lambda$ cases and observed $\lambda$ successes (exactly half). So we just combine the prior sample with the observed sample to get $y_i+\lambda$ successes from $n+2\lambda$ cases, and that becomes the posterior mean. Interpretation Notice what is happening here. If the prior distribution was diffuse, then the $p_i$s will vary from one observation to another, and the variance of the $y_i$ will be relatively large. If the prior distribution was very concentrated, then the $p_i$ should be very consistent and the $y_i$ should be less variable. So we can use the variance of the $y_i$ to guess what the prior precision $2\lambda$ might have been. If the $y_i$ values are very tight, then we conclude that $\lambda$ is large and we give more weight to the prior distribution, moving all the $\hat p_i$ values towards 1/2. If the $y_i$ values are very dispersed, then we conclude that $\lambda$ was small, and we give less weight to the prior, leaving the $\hat p_i$ values more as they are. This is the essential idea of empirical Bayes, common to all empirical Bayes applications.
Hyper-parameter estimation for Beta-Binomial Empirical Bayes
The hierarchical model You don't actually even need the marginal probability mass function $m()$, you actually only need the marginal moments of $Y$. In this tutorial, Casella (1992) is assuming the f
Hyper-parameter estimation for Beta-Binomial Empirical Bayes The hierarchical model You don't actually even need the marginal probability mass function $m()$, you actually only need the marginal moments of $Y$. In this tutorial, Casella (1992) is assuming the following hierarchical model for a response count $Y$: $$Y|p\sim\mbox{bin}(n,p)$$ and $$p \sim \mbox{Beta}(\lambda,\lambda)$$ with $n=50$. Moments of the prior distribution The Beta distribution usually has two parameters, $\alpha$ and $\beta$ say, and the mean is $\alpha/(\alpha+\beta)$. The variance is slightly more complicated, see the Wikipedia article on the Beta distribution. In this case, both parameters are the same, $\alpha=\beta=\lambda$, so the prior distribution for $p$ is symmetric with mean 1/2. The hyper-parameter $\lambda$ affects the variance of the prior distribution around 1/2, with larger values of $\lambda$ corresponding to smaller variances. In other words, $\lambda$ determines the precision (and hence the informativeness) of the prior. Specifically, the mean and variance of the prior distribution are $E(p)=1/2$ and $\mbox{var}(p)=1/\{4(2\lambda+1)\}$. It will also be convenient later to note that $$E[p(1-p)]=\frac12-\frac14-\frac1{4(2\lambda+1)}=\frac{\lambda}{2(2\lambda+1)}$$ Marginal moments for $Y$ Now we can obtain the marginal moments of $Y$. It is a characteristic of empirical Bayes that it uses the marginal distribution for marginal moments to estimate the unknown parameters in the prior. The marginal mean of $Y$ is obviously $$E(Y)=E_p(np)=n/2$$ The marginal variance of $Y$ is most easily obtained by the law of total variance: \begin{eqnarray}\mbox{var}(Y)&=&E_p \mbox{var}(Y|p) + \mbox{var}_p E(Y|p)\\ &=&E_p[ np(1-p)] + \mbox{var}_p[np]\\ &=&\frac{n\lambda}{2(2\lambda+1)}+\frac{n^2}{4(2\lambda+1)}\\ &=&\frac{n}{4}\frac{2\lambda+n}{2\lambda+1} \end{eqnarray} It might not be obvious, but var($Y$) is a decreasing function of $\lambda$. It has a maximum value of $n^2/4$ for $\lambda=0$ and a minimum value of $n/4$ for $\lambda=\infty$. Hyper-parameter estimation We can use the observed variance of $Y$ to estimate $\lambda$. Suppose we observe y-values 35 and 27. The sample variance of these two values is 32. Equating $$\mbox{var}(Y)=\frac{n}{4}\frac{2\lambda+n}{2\lambda+1}=32$$ and solving for $\lambda$ gives $\hat\lambda=$15.205. Posterior Inference Now that we have estimated the hyper-parameter $\hat\lambda$, we can now proceed with Bayesian posterior inference. Given an observation $Y=y_i$, we have two possible estimators of the corresponding $p_i$. The usual maximum likelihood estimator (MLE) is $\hat p_i=y_i/n$, but we also have the prior estimate $p_0=1/2$ predicted by the prior distribution. How should we combine these two estimators? The precision of the MLE is determined by $n$ and the precision of the prior is determined by $2\lambda$, so we weight the two estimators accordingly. The posterior estimator for $p_i$ is the weighted average of the two estimators $$E(p_i|y_i,\lambda)=w_0 p_0 + w_1 \hat{p}_i$$ with weights equal to the relative precisions $$w_0=\frac{2\lambda}{2\lambda+n}$$ and $$w_1=\frac{n}{2\lambda+n}$$ This gives $$E(p_i|y_i,\lambda)=\frac{y_i+\lambda}{n+2 \lambda}$$ and we just plug-in $\lambda=\hat\lambda$. Another way to interpret the prior estimator is like this. It is as if we observed another $n=2\lambda$ cases and observed $\lambda$ successes (exactly half). So we just combine the prior sample with the observed sample to get $y_i+\lambda$ successes from $n+2\lambda$ cases, and that becomes the posterior mean. Interpretation Notice what is happening here. If the prior distribution was diffuse, then the $p_i$s will vary from one observation to another, and the variance of the $y_i$ will be relatively large. If the prior distribution was very concentrated, then the $p_i$ should be very consistent and the $y_i$ should be less variable. So we can use the variance of the $y_i$ to guess what the prior precision $2\lambda$ might have been. If the $y_i$ values are very tight, then we conclude that $\lambda$ is large and we give more weight to the prior distribution, moving all the $\hat p_i$ values towards 1/2. If the $y_i$ values are very dispersed, then we conclude that $\lambda$ was small, and we give less weight to the prior, leaving the $\hat p_i$ values more as they are. This is the essential idea of empirical Bayes, common to all empirical Bayes applications.
Hyper-parameter estimation for Beta-Binomial Empirical Bayes The hierarchical model You don't actually even need the marginal probability mass function $m()$, you actually only need the marginal moments of $Y$. In this tutorial, Casella (1992) is assuming the f
47,122
Interpretation of an I(2) process?
One interpetation is that the rate of change is random walk. It's like a free fall where the gravitational force is stochastically changing. If you drop the body on earth, it's moving according to the law: $$\frac{d^2}{dt^2}x=g$$ where $g$ is a gravitational constant. This means that the body's acceleration is always the same and equal to $g$. In a discretized version this would be $$\Delta^2x_t=g$$ If you replace the constant with a random variable, you get I(2) process: $$\Delta^2x_t=\varepsilon_t$$ It means that the acceleration is random, not constant anymore. Here's a demo. We're shooting a canon at 45 degree angle to the right, the initial velocity is 100, gravitational constant is 9.81. The red line show the constant acceleration, and the black lines are of stochastic acceleration i.e. I(2): Python code: import matplotlib.pyplot as plt import numpy as np import math dt = 0.1 g = 9.81 angle = math.pi/4 v = 100 vx = math.acos(angle)*v vy = math.asin(angle)*v x, y = 0, 0 while (y>=0): plt.plot(x,y,'r.') dx = vx*dt dy = vy*dt dvy = -g*dt x = x + dx y = y + dy vy = vy + dvy # I(2) np.random.seed(0) vx = math.acos(angle)*v for i in range(4): g0 = g x, y = 0, 0 vy = math.asin(angle)*v while (y>=0): plt.plot(x,y,'k.') g = g0 + np.random.randn()*20 dx = vx*dt dy = vy*dt dvy = -g*dt x = x + dx y = y + dy vy = vy + dvy plt.show()
Interpretation of an I(2) process?
One interpetation is that the rate of change is random walk. It's like a free fall where the gravitational force is stochastically changing. If you drop the body on earth, it's moving according to th
Interpretation of an I(2) process? One interpetation is that the rate of change is random walk. It's like a free fall where the gravitational force is stochastically changing. If you drop the body on earth, it's moving according to the law: $$\frac{d^2}{dt^2}x=g$$ where $g$ is a gravitational constant. This means that the body's acceleration is always the same and equal to $g$. In a discretized version this would be $$\Delta^2x_t=g$$ If you replace the constant with a random variable, you get I(2) process: $$\Delta^2x_t=\varepsilon_t$$ It means that the acceleration is random, not constant anymore. Here's a demo. We're shooting a canon at 45 degree angle to the right, the initial velocity is 100, gravitational constant is 9.81. The red line show the constant acceleration, and the black lines are of stochastic acceleration i.e. I(2): Python code: import matplotlib.pyplot as plt import numpy as np import math dt = 0.1 g = 9.81 angle = math.pi/4 v = 100 vx = math.acos(angle)*v vy = math.asin(angle)*v x, y = 0, 0 while (y>=0): plt.plot(x,y,'r.') dx = vx*dt dy = vy*dt dvy = -g*dt x = x + dx y = y + dy vy = vy + dvy # I(2) np.random.seed(0) vx = math.acos(angle)*v for i in range(4): g0 = g x, y = 0, 0 vy = math.asin(angle)*v while (y>=0): plt.plot(x,y,'k.') g = g0 + np.random.randn()*20 dx = vx*dt dy = vy*dt dvy = -g*dt x = x + dx y = y + dy vy = vy + dvy plt.show()
Interpretation of an I(2) process? One interpetation is that the rate of change is random walk. It's like a free fall where the gravitational force is stochastically changing. If you drop the body on earth, it's moving according to th
47,123
Calculate entropy of sample
Your question, as I understand it, basically amounts to, "what are the best practices for calculating entropy for an empirically measured distribution of a continuous random variable?" That's the question I'll attempt to answer. The good news is that the entropy of a continuous random variable is well-defined: one simply calculates an integral rather than a discrete sum: $$ H = -\sum_{i} p_{i} \log p_{i} \Rightarrow - \int_{X} p(x) \log p(x) $$ So now your question becomes, essentially, "given a set of emprical observations of a continuous variable $x$, how can I approximate or represent the distribution $p(x)$, so that I may calculate the necessary integral?" I can think of three different ways: If you believe you have a good theoretical or mathematical model that describes the underlying shape of the distribution (for example, a Gaussian mixture model), then you can use standard parameter estimation techniques such as regression analysis or maximum likelihood estimation to come up with estimated values for the model parameters (e.g., such as Gaussian mean, variance, and mixture component weights, or whatever other parameters control the shape of the underlying model) that are the most consistent with the data that you actually observed. Once you know those parameters, that information effectively defines $p(x)$, and you can simply perform the integral by whatever means you prefer (e.g., an analytic calculation, or a numerical integral, or whatever). You can generate a kernel density estimate, as you are already doing, and simply perform a numerical integration across all non-zero output values (i.e., across the so-called support for the distribution). You can calculate a histogram of the observed data, and then calculate the entropy by summing over the bins of the histogram. (Technically you could argue that a histogram is really just a trivial example of a kernel density estimate anyway--one in which the kernel function is a simple boxcar, and the kernel bandwidth is therefore identical to the histogram bin width.) Of these three methods, I find the first the most aesthetically appealing, provided one actually has a good theoretical model to explain the underlying data. However, coming up with a good theoretical model and then fitting it to the observed data isn't always possible, and in those cases, the other two methods are also perfectly defensible, as long as they are implemented in a way that generates a "reasonable" estimate of the underlying probability distribution $p(x)$. To generate a reasonable approximation of the distribution, the most important thing to do is simply make sure that you choose a reasonable value for the bandwidth (e.g., using this rule of thumb) if you're using a kernel density estimation technique, or the bin width (using one of these rules of thumb) if you're representing $p(x)$ as a histogram. In summary, yes there are other techniques besides kernel density estimation that you can use to derive an estimate for $p(x)$ and calculate the entropy, but the way that you are already doing it is also perfectly valid, provided you're using a typical kernel function and setting the bandwidth value appropriately.
Calculate entropy of sample
Your question, as I understand it, basically amounts to, "what are the best practices for calculating entropy for an empirically measured distribution of a continuous random variable?" That's the que
Calculate entropy of sample Your question, as I understand it, basically amounts to, "what are the best practices for calculating entropy for an empirically measured distribution of a continuous random variable?" That's the question I'll attempt to answer. The good news is that the entropy of a continuous random variable is well-defined: one simply calculates an integral rather than a discrete sum: $$ H = -\sum_{i} p_{i} \log p_{i} \Rightarrow - \int_{X} p(x) \log p(x) $$ So now your question becomes, essentially, "given a set of emprical observations of a continuous variable $x$, how can I approximate or represent the distribution $p(x)$, so that I may calculate the necessary integral?" I can think of three different ways: If you believe you have a good theoretical or mathematical model that describes the underlying shape of the distribution (for example, a Gaussian mixture model), then you can use standard parameter estimation techniques such as regression analysis or maximum likelihood estimation to come up with estimated values for the model parameters (e.g., such as Gaussian mean, variance, and mixture component weights, or whatever other parameters control the shape of the underlying model) that are the most consistent with the data that you actually observed. Once you know those parameters, that information effectively defines $p(x)$, and you can simply perform the integral by whatever means you prefer (e.g., an analytic calculation, or a numerical integral, or whatever). You can generate a kernel density estimate, as you are already doing, and simply perform a numerical integration across all non-zero output values (i.e., across the so-called support for the distribution). You can calculate a histogram of the observed data, and then calculate the entropy by summing over the bins of the histogram. (Technically you could argue that a histogram is really just a trivial example of a kernel density estimate anyway--one in which the kernel function is a simple boxcar, and the kernel bandwidth is therefore identical to the histogram bin width.) Of these three methods, I find the first the most aesthetically appealing, provided one actually has a good theoretical model to explain the underlying data. However, coming up with a good theoretical model and then fitting it to the observed data isn't always possible, and in those cases, the other two methods are also perfectly defensible, as long as they are implemented in a way that generates a "reasonable" estimate of the underlying probability distribution $p(x)$. To generate a reasonable approximation of the distribution, the most important thing to do is simply make sure that you choose a reasonable value for the bandwidth (e.g., using this rule of thumb) if you're using a kernel density estimation technique, or the bin width (using one of these rules of thumb) if you're representing $p(x)$ as a histogram. In summary, yes there are other techniques besides kernel density estimation that you can use to derive an estimate for $p(x)$ and calculate the entropy, but the way that you are already doing it is also perfectly valid, provided you're using a typical kernel function and setting the bandwidth value appropriately.
Calculate entropy of sample Your question, as I understand it, basically amounts to, "what are the best practices for calculating entropy for an empirically measured distribution of a continuous random variable?" That's the que
47,124
Determining whether a Time series is white noise
You want to look at an autocorrelation function (ACF) plot. If no lags are significantly correlated, then you basically have white noise or a MA(q) process aka moving average. You can use this guide here to compare what your ACF plot looks like to determine if your time-series is "white noise" or not. Guide to ACF/PACF Plots Also, feel free to browse through previous time-series related posts like: How to interpret ACF and PACF plots Help interpreting ACF- and PACF-plots Interpreting ACF and PACF Plot
Determining whether a Time series is white noise
You want to look at an autocorrelation function (ACF) plot. If no lags are significantly correlated, then you basically have white noise or a MA(q) process aka moving average. You can use this guide h
Determining whether a Time series is white noise You want to look at an autocorrelation function (ACF) plot. If no lags are significantly correlated, then you basically have white noise or a MA(q) process aka moving average. You can use this guide here to compare what your ACF plot looks like to determine if your time-series is "white noise" or not. Guide to ACF/PACF Plots Also, feel free to browse through previous time-series related posts like: How to interpret ACF and PACF plots Help interpreting ACF- and PACF-plots Interpreting ACF and PACF Plot
Determining whether a Time series is white noise You want to look at an autocorrelation function (ACF) plot. If no lags are significantly correlated, then you basically have white noise or a MA(q) process aka moving average. You can use this guide h
47,125
In multinomial logistic regression, why do the decision boundaries tend to be parallel to each other?
In multinomial logistic regression, $$ p(k) = \frac{e^{x\beta_k}}{\sum_i e^{x\beta_i}} $$ where $i, k$ are possible class labels, $x$ - input data, $\beta_i$ - coefficient vector for the class $i$. Given class $k$ and base class $j$, log-odds are calculated as $$ \log\frac{p(k)}{p(j)}=\log\frac{e^{x\beta_k}}{e^{x\beta_j}} = x(\beta_k-\beta_j) $$ The object is classified as $k$ instead of $j$ if $p(k)>p(j)$, that is, if $x(\beta_k-\beta_j)>0$. The last inequality is linear in $x$. That's why decision boundary of logistic regression is always linear. Orientation of the decision boundary between $k$ and $j$ is determined by $\beta_k$ and $\beta_j$. If elements of $\beta_k$ are much larger than of $\beta_j$, this orientation is determined mostly by $\beta_k$. Thus, if there is a class $k$ with especially large $\beta$, all the decision boundaries would be dominated by it, and would be nearly parallel.
In multinomial logistic regression, why do the decision boundaries tend to be parallel to each other
In multinomial logistic regression, $$ p(k) = \frac{e^{x\beta_k}}{\sum_i e^{x\beta_i}} $$ where $i, k$ are possible class labels, $x$ - input data, $\beta_i$ - coefficient vector for the class $i$. G
In multinomial logistic regression, why do the decision boundaries tend to be parallel to each other? In multinomial logistic regression, $$ p(k) = \frac{e^{x\beta_k}}{\sum_i e^{x\beta_i}} $$ where $i, k$ are possible class labels, $x$ - input data, $\beta_i$ - coefficient vector for the class $i$. Given class $k$ and base class $j$, log-odds are calculated as $$ \log\frac{p(k)}{p(j)}=\log\frac{e^{x\beta_k}}{e^{x\beta_j}} = x(\beta_k-\beta_j) $$ The object is classified as $k$ instead of $j$ if $p(k)>p(j)$, that is, if $x(\beta_k-\beta_j)>0$. The last inequality is linear in $x$. That's why decision boundary of logistic regression is always linear. Orientation of the decision boundary between $k$ and $j$ is determined by $\beta_k$ and $\beta_j$. If elements of $\beta_k$ are much larger than of $\beta_j$, this orientation is determined mostly by $\beta_k$. Thus, if there is a class $k$ with especially large $\beta$, all the decision boundaries would be dominated by it, and would be nearly parallel.
In multinomial logistic regression, why do the decision boundaries tend to be parallel to each other In multinomial logistic regression, $$ p(k) = \frac{e^{x\beta_k}}{\sum_i e^{x\beta_i}} $$ where $i, k$ are possible class labels, $x$ - input data, $\beta_i$ - coefficient vector for the class $i$. G
47,126
Can the product of a Beta and some other distribution give an Exponential?
Based on multiple answers to Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees , let $X \sim \mathrm{Beta} \left(1,K-1 \right) $ and $Y$ be chi-squared with $2K$ degrees of freedom. Then the product is exponential with parameter $\frac{1}{2}$ .
Can the product of a Beta and some other distribution give an Exponential?
Based on multiple answers to Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees , let $X \sim \mathrm{Beta} \left(1,K-1 \right) $ and $Y$ be chi-squared with $2K
Can the product of a Beta and some other distribution give an Exponential? Based on multiple answers to Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees , let $X \sim \mathrm{Beta} \left(1,K-1 \right) $ and $Y$ be chi-squared with $2K$ degrees of freedom. Then the product is exponential with parameter $\frac{1}{2}$ .
Can the product of a Beta and some other distribution give an Exponential? Based on multiple answers to Distribution of $XY$ if $X \sim$ Beta$(1,K-1)$ and $Y \sim$ chi-squared with $2K$ degrees , let $X \sim \mathrm{Beta} \left(1,K-1 \right) $ and $Y$ be chi-squared with $2K
47,127
Can the product of a Beta and some other distribution give an Exponential?
A thought: Since we are prescribing the distributions of $Z, X$, then $Z = XY \implies Y = Z/X$, so why not try to calculate $Y$ as a ratio distribution and see what we get? We have $$f_y(y) = \int_0^1 x f_z(yx)f_x(x)dx$$ We assume that $X$ is a $Beta(a,b)$ and $Z$ is an $Exp(\lambda)$ (rate parameter). So $$f_y(y) = \frac {\lambda}{B(a,b)} \int_0^1 x \exp \{(-\lambda y)x\} x^{a-1}(1-x)^{b-1}dx$$ $$=\frac {\lambda}{B(a,b)} \int_0^1 x^a (1-x)^{b-1}\exp \{(-\lambda y)x\} dx$$ Looking up Gradshteyn & Ryzhik (2007, 7th ed.) p 347, eq. 3.383(1) and mapping coefficients, we get $$f_y(y) = \lambda \frac {B(b,1+a)}{B(a,b)} \cdot {}_1F_{1}(1+a;1+a+b;-\lambda y)$$ where the function is Kummer's confluent hypergeometric function. Is this a probability density over $[0,\infty]$?
Can the product of a Beta and some other distribution give an Exponential?
A thought: Since we are prescribing the distributions of $Z, X$, then $Z = XY \implies Y = Z/X$, so why not try to calculate $Y$ as a ratio distribution and see what we get? We have $$f_y(y) = \int_0
Can the product of a Beta and some other distribution give an Exponential? A thought: Since we are prescribing the distributions of $Z, X$, then $Z = XY \implies Y = Z/X$, so why not try to calculate $Y$ as a ratio distribution and see what we get? We have $$f_y(y) = \int_0^1 x f_z(yx)f_x(x)dx$$ We assume that $X$ is a $Beta(a,b)$ and $Z$ is an $Exp(\lambda)$ (rate parameter). So $$f_y(y) = \frac {\lambda}{B(a,b)} \int_0^1 x \exp \{(-\lambda y)x\} x^{a-1}(1-x)^{b-1}dx$$ $$=\frac {\lambda}{B(a,b)} \int_0^1 x^a (1-x)^{b-1}\exp \{(-\lambda y)x\} dx$$ Looking up Gradshteyn & Ryzhik (2007, 7th ed.) p 347, eq. 3.383(1) and mapping coefficients, we get $$f_y(y) = \lambda \frac {B(b,1+a)}{B(a,b)} \cdot {}_1F_{1}(1+a;1+a+b;-\lambda y)$$ where the function is Kummer's confluent hypergeometric function. Is this a probability density over $[0,\infty]$?
Can the product of a Beta and some other distribution give an Exponential? A thought: Since we are prescribing the distributions of $Z, X$, then $Z = XY \implies Y = Z/X$, so why not try to calculate $Y$ as a ratio distribution and see what we get? We have $$f_y(y) = \int_0
47,128
Interpretation when converting correlation of continuous data to Cohen's d
You've hit on a personal pet peeve of mine. I don't think that the interpretation given in the book (of an r-to-d transformed value of a correlation coefficient that is based on two continuous variables) makes any sense. There is no explicit or implicit dichotomization happening here (and of which variable, the first or the second? and dichotomized at what point?) and I've never seen any proper analytic demonstration that this interpretation is justified. In the other direction, the conversion of d to r makes perfect sense, as long as we realize that the conversion yields a point-biserial correlation coefficient (not a Pearson product-moment correlation coefficient of a bivariate normal distribution or some other bivariate distribution of two continuous variables). And to be precise, the correct equation for the conversion is $$r_{pb} = \frac{d}{\sqrt{d^2 + h}},$$ where $$h = \frac{m}{n_1} + \frac{m}{n_2}$$ and $m = n_1 + n_2 - 2$. Equation 7.7 in the book is not quite right, although the difference will usually be small. An example: grp <- c(0,0,0,0,1,1,1,1,1,1) out <- c(2,4,3,4,2,3,5,4,5,5) cor(grp, out) ### point-biserial correlation This yields: [1] 0.3340213 First, we compute the standardized mean difference: m <- c(by(out, grp, mean)) v <- c(by(out, grp, var)) n <- c(by(out, grp, length)) vp <- ((n[1] - 1)*v[1] + (n[2] - 1)*v[2]) / (n[1] + n[2] - 2) d <- (m[2] - m[1]) / sqrt(vp) Exact conversion: m <- n[1] + n[2] - 2 h <- m/n[1] + m/n[2] d / sqrt(d^2 + h) This yields: [1] 0.3340213 as it should. Now try the equation from Borenstein et al.: a <- (n[1] + n[2])^2 / (n[1]*n[2]) d / sqrt(d^2 + a) This yields: 0.3021478 Not quite right. Also, this conversion does not assume that "a continuous variable was dichotomized to create the treatment and control groups." (p. 49). No such assumption is necessary. The assumption (that a continuous variable was dichotomized) comes into play when we want to convert a d value into a biserial correlation coefficient. See: Jacobs, P., & Viechtbauer, W. (2017). Estimation of the biserial correlation and its sampling variance for use in meta-analysis. Research Synthesis Methods, 8(2), 161-180. doi:10.1002/jrsm.1218 Quite problematic is also the last paragraph on page 49. It suggests that we can just transform measures in any direction. But the interpretation of the converted measures is more than dubious (as in the case of going from a correlation of two continuous variables to d). Moreover, the sampling variances of such converted measures is often much more complicated than this paragraph suggests. For example, if you do d-to-r-to-z (so, going from a standardized mean difference to a point-biserial correlation and then applying Fisher's r-to-z transformation), then the sampling variance of the resulting value is not $1/(n-3)$. The conversion of r-to-z applies when r is a correlation between two continuous variables (that are bivariate normal), which isn't the case here. Another relevant article in this regard is: Pustejovsky, J. E. (2014). Converting from d to r to z when the design uses extreme groups, dichotomization, or experimental control. Psychological Methods, 19(1), 92-112.
Interpretation when converting correlation of continuous data to Cohen's d
You've hit on a personal pet peeve of mine. I don't think that the interpretation given in the book (of an r-to-d transformed value of a correlation coefficient that is based on two continuous variabl
Interpretation when converting correlation of continuous data to Cohen's d You've hit on a personal pet peeve of mine. I don't think that the interpretation given in the book (of an r-to-d transformed value of a correlation coefficient that is based on two continuous variables) makes any sense. There is no explicit or implicit dichotomization happening here (and of which variable, the first or the second? and dichotomized at what point?) and I've never seen any proper analytic demonstration that this interpretation is justified. In the other direction, the conversion of d to r makes perfect sense, as long as we realize that the conversion yields a point-biserial correlation coefficient (not a Pearson product-moment correlation coefficient of a bivariate normal distribution or some other bivariate distribution of two continuous variables). And to be precise, the correct equation for the conversion is $$r_{pb} = \frac{d}{\sqrt{d^2 + h}},$$ where $$h = \frac{m}{n_1} + \frac{m}{n_2}$$ and $m = n_1 + n_2 - 2$. Equation 7.7 in the book is not quite right, although the difference will usually be small. An example: grp <- c(0,0,0,0,1,1,1,1,1,1) out <- c(2,4,3,4,2,3,5,4,5,5) cor(grp, out) ### point-biserial correlation This yields: [1] 0.3340213 First, we compute the standardized mean difference: m <- c(by(out, grp, mean)) v <- c(by(out, grp, var)) n <- c(by(out, grp, length)) vp <- ((n[1] - 1)*v[1] + (n[2] - 1)*v[2]) / (n[1] + n[2] - 2) d <- (m[2] - m[1]) / sqrt(vp) Exact conversion: m <- n[1] + n[2] - 2 h <- m/n[1] + m/n[2] d / sqrt(d^2 + h) This yields: [1] 0.3340213 as it should. Now try the equation from Borenstein et al.: a <- (n[1] + n[2])^2 / (n[1]*n[2]) d / sqrt(d^2 + a) This yields: 0.3021478 Not quite right. Also, this conversion does not assume that "a continuous variable was dichotomized to create the treatment and control groups." (p. 49). No such assumption is necessary. The assumption (that a continuous variable was dichotomized) comes into play when we want to convert a d value into a biserial correlation coefficient. See: Jacobs, P., & Viechtbauer, W. (2017). Estimation of the biserial correlation and its sampling variance for use in meta-analysis. Research Synthesis Methods, 8(2), 161-180. doi:10.1002/jrsm.1218 Quite problematic is also the last paragraph on page 49. It suggests that we can just transform measures in any direction. But the interpretation of the converted measures is more than dubious (as in the case of going from a correlation of two continuous variables to d). Moreover, the sampling variances of such converted measures is often much more complicated than this paragraph suggests. For example, if you do d-to-r-to-z (so, going from a standardized mean difference to a point-biserial correlation and then applying Fisher's r-to-z transformation), then the sampling variance of the resulting value is not $1/(n-3)$. The conversion of r-to-z applies when r is a correlation between two continuous variables (that are bivariate normal), which isn't the case here. Another relevant article in this regard is: Pustejovsky, J. E. (2014). Converting from d to r to z when the design uses extreme groups, dichotomization, or experimental control. Psychological Methods, 19(1), 92-112.
Interpretation when converting correlation of continuous data to Cohen's d You've hit on a personal pet peeve of mine. I don't think that the interpretation given in the book (of an r-to-d transformed value of a correlation coefficient that is based on two continuous variabl
47,129
How to interpret glm and ols with offset
You show four models, one of them is strange (the one marked OLS) so I will first discuss the three others. What is common is that a response variable (amount of pay for the Gamma, a count of days for the others) is modeled as a function of covariates, but what is modeled is value pr year, that is: $$ \DeclareMathOperator{\E}{\mathbb{E}} \frac{\E Y}{\text{years}} = \exp(\beta^T x) = \exp(\eta), \qquad \text{say} $$ (as you are using a log link function). Taking logarithms (natural) on both sides give: $$ \log \E Y - \log\text{years} = \eta $$ and moving one term above over on the right hand side: $$ \log \E Y = \log\text{years} + \eta $$ and that answers your question: the combination of a log link function, a non-negative response and offset of log of exposure means that you are modeling the ratio of total amount divided into exposure, that is, payment per year or number of days per year. The interpretation of the other variables (linear parameters in the linear predictor $\eta$ should then be clear, it is interpreted as usual in regression models. Please note that the exact choice of distribution family in the explanation above do not play any role! Your fourth model do not make much sense to me, you can of course use a gaussian model for a non-negative response, that in itself is not a problem. But, the use of identity link function together with offset of log exposure is meaningless, as far as I can see. Let us try to mimic the logic above: $$ \frac{\E Y}{\text{years}} = \beta^T x = \eta, \qquad \text{say} $$ Note we changed to identity link function. But now taking logs doesn't work as above, that worked above only because we had a log link function. So I would not try to interpret the parameters in your OLS model, they are meaningless. But you could try a gaussian family, but with log link! For a more extensive discussion of the arguments above, see Goodness of fit and which model to choose linear regression or Poisson EDIT To the additional question in comments: So does that mean offset only works for log links? No, but log link and rate modeling is the major use case. Most posts on this site mentioning offset is this case. A few posts discussing other uses: Binary Models (Probit and Logit) with a Logarithmic Offset , Using offset in binomial model to account for increased numbers of patients , Offset in Logistic regression: what are the typical use cases?
How to interpret glm and ols with offset
You show four models, one of them is strange (the one marked OLS) so I will first discuss the three others. What is common is that a response variable (amount of pay for the Gamma, a count of days for
How to interpret glm and ols with offset You show four models, one of them is strange (the one marked OLS) so I will first discuss the three others. What is common is that a response variable (amount of pay for the Gamma, a count of days for the others) is modeled as a function of covariates, but what is modeled is value pr year, that is: $$ \DeclareMathOperator{\E}{\mathbb{E}} \frac{\E Y}{\text{years}} = \exp(\beta^T x) = \exp(\eta), \qquad \text{say} $$ (as you are using a log link function). Taking logarithms (natural) on both sides give: $$ \log \E Y - \log\text{years} = \eta $$ and moving one term above over on the right hand side: $$ \log \E Y = \log\text{years} + \eta $$ and that answers your question: the combination of a log link function, a non-negative response and offset of log of exposure means that you are modeling the ratio of total amount divided into exposure, that is, payment per year or number of days per year. The interpretation of the other variables (linear parameters in the linear predictor $\eta$ should then be clear, it is interpreted as usual in regression models. Please note that the exact choice of distribution family in the explanation above do not play any role! Your fourth model do not make much sense to me, you can of course use a gaussian model for a non-negative response, that in itself is not a problem. But, the use of identity link function together with offset of log exposure is meaningless, as far as I can see. Let us try to mimic the logic above: $$ \frac{\E Y}{\text{years}} = \beta^T x = \eta, \qquad \text{say} $$ Note we changed to identity link function. But now taking logs doesn't work as above, that worked above only because we had a log link function. So I would not try to interpret the parameters in your OLS model, they are meaningless. But you could try a gaussian family, but with log link! For a more extensive discussion of the arguments above, see Goodness of fit and which model to choose linear regression or Poisson EDIT To the additional question in comments: So does that mean offset only works for log links? No, but log link and rate modeling is the major use case. Most posts on this site mentioning offset is this case. A few posts discussing other uses: Binary Models (Probit and Logit) with a Logarithmic Offset , Using offset in binomial model to account for increased numbers of patients , Offset in Logistic regression: what are the typical use cases?
How to interpret glm and ols with offset You show four models, one of them is strange (the one marked OLS) so I will first discuss the three others. What is common is that a response variable (amount of pay for the Gamma, a count of days for
47,130
How to interpret glm and ols with offset
Your OLS model: lm(formula = payment_amt ~ offset(years) + as.factor(gender) + age, data = pm) Is the same as: lm(formula = payment_amt - years ~ as.factor(gender) + age, data = pm) With a log-link, you can use offsets to model rates because of how math works with logarithms, but for an identity link there's really no point to using an offset.
How to interpret glm and ols with offset
Your OLS model: lm(formula = payment_amt ~ offset(years) + as.factor(gender) + age, data = pm) Is the same as: lm(formula = payment_amt - years ~ as.factor(gender) + age, data = pm) Wit
How to interpret glm and ols with offset Your OLS model: lm(formula = payment_amt ~ offset(years) + as.factor(gender) + age, data = pm) Is the same as: lm(formula = payment_amt - years ~ as.factor(gender) + age, data = pm) With a log-link, you can use offsets to model rates because of how math works with logarithms, but for an identity link there's really no point to using an offset.
How to interpret glm and ols with offset Your OLS model: lm(formula = payment_amt ~ offset(years) + as.factor(gender) + age, data = pm) Is the same as: lm(formula = payment_amt - years ~ as.factor(gender) + age, data = pm) Wit
47,131
Cross entropy versus Mean of Cross Entropy [duplicate]
For online training methods like stochastic gradient descent, the loss on each iteration reflects the contribution of a single data point. So, no summation is necessary in this case. For batch or minibatch training, it's necessary to combine the loss from each point in the batch/minibatch by taking the sum or mean. When taking the sum, the loss depends on the number of data points (in the case of batch training) or minibatch size (in the case of minibatch training). Also note that the number of points in each minibatch may vary. Taking the mean decouples the loss from these influences. This has a few benefits: It makes it easier to compare the loss across datasets with a different number of points, or across iterations with a different mini-batch size. It makes it possible to change the number of points or mini-batch size, without changing other parameters like step size, regularization (or penalty) strengths, etc. In the case of minibatch training, it ensures that all mini-batches contribute equally. Taking the sum would give higher weight to mini-batches containing more points.
Cross entropy versus Mean of Cross Entropy [duplicate]
For online training methods like stochastic gradient descent, the loss on each iteration reflects the contribution of a single data point. So, no summation is necessary in this case. For batch or mini
Cross entropy versus Mean of Cross Entropy [duplicate] For online training methods like stochastic gradient descent, the loss on each iteration reflects the contribution of a single data point. So, no summation is necessary in this case. For batch or minibatch training, it's necessary to combine the loss from each point in the batch/minibatch by taking the sum or mean. When taking the sum, the loss depends on the number of data points (in the case of batch training) or minibatch size (in the case of minibatch training). Also note that the number of points in each minibatch may vary. Taking the mean decouples the loss from these influences. This has a few benefits: It makes it easier to compare the loss across datasets with a different number of points, or across iterations with a different mini-batch size. It makes it possible to change the number of points or mini-batch size, without changing other parameters like step size, regularization (or penalty) strengths, etc. In the case of minibatch training, it ensures that all mini-batches contribute equally. Taking the sum would give higher weight to mini-batches containing more points.
Cross entropy versus Mean of Cross Entropy [duplicate] For online training methods like stochastic gradient descent, the loss on each iteration reflects the contribution of a single data point. So, no summation is necessary in this case. For batch or mini
47,132
How to set step-size in Hamiltonian Monte Carlo?
There's a section Radford Neal's Handbook on HMC that discusses how to set the discretisation length $\epsilon$ and the number of leapfrog steps $L$ appropriately: http://www.mcmchandbook.net/HandbookChapter5.pdf. Here I can summarise the key points: The overall distance moved is $\epsilon L$ so both have to be considered. Setting $\epsilon$: The reason proposals are rejected in HMC is purely due to discretisation error (otherwise the dynamics perfectly preserve probability density/energy). If $\epsilon$ is too large, then there will be large discretisation error and low acceptance, if $\epsilon$ is too small then more expensive leapfrog steps will be required to move large distances. Ideally we want the largest possible value of $\epsilon$ that gives reasonable acceptance probability. Unfortunately this may vary for different values of the target variable. A simple heuristic to set this may be to do a preliminary run with fixed $L$, gradually increasing $\epsilon$ until the acceptance probability is at an appropriate level. Setting $L$: Neal says: "Setting the trajectory length by trial and error therefore seems necessary. For a problem thought to be fairly difficult, a trajectory with L = 100 might be a suitable starting point. If preliminary runs (with a suitable ε; see above) show that HMC reaches a nearly independent point after only one iteration, a smaller value of L might be tried next. (Unless these “preliminary” runs are actually sufficient, in which case there is of course no need to do more runs.) If instead there is high autocorrelation in the run with L = 100, runs with L = 1000 might be tried next" It may also be advisable to randomly sample $\epsilon$ and $L$ form suitable ranges to avoid the possibility of having paths that are close to periodic as this would slow mixing.
How to set step-size in Hamiltonian Monte Carlo?
There's a section Radford Neal's Handbook on HMC that discusses how to set the discretisation length $\epsilon$ and the number of leapfrog steps $L$ appropriately: http://www.mcmchandbook.net/Handbook
How to set step-size in Hamiltonian Monte Carlo? There's a section Radford Neal's Handbook on HMC that discusses how to set the discretisation length $\epsilon$ and the number of leapfrog steps $L$ appropriately: http://www.mcmchandbook.net/HandbookChapter5.pdf. Here I can summarise the key points: The overall distance moved is $\epsilon L$ so both have to be considered. Setting $\epsilon$: The reason proposals are rejected in HMC is purely due to discretisation error (otherwise the dynamics perfectly preserve probability density/energy). If $\epsilon$ is too large, then there will be large discretisation error and low acceptance, if $\epsilon$ is too small then more expensive leapfrog steps will be required to move large distances. Ideally we want the largest possible value of $\epsilon$ that gives reasonable acceptance probability. Unfortunately this may vary for different values of the target variable. A simple heuristic to set this may be to do a preliminary run with fixed $L$, gradually increasing $\epsilon$ until the acceptance probability is at an appropriate level. Setting $L$: Neal says: "Setting the trajectory length by trial and error therefore seems necessary. For a problem thought to be fairly difficult, a trajectory with L = 100 might be a suitable starting point. If preliminary runs (with a suitable ε; see above) show that HMC reaches a nearly independent point after only one iteration, a smaller value of L might be tried next. (Unless these “preliminary” runs are actually sufficient, in which case there is of course no need to do more runs.) If instead there is high autocorrelation in the run with L = 100, runs with L = 1000 might be tried next" It may also be advisable to randomly sample $\epsilon$ and $L$ form suitable ranges to avoid the possibility of having paths that are close to periodic as this would slow mixing.
How to set step-size in Hamiltonian Monte Carlo? There's a section Radford Neal's Handbook on HMC that discusses how to set the discretisation length $\epsilon$ and the number of leapfrog steps $L$ appropriately: http://www.mcmchandbook.net/Handbook
47,133
If KL-divergence's asymmetrical should I minimize KL(P||Q) or KL(Q||P)?
You usually want $KL(Q||P)$. That's from $P$ to $Q$. I remember that it goes from right to left, just like the notation for conditional probabilities. You want the expectation being taken with respect to the true distribution $P$. That way, sample averages can be assumed to converge to the true expectations, by the law of large numbers.
If KL-divergence's asymmetrical should I minimize KL(P||Q) or KL(Q||P)?
You usually want $KL(Q||P)$. That's from $P$ to $Q$. I remember that it goes from right to left, just like the notation for conditional probabilities. You want the expectation being taken with respec
If KL-divergence's asymmetrical should I minimize KL(P||Q) or KL(Q||P)? You usually want $KL(Q||P)$. That's from $P$ to $Q$. I remember that it goes from right to left, just like the notation for conditional probabilities. You want the expectation being taken with respect to the true distribution $P$. That way, sample averages can be assumed to converge to the true expectations, by the law of large numbers.
If KL-divergence's asymmetrical should I minimize KL(P||Q) or KL(Q||P)? You usually want $KL(Q||P)$. That's from $P$ to $Q$. I remember that it goes from right to left, just like the notation for conditional probabilities. You want the expectation being taken with respec
47,134
If KL-divergence's asymmetrical should I minimize KL(P||Q) or KL(Q||P)?
The KL divergence is not a distance this is why the alternative word divergence is used instead. If you want symmetry you can take the sum of $KL(Q||P)$ and $KL(P||Q)$ as mentioned in one of the answers in the linked post. The intuition is that you do not know the true distribution $Q$ so you make an estimate or a guess of the true distribution $P$. The two may be in the same parametric family or they may not be similar at all. Therefore to understand some notion of how far your assigned probabilities (a view of the events) are from the true probabilities (how much the two perspectives diverge) you would take an expectation under your estimated probabilities. However, you would still like this divergence to be $0$ if you somehow specified the exact model, to ensure this you subtract that true value. Using the logarithm property $log(x/y) =log(x) - log(y)$ then gives you the KL-divergence equation.
If KL-divergence's asymmetrical should I minimize KL(P||Q) or KL(Q||P)?
The KL divergence is not a distance this is why the alternative word divergence is used instead. If you want symmetry you can take the sum of $KL(Q||P)$ and $KL(P||Q)$ as mentioned in one of the answe
If KL-divergence's asymmetrical should I minimize KL(P||Q) or KL(Q||P)? The KL divergence is not a distance this is why the alternative word divergence is used instead. If you want symmetry you can take the sum of $KL(Q||P)$ and $KL(P||Q)$ as mentioned in one of the answers in the linked post. The intuition is that you do not know the true distribution $Q$ so you make an estimate or a guess of the true distribution $P$. The two may be in the same parametric family or they may not be similar at all. Therefore to understand some notion of how far your assigned probabilities (a view of the events) are from the true probabilities (how much the two perspectives diverge) you would take an expectation under your estimated probabilities. However, you would still like this divergence to be $0$ if you somehow specified the exact model, to ensure this you subtract that true value. Using the logarithm property $log(x/y) =log(x) - log(y)$ then gives you the KL-divergence equation.
If KL-divergence's asymmetrical should I minimize KL(P||Q) or KL(Q||P)? The KL divergence is not a distance this is why the alternative word divergence is used instead. If you want symmetry you can take the sum of $KL(Q||P)$ and $KL(P||Q)$ as mentioned in one of the answe
47,135
Simulating Responses from fitted Generalized Additive Model
I'll illustrate with the classic 4 term data set oft used to illustrate GAMs, but will only simulate data from the strongly nonlinear term $f(x_2)$ as it is easy to visualise the process with a single covariate. library('mgcv') set.seed(20) f2 <- function(x) 0.2 * x^11 * (10 * (1 - x))^6 + 10 * (10 * x)^3 * (1 - x)^10 ysim <- function(n = 500, scale = 2) { x <- runif(n) e <- rnorm(n, 0, scale) f <- f2(x) y <- f + e data.frame(y = y, x2 = x, f2 = f) } df <- ysim() head(df) Fit the model: m <- gam(y ~ s(x2), data = df) Now, simulate 50 new data points from the posterior distribution of the response conditional upon the estimated spline coefficients and smoothness parameters. set.seed(10) nsim <- 50 drawx <- function(x, n) runif(n, min = min(x), max = max(x)) newx <- data.frame(x2 = drawx(df[, 'x2'], n = nsim)) Here I'm drawing 50 values uniformly at random over the range of $x_2$. The simulated values are given by $$y \sim \mathcal{N}(\hat{y}, \hat{\sigma}^2) $$ where $\hat{y}$ is $$\hat{y} = \alpha + s(x_2)$$ and $\hat{\sigma}$ is the residual standard error, which is generally estimated from the residuals of a Gaussian model rather than modelled directly (although the latter is certainly possible). We get $\hat{y}$ via predict(). First grab the estimated residual variance from the model sig2 <- m$sig2 Next predict for the 50 new locations set.seed(10) newx <- transform(newx, newy = predict(m, newx, type = "response")) and then, using these values of $\hat{y}$ in newy, simulate 50 new values from a Gaussian with mean given by newy and standard deviation (sqrt of sig2) newx <- transform(newx, ysim = rnorm(nsim, mean = newy, sd = sqrt(sig2))) Notice that each simulated value is a random draw from a Gaussian distribution with mean value equal to the model estimated value and variance $\hat{\sigma}^2$. We should check what we've done. First, generate more values from the fitted spline so we can see what model was estimated pred <- with(df, data.frame(x2 = seq(min(x2), max(x2), length = 500))) pred <- transform(pred, fitted = predict(m, newdata = pred, type = "response")) Now we can put this all together library('ggplot2') theme_set(theme_bw()) ggplot(df) + geom_point(aes(x = x2, y = y), colour = "grey") + geom_line(aes(x = x2, y = f2), colour = "forestgreen", size = 1.3) + geom_line(aes(x = x2, y = fitted), data = pred, colour = "blue") + geom_point(aes(x = x2, y = newy), data = newx, colour = "blue", size = 2) + geom_point(aes(x = x2, y = ysim), data = newx, colour = "red", size = 2) The thick green line is the true function $f(x_2)$. The grey dots are the original data to which the GAM was fitted. The blue line is the fitted smooth, the estimate $\hat{f}(x_2)$. The blue points are the fitted values for the 50 locations at which we simulated from the model. The red points are the random draws from the posterior distribution of $y$ conditional upon the estimated model. This approach extends to multiple covariates — it's just not so easy to visualize what's going on. This also extends to non-Gaussian responses, such as Poisson or binomial-distributed response. The key points are: Predict from the model using predict(), to get the expectation of the response (this is the mean in the case of the Gaussian, but is the expected count say for the Poisson) Predict or extract values for any additional parameters needed for the conditional distribution of the response (for the Gaussian, as shown here, there is a second parameter $\sigma^2$, which is needed to fully specify the conditional distribution of the response. For the Poisson, for example, there is only the "mean", the expected count.) Simulate from the conditional distribution of the response (here we could use rnorm() directly because the parameters of the distribution estimated via the GLM/GAM were in exactly the same form as that expected by rnorm(). This is also the case for the Poisson and Binomial distributions. For other distributions this may not be case. For example the parameters of a GLM/GAM with a Gamma family fitted via glm() and gam() require some translation before you can plug them into the rgamma() function.
Simulating Responses from fitted Generalized Additive Model
I'll illustrate with the classic 4 term data set oft used to illustrate GAMs, but will only simulate data from the strongly nonlinear term $f(x_2)$ as it is easy to visualise the process with a single
Simulating Responses from fitted Generalized Additive Model I'll illustrate with the classic 4 term data set oft used to illustrate GAMs, but will only simulate data from the strongly nonlinear term $f(x_2)$ as it is easy to visualise the process with a single covariate. library('mgcv') set.seed(20) f2 <- function(x) 0.2 * x^11 * (10 * (1 - x))^6 + 10 * (10 * x)^3 * (1 - x)^10 ysim <- function(n = 500, scale = 2) { x <- runif(n) e <- rnorm(n, 0, scale) f <- f2(x) y <- f + e data.frame(y = y, x2 = x, f2 = f) } df <- ysim() head(df) Fit the model: m <- gam(y ~ s(x2), data = df) Now, simulate 50 new data points from the posterior distribution of the response conditional upon the estimated spline coefficients and smoothness parameters. set.seed(10) nsim <- 50 drawx <- function(x, n) runif(n, min = min(x), max = max(x)) newx <- data.frame(x2 = drawx(df[, 'x2'], n = nsim)) Here I'm drawing 50 values uniformly at random over the range of $x_2$. The simulated values are given by $$y \sim \mathcal{N}(\hat{y}, \hat{\sigma}^2) $$ where $\hat{y}$ is $$\hat{y} = \alpha + s(x_2)$$ and $\hat{\sigma}$ is the residual standard error, which is generally estimated from the residuals of a Gaussian model rather than modelled directly (although the latter is certainly possible). We get $\hat{y}$ via predict(). First grab the estimated residual variance from the model sig2 <- m$sig2 Next predict for the 50 new locations set.seed(10) newx <- transform(newx, newy = predict(m, newx, type = "response")) and then, using these values of $\hat{y}$ in newy, simulate 50 new values from a Gaussian with mean given by newy and standard deviation (sqrt of sig2) newx <- transform(newx, ysim = rnorm(nsim, mean = newy, sd = sqrt(sig2))) Notice that each simulated value is a random draw from a Gaussian distribution with mean value equal to the model estimated value and variance $\hat{\sigma}^2$. We should check what we've done. First, generate more values from the fitted spline so we can see what model was estimated pred <- with(df, data.frame(x2 = seq(min(x2), max(x2), length = 500))) pred <- transform(pred, fitted = predict(m, newdata = pred, type = "response")) Now we can put this all together library('ggplot2') theme_set(theme_bw()) ggplot(df) + geom_point(aes(x = x2, y = y), colour = "grey") + geom_line(aes(x = x2, y = f2), colour = "forestgreen", size = 1.3) + geom_line(aes(x = x2, y = fitted), data = pred, colour = "blue") + geom_point(aes(x = x2, y = newy), data = newx, colour = "blue", size = 2) + geom_point(aes(x = x2, y = ysim), data = newx, colour = "red", size = 2) The thick green line is the true function $f(x_2)$. The grey dots are the original data to which the GAM was fitted. The blue line is the fitted smooth, the estimate $\hat{f}(x_2)$. The blue points are the fitted values for the 50 locations at which we simulated from the model. The red points are the random draws from the posterior distribution of $y$ conditional upon the estimated model. This approach extends to multiple covariates — it's just not so easy to visualize what's going on. This also extends to non-Gaussian responses, such as Poisson or binomial-distributed response. The key points are: Predict from the model using predict(), to get the expectation of the response (this is the mean in the case of the Gaussian, but is the expected count say for the Poisson) Predict or extract values for any additional parameters needed for the conditional distribution of the response (for the Gaussian, as shown here, there is a second parameter $\sigma^2$, which is needed to fully specify the conditional distribution of the response. For the Poisson, for example, there is only the "mean", the expected count.) Simulate from the conditional distribution of the response (here we could use rnorm() directly because the parameters of the distribution estimated via the GLM/GAM were in exactly the same form as that expected by rnorm(). This is also the case for the Poisson and Binomial distributions. For other distributions this may not be case. For example the parameters of a GLM/GAM with a Gamma family fitted via glm() and gam() require some translation before you can plug them into the rgamma() function.
Simulating Responses from fitted Generalized Additive Model I'll illustrate with the classic 4 term data set oft used to illustrate GAMs, but will only simulate data from the strongly nonlinear term $f(x_2)$ as it is easy to visualise the process with a single
47,136
Can an LS estimator be unbiased if there are infinite solutions?
If $\mathbf A$ doesn't have full rank, then the model is not identifiable, which implies that an unbiased estimator does not exist. Here is what the proof looks like in this specific scenario. If $\mathbf A$ doesn't have full rank, then there exist two distinct vectors $\mathbf x^{(1)}$ and $\mathbf x^{(2)}$ such that $\mathbf A\mathbf x^{(1)} = \mathbf A\mathbf x^{(2)}$. In this case, the data $\mathbf y = \mathbf A\mathbf x + \eta$ has the same distribution under both $\mathbf x = \mathbf x^{(1)}$ and $\mathbf x = \mathbf x^{(2)}$. Suppose then that an unbiased estimator $T(\mathbf y)$ were to exist. Then by the definition of $T(\mathbf y)$ being unbiased, we must have $E_{\mathbf x^{(1)}}(T(\mathbf y)) = \mathbf x^{(1)}$, where $E_{\mathbf x^{(1)}}$ denotes the expected value taken under the scenario where $\mathbf x=\mathbf x^{(1)}$. Likewise $E_{\mathbf x^{(2)}}(T(\mathbf y)) = \mathbf x^{(2)}$. And yet, since $\mathbf y$ has the same distribution whether $\mathbf x = \mathbf x^{(1)}$ or $\mathbf x = \mathbf x^{(2)}$, it follows that $T(\mathbf y)$ also has the same distribution in both of these scenarios, which means that $E_{\mathbf x^{(1)}}(T(\mathbf y)) = E_{\mathbf x^{(2)}}(T(\mathbf y))$. Putting this together gives $\mathbf x^{(1)} = \mathbf x^{(2)}$, which is a contradiction since $\mathbf x^{(1)}$ and $\mathbf x^{(2)}$ were chosen to be distinct.
Can an LS estimator be unbiased if there are infinite solutions?
If $\mathbf A$ doesn't have full rank, then the model is not identifiable, which implies that an unbiased estimator does not exist. Here is what the proof looks like in this specific scenario. If $\m
Can an LS estimator be unbiased if there are infinite solutions? If $\mathbf A$ doesn't have full rank, then the model is not identifiable, which implies that an unbiased estimator does not exist. Here is what the proof looks like in this specific scenario. If $\mathbf A$ doesn't have full rank, then there exist two distinct vectors $\mathbf x^{(1)}$ and $\mathbf x^{(2)}$ such that $\mathbf A\mathbf x^{(1)} = \mathbf A\mathbf x^{(2)}$. In this case, the data $\mathbf y = \mathbf A\mathbf x + \eta$ has the same distribution under both $\mathbf x = \mathbf x^{(1)}$ and $\mathbf x = \mathbf x^{(2)}$. Suppose then that an unbiased estimator $T(\mathbf y)$ were to exist. Then by the definition of $T(\mathbf y)$ being unbiased, we must have $E_{\mathbf x^{(1)}}(T(\mathbf y)) = \mathbf x^{(1)}$, where $E_{\mathbf x^{(1)}}$ denotes the expected value taken under the scenario where $\mathbf x=\mathbf x^{(1)}$. Likewise $E_{\mathbf x^{(2)}}(T(\mathbf y)) = \mathbf x^{(2)}$. And yet, since $\mathbf y$ has the same distribution whether $\mathbf x = \mathbf x^{(1)}$ or $\mathbf x = \mathbf x^{(2)}$, it follows that $T(\mathbf y)$ also has the same distribution in both of these scenarios, which means that $E_{\mathbf x^{(1)}}(T(\mathbf y)) = E_{\mathbf x^{(2)}}(T(\mathbf y))$. Putting this together gives $\mathbf x^{(1)} = \mathbf x^{(2)}$, which is a contradiction since $\mathbf x^{(1)}$ and $\mathbf x^{(2)}$ were chosen to be distinct.
Can an LS estimator be unbiased if there are infinite solutions? If $\mathbf A$ doesn't have full rank, then the model is not identifiable, which implies that an unbiased estimator does not exist. Here is what the proof looks like in this specific scenario. If $\m
47,137
How can preprocessing with PCA but keeping the same dimensionality improve random forest results? [duplicate]
Random forest struggles when the decision boundary is "diagonal" in the feature space because RF has to approximate that diagonal with lots of "rectangular" splits. To the extent that PCA re-orients the data so that splits perpendicular to the rotated & rescaled axes align well with the decision boundary, PCA will help. But there's no reason to believe that PCA will help in general, because not all decision boundaries are improved when rotated (e.g. a circle). And even if you do have a diagonal decision boundary, or a boundary that would be easier to find in a rotated space, applying PCA will only find that rotation by coincidence, because PCA has no knowledge at all about the classification component of the task (it is not "$y$-aware"). Also, @hxd1011's caveat applies to all projects using PCA for supervised learning: data rotated by PCA may have little-to-no relevance to the classification objective.
How can preprocessing with PCA but keeping the same dimensionality improve random forest results? [d
Random forest struggles when the decision boundary is "diagonal" in the feature space because RF has to approximate that diagonal with lots of "rectangular" splits. To the extent that PCA re-orients t
How can preprocessing with PCA but keeping the same dimensionality improve random forest results? [duplicate] Random forest struggles when the decision boundary is "diagonal" in the feature space because RF has to approximate that diagonal with lots of "rectangular" splits. To the extent that PCA re-orients the data so that splits perpendicular to the rotated & rescaled axes align well with the decision boundary, PCA will help. But there's no reason to believe that PCA will help in general, because not all decision boundaries are improved when rotated (e.g. a circle). And even if you do have a diagonal decision boundary, or a boundary that would be easier to find in a rotated space, applying PCA will only find that rotation by coincidence, because PCA has no knowledge at all about the classification component of the task (it is not "$y$-aware"). Also, @hxd1011's caveat applies to all projects using PCA for supervised learning: data rotated by PCA may have little-to-no relevance to the classification objective.
How can preprocessing with PCA but keeping the same dimensionality improve random forest results? [d Random forest struggles when the decision boundary is "diagonal" in the feature space because RF has to approximate that diagonal with lots of "rectangular" splits. To the extent that PCA re-orients t
47,138
Variance condition for (weak) stationarity
Yes, weak stationarity requires both constant variance and constant mean (over time). To quote from wikipedia: A wide-sense stationary random processes only require that 1st moment (i.e. the mean) and autocovariance do not vary with respect to time.
Variance condition for (weak) stationarity
Yes, weak stationarity requires both constant variance and constant mean (over time). To quote from wikipedia: A wide-sense stationary random processes only require that 1st moment (i.e. the mean) and
Variance condition for (weak) stationarity Yes, weak stationarity requires both constant variance and constant mean (over time). To quote from wikipedia: A wide-sense stationary random processes only require that 1st moment (i.e. the mean) and autocovariance do not vary with respect to time.
Variance condition for (weak) stationarity Yes, weak stationarity requires both constant variance and constant mean (over time). To quote from wikipedia: A wide-sense stationary random processes only require that 1st moment (i.e. the mean) and
47,139
Variance condition for (weak) stationarity
To give another view than that of Digio, I have actually only encountered the requirement for a finite second moment¹, and not for a constant one; at least in books and academic papers, as opposed to online resources (presentations, blogposts, etc.). I thus believe the formal definition for a weak (or wide-sense) stationary process is: The first moment of $x_i$ is constant; i.e. $∀t, E[x_i]=𝜇$ The second moment of $x_i$ is finite for all $t$; i.e. $∀t, E[x_i²]<∞$ (which also implies of course $E[(x_i-𝜇)²]<∞$; i.e. that variance is finite for all $t$) The cross moment ― i.e. the auto-covariance ― depends only on the difference $u-v$; i.e. $∀u,v,\tau, cov(x_u, x_v)=cov(x_{u+\tau}, x_{v+\tau})$ However, I believe that the apparent confusion between the two conditions, and the fact that in some places a requirement for constant variance is stated instead of a finite one, is due to the fact that this indeed follows directly from the three conditions above. The third condition implies that every lag $\tau \in \mathbb{N}$ has a constant covariance value associated with it: $$cov(X_{t_1}, X_{t_2}) = K_{XX}(t_1,t_2) = K_{XX}(t_2-t_1,0) = K_{XX}(\tau)$$ Note that this directly implies that the variance of the process is also constant, since we get that for all $t \in \mathbb{N}$ $$ Var(X_t) = cov(X_t, X_t) = K_{XX}(t,t) = K_{XX}(0) = d$$ for some constant $d$. 1 When writing second moment I mean $E[x_i^2]$, and not variance, which is the second central moment.
Variance condition for (weak) stationarity
To give another view than that of Digio, I have actually only encountered the requirement for a finite second moment¹, and not for a constant one; at least in books and academic papers, as opposed to
Variance condition for (weak) stationarity To give another view than that of Digio, I have actually only encountered the requirement for a finite second moment¹, and not for a constant one; at least in books and academic papers, as opposed to online resources (presentations, blogposts, etc.). I thus believe the formal definition for a weak (or wide-sense) stationary process is: The first moment of $x_i$ is constant; i.e. $∀t, E[x_i]=𝜇$ The second moment of $x_i$ is finite for all $t$; i.e. $∀t, E[x_i²]<∞$ (which also implies of course $E[(x_i-𝜇)²]<∞$; i.e. that variance is finite for all $t$) The cross moment ― i.e. the auto-covariance ― depends only on the difference $u-v$; i.e. $∀u,v,\tau, cov(x_u, x_v)=cov(x_{u+\tau}, x_{v+\tau})$ However, I believe that the apparent confusion between the two conditions, and the fact that in some places a requirement for constant variance is stated instead of a finite one, is due to the fact that this indeed follows directly from the three conditions above. The third condition implies that every lag $\tau \in \mathbb{N}$ has a constant covariance value associated with it: $$cov(X_{t_1}, X_{t_2}) = K_{XX}(t_1,t_2) = K_{XX}(t_2-t_1,0) = K_{XX}(\tau)$$ Note that this directly implies that the variance of the process is also constant, since we get that for all $t \in \mathbb{N}$ $$ Var(X_t) = cov(X_t, X_t) = K_{XX}(t,t) = K_{XX}(0) = d$$ for some constant $d$. 1 When writing second moment I mean $E[x_i^2]$, and not variance, which is the second central moment.
Variance condition for (weak) stationarity To give another view than that of Digio, I have actually only encountered the requirement for a finite second moment¹, and not for a constant one; at least in books and academic papers, as opposed to
47,140
Are the marginals of the multivariate t distribution univariate Student t distributions?
Yes. The proof is simple: The definition of a multivariate-t that you give is that it is a random variable that is the ratio of a multivariate Gaussian and the square-root of a Gamma variable The marginal distribution of that is the marginal distribution of the ratio of the Gaussian and the square-root of a gamma The distribution of a ratio of normal over square-root of Gamma is a univariate-t
Are the marginals of the multivariate t distribution univariate Student t distributions?
Yes. The proof is simple: The definition of a multivariate-t that you give is that it is a random variable that is the ratio of a multivariate Gaussian and the square-root of a Gamma variable The mar
Are the marginals of the multivariate t distribution univariate Student t distributions? Yes. The proof is simple: The definition of a multivariate-t that you give is that it is a random variable that is the ratio of a multivariate Gaussian and the square-root of a Gamma variable The marginal distribution of that is the marginal distribution of the ratio of the Gaussian and the square-root of a gamma The distribution of a ratio of normal over square-root of Gamma is a univariate-t
Are the marginals of the multivariate t distribution univariate Student t distributions? Yes. The proof is simple: The definition of a multivariate-t that you give is that it is a random variable that is the ratio of a multivariate Gaussian and the square-root of a Gamma variable The mar
47,141
Partial correlation in panda dataframe python [closed]
This will give you what you are asking for: from scipy import stats, linalg def partial_corr(C): """ Returns the sample linear partial correlation coefficients between pairs of variables in C, controlling for the remaining variables in C. Parameters ---------- C : array-like, shape (n, p) Array with the different variables. Each column of C is taken as a variable Returns ------- P : array-like, shape (p, p) P[i, j] contains the partial correlation of C[:, i] and C[:, j] controlling for the remaining variables in C. """ C = np.asarray(C) p = C.shape[1] P_corr = np.zeros((p, p), dtype=np.float) for i in range(p): P_corr[i, i] = 1 for j in range(i+1, p): idx = np.ones(p, dtype=np.bool) idx[i] = False idx[j] = False beta_i = linalg.lstsq(C[:, idx], C[:, j])[0] beta_j = linalg.lstsq(C[:, idx], C[:, i])[0] res_j = C[:, j] - C[:, idx].dot( beta_i) res_i = C[:, i] - C[:, idx].dot(beta_j) corr = stats.pearsonr(res_i, res_j)[0] P_corr[i, j] = corr P_corr[j, i] = corr return P_corr partial_corr_array = df.as_matrix(columns = ['price', 'sqft_living', 'sqft_living15']) # Calculate the partial correlation coefficients partial_corr(partial_corr_array)
Partial correlation in panda dataframe python [closed]
This will give you what you are asking for: from scipy import stats, linalg def partial_corr(C): """ Returns the sample linear partial correlation coefficients between pairs of variables in C
Partial correlation in panda dataframe python [closed] This will give you what you are asking for: from scipy import stats, linalg def partial_corr(C): """ Returns the sample linear partial correlation coefficients between pairs of variables in C, controlling for the remaining variables in C. Parameters ---------- C : array-like, shape (n, p) Array with the different variables. Each column of C is taken as a variable Returns ------- P : array-like, shape (p, p) P[i, j] contains the partial correlation of C[:, i] and C[:, j] controlling for the remaining variables in C. """ C = np.asarray(C) p = C.shape[1] P_corr = np.zeros((p, p), dtype=np.float) for i in range(p): P_corr[i, i] = 1 for j in range(i+1, p): idx = np.ones(p, dtype=np.bool) idx[i] = False idx[j] = False beta_i = linalg.lstsq(C[:, idx], C[:, j])[0] beta_j = linalg.lstsq(C[:, idx], C[:, i])[0] res_j = C[:, j] - C[:, idx].dot( beta_i) res_i = C[:, i] - C[:, idx].dot(beta_j) corr = stats.pearsonr(res_i, res_j)[0] P_corr[i, j] = corr P_corr[j, i] = corr return P_corr partial_corr_array = df.as_matrix(columns = ['price', 'sqft_living', 'sqft_living15']) # Calculate the partial correlation coefficients partial_corr(partial_corr_array)
Partial correlation in panda dataframe python [closed] This will give you what you are asking for: from scipy import stats, linalg def partial_corr(C): """ Returns the sample linear partial correlation coefficients between pairs of variables in C
47,142
Partial correlation in panda dataframe python [closed]
AFAIU from your comment, you're talking about recursive feature elimination, specifically, using linear regression. As described here: Recursive feature elimination is based on the idea to repeatedly construct a model (for example an SVM or a regression model) and choose either the best or worst performing feature (for example based on coefficients), setting the feature aside and then repeating the process with the rest of the features. This process is applied until all features in the dataset are exhausted. Features are then ranked according to when they were eliminated. As such, it is a greedy optimization for finding the best performing subset of features. For your case, you could do the following with sklearn: from sklearn.feature_selection import RFE from sklearn.linear_model import LinearRegression features = ['X1', 'X2', 'X3'] X = df[features] y = df['Y'] prd = LinearRegression() rfe = RFE(prd, n_features_to_select=1) rfe.fit(X, y) You should be able to see the ranks in rfe.ranking_.
Partial correlation in panda dataframe python [closed]
AFAIU from your comment, you're talking about recursive feature elimination, specifically, using linear regression. As described here: Recursive feature elimination is based on the idea to repeatedly
Partial correlation in panda dataframe python [closed] AFAIU from your comment, you're talking about recursive feature elimination, specifically, using linear regression. As described here: Recursive feature elimination is based on the idea to repeatedly construct a model (for example an SVM or a regression model) and choose either the best or worst performing feature (for example based on coefficients), setting the feature aside and then repeating the process with the rest of the features. This process is applied until all features in the dataset are exhausted. Features are then ranked according to when they were eliminated. As such, it is a greedy optimization for finding the best performing subset of features. For your case, you could do the following with sklearn: from sklearn.feature_selection import RFE from sklearn.linear_model import LinearRegression features = ['X1', 'X2', 'X3'] X = df[features] y = df['Y'] prd = LinearRegression() rfe = RFE(prd, n_features_to_select=1) rfe.fit(X, y) You should be able to see the ranks in rfe.ranking_.
Partial correlation in panda dataframe python [closed] AFAIU from your comment, you're talking about recursive feature elimination, specifically, using linear regression. As described here: Recursive feature elimination is based on the idea to repeatedly
47,143
"report the statistical results of the analysis without the covariate"
At its face this requirement is quite absurd. The most important issue is having a pre-specified, sound, statistical analysis plan. Adjustment variables should usually be pre-specified as part of this plan, and the reasons for adjustment made clear. That makes the covariate-adjusted analysis the "gold standard" and any alternate analysis will just add confusion, and doubt in the minds of reviewers. Results that hinge on covariates despite randomization are quite common, if too few subjects were randomized to yield sufficient power for an unadjusted analysis. More details can be found in my analysis of covariance chapter in BBR - see https://hbiostat.org/bbr/md/ancova.html.
"report the statistical results of the analysis without the covariate"
At its face this requirement is quite absurd. The most important issue is having a pre-specified, sound, statistical analysis plan. Adjustment variables should usually be pre-specified as part of th
"report the statistical results of the analysis without the covariate" At its face this requirement is quite absurd. The most important issue is having a pre-specified, sound, statistical analysis plan. Adjustment variables should usually be pre-specified as part of this plan, and the reasons for adjustment made clear. That makes the covariate-adjusted analysis the "gold standard" and any alternate analysis will just add confusion, and doubt in the minds of reviewers. Results that hinge on covariates despite randomization are quite common, if too few subjects were randomized to yield sufficient power for an unadjusted analysis. More details can be found in my analysis of covariance chapter in BBR - see https://hbiostat.org/bbr/md/ancova.html.
"report the statistical results of the analysis without the covariate" At its face this requirement is quite absurd. The most important issue is having a pre-specified, sound, statistical analysis plan. Adjustment variables should usually be pre-specified as part of th
47,144
Standard Errors with Weighted Least Squares Regression
Essentially you already computed everything you need. The missing piece is just that the sig_i should be the residual standard error divided by the corresponding square root of the weight. In OLS this isn't necessary because all weights are 1. sig_i <- resid_var2 / sqrt(wts) var_betas2 <- solve(t(X) %*% W %*% X) %*% (t(X) %*% W %*% diag(sig_i^2) %*% t(W) %*% X) %*% solve(t(X) %*% W %*% X) And then you get: sqrt(diag(var_betas2)) ## z ## 0.1760843 0.2508150 which matches the output of summary() and vcov(): sqrt(diag(vcov(lm_wls))) ## (Intercept) z ## 0.1760843 0.2508150 Even more familiar might be the equations as $\hat \sigma^2 (X^\top W X)^{-1}$ where the terms from the full sandwich (= bread * meat * bread) have already been simplified to just the bread: var_betas2a <- resid_var2^2 * solve(t(X) %*% W %*% X) sqrt(diag(var_betas2a)) ## z ## 0.1760843 0.2508150
Standard Errors with Weighted Least Squares Regression
Essentially you already computed everything you need. The missing piece is just that the sig_i should be the residual standard error divided by the corresponding square root of the weight. In OLS this
Standard Errors with Weighted Least Squares Regression Essentially you already computed everything you need. The missing piece is just that the sig_i should be the residual standard error divided by the corresponding square root of the weight. In OLS this isn't necessary because all weights are 1. sig_i <- resid_var2 / sqrt(wts) var_betas2 <- solve(t(X) %*% W %*% X) %*% (t(X) %*% W %*% diag(sig_i^2) %*% t(W) %*% X) %*% solve(t(X) %*% W %*% X) And then you get: sqrt(diag(var_betas2)) ## z ## 0.1760843 0.2508150 which matches the output of summary() and vcov(): sqrt(diag(vcov(lm_wls))) ## (Intercept) z ## 0.1760843 0.2508150 Even more familiar might be the equations as $\hat \sigma^2 (X^\top W X)^{-1}$ where the terms from the full sandwich (= bread * meat * bread) have already been simplified to just the bread: var_betas2a <- resid_var2^2 * solve(t(X) %*% W %*% X) sqrt(diag(var_betas2a)) ## z ## 0.1760843 0.2508150
Standard Errors with Weighted Least Squares Regression Essentially you already computed everything you need. The missing piece is just that the sig_i should be the residual standard error divided by the corresponding square root of the weight. In OLS this
47,145
OLS with Time Series Data - yay or nay?
There are time series models (such as VAR, ARIMA, etc.) and there are estimation techniques (such as OLS, maximum likelihood (ML), etc.). Different models can be estimated by different techniques (sometimes more than one). E.g. a VAR can be estimated by OLS or ML while ARIMA (with a nonempty MA part) cannot be estimated by OLS but can be estimated by ML. When modelling some data, you need to choose a sensible model and then estimate it. The choice of a sensible model may be hard, I would say, much harder than the estimation of the chosen model. But once the choice is done, you proceed to estimation. If you choose a VAR, then you can estimate it by OLS. Indeed, as Matthew Gunn says, Estimating VAR models with ordinary least squares is a commonplace, perfectly acceptable practice in finance and economics. And as Christoph Hanck correctly adds, if typical VAR assumptions are met (i.e., each equation has the same regressors, the errors are mean independent of the lagged variables - i.e., you got the dynamics right), OLS is even the efficient systems estimator. Thus the statement OLS is not sophisticated enough for time series analysis is simply not true in general.
OLS with Time Series Data - yay or nay?
There are time series models (such as VAR, ARIMA, etc.) and there are estimation techniques (such as OLS, maximum likelihood (ML), etc.). Different models can be estimated by different techniques (som
OLS with Time Series Data - yay or nay? There are time series models (such as VAR, ARIMA, etc.) and there are estimation techniques (such as OLS, maximum likelihood (ML), etc.). Different models can be estimated by different techniques (sometimes more than one). E.g. a VAR can be estimated by OLS or ML while ARIMA (with a nonempty MA part) cannot be estimated by OLS but can be estimated by ML. When modelling some data, you need to choose a sensible model and then estimate it. The choice of a sensible model may be hard, I would say, much harder than the estimation of the chosen model. But once the choice is done, you proceed to estimation. If you choose a VAR, then you can estimate it by OLS. Indeed, as Matthew Gunn says, Estimating VAR models with ordinary least squares is a commonplace, perfectly acceptable practice in finance and economics. And as Christoph Hanck correctly adds, if typical VAR assumptions are met (i.e., each equation has the same regressors, the errors are mean independent of the lagged variables - i.e., you got the dynamics right), OLS is even the efficient systems estimator. Thus the statement OLS is not sophisticated enough for time series analysis is simply not true in general.
OLS with Time Series Data - yay or nay? There are time series models (such as VAR, ARIMA, etc.) and there are estimation techniques (such as OLS, maximum likelihood (ML), etc.). Different models can be estimated by different techniques (som
47,146
How does outlier impact logistic regression?
Outliers may have the same essential impact on a logistic regression as they have in linear regression: The deletion-diagnostic model, fit by deleting the outlying observation, may have DF-betas greater than the full-model coefficient; this means that the sigmoid-slope of association may be of opposite direction. Separately, the inference may not agree in the two models, suggesting one commits a type II error, or the other commits a type I error. This point underscores the problem of suggesting that, when outliers are encountered, they should summarily be deleted. The implication for logistic regression data analysis is the same as well: if there is a single observation (or a small cluster of observations) which entirely drives the estimates and inference, they should be identified and discussed in the data analysis. DF-beta residual diagnostics is an effective numerical and graphical tool for either type of model which is easy to interpret by statisticians and non-statisticians alike. There are some differences to discuss. In linear regression, it is very easy to visualize outliers using a scatter plot. The scaled vertical displacement from the line of best fit as well as the scaled horizontal distance from the centroid of predictor-scale X together determine the influence and leverage (outlier-ness) of an observation. For a logistic model, the mean-variance relationship means that the scaling factor for vertical displacement is a continuous function of the fitted sigmoid slope. Farther out in the tails, the mean is closer to either 0 or 1, leading to smaller variance so that seemingly small perturbations can have more substantial impacts on estimates and inference. However, whereas a Y value in linear regression may be arbitrarily large, the maximum fitted distance between a fitted and observed logistic value is bounded. Does that mean that a logistic regression is robust to outliers? Absolutely not.
How does outlier impact logistic regression?
Outliers may have the same essential impact on a logistic regression as they have in linear regression: The deletion-diagnostic model, fit by deleting the outlying observation, may have DF-betas great
How does outlier impact logistic regression? Outliers may have the same essential impact on a logistic regression as they have in linear regression: The deletion-diagnostic model, fit by deleting the outlying observation, may have DF-betas greater than the full-model coefficient; this means that the sigmoid-slope of association may be of opposite direction. Separately, the inference may not agree in the two models, suggesting one commits a type II error, or the other commits a type I error. This point underscores the problem of suggesting that, when outliers are encountered, they should summarily be deleted. The implication for logistic regression data analysis is the same as well: if there is a single observation (or a small cluster of observations) which entirely drives the estimates and inference, they should be identified and discussed in the data analysis. DF-beta residual diagnostics is an effective numerical and graphical tool for either type of model which is easy to interpret by statisticians and non-statisticians alike. There are some differences to discuss. In linear regression, it is very easy to visualize outliers using a scatter plot. The scaled vertical displacement from the line of best fit as well as the scaled horizontal distance from the centroid of predictor-scale X together determine the influence and leverage (outlier-ness) of an observation. For a logistic model, the mean-variance relationship means that the scaling factor for vertical displacement is a continuous function of the fitted sigmoid slope. Farther out in the tails, the mean is closer to either 0 or 1, leading to smaller variance so that seemingly small perturbations can have more substantial impacts on estimates and inference. However, whereas a Y value in linear regression may be arbitrarily large, the maximum fitted distance between a fitted and observed logistic value is bounded. Does that mean that a logistic regression is robust to outliers? Absolutely not.
How does outlier impact logistic regression? Outliers may have the same essential impact on a logistic regression as they have in linear regression: The deletion-diagnostic model, fit by deleting the outlying observation, may have DF-betas great
47,147
How does outlier impact logistic regression?
Logistic regression is robust to concordant outliers, (with an extreme X value but an outcome that accords with the X value), in a way that the linear probability model is not. See http://teaching.sociology.ul.ie:3838/logitinfl for a simple illustration. It might be better to say that such observations are outliers for the linear probability model, but not for logistic.
How does outlier impact logistic regression?
Logistic regression is robust to concordant outliers, (with an extreme X value but an outcome that accords with the X value), in a way that the linear probability model is not. See http://teaching.soc
How does outlier impact logistic regression? Logistic regression is robust to concordant outliers, (with an extreme X value but an outcome that accords with the X value), in a way that the linear probability model is not. See http://teaching.sociology.ul.ie:3838/logitinfl for a simple illustration. It might be better to say that such observations are outliers for the linear probability model, but not for logistic.
How does outlier impact logistic regression? Logistic regression is robust to concordant outliers, (with an extreme X value but an outcome that accords with the X value), in a way that the linear probability model is not. See http://teaching.soc
47,148
Error metric for regression with right-skewed data and outliers
I don't think the problem here is your metric; RMSE & R^2 are generally quite acceptable. And in general, deviations from normality are not a major problem (see discussion here). However, if you have a number of outliers, you will likely improve your model if you change the error distribution you are using to one that can exhibit skewness. Or alternately, you could transform your data so that your residuals are subsequently more normally distributed. If your residuals are right-skewed, a log-transformation or a square root transformation might solve your problem.
Error metric for regression with right-skewed data and outliers
I don't think the problem here is your metric; RMSE & R^2 are generally quite acceptable. And in general, deviations from normality are not a major problem (see discussion here). However, if you have
Error metric for regression with right-skewed data and outliers I don't think the problem here is your metric; RMSE & R^2 are generally quite acceptable. And in general, deviations from normality are not a major problem (see discussion here). However, if you have a number of outliers, you will likely improve your model if you change the error distribution you are using to one that can exhibit skewness. Or alternately, you could transform your data so that your residuals are subsequently more normally distributed. If your residuals are right-skewed, a log-transformation or a square root transformation might solve your problem.
Error metric for regression with right-skewed data and outliers I don't think the problem here is your metric; RMSE & R^2 are generally quite acceptable. And in general, deviations from normality are not a major problem (see discussion here). However, if you have
47,149
Error metric for regression with right-skewed data and outliers
Just spitballing here, but this seems like as much of an economics problem as a statistics one. Given your application, it seems like you want to pick the model that maximizes your "profit": what the user would spend without the voucher plus the additional spend due to the voucher less the cost of the voucher. I'm assuming you are predicting spend and, based on predicted spend, classifying them into one of a small number of voucher categories. If so, misclassification costs you more for different types of spenders, depending on how many there are, how much they spend, and how sensitive they are to your vouchers. If so, you could do something like the following: Write down an equation for profit from a user conditional on their predicted and actual spend category. Aka, what will the average person in a spend category spend given their assigned voucher / predicted spend. $ \pi(s,\hat{s})$ = ... Write down total expected profits using the the share of people in each category (from historical data) and the probability of misclassification. $ \pi = \sum_sPr(s)\sum_\hat{s}Pr(\hat{s}|s)\pi(s,\hat{s})$ Now you have a function for profit based on your probabilities of misclassification. You can use this to select a model. Like RMSE or other metrics, this weights different size errors more or less, but it's based on your specific situation rather than a mathematical function.
Error metric for regression with right-skewed data and outliers
Just spitballing here, but this seems like as much of an economics problem as a statistics one. Given your application, it seems like you want to pick the model that maximizes your "profit": what the
Error metric for regression with right-skewed data and outliers Just spitballing here, but this seems like as much of an economics problem as a statistics one. Given your application, it seems like you want to pick the model that maximizes your "profit": what the user would spend without the voucher plus the additional spend due to the voucher less the cost of the voucher. I'm assuming you are predicting spend and, based on predicted spend, classifying them into one of a small number of voucher categories. If so, misclassification costs you more for different types of spenders, depending on how many there are, how much they spend, and how sensitive they are to your vouchers. If so, you could do something like the following: Write down an equation for profit from a user conditional on their predicted and actual spend category. Aka, what will the average person in a spend category spend given their assigned voucher / predicted spend. $ \pi(s,\hat{s})$ = ... Write down total expected profits using the the share of people in each category (from historical data) and the probability of misclassification. $ \pi = \sum_sPr(s)\sum_\hat{s}Pr(\hat{s}|s)\pi(s,\hat{s})$ Now you have a function for profit based on your probabilities of misclassification. You can use this to select a model. Like RMSE or other metrics, this weights different size errors more or less, but it's based on your specific situation rather than a mathematical function.
Error metric for regression with right-skewed data and outliers Just spitballing here, but this seems like as much of an economics problem as a statistics one. Given your application, it seems like you want to pick the model that maximizes your "profit": what the
47,150
Error metric for regression with right-skewed data and outliers
Since your response variable is spending, it might be plausible to assume it's log normal and use a log transformation, which could remove the skewness. I believe the distribution of income is often fit well by a log normal, so maybe spending is as well. What do you mean by time sensitive? Do you have measurements through time? If so you might be dealing with a time series problem where your errors are not independent. This will invalidate things like standard errors for a typical regression. You may want to look into models that account for correlation through time.
Error metric for regression with right-skewed data and outliers
Since your response variable is spending, it might be plausible to assume it's log normal and use a log transformation, which could remove the skewness. I believe the distribution of income is often f
Error metric for regression with right-skewed data and outliers Since your response variable is spending, it might be plausible to assume it's log normal and use a log transformation, which could remove the skewness. I believe the distribution of income is often fit well by a log normal, so maybe spending is as well. What do you mean by time sensitive? Do you have measurements through time? If so you might be dealing with a time series problem where your errors are not independent. This will invalidate things like standard errors for a typical regression. You may want to look into models that account for correlation through time.
Error metric for regression with right-skewed data and outliers Since your response variable is spending, it might be plausible to assume it's log normal and use a log transformation, which could remove the skewness. I believe the distribution of income is often f
47,151
Marginal independence does not imply joint independence
Your first question assumes that $X, Y$, and $Z$ are pairwise independent random variables and asks whether $$ X,Y, Z~~\text{pairwise independent} \implies (X,Y)~~\text{and}~~Z~~\text{independent}??\tag{1} $$ In general, the answer is NO, the implication $(1)$ does not hold in all cases. The proof of this is by a reductio ad absurdum argument: if the implication $(1)$ were to hold, then pairwise independence of $X$, $Y$, and $Z$ would imply that $X$, $Y$, and $Z$ are mutually independent which we know is not true in general. Suppose that implication $(1)$ is true. Then, $$p_{X,Y,Z} = \underbrace{p_{X,Y}\cdot p_Z}_{(X,Y)\perp Z ~\text{via}~(1)} = \underbrace{p_{X}\cdot p_Y}_{X\perp Y~\text{by hypothesis}}\cdot p_Z$$ and so $X$, $Y$, and $Z$ are mutually independent which is not true in general. So, it must be that the hypothesis that $(1)$ holds is false. The simplest example of pairwise independent random variables that are not mutually independent random variables is $X, Y$, and $Z$ being Bernoulli$(\frac 12)$ random variables whose joint pmf has value $\frac 14$ when $(X,Y,Z)$ equals $(0,0,0)$ or $(0,1,1)$ or $(1,0,1)$, or $(1,1,0)$. These are pairwise independent random variables but not mutually independent random variables. In particular, $$p_{X,Y,Z}(1,1,1) = 0 \neq p_{X,Y}(1,1)\cdot p_Z(1) = \frac 14\cdot \frac 12$$ and so $(X,Y)$ is not independent of $Z$ as you suspect. Indeed, it is even possible to have standard normal random variables that are pairwise independent but are not mutually independent. See the first couple of paragraphs of this answer of mine for a construction. Your second question asks independence of $(X,Y)$ and $Z$ allows us to deduce that $X$ and $Z$ are independent and that $Y$ and $Z$ are independent, and here the answer is YES. We have that for discrete random variables, $$p_{X,Z} = \sum_y p_{X,Y,Z} = \sum_y \underbrace{p_{X,Y}\cdot p_Z}_{(X,Y)\perp Z} = \left(\sum_y p_{X,Y}\right)\cdot p_Z = p_X\cdot p_Z$$ and similarly for $Y$ and $Z$, (and for continuous random variables when sums are replaced by integrals, etc).
Marginal independence does not imply joint independence
Your first question assumes that $X, Y$, and $Z$ are pairwise independent random variables and asks whether $$ X,Y, Z~~\text{pairwise independent} \implies (X,Y)~~\text{and}~~Z~~\text{independent}??\
Marginal independence does not imply joint independence Your first question assumes that $X, Y$, and $Z$ are pairwise independent random variables and asks whether $$ X,Y, Z~~\text{pairwise independent} \implies (X,Y)~~\text{and}~~Z~~\text{independent}??\tag{1} $$ In general, the answer is NO, the implication $(1)$ does not hold in all cases. The proof of this is by a reductio ad absurdum argument: if the implication $(1)$ were to hold, then pairwise independence of $X$, $Y$, and $Z$ would imply that $X$, $Y$, and $Z$ are mutually independent which we know is not true in general. Suppose that implication $(1)$ is true. Then, $$p_{X,Y,Z} = \underbrace{p_{X,Y}\cdot p_Z}_{(X,Y)\perp Z ~\text{via}~(1)} = \underbrace{p_{X}\cdot p_Y}_{X\perp Y~\text{by hypothesis}}\cdot p_Z$$ and so $X$, $Y$, and $Z$ are mutually independent which is not true in general. So, it must be that the hypothesis that $(1)$ holds is false. The simplest example of pairwise independent random variables that are not mutually independent random variables is $X, Y$, and $Z$ being Bernoulli$(\frac 12)$ random variables whose joint pmf has value $\frac 14$ when $(X,Y,Z)$ equals $(0,0,0)$ or $(0,1,1)$ or $(1,0,1)$, or $(1,1,0)$. These are pairwise independent random variables but not mutually independent random variables. In particular, $$p_{X,Y,Z}(1,1,1) = 0 \neq p_{X,Y}(1,1)\cdot p_Z(1) = \frac 14\cdot \frac 12$$ and so $(X,Y)$ is not independent of $Z$ as you suspect. Indeed, it is even possible to have standard normal random variables that are pairwise independent but are not mutually independent. See the first couple of paragraphs of this answer of mine for a construction. Your second question asks independence of $(X,Y)$ and $Z$ allows us to deduce that $X$ and $Z$ are independent and that $Y$ and $Z$ are independent, and here the answer is YES. We have that for discrete random variables, $$p_{X,Z} = \sum_y p_{X,Y,Z} = \sum_y \underbrace{p_{X,Y}\cdot p_Z}_{(X,Y)\perp Z} = \left(\sum_y p_{X,Y}\right)\cdot p_Z = p_X\cdot p_Z$$ and similarly for $Y$ and $Z$, (and for continuous random variables when sums are replaced by integrals, etc).
Marginal independence does not imply joint independence Your first question assumes that $X, Y$, and $Z$ are pairwise independent random variables and asks whether $$ X,Y, Z~~\text{pairwise independent} \implies (X,Y)~~\text{and}~~Z~~\text{independent}??\
47,152
AIC and BIC criterion for Model selection, how is it used in this paper?
In my answer here I show that in a case like the present one, in which we test nested models against each other, the minimum AIC rule selects the larger model (i.e., rejects the null) if the likelihood ratio statistic $$ \mathcal{LR}=n[\log(\widehat{\sigma}^2_1)-\log(\widehat{\sigma}^2_2)], $$ with $\widehat{\sigma}^2_i$ the ML error variance estimates of the restricted and unrestricted models, exceeds $2K_2$. Here, $K_2$ is the number of additional variables in the larger model. In your case, $K_2=1$, corresponding to $x_{i2}$. Thus, select the larger model if $\mathcal{LR}>2$. Now, in the present linear regression framework, the absolute value of the $t$-statistic $$|t|=\left| \dfrac{\sqrt{n}\hat\beta(U) }{\sigma_\beta} \right|$$ is simply the positive square root of the LR-statistic. (Actually, this in general only holds asymptotically, as we have $t^2=F$, the $F$- or Wald-statistic, which is in general not numerically identical to $\cal{LR}$ in finite samples. Leeb and Pötscher however assume that $\sigma^2$ is known, which, as is shown here, restores exact numerical equivalence of Wald, LR and score statistics in this setup.) Hence, going with the larger model according to the mininum AIC rule when $\mathcal{LR}>2=c$ corresponds to rejecting when the t-statistic exceeds $\sqrt{c}$. It is worth pointing out that this implies that, in this case, the AIC rule is nothing but a hypothesis test at level $\alpha=0.157$, as (the LR statistic being $\chi^2_1$ under the present $H_0$ of the smaller model being the correct one) > 1-pchisq(2,df = 1) [1] 0.1572992 or > 2*pnorm(-sqrt(2)) [1] 0.1572992 Solving the equation $1.96=\sqrt{\ln n}$ for $n$ gives that BIC would be of the same size as a test at the 5%-level at $n\approx46$. It does not seem to be a general result that AIC corresponds to a liberal nested hypothesis test. For example, when $K_2=8$, AIC is equivalent to rejecting when $\mathcal{LR}>16$, which, under the null, has probability > 1-pchisq(2*8,df = 8) [1] 0.04238011 In fact, the probability tends to zero with $K_2$:
AIC and BIC criterion for Model selection, how is it used in this paper?
In my answer here I show that in a case like the present one, in which we test nested models against each other, the minimum AIC rule selects the larger model (i.e., rejects the null) if the likelihoo
AIC and BIC criterion for Model selection, how is it used in this paper? In my answer here I show that in a case like the present one, in which we test nested models against each other, the minimum AIC rule selects the larger model (i.e., rejects the null) if the likelihood ratio statistic $$ \mathcal{LR}=n[\log(\widehat{\sigma}^2_1)-\log(\widehat{\sigma}^2_2)], $$ with $\widehat{\sigma}^2_i$ the ML error variance estimates of the restricted and unrestricted models, exceeds $2K_2$. Here, $K_2$ is the number of additional variables in the larger model. In your case, $K_2=1$, corresponding to $x_{i2}$. Thus, select the larger model if $\mathcal{LR}>2$. Now, in the present linear regression framework, the absolute value of the $t$-statistic $$|t|=\left| \dfrac{\sqrt{n}\hat\beta(U) }{\sigma_\beta} \right|$$ is simply the positive square root of the LR-statistic. (Actually, this in general only holds asymptotically, as we have $t^2=F$, the $F$- or Wald-statistic, which is in general not numerically identical to $\cal{LR}$ in finite samples. Leeb and Pötscher however assume that $\sigma^2$ is known, which, as is shown here, restores exact numerical equivalence of Wald, LR and score statistics in this setup.) Hence, going with the larger model according to the mininum AIC rule when $\mathcal{LR}>2=c$ corresponds to rejecting when the t-statistic exceeds $\sqrt{c}$. It is worth pointing out that this implies that, in this case, the AIC rule is nothing but a hypothesis test at level $\alpha=0.157$, as (the LR statistic being $\chi^2_1$ under the present $H_0$ of the smaller model being the correct one) > 1-pchisq(2,df = 1) [1] 0.1572992 or > 2*pnorm(-sqrt(2)) [1] 0.1572992 Solving the equation $1.96=\sqrt{\ln n}$ for $n$ gives that BIC would be of the same size as a test at the 5%-level at $n\approx46$. It does not seem to be a general result that AIC corresponds to a liberal nested hypothesis test. For example, when $K_2=8$, AIC is equivalent to rejecting when $\mathcal{LR}>16$, which, under the null, has probability > 1-pchisq(2*8,df = 8) [1] 0.04238011 In fact, the probability tends to zero with $K_2$:
AIC and BIC criterion for Model selection, how is it used in this paper? In my answer here I show that in a case like the present one, in which we test nested models against each other, the minimum AIC rule selects the larger model (i.e., rejects the null) if the likelihoo
47,153
Covariance between a normally distributed variable and its exponent
First solving the following integral by completing the square (4th equality) and recognising the resulting integral as the expected value of a normal variate with an expected value of $\mu+\sigma^2$ (last equality), \begin{align} E(Xe^X) &=\int_{-\infty}^\infty xe^x\frac1{\sqrt{2\pi}\sigma}e^{-\frac1{2\sigma^2 }(x-\mu)^2}dx \\&=\int_{-\infty}^\infty x\frac1{\sqrt{2\pi}\sigma}e^{-\frac1{2\sigma^2 }(x^2-2\mu x+\mu^2-2\sigma^2 x)}dx \\&=e^{-\frac{\mu^2}{2\sigma^2}}\int_{-\infty}^\infty x\frac1{\sqrt{2\pi}\sigma}e^{-\frac1{2\sigma^2 }[x^2-2(\mu+\sigma^2)x]}dx \\&=e^{-\frac{\mu^2}{2\sigma^2}}\int_{-\infty}^\infty x\frac1{\sqrt{2\pi}\sigma}e^{-\frac1{2\sigma^2 }[(x-\mu-\sigma^2)^2-(\mu+\sigma^2)^2]}dx \\&=e^{-\frac{\mu^2-(\mu+\sigma^2)^2}{2\sigma^2}}\int_{-\infty}^\infty x\frac1{\sqrt{2\pi}\sigma}e^{-\frac1{2\sigma^2 }(x-\mu-\sigma^2)^2}dx \\&=e^{\mu+\frac{\sigma^2}2}(\mu+\sigma^2), \end{align} and \begin{align} \operatorname{Cov}(X,e^X)&=E(Xe^X)-EXEe^X \\&=e^{\mu+\frac{\sigma^2}2}(\mu+\sigma^2)-\mu e^{\mu+\frac{\sigma^2}2} \\&=e^{\mu+\frac{\sigma^2}2}\sigma^2. \end{align}
Covariance between a normally distributed variable and its exponent
First solving the following integral by completing the square (4th equality) and recognising the resulting integral as the expected value of a normal variate with an expected value of $\mu+\sigma^2$ (
Covariance between a normally distributed variable and its exponent First solving the following integral by completing the square (4th equality) and recognising the resulting integral as the expected value of a normal variate with an expected value of $\mu+\sigma^2$ (last equality), \begin{align} E(Xe^X) &=\int_{-\infty}^\infty xe^x\frac1{\sqrt{2\pi}\sigma}e^{-\frac1{2\sigma^2 }(x-\mu)^2}dx \\&=\int_{-\infty}^\infty x\frac1{\sqrt{2\pi}\sigma}e^{-\frac1{2\sigma^2 }(x^2-2\mu x+\mu^2-2\sigma^2 x)}dx \\&=e^{-\frac{\mu^2}{2\sigma^2}}\int_{-\infty}^\infty x\frac1{\sqrt{2\pi}\sigma}e^{-\frac1{2\sigma^2 }[x^2-2(\mu+\sigma^2)x]}dx \\&=e^{-\frac{\mu^2}{2\sigma^2}}\int_{-\infty}^\infty x\frac1{\sqrt{2\pi}\sigma}e^{-\frac1{2\sigma^2 }[(x-\mu-\sigma^2)^2-(\mu+\sigma^2)^2]}dx \\&=e^{-\frac{\mu^2-(\mu+\sigma^2)^2}{2\sigma^2}}\int_{-\infty}^\infty x\frac1{\sqrt{2\pi}\sigma}e^{-\frac1{2\sigma^2 }(x-\mu-\sigma^2)^2}dx \\&=e^{\mu+\frac{\sigma^2}2}(\mu+\sigma^2), \end{align} and \begin{align} \operatorname{Cov}(X,e^X)&=E(Xe^X)-EXEe^X \\&=e^{\mu+\frac{\sigma^2}2}(\mu+\sigma^2)-\mu e^{\mu+\frac{\sigma^2}2} \\&=e^{\mu+\frac{\sigma^2}2}\sigma^2. \end{align}
Covariance between a normally distributed variable and its exponent First solving the following integral by completing the square (4th equality) and recognising the resulting integral as the expected value of a normal variate with an expected value of $\mu+\sigma^2$ (
47,154
Is the following inequality correct? How to prove it?
Expand using product rule: $$P(X \ge a_0 \cap Y \le b_0) = P(X \ge a_0 | Y \le b_0) P(Y \le b_0)$$ Assuming $P(Y \le b_0)$ is nonzero, you can use the first inequality to obtain: $$P(X \ge a_0 | Y \le b_0) P(Y \le b_0) \le f(y\le b_0) P(Y \le b_0)$$ Because $f(y)$ is increasing in $y$, $f(y \le b_0) \le f(b_0)$ so the inequality of interest holds. By the way, in the context of probability $f$ is normally used for PDFs so you may want to use a different letter to avoid confusion. EDIT: Granted, $f(y \le b_0)$ is an abuse of notation. It should be read as $f(y), y \le b_0$ and not as the function taking a set for its argument.
Is the following inequality correct? How to prove it?
Expand using product rule: $$P(X \ge a_0 \cap Y \le b_0) = P(X \ge a_0 | Y \le b_0) P(Y \le b_0)$$ Assuming $P(Y \le b_0)$ is nonzero, you can use the first inequality to obtain: $$P(X \ge a_0 | Y \le
Is the following inequality correct? How to prove it? Expand using product rule: $$P(X \ge a_0 \cap Y \le b_0) = P(X \ge a_0 | Y \le b_0) P(Y \le b_0)$$ Assuming $P(Y \le b_0)$ is nonzero, you can use the first inequality to obtain: $$P(X \ge a_0 | Y \le b_0) P(Y \le b_0) \le f(y\le b_0) P(Y \le b_0)$$ Because $f(y)$ is increasing in $y$, $f(y \le b_0) \le f(b_0)$ so the inequality of interest holds. By the way, in the context of probability $f$ is normally used for PDFs so you may want to use a different letter to avoid confusion. EDIT: Granted, $f(y \le b_0)$ is an abuse of notation. It should be read as $f(y), y \le b_0$ and not as the function taking a set for its argument.
Is the following inequality correct? How to prove it? Expand using product rule: $$P(X \ge a_0 \cap Y \le b_0) = P(X \ge a_0 | Y \le b_0) P(Y \le b_0)$$ Assuming $P(Y \le b_0)$ is nonzero, you can use the first inequality to obtain: $$P(X \ge a_0 | Y \le
47,155
Is the following inequality correct? How to prove it?
First, we have $$\eqalign{ \textbf{Pr}(X \ge a_0|Y = y) &=\int_{a_0}^{+\infty}p_{X}(x|Y= y)dx \\ &=\int_{a_0}^{+\infty}\frac{p_{X,Y}(x,y)}{p_Y(y)}dx\\ &=\frac{1}{p_Y(y)}\int_{a_0}^{+\infty}{p_{X,Y}(x,y)}dx, }$$ where $p_{X,Y}(x, y)$ is the joint PDF of $(X,Y)$, $p_{X}(x| Y=y)$ is the PDF of $X$ conditional on $Y=y$, and $p_Y(y)$ is the PDF of $Y$. Because when $y \le b_0$, $f(y)\le f(b_0)$, that is $$\int_{a_0}^{+\infty}{p_{X,Y}(x,y)}dx \le f(b_0)p_Y(y) $$ Finally, substitute it into the following, $$\eqalign{ \textbf{Pr}(X \ge a_0, Y \le b_0) &= \int_{a_0}^{+\infty}\int_{-\infty}^{b_0}p_{X,Y}(x, y)dy dx \\ &\le \int_{-\infty}^{b_0} f(b_0)p_Y(y) dy \\ & \le f(b_0), }$$ which proves the required inequality.
Is the following inequality correct? How to prove it?
First, we have $$\eqalign{ \textbf{Pr}(X \ge a_0|Y = y) &=\int_{a_0}^{+\infty}p_{X}(x|Y= y)dx \\ &=\int_{a_0}^{+\infty}\frac{p_{X,Y}(x,y)}{p_Y(y)}dx\\ &=\frac{1}{p_Y(y)}\int_{a_0}^{+\infty}{p_{X,Y}(x,
Is the following inequality correct? How to prove it? First, we have $$\eqalign{ \textbf{Pr}(X \ge a_0|Y = y) &=\int_{a_0}^{+\infty}p_{X}(x|Y= y)dx \\ &=\int_{a_0}^{+\infty}\frac{p_{X,Y}(x,y)}{p_Y(y)}dx\\ &=\frac{1}{p_Y(y)}\int_{a_0}^{+\infty}{p_{X,Y}(x,y)}dx, }$$ where $p_{X,Y}(x, y)$ is the joint PDF of $(X,Y)$, $p_{X}(x| Y=y)$ is the PDF of $X$ conditional on $Y=y$, and $p_Y(y)$ is the PDF of $Y$. Because when $y \le b_0$, $f(y)\le f(b_0)$, that is $$\int_{a_0}^{+\infty}{p_{X,Y}(x,y)}dx \le f(b_0)p_Y(y) $$ Finally, substitute it into the following, $$\eqalign{ \textbf{Pr}(X \ge a_0, Y \le b_0) &= \int_{a_0}^{+\infty}\int_{-\infty}^{b_0}p_{X,Y}(x, y)dy dx \\ &\le \int_{-\infty}^{b_0} f(b_0)p_Y(y) dy \\ & \le f(b_0), }$$ which proves the required inequality.
Is the following inequality correct? How to prove it? First, we have $$\eqalign{ \textbf{Pr}(X \ge a_0|Y = y) &=\int_{a_0}^{+\infty}p_{X}(x|Y= y)dx \\ &=\int_{a_0}^{+\infty}\frac{p_{X,Y}(x,y)}{p_Y(y)}dx\\ &=\frac{1}{p_Y(y)}\int_{a_0}^{+\infty}{p_{X,Y}(x,
47,156
Why is power to detect interactions less than that for main effects?
It's signal and noise. When looking for an interaction, you're looking for it against more noise. Consider looking for a mean in a single group. Only the noise of that group affects your estimate of the mean. Now consider looking for a difference of means between two groups. The estimated difference is affected by the independent noise of both groups. The difference (the signal) is subject to more noise, so we are less likely to reliably detect it. Now consider looking for a difference of differences of means, that is, a two-way interaction. That involves the noise from four independent groups. The difference of differences is subject to yet more noise, so we are even less likely to reliably detect it. That's a quick conceptual answer. Others may want to provide more technical details...
Why is power to detect interactions less than that for main effects?
It's signal and noise. When looking for an interaction, you're looking for it against more noise. Consider looking for a mean in a single group. Only the noise of that group affects your estimate of t
Why is power to detect interactions less than that for main effects? It's signal and noise. When looking for an interaction, you're looking for it against more noise. Consider looking for a mean in a single group. Only the noise of that group affects your estimate of the mean. Now consider looking for a difference of means between two groups. The estimated difference is affected by the independent noise of both groups. The difference (the signal) is subject to more noise, so we are less likely to reliably detect it. Now consider looking for a difference of differences of means, that is, a two-way interaction. That involves the noise from four independent groups. The difference of differences is subject to yet more noise, so we are even less likely to reliably detect it. That's a quick conceptual answer. Others may want to provide more technical details...
Why is power to detect interactions less than that for main effects? It's signal and noise. When looking for an interaction, you're looking for it against more noise. Consider looking for a mean in a single group. Only the noise of that group affects your estimate of t
47,157
Why is power to detect interactions less than that for main effects?
Here's the pure intuition. Consider these two functions: $$f(x_1,x_2)=\beta_0+\beta_1x_1+\beta_2x_2$$ vs. $$g(x_1,x_2)=\beta_0+\beta_1x_1+\beta_2x_2+\beta_{12}x_1x_2$$ You need just three observations to solve for the parameters of $f(x_1,x_2|\beta_0,\beta_1,\beta_2)$, but you need four observations of function $g(x_1,x_2|\beta_0,\beta_1,\beta_2,\beta_{12})$ because it has one more parameter. The function $g(.)$ represents a model with an interaction term, and function $f(.)$ a model with just the main effects. Even if you forget about the random noise, you see that $g(.)$ needs more data than $f(.)$ to establish its parameters.
Why is power to detect interactions less than that for main effects?
Here's the pure intuition. Consider these two functions: $$f(x_1,x_2)=\beta_0+\beta_1x_1+\beta_2x_2$$ vs. $$g(x_1,x_2)=\beta_0+\beta_1x_1+\beta_2x_2+\beta_{12}x_1x_2$$ You need just three observations
Why is power to detect interactions less than that for main effects? Here's the pure intuition. Consider these two functions: $$f(x_1,x_2)=\beta_0+\beta_1x_1+\beta_2x_2$$ vs. $$g(x_1,x_2)=\beta_0+\beta_1x_1+\beta_2x_2+\beta_{12}x_1x_2$$ You need just three observations to solve for the parameters of $f(x_1,x_2|\beta_0,\beta_1,\beta_2)$, but you need four observations of function $g(x_1,x_2|\beta_0,\beta_1,\beta_2,\beta_{12})$ because it has one more parameter. The function $g(.)$ represents a model with an interaction term, and function $f(.)$ a model with just the main effects. Even if you forget about the random noise, you see that $g(.)$ needs more data than $f(.)$ to establish its parameters.
Why is power to detect interactions less than that for main effects? Here's the pure intuition. Consider these two functions: $$f(x_1,x_2)=\beta_0+\beta_1x_1+\beta_2x_2$$ vs. $$g(x_1,x_2)=\beta_0+\beta_1x_1+\beta_2x_2+\beta_{12}x_1x_2$$ You need just three observations
47,158
Why is power to detect interactions less than that for main effects?
I don't think this is a statistical question as much as a question of the state of the world. In most realistic situations, differences between effects are smaller than the effects themselves. However, this is not statistically or logically necessary.
Why is power to detect interactions less than that for main effects?
I don't think this is a statistical question as much as a question of the state of the world. In most realistic situations, differences between effects are smaller than the effects themselves. However
Why is power to detect interactions less than that for main effects? I don't think this is a statistical question as much as a question of the state of the world. In most realistic situations, differences between effects are smaller than the effects themselves. However, this is not statistically or logically necessary.
Why is power to detect interactions less than that for main effects? I don't think this is a statistical question as much as a question of the state of the world. In most realistic situations, differences between effects are smaller than the effects themselves. However
47,159
Why is power to detect interactions less than that for main effects?
Power is less for interactions, because interactions are generally quite small. Theoretically, this can be explained by the Piranha Problem: Statistically observable interactions are small because either: 1) Only small interactions are possible, or 2) Large interactions are possible, but then they wash each other out, leaving only small observable effects. Empirically, observed effect sizes for interactions tend to be very small, Aguinis, 2005 is the classic citation for this.
Why is power to detect interactions less than that for main effects?
Power is less for interactions, because interactions are generally quite small. Theoretically, this can be explained by the Piranha Problem: Statistically observable interactions are small because eit
Why is power to detect interactions less than that for main effects? Power is less for interactions, because interactions are generally quite small. Theoretically, this can be explained by the Piranha Problem: Statistically observable interactions are small because either: 1) Only small interactions are possible, or 2) Large interactions are possible, but then they wash each other out, leaving only small observable effects. Empirically, observed effect sizes for interactions tend to be very small, Aguinis, 2005 is the classic citation for this.
Why is power to detect interactions less than that for main effects? Power is less for interactions, because interactions are generally quite small. Theoretically, this can be explained by the Piranha Problem: Statistically observable interactions are small because eit
47,160
Scikit-Learn - Adding Weights to Features
Generally, it's not a great idea to try to meddle with feature weights - RF (and machine learning algorithms in general) works out the importance of features by itself. See also: https://stackoverflow.com/questions/38034702/how-to-put-more-weight-on-certain-features-in-machine-learning
Scikit-Learn - Adding Weights to Features
Generally, it's not a great idea to try to meddle with feature weights - RF (and machine learning algorithms in general) works out the importance of features by itself. See also: https://stackoverflow
Scikit-Learn - Adding Weights to Features Generally, it's not a great idea to try to meddle with feature weights - RF (and machine learning algorithms in general) works out the importance of features by itself. See also: https://stackoverflow.com/questions/38034702/how-to-put-more-weight-on-certain-features-in-machine-learning
Scikit-Learn - Adding Weights to Features Generally, it's not a great idea to try to meddle with feature weights - RF (and machine learning algorithms in general) works out the importance of features by itself. See also: https://stackoverflow
47,161
Model Stacking - Gives poor performance
It sounds like you may not be generating the "probabilities" (aka "level-one" data) correctly. These predicted values should be cross-validated predicted values from the base learners (or sometimes people use a separate hold-out set to generate these predicted values). My guess is that you are using predictions generated exclusively from the training set, which is leading to overfitting. Here are some references which explain the construction of the level-one dataset in more detail: Scalable Ensemble Learning in H2O (Strata San Jose 2016) Slides useR! Machine Learning Tutorial: Stacking h2oEnsemble Stacking Tutorial "Scalable Ensemble Learning and Computationally Efficient Variance Estimation" (PhD Thesis, see chapter 2) Soon, we will release H2O with XGBoost support, so you should be able to ensemble XGBoost models much more easily using the Stacked Ensemble method in H2O. Or you could use H2O models for the time-being and skip the manual construction of the ensemble.
Model Stacking - Gives poor performance
It sounds like you may not be generating the "probabilities" (aka "level-one" data) correctly. These predicted values should be cross-validated predicted values from the base learners (or sometimes p
Model Stacking - Gives poor performance It sounds like you may not be generating the "probabilities" (aka "level-one" data) correctly. These predicted values should be cross-validated predicted values from the base learners (or sometimes people use a separate hold-out set to generate these predicted values). My guess is that you are using predictions generated exclusively from the training set, which is leading to overfitting. Here are some references which explain the construction of the level-one dataset in more detail: Scalable Ensemble Learning in H2O (Strata San Jose 2016) Slides useR! Machine Learning Tutorial: Stacking h2oEnsemble Stacking Tutorial "Scalable Ensemble Learning and Computationally Efficient Variance Estimation" (PhD Thesis, see chapter 2) Soon, we will release H2O with XGBoost support, so you should be able to ensemble XGBoost models much more easily using the Stacked Ensemble method in H2O. Or you could use H2O models for the time-being and skip the manual construction of the ensemble.
Model Stacking - Gives poor performance It sounds like you may not be generating the "probabilities" (aka "level-one" data) correctly. These predicted values should be cross-validated predicted values from the base learners (or sometimes p
47,162
Model Stacking - Gives poor performance
Stacking can give poor performance relative to the base models if a lot of overlap exists in the correct predictions of the ensembled models. Also, stacking tends to do better with a larger number of input models than with a smaller number of ensembled models.
Model Stacking - Gives poor performance
Stacking can give poor performance relative to the base models if a lot of overlap exists in the correct predictions of the ensembled models. Also, stacking tends to do better with a larger number of
Model Stacking - Gives poor performance Stacking can give poor performance relative to the base models if a lot of overlap exists in the correct predictions of the ensembled models. Also, stacking tends to do better with a larger number of input models than with a smaller number of ensembled models.
Model Stacking - Gives poor performance Stacking can give poor performance relative to the base models if a lot of overlap exists in the correct predictions of the ensembled models. Also, stacking tends to do better with a larger number of
47,163
Model Stacking - Gives poor performance
It is quite easy to mess up the first stage model or to fail to see the leakage of informations when working with large blends of models. As stated by @Erin LeDell you should make sure that the second stage is learned from cross validated predictions of the first stage. I wrote the following tutorials regarding blending if you are interested: Introduction to blending in Python (method and implementation oriented) Why does blending works ? (theoretical arguments about the success of this method)
Model Stacking - Gives poor performance
It is quite easy to mess up the first stage model or to fail to see the leakage of informations when working with large blends of models. As stated by @Erin LeDell you should make sure that the second
Model Stacking - Gives poor performance It is quite easy to mess up the first stage model or to fail to see the leakage of informations when working with large blends of models. As stated by @Erin LeDell you should make sure that the second stage is learned from cross validated predictions of the first stage. I wrote the following tutorials regarding blending if you are interested: Introduction to blending in Python (method and implementation oriented) Why does blending works ? (theoretical arguments about the success of this method)
Model Stacking - Gives poor performance It is quite easy to mess up the first stage model or to fail to see the leakage of informations when working with large blends of models. As stated by @Erin LeDell you should make sure that the second
47,164
What is information-theoric about the Kullback-Leibler divergence?
This question attempts to explain (1) the information-theoretic interpretation of KL divergence, (2) how such an application lends itself to Bayesian analysis. What follows is directly quoted from pp. 148-150, Section 6.6. of Stone's Information Theory, a very good book which I recommend. Kullback-Leibler divergence (KL-divergence) is a general measure of the difference between two distributions, and is also known as the relative entropy. Given two distributions $p(X)$ and $q(X)$ of the same variable $X$, the KL-divergence between these distributions is $$ D_{KL}(p(X)||q(X))=\int_x p(x) \log\frac{p(x)}{q(x)}dx \,.$$ KL-divergence is not a true measure of distance because, usually $$D_{KL}(p(X)||q(X)) \not= D_{KL}(q(X)||p(X)) \,.$$ Note that $D_{KL}(p(X)||q(X))>0$, unless $p=q$, in which case it is equal to zero. The KL-divergence between the joint distribution $p(X,Y)$ and the joint distribution $[p(X)p(Y)]$ obtained from the outer product of the marginal distributions $p(X)$ and $p(Y)$ is $$D_{KL}(p(X,Y)||[p(X)p(Y)])=\int_x \int_y p(x,y) \log\frac{p(x,y)}{p(x)p(y)} dy dx $$ which we can recognize from Equation 6.25 $$I(X,Y) = \int_y\int_x p(x,y)\log\frac{p(x,y)}{p(x)p(y)}dx dy $$ as the mutual information between $X$ and $Y$. Thus the mutual information between $X$ and $Y$ is the KL-divergence between the joint distribution $p(X,Y)$ and the joint distribution $[p(X)p(Y)]$ obtained by evaluating the outer product of the marginal distributions of $p(X)$ and $p(Y)$. Bayes' Rule We can express the KL-divergence between two variables in terms of Bayes' rule (see Stone (2013)$^{52}$ and Appendix F). Given that $p(x,y)=p(x|y)p(y)$, mutual information can be expressed as $$I(X,Y) = \int_y p(y) \int_x p(x|y)\log\frac{p(x|y)}{p(x)}dx dy \,, $$ where the inner integral can be recognized as the KL-divergence between the distributions $p(X|y)$ and $p(X)$, $$D_{KL}(p(X|y)||p(X))=\int_x p(x|y)\log\frac{p(x|y)}{p(x)}dx \,, $$ where $p(X|y)$ is the posterior distribution and $p(X)$ is the prior distribution. Thus, the mutual information between $X$ and $Y$ is $$I(X,Y) = \int_y p(y) D_{KL}(p(X|y)||p(X))dy \,, $$ which is the expected KL-divergence between the posterior and the prior, $$I(X,Y) = \mathbb{E}_y [D_{KL}(p(X|y)||p(X))]\,, $$ where the expectation is taken over values of $Y$. The application to Bayesian analysis can be found in Appendix H, pp. 157-158 of Stone's also very good book Bayes' Rule. Reference Priors The question of what constitutes an un-biased or fair prior has several answers. Here, we provide a brief account of the answer given by Bernardo(1979)$^3$, who called them reference priors. Reference priors rely on the idea of mutual information. In essence, the mutual information between two variables is a measure of how tightly coupled they are, and can be considered to be a general measure of the correlation between variables. More formally, it is the average amount of Shannon information conveyed about one variable by the other variable. For our purposes, we note that the mutual information $I(x,\theta)$ between $x$ and $\theta$ is also the average difference between the posterior $p(\theta|x)$ and the prior $p(\theta)$, where this difference is measured as the Kullback-Leibler divergence. A reference prior is defined as that particular prior which makes the mutual information between $x$ and $\theta$ as large as possible, and (equivalently) maximizes the average Kullback-Leibler divergence between the posterior and the prior. What has this to do with fair priors? A defining, and useful, feature of mutual information is that it is immune or invariant to the effects of transformations of variables. For example, if a measurement device adds a constant amount $k$ to each reading, so that we measure $x$ as $y=x+k$, then the mean $\theta$ becomes $\phi=\theta+k$, where $\theta$ and $\phi$ are location parameters. Despite the addition of $k$ to measured values, the mutual information between $\phi$ and $y$ remains the same as the mutual information between $\theta$ and $x$; that is, $I(y,\phi) = I(x,\theta)$. Thus, the fairness of a prior (defined in terms of transformation invariance) is guaranteed if we choose a common prior for $\theta$ and $\phi$ which ensures that $I(y,\phi) = I(x,\theta)$. Indeed, it is possible to harness this equality to derive priors which have precisely the desired invariance. It can be shown that the only prior that satisfies this equality for a location parameter (such as the mean) is the uniform prior...
What is information-theoric about the Kullback-Leibler divergence?
This question attempts to explain (1) the information-theoretic interpretation of KL divergence, (2) how such an application lends itself to Bayesian analysis. What follows is directly quoted from pp.
What is information-theoric about the Kullback-Leibler divergence? This question attempts to explain (1) the information-theoretic interpretation of KL divergence, (2) how such an application lends itself to Bayesian analysis. What follows is directly quoted from pp. 148-150, Section 6.6. of Stone's Information Theory, a very good book which I recommend. Kullback-Leibler divergence (KL-divergence) is a general measure of the difference between two distributions, and is also known as the relative entropy. Given two distributions $p(X)$ and $q(X)$ of the same variable $X$, the KL-divergence between these distributions is $$ D_{KL}(p(X)||q(X))=\int_x p(x) \log\frac{p(x)}{q(x)}dx \,.$$ KL-divergence is not a true measure of distance because, usually $$D_{KL}(p(X)||q(X)) \not= D_{KL}(q(X)||p(X)) \,.$$ Note that $D_{KL}(p(X)||q(X))>0$, unless $p=q$, in which case it is equal to zero. The KL-divergence between the joint distribution $p(X,Y)$ and the joint distribution $[p(X)p(Y)]$ obtained from the outer product of the marginal distributions $p(X)$ and $p(Y)$ is $$D_{KL}(p(X,Y)||[p(X)p(Y)])=\int_x \int_y p(x,y) \log\frac{p(x,y)}{p(x)p(y)} dy dx $$ which we can recognize from Equation 6.25 $$I(X,Y) = \int_y\int_x p(x,y)\log\frac{p(x,y)}{p(x)p(y)}dx dy $$ as the mutual information between $X$ and $Y$. Thus the mutual information between $X$ and $Y$ is the KL-divergence between the joint distribution $p(X,Y)$ and the joint distribution $[p(X)p(Y)]$ obtained by evaluating the outer product of the marginal distributions of $p(X)$ and $p(Y)$. Bayes' Rule We can express the KL-divergence between two variables in terms of Bayes' rule (see Stone (2013)$^{52}$ and Appendix F). Given that $p(x,y)=p(x|y)p(y)$, mutual information can be expressed as $$I(X,Y) = \int_y p(y) \int_x p(x|y)\log\frac{p(x|y)}{p(x)}dx dy \,, $$ where the inner integral can be recognized as the KL-divergence between the distributions $p(X|y)$ and $p(X)$, $$D_{KL}(p(X|y)||p(X))=\int_x p(x|y)\log\frac{p(x|y)}{p(x)}dx \,, $$ where $p(X|y)$ is the posterior distribution and $p(X)$ is the prior distribution. Thus, the mutual information between $X$ and $Y$ is $$I(X,Y) = \int_y p(y) D_{KL}(p(X|y)||p(X))dy \,, $$ which is the expected KL-divergence between the posterior and the prior, $$I(X,Y) = \mathbb{E}_y [D_{KL}(p(X|y)||p(X))]\,, $$ where the expectation is taken over values of $Y$. The application to Bayesian analysis can be found in Appendix H, pp. 157-158 of Stone's also very good book Bayes' Rule. Reference Priors The question of what constitutes an un-biased or fair prior has several answers. Here, we provide a brief account of the answer given by Bernardo(1979)$^3$, who called them reference priors. Reference priors rely on the idea of mutual information. In essence, the mutual information between two variables is a measure of how tightly coupled they are, and can be considered to be a general measure of the correlation between variables. More formally, it is the average amount of Shannon information conveyed about one variable by the other variable. For our purposes, we note that the mutual information $I(x,\theta)$ between $x$ and $\theta$ is also the average difference between the posterior $p(\theta|x)$ and the prior $p(\theta)$, where this difference is measured as the Kullback-Leibler divergence. A reference prior is defined as that particular prior which makes the mutual information between $x$ and $\theta$ as large as possible, and (equivalently) maximizes the average Kullback-Leibler divergence between the posterior and the prior. What has this to do with fair priors? A defining, and useful, feature of mutual information is that it is immune or invariant to the effects of transformations of variables. For example, if a measurement device adds a constant amount $k$ to each reading, so that we measure $x$ as $y=x+k$, then the mean $\theta$ becomes $\phi=\theta+k$, where $\theta$ and $\phi$ are location parameters. Despite the addition of $k$ to measured values, the mutual information between $\phi$ and $y$ remains the same as the mutual information between $\theta$ and $x$; that is, $I(y,\phi) = I(x,\theta)$. Thus, the fairness of a prior (defined in terms of transformation invariance) is guaranteed if we choose a common prior for $\theta$ and $\phi$ which ensures that $I(y,\phi) = I(x,\theta)$. Indeed, it is possible to harness this equality to derive priors which have precisely the desired invariance. It can be shown that the only prior that satisfies this equality for a location parameter (such as the mean) is the uniform prior...
What is information-theoric about the Kullback-Leibler divergence? This question attempts to explain (1) the information-theoretic interpretation of KL divergence, (2) how such an application lends itself to Bayesian analysis. What follows is directly quoted from pp.
47,165
What is information-theoric about the Kullback-Leibler divergence?
There is a lot of material I found in Wikipedia, but to sum up, one way to look at the Kullback-Liebler divergence is as following: Let's say you designed a code that is optimal for a source with distribution q. Now you need to use the same code for another source with distribution p. The Kullback-Liebler divergence represents the extra bits needed to code this source. More detail can be found on Wikipedia (sorry my answer is not as rigorous as you asked). In addition you will find there that this divergence is actually $ D_{kl}(P,Q) = H(P,Q) -H(P) $, $H(P,Q)$ is the cross entropy of P,Q.
What is information-theoric about the Kullback-Leibler divergence?
There is a lot of material I found in Wikipedia, but to sum up, one way to look at the Kullback-Liebler divergence is as following: Let's say you designed a code that is optimal for a source with dist
What is information-theoric about the Kullback-Leibler divergence? There is a lot of material I found in Wikipedia, but to sum up, one way to look at the Kullback-Liebler divergence is as following: Let's say you designed a code that is optimal for a source with distribution q. Now you need to use the same code for another source with distribution p. The Kullback-Liebler divergence represents the extra bits needed to code this source. More detail can be found on Wikipedia (sorry my answer is not as rigorous as you asked). In addition you will find there that this divergence is actually $ D_{kl}(P,Q) = H(P,Q) -H(P) $, $H(P,Q)$ is the cross entropy of P,Q.
What is information-theoric about the Kullback-Leibler divergence? There is a lot of material I found in Wikipedia, but to sum up, one way to look at the Kullback-Liebler divergence is as following: Let's say you designed a code that is optimal for a source with dist
47,166
Bayesian MCMC when a likelihood function cannot be written
The situation you describe where $p(x|\theta)$ cannot be computed but simulations from $p(\cdot|\theta)$ can be produced is call a generative model. It leads to likelihood-free resolutions like ABC (Approximate Bayesian computation), which is indeed properly introduced in the Wikipedia page: Approximate Bayesian computation; synthetic likelihood, as in Wood (2010), where the unknown model $p(\cdot|\theta)$ is approximated by a Normal $\text{N}(\mu(\theta),\sigma(\theta)^2)$, where $\mu(\theta),\sigma(\theta)$ are estimated by simulation; Bayesian solutions derived from indirect inference, as in Drovandi et al. (2015)
Bayesian MCMC when a likelihood function cannot be written
The situation you describe where $p(x|\theta)$ cannot be computed but simulations from $p(\cdot|\theta)$ can be produced is call a generative model. It leads to likelihood-free resolutions like ABC (
Bayesian MCMC when a likelihood function cannot be written The situation you describe where $p(x|\theta)$ cannot be computed but simulations from $p(\cdot|\theta)$ can be produced is call a generative model. It leads to likelihood-free resolutions like ABC (Approximate Bayesian computation), which is indeed properly introduced in the Wikipedia page: Approximate Bayesian computation; synthetic likelihood, as in Wood (2010), where the unknown model $p(\cdot|\theta)$ is approximated by a Normal $\text{N}(\mu(\theta),\sigma(\theta)^2)$, where $\mu(\theta),\sigma(\theta)$ are estimated by simulation; Bayesian solutions derived from indirect inference, as in Drovandi et al. (2015)
Bayesian MCMC when a likelihood function cannot be written The situation you describe where $p(x|\theta)$ cannot be computed but simulations from $p(\cdot|\theta)$ can be produced is call a generative model. It leads to likelihood-free resolutions like ABC (
47,167
Why odds ratio in logistic regression
You are right. If the book said that, it is wrong. I do wonder if it is a typo or a poorly phrased passage that lends itself to misunderstanding, though. As you show, $\exp(\beta_0 + \beta_1X)$ is the odds of 'success' predicted by the model. The odds ratio associated with a $1$-unit change in $X$ is $\exp(\beta)$. You can also think of is as the factor by which you would multiply the odds of 'success' associated with $x_i$ to get the odds associated with $(x_i + 1)$ (these are the same, phrased differently). Since $p$ is the probability of success, $p/(1-p)$ is the odds of success by definition. Imagine $X=0$, then the right hand side simplifies to $\exp(\beta_0)$, but the left hand side is unchanged. Thus we can see that $\exp(\beta_0)$ is the odds of success when $X=0$. Now imagine we move to where $X=1$, then we can rewrite the RHS as $\exp(\beta_0)\times\exp(\beta_1)$ using the rules for exponentiation. Thus we can see that $\exp(\beta_1)$ is the factor by which you would multiply the odds of success to determine the odds of success associated with a $1$-unit increase in $X$. I think the pdf you link to is sloppily written. At one point it says, "Odds Ratio. The odds ratio is equal to exp(B)", but there are no subscripts, whereas above that the intercept and the coefficient on X are differentiated by subscripts. That sets up the reader for a misunderstanding here.
Why odds ratio in logistic regression
You are right. If the book said that, it is wrong. I do wonder if it is a typo or a poorly phrased passage that lends itself to misunderstanding, though. As you show, $\exp(\beta_0 + \beta_1X)$ is
Why odds ratio in logistic regression You are right. If the book said that, it is wrong. I do wonder if it is a typo or a poorly phrased passage that lends itself to misunderstanding, though. As you show, $\exp(\beta_0 + \beta_1X)$ is the odds of 'success' predicted by the model. The odds ratio associated with a $1$-unit change in $X$ is $\exp(\beta)$. You can also think of is as the factor by which you would multiply the odds of 'success' associated with $x_i$ to get the odds associated with $(x_i + 1)$ (these are the same, phrased differently). Since $p$ is the probability of success, $p/(1-p)$ is the odds of success by definition. Imagine $X=0$, then the right hand side simplifies to $\exp(\beta_0)$, but the left hand side is unchanged. Thus we can see that $\exp(\beta_0)$ is the odds of success when $X=0$. Now imagine we move to where $X=1$, then we can rewrite the RHS as $\exp(\beta_0)\times\exp(\beta_1)$ using the rules for exponentiation. Thus we can see that $\exp(\beta_1)$ is the factor by which you would multiply the odds of success to determine the odds of success associated with a $1$-unit increase in $X$. I think the pdf you link to is sloppily written. At one point it says, "Odds Ratio. The odds ratio is equal to exp(B)", but there are no subscripts, whereas above that the intercept and the coefficient on X are differentiated by subscripts. That sets up the reader for a misunderstanding here.
Why odds ratio in logistic regression You are right. If the book said that, it is wrong. I do wonder if it is a typo or a poorly phrased passage that lends itself to misunderstanding, though. As you show, $\exp(\beta_0 + \beta_1X)$ is
47,168
visualizing snow depth
The snow-depth maps presented by the US National Weather Service seem to work well, with a color scale starting with a silver-gray (not pure white) running into blues, purples and browns. This overlays nicely onto their mapping of elevation. Here's an example: I don't think that this corresponds to any of the standard Color Brewer palettes, but I suspect that the Weather Service did a good deal of study before coming up with this scheme. The site linked above shows additional color schemes for snow water equivalent, melt, sublimation, and so on. I'm not a professional hydrologist, but as someone somewhat obsessed with both snow and maps I've found the Weather Service schemes to be worthy of being a standard.
visualizing snow depth
The snow-depth maps presented by the US National Weather Service seem to work well, with a color scale starting with a silver-gray (not pure white) running into blues, purples and browns. This overlay
visualizing snow depth The snow-depth maps presented by the US National Weather Service seem to work well, with a color scale starting with a silver-gray (not pure white) running into blues, purples and browns. This overlays nicely onto their mapping of elevation. Here's an example: I don't think that this corresponds to any of the standard Color Brewer palettes, but I suspect that the Weather Service did a good deal of study before coming up with this scheme. The site linked above shows additional color schemes for snow water equivalent, melt, sublimation, and so on. I'm not a professional hydrologist, but as someone somewhat obsessed with both snow and maps I've found the Weather Service schemes to be worthy of being a standard.
visualizing snow depth The snow-depth maps presented by the US National Weather Service seem to work well, with a color scale starting with a silver-gray (not pure white) running into blues, purples and browns. This overlay
47,169
Data Distribution and Feature Scaling Techniques
I cannot speak in terms of machine learning, but I can speak in terms of scaling. From our tag wiki: tl;dr version first: normalization refers to scaling all numeric variables in the range [0,1], such as using the formula: $$x_{new}=\frac{x-x_{min}}{x_{max}-x_{min}}$$ standardization refers to a transform to the data set to have zero mean and unit variance, for example using the equation: $$x_{new}=\frac{x-\overline{x}}{s}$$ That is, normalization does not rely on the underlying distribution; standardization transforms the data based upon the parameters of a Gaussian distribution. Fuller explanations: "Normalization" refers to several related processes: ("Feature scaling") A set of numbers whose maximum is $M$ and minimum is $m$ can be converted to the range from $0$ to $1$ by means of an affine transformation (which amounts to changing their units of measurement) $x \to (x-m)/(M-m)$. A set of positive numbers $\{p_i\}$ representing probabilities or weights can be uniformly rescaled to sum to unity: divide each $p_i$ by the sum of all the $p_i$. Analogously, a distribution (or indeed any non-negative function with a finite nonzero integral) can be normalized to have a unit integral by dividing its values by the integral. A vector in a normed linear space is normalized (to unit length) by dividing it by its norm. This is a general procedure encompassing the two preceding operations as special examples. The range from $0$ to $1$ can be made from $0$ to any desired limit $\alpha$ by multiplying a previously unit-normalized value by $\alpha$. Other kinds of operations exist having a similar intent of re-expressing values in a predetermined range. Many of these are nonlinear and tend to be used in specialized settings. Standardization: Shifting and rescaling data to assure zero mean and unit variance. Specifically, when $(x_i), i=1, \ldots, n$ is a batch of data, its mean is $m=(\sum_i x_i)/n$ and its variance is $s^2 = > v=(\sum_i(x_i-m)^2)/\nu$ where $\nu$ is either $n$ or $n-1$ (choices vary with application). Standardization replaces each $x_i$ with $z_i > = (x_i-m)/s$.
Data Distribution and Feature Scaling Techniques
I cannot speak in terms of machine learning, but I can speak in terms of scaling. From our tag wiki: tl;dr version first: normalization refers to scaling all numeric variables in the range [0,1], s
Data Distribution and Feature Scaling Techniques I cannot speak in terms of machine learning, but I can speak in terms of scaling. From our tag wiki: tl;dr version first: normalization refers to scaling all numeric variables in the range [0,1], such as using the formula: $$x_{new}=\frac{x-x_{min}}{x_{max}-x_{min}}$$ standardization refers to a transform to the data set to have zero mean and unit variance, for example using the equation: $$x_{new}=\frac{x-\overline{x}}{s}$$ That is, normalization does not rely on the underlying distribution; standardization transforms the data based upon the parameters of a Gaussian distribution. Fuller explanations: "Normalization" refers to several related processes: ("Feature scaling") A set of numbers whose maximum is $M$ and minimum is $m$ can be converted to the range from $0$ to $1$ by means of an affine transformation (which amounts to changing their units of measurement) $x \to (x-m)/(M-m)$. A set of positive numbers $\{p_i\}$ representing probabilities or weights can be uniformly rescaled to sum to unity: divide each $p_i$ by the sum of all the $p_i$. Analogously, a distribution (or indeed any non-negative function with a finite nonzero integral) can be normalized to have a unit integral by dividing its values by the integral. A vector in a normed linear space is normalized (to unit length) by dividing it by its norm. This is a general procedure encompassing the two preceding operations as special examples. The range from $0$ to $1$ can be made from $0$ to any desired limit $\alpha$ by multiplying a previously unit-normalized value by $\alpha$. Other kinds of operations exist having a similar intent of re-expressing values in a predetermined range. Many of these are nonlinear and tend to be used in specialized settings. Standardization: Shifting and rescaling data to assure zero mean and unit variance. Specifically, when $(x_i), i=1, \ldots, n$ is a batch of data, its mean is $m=(\sum_i x_i)/n$ and its variance is $s^2 = > v=(\sum_i(x_i-m)^2)/\nu$ where $\nu$ is either $n$ or $n-1$ (choices vary with application). Standardization replaces each $x_i$ with $z_i > = (x_i-m)/s$.
Data Distribution and Feature Scaling Techniques I cannot speak in terms of machine learning, but I can speak in terms of scaling. From our tag wiki: tl;dr version first: normalization refers to scaling all numeric variables in the range [0,1], s
47,170
Data Distribution and Feature Scaling Techniques
It's not depend on Gaussian distribution,its depend on the MODEL that used this features. The result of standardization (or Z-score normalization) is that the features will be rescaled so that they’ll have the properties of a standard normal distribution with μ=0 and σ=1 that help in different cases such as when you want to compute measure the distance between to variable with different units,or more important one,when your algorithm use need this,for example when it use gradient descent,if the features not on same scale,some of features may update faster then the others. these algorithms like: k-nearest neighbors with an Euclidean distance measure k-means (see k-nearest neighbors) logistic regression, SVMs, perceptrons, neural networks etc in the other hand we have Z-score normalization (or standardization) is the so-called Min-Max scaling.in this approach, the data is scaled to a fixed range - usually 0 to 1(not always). now the question : Z-score standardization or Min-Max scaling? There is no obvious answer to this question: it really depends on the application. i have some example for you : in clustering analyses, standardization may be especially crucial in order to compare similarities between features based on certain distance measures. Another prominent example is the Principal Component Analysis, where we usually prefer standardization over Min-Max scaling, since we are interested in the components that maximize the variance. However, this doesn’t mean that Min-Max scaling is not useful at all! A popular application is image processing, where pixel intensities have to be normalized to fit within a certain range (i.e., 0 to 255 for the RGB color range). Also, typical neural network algorithm require data that on a 0-1 scale.
Data Distribution and Feature Scaling Techniques
It's not depend on Gaussian distribution,its depend on the MODEL that used this features. The result of standardization (or Z-score normalization) is that the features will be rescaled so that they’ll
Data Distribution and Feature Scaling Techniques It's not depend on Gaussian distribution,its depend on the MODEL that used this features. The result of standardization (or Z-score normalization) is that the features will be rescaled so that they’ll have the properties of a standard normal distribution with μ=0 and σ=1 that help in different cases such as when you want to compute measure the distance between to variable with different units,or more important one,when your algorithm use need this,for example when it use gradient descent,if the features not on same scale,some of features may update faster then the others. these algorithms like: k-nearest neighbors with an Euclidean distance measure k-means (see k-nearest neighbors) logistic regression, SVMs, perceptrons, neural networks etc in the other hand we have Z-score normalization (or standardization) is the so-called Min-Max scaling.in this approach, the data is scaled to a fixed range - usually 0 to 1(not always). now the question : Z-score standardization or Min-Max scaling? There is no obvious answer to this question: it really depends on the application. i have some example for you : in clustering analyses, standardization may be especially crucial in order to compare similarities between features based on certain distance measures. Another prominent example is the Principal Component Analysis, where we usually prefer standardization over Min-Max scaling, since we are interested in the components that maximize the variance. However, this doesn’t mean that Min-Max scaling is not useful at all! A popular application is image processing, where pixel intensities have to be normalized to fit within a certain range (i.e., 0 to 255 for the RGB color range). Also, typical neural network algorithm require data that on a 0-1 scale.
Data Distribution and Feature Scaling Techniques It's not depend on Gaussian distribution,its depend on the MODEL that used this features. The result of standardization (or Z-score normalization) is that the features will be rescaled so that they’ll
47,171
Statistical language in "The Avengers"
To "recognise" something it must first exist, so you will be using a supervised algorithm while clustering is an unsupervised class of machine learning methods. Clustering algorithms group in terms of similarity, rather then recognize known patterns. So I'd say it sounds like another example where there is less science and more fiction in the movies and where unrelated geeky terms are used in random combination to sound scientific...
Statistical language in "The Avengers"
To "recognise" something it must first exist, so you will be using a supervised algorithm while clustering is an unsupervised class of machine learning methods. Clustering algorithms group in terms of
Statistical language in "The Avengers" To "recognise" something it must first exist, so you will be using a supervised algorithm while clustering is an unsupervised class of machine learning methods. Clustering algorithms group in terms of similarity, rather then recognize known patterns. So I'd say it sounds like another example where there is less science and more fiction in the movies and where unrelated geeky terms are used in random combination to sound scientific...
Statistical language in "The Avengers" To "recognise" something it must first exist, so you will be using a supervised algorithm while clustering is an unsupervised class of machine learning methods. Clustering algorithms group in terms of
47,172
Statistical language in "The Avengers"
Clusters of detected gamma photons are being studied in order to find potential sources of gamma rays The cube or tesseract is emitting gamma radiation. In order to find sources of gamma radiation (and thus a potential location of the tesseract) one can use algorithms to detect clusters in the detected locations of gamma radiation. Note that the estimated locations/directions of the observed photons are not so accurate, with error, so statistics comes into play. Whenever the detected photons are a lot near each other then this may indicate that they are related to a source radiating gamma photons. Finding clusters of gamma rays is a way to find out whether a detected gamma ray is background or belongs, along with other detected gamma rays, to some potential common source. Astronomers have been using the minimal spanning tree algorithm to find clusters of (ptentially) associated detected gamma rays( see for instance: Campana 2008 ). An example image of how this works An example image of how this works can be generated with the R statistical software (see below): It is a similar image as those found in the works (but I can not find an image with clear free license): Campana, R., et al. "Minimal spanning tree algorithm for γ-ray source detection in sparse photon images: cluster parameters and selection strategies." Astrophysics and Space Science 347.1 (2013): 169-182. link to axiv paper https://arxiv.org/abs/1305.2025 Campana, Riccardo, et al. "A Minimal Spanning Tree algorithm for source detection in γ-ray images." Monthly Notices of the Royal Astronomical Society 383.3 (2008): 1166-1174. link to journal library(emstreeR) ## 2D artifical data set.seed(1) n <- 20 n2 <- 400-n*3 ## c1 to c3 are artificial clusters ## c4 is background noise c1 <- data.frame(y = rnorm(n, 45, sd = 1), x = rnorm(n, 130, sd = 1)) c2 <- data.frame(y = rnorm(n, 50, sd = 1), x = rnorm(n, 125, sd = 1)) c3 <- data.frame(y = rnorm(n, 55, sd = 1), x = rnorm(n, 135, sd = 1)) c4 <- data.frame(y = runif(n2, 40,60), x = runif(n2, 120,150)) d <- rbind(c1, c2, c3, c4) ## MST: out <- ComputeMST(d) ## 2D plot of points: plot(-100,-100,xlim = c(120,150), ylim = c(40,60), xlab="latitude", ylab="longitude") points(out$x,out$y, pch = 21, col = 1, bg = 1, cex=0.4) title("approximate spatial distribution \n of detected signals", cex.main=1) plot(-100,-100,xlim = c(120,150), ylim = c(40,60), xlab="latitude", ylab="longitude") points(out$x,out$y, pch = 21, col = 1, bg = 1, cex=0.4) title("red lines: small edges \n green dots: connected with n >= 10", cex.main = 1) # draw clusters seperately with large size library(igraph) edgevector <- as.numeric(matrix(cbind(out$from[edgeselect],out$to[edgeselect]),2,byrow=TRUE)) graph <- make_graph(edgevector, directed = FALSE) groepen <- groups(components(graph)) sizes <- which(components(graph)$csize>=10) for (s in sizes) { coordinates <- unlist(groepen[s]) points(out$x[coordinates], out$y[coordinates],col=3) } # draw the tree and use mean distance as boundaries between clusters boundary = mean(out$distance) edgeselect = out$distance<boundary colors = rgb(0.75+edgeselect*0.25, 0.75-edgeselect*0.75, 0.75-edgeselect*0.75) for (i in 1:400) { lines(c(out$x[out$from[i]],out$x[out$to[i]]), c(out$y[out$from[i]],out$y[out$to[i]]), col = colors[i]) }
Statistical language in "The Avengers"
Clusters of detected gamma photons are being studied in order to find potential sources of gamma rays The cube or tesseract is emitting gamma radiation. In order to find sources of gamma radiation (an
Statistical language in "The Avengers" Clusters of detected gamma photons are being studied in order to find potential sources of gamma rays The cube or tesseract is emitting gamma radiation. In order to find sources of gamma radiation (and thus a potential location of the tesseract) one can use algorithms to detect clusters in the detected locations of gamma radiation. Note that the estimated locations/directions of the observed photons are not so accurate, with error, so statistics comes into play. Whenever the detected photons are a lot near each other then this may indicate that they are related to a source radiating gamma photons. Finding clusters of gamma rays is a way to find out whether a detected gamma ray is background or belongs, along with other detected gamma rays, to some potential common source. Astronomers have been using the minimal spanning tree algorithm to find clusters of (ptentially) associated detected gamma rays( see for instance: Campana 2008 ). An example image of how this works An example image of how this works can be generated with the R statistical software (see below): It is a similar image as those found in the works (but I can not find an image with clear free license): Campana, R., et al. "Minimal spanning tree algorithm for γ-ray source detection in sparse photon images: cluster parameters and selection strategies." Astrophysics and Space Science 347.1 (2013): 169-182. link to axiv paper https://arxiv.org/abs/1305.2025 Campana, Riccardo, et al. "A Minimal Spanning Tree algorithm for source detection in γ-ray images." Monthly Notices of the Royal Astronomical Society 383.3 (2008): 1166-1174. link to journal library(emstreeR) ## 2D artifical data set.seed(1) n <- 20 n2 <- 400-n*3 ## c1 to c3 are artificial clusters ## c4 is background noise c1 <- data.frame(y = rnorm(n, 45, sd = 1), x = rnorm(n, 130, sd = 1)) c2 <- data.frame(y = rnorm(n, 50, sd = 1), x = rnorm(n, 125, sd = 1)) c3 <- data.frame(y = rnorm(n, 55, sd = 1), x = rnorm(n, 135, sd = 1)) c4 <- data.frame(y = runif(n2, 40,60), x = runif(n2, 120,150)) d <- rbind(c1, c2, c3, c4) ## MST: out <- ComputeMST(d) ## 2D plot of points: plot(-100,-100,xlim = c(120,150), ylim = c(40,60), xlab="latitude", ylab="longitude") points(out$x,out$y, pch = 21, col = 1, bg = 1, cex=0.4) title("approximate spatial distribution \n of detected signals", cex.main=1) plot(-100,-100,xlim = c(120,150), ylim = c(40,60), xlab="latitude", ylab="longitude") points(out$x,out$y, pch = 21, col = 1, bg = 1, cex=0.4) title("red lines: small edges \n green dots: connected with n >= 10", cex.main = 1) # draw clusters seperately with large size library(igraph) edgevector <- as.numeric(matrix(cbind(out$from[edgeselect],out$to[edgeselect]),2,byrow=TRUE)) graph <- make_graph(edgevector, directed = FALSE) groepen <- groups(components(graph)) sizes <- which(components(graph)$csize>=10) for (s in sizes) { coordinates <- unlist(groepen[s]) points(out$x[coordinates], out$y[coordinates],col=3) } # draw the tree and use mean distance as boundaries between clusters boundary = mean(out$distance) edgeselect = out$distance<boundary colors = rgb(0.75+edgeselect*0.25, 0.75-edgeselect*0.75, 0.75-edgeselect*0.75) for (i in 1:400) { lines(c(out$x[out$from[i]],out$x[out$to[i]]), c(out$y[out$from[i]],out$y[out$to[i]]), col = colors[i]) }
Statistical language in "The Avengers" Clusters of detected gamma photons are being studied in order to find potential sources of gamma rays The cube or tesseract is emitting gamma radiation. In order to find sources of gamma radiation (an
47,173
Statistical language in "The Avengers"
this is so funny. I was re-watching the Avengers and heard Banner say that. I have been learning ML for the past year, so I was wondering if anyone else caught that. Clustering analysis is the process of minimizing distance between data points and maximizing centroids (clusters). As Tim suggested, this is unsupervised learning so there is no 'target/known variable'. To answer your question, I think it is indeed a coherent thing to say. I'm assuming a clustering algo can be created to analyze certain variable including the gamma radiation these labs pick up over time. I'm also assuming that the readings may fluctuate, even if the cube is not near it. With readings of multiple labs, the cluster algorithm can cluster labs together that had elevated readings at certain times. To track and perhaps look at movement of the tessaract. To ,at least, narrow down the search of where it has been or where it is. This I'm assuming would be part of the algorithm. Afterward may be a search of the cellphones/laptops etc. that Fury had mentioned in that area, or other anomalies in the area (crazy deaths due to loki, missing/stolen item/reports of the materials loki was after, location of reactors etc.).
Statistical language in "The Avengers"
this is so funny. I was re-watching the Avengers and heard Banner say that. I have been learning ML for the past year, so I was wondering if anyone else caught that. Clustering analysis is the process
Statistical language in "The Avengers" this is so funny. I was re-watching the Avengers and heard Banner say that. I have been learning ML for the past year, so I was wondering if anyone else caught that. Clustering analysis is the process of minimizing distance between data points and maximizing centroids (clusters). As Tim suggested, this is unsupervised learning so there is no 'target/known variable'. To answer your question, I think it is indeed a coherent thing to say. I'm assuming a clustering algo can be created to analyze certain variable including the gamma radiation these labs pick up over time. I'm also assuming that the readings may fluctuate, even if the cube is not near it. With readings of multiple labs, the cluster algorithm can cluster labs together that had elevated readings at certain times. To track and perhaps look at movement of the tessaract. To ,at least, narrow down the search of where it has been or where it is. This I'm assuming would be part of the algorithm. Afterward may be a search of the cellphones/laptops etc. that Fury had mentioned in that area, or other anomalies in the area (crazy deaths due to loki, missing/stolen item/reports of the materials loki was after, location of reactors etc.).
Statistical language in "The Avengers" this is so funny. I was re-watching the Avengers and heard Banner say that. I have been learning ML for the past year, so I was wondering if anyone else caught that. Clustering analysis is the process
47,174
Whats the difference between applying Correlation and DTW in a Time Series
Dynamic Time Warping (DTW) and correlation capture very different aspects of similarity between two time-series. Which one to choose depends on what you are interested in - an information that you did not provide in your question. Yet I will give an example which might help to clarify the difference for you. Assume you consider the following two time-series as equal: a = [1,1,2,3,4,3,2,1,1,1,1,1,1,1,1,1,1] b = [1,1,1,1,1,1,1,1,1,1,1,2,3,4,3,2,1] For this example, the DTW Distance - computed as in here - returns: DTWDistance(a,b) = 0, since DTW Distance allows shift in time and effectively compares the shape of the time-series giving little importance to stretching. Whereas the correlation here returns such as np.corrcoeff(a,b) = -0.33471074 We want to cluster objects together that are similar. Therefore we use a dissimilarity measure, which yields 0, if two objects are equal, a higher value, the more different they are. Most relevant attributes of such a dissimilarity measure would be the metric requirements such as in Wikipedia. For correlation - assuming you mean pearsons correlation coefficient - these requirements are not met. Therefore I would suggest to use DTW. Yet there might be some applications in which clustering based on correlation could yield great result. Best way to go: Try both and compare the results. Then choose the one which fits your expectation.
Whats the difference between applying Correlation and DTW in a Time Series
Dynamic Time Warping (DTW) and correlation capture very different aspects of similarity between two time-series. Which one to choose depends on what you are interested in - an information that you did
Whats the difference between applying Correlation and DTW in a Time Series Dynamic Time Warping (DTW) and correlation capture very different aspects of similarity between two time-series. Which one to choose depends on what you are interested in - an information that you did not provide in your question. Yet I will give an example which might help to clarify the difference for you. Assume you consider the following two time-series as equal: a = [1,1,2,3,4,3,2,1,1,1,1,1,1,1,1,1,1] b = [1,1,1,1,1,1,1,1,1,1,1,2,3,4,3,2,1] For this example, the DTW Distance - computed as in here - returns: DTWDistance(a,b) = 0, since DTW Distance allows shift in time and effectively compares the shape of the time-series giving little importance to stretching. Whereas the correlation here returns such as np.corrcoeff(a,b) = -0.33471074 We want to cluster objects together that are similar. Therefore we use a dissimilarity measure, which yields 0, if two objects are equal, a higher value, the more different they are. Most relevant attributes of such a dissimilarity measure would be the metric requirements such as in Wikipedia. For correlation - assuming you mean pearsons correlation coefficient - these requirements are not met. Therefore I would suggest to use DTW. Yet there might be some applications in which clustering based on correlation could yield great result. Best way to go: Try both and compare the results. Then choose the one which fits your expectation.
Whats the difference between applying Correlation and DTW in a Time Series Dynamic Time Warping (DTW) and correlation capture very different aspects of similarity between two time-series. Which one to choose depends on what you are interested in - an information that you did
47,175
What distribution to fit if the log of log is still convex?
It is plausible these data follow a Zipf distribution. Here, for comparison, are random data generated according to a Zipf (power-law) distribution with power near $-1.4$ and plotted as in the question and the linked discussion. I have tuned the power and the total frequencies to match the figures in the question--the match looks pretty good in the raw plot of ordered frequencies (at left) and the (untitled) log-log-log plot (second from left). A good way to analyze data that look like this is to display frequency against rank on log-log axes, as shown in the "Zipf Plot" above. Even if it turns out these data are not Zipf distributed, a comparison to a Zipf distribution (as exhibited in the "Observed vs. Fit" plot at the right) is likely to be informative. More information about these figures can be gleaned from the R code used to generate them. x <- 1:100 Y <- exp(19.5 - 1.392 * log(x)) Y <- round(Y + rnorm(length(Y), sqrt(Y))) par(mfrow=c(1,4)) plot(x,Y,pch=19, main="Ordered Frequencies") abline(h=seq(5e7, 3e8, by=5e7), col="Gray") abline(v=seq(0, 100, by=25), col="Gray") plot(x, log(log(log(Y))), pch=19) abline(h=seq(0.925, 1.10, by=0.025), col="Gray") abline(v=seq(0, 100, by=25), col="Gray") plot(x, Y, log="xy", main="Zipf Plot") beta.hat <- coef(lm(log(Y) ~ I(log(x)))) curve(exp(beta.hat[1]+beta.hat[2]*log(x)), add=TRUE, col="Red") H <- sum(Y)/sum(x^(beta.hat[2])) plot(H*x^(beta.hat[2]), Y, log="xy", ylab="Observed Frequency", xlab="Fitted Frequency", main="Observed vs. Fit") abline(c(0,1), col="Red")
What distribution to fit if the log of log is still convex?
It is plausible these data follow a Zipf distribution. Here, for comparison, are random data generated according to a Zipf (power-law) distribution with power near $-1.4$ and plotted as in the questio
What distribution to fit if the log of log is still convex? It is plausible these data follow a Zipf distribution. Here, for comparison, are random data generated according to a Zipf (power-law) distribution with power near $-1.4$ and plotted as in the question and the linked discussion. I have tuned the power and the total frequencies to match the figures in the question--the match looks pretty good in the raw plot of ordered frequencies (at left) and the (untitled) log-log-log plot (second from left). A good way to analyze data that look like this is to display frequency against rank on log-log axes, as shown in the "Zipf Plot" above. Even if it turns out these data are not Zipf distributed, a comparison to a Zipf distribution (as exhibited in the "Observed vs. Fit" plot at the right) is likely to be informative. More information about these figures can be gleaned from the R code used to generate them. x <- 1:100 Y <- exp(19.5 - 1.392 * log(x)) Y <- round(Y + rnorm(length(Y), sqrt(Y))) par(mfrow=c(1,4)) plot(x,Y,pch=19, main="Ordered Frequencies") abline(h=seq(5e7, 3e8, by=5e7), col="Gray") abline(v=seq(0, 100, by=25), col="Gray") plot(x, log(log(log(Y))), pch=19) abline(h=seq(0.925, 1.10, by=0.025), col="Gray") abline(v=seq(0, 100, by=25), col="Gray") plot(x, Y, log="xy", main="Zipf Plot") beta.hat <- coef(lm(log(Y) ~ I(log(x)))) curve(exp(beta.hat[1]+beta.hat[2]*log(x)), add=TRUE, col="Red") H <- sum(Y)/sum(x^(beta.hat[2])) plot(H*x^(beta.hat[2]), Y, log="xy", ylab="Observed Frequency", xlab="Fitted Frequency", main="Observed vs. Fit") abline(c(0,1), col="Red")
What distribution to fit if the log of log is still convex? It is plausible these data follow a Zipf distribution. Here, for comparison, are random data generated according to a Zipf (power-law) distribution with power near $-1.4$ and plotted as in the questio
47,176
Metric as straightforward as R^2 for Bayesian models
See also Andrew Gelman's paper literally titled "R-squared for Bayesian regression models": http://www.stat.columbia.edu/~gelman/research/unpublished/bayes_R2.pdf In that paper, he proposes $R^2 = Var(\hat{y}) / (Var(\hat{y}) + Var(e)) $ which has a similar interpretation to traditional $R^2$. However, since this is bayesian, that value is now a r.v. and needs to be summarised, eg by posterior median. He also provides a small R function for calculating it.
Metric as straightforward as R^2 for Bayesian models
See also Andrew Gelman's paper literally titled "R-squared for Bayesian regression models": http://www.stat.columbia.edu/~gelman/research/unpublished/bayes_R2.pdf In that paper, he proposes $R^2 = Var
Metric as straightforward as R^2 for Bayesian models See also Andrew Gelman's paper literally titled "R-squared for Bayesian regression models": http://www.stat.columbia.edu/~gelman/research/unpublished/bayes_R2.pdf In that paper, he proposes $R^2 = Var(\hat{y}) / (Var(\hat{y}) + Var(e)) $ which has a similar interpretation to traditional $R^2$. However, since this is bayesian, that value is now a r.v. and needs to be summarised, eg by posterior median. He also provides a small R function for calculating it.
Metric as straightforward as R^2 for Bayesian models See also Andrew Gelman's paper literally titled "R-squared for Bayesian regression models": http://www.stat.columbia.edu/~gelman/research/unpublished/bayes_R2.pdf In that paper, he proposes $R^2 = Var
47,177
Metric as straightforward as R^2 for Bayesian models
To check model adequacy, hierarchical Bayesian models are usually evaluated exactly like in DHARMa - you simulated from the fitted model and calculate the quantile residuals. The only difference to DHARMa is that you vary parameters as well while doing the simulations. The approach is explained in many textbooks. Keywords are "posterior predictive simulations", "posterior model checks", or "Bayesian p-values". A few notes As for mixed models, the question arises how many levels of the hierarchy your re-simulate. Especially state-space population models look great when re-simulating only the final observation model, but if you re-simulate the process model as well, it often looks very very different -> good reason to be skeptical when people only show the final fit of the SSMs, this can look great even if the model is horribly wrong. The distributional theory for these residuals is not quite clear for complex models - for GLMMs, all simulations I did so far showed that simulated quantile residuals are with good approximation flat, but this may not be so for any complex model structure. In doubt, run a test on a properly specified model. DHARMa has a function to input posterior predictive simulations (createDHARMa), so that you can use all tools of DHARMa together with hierarchical Bayesian models as well However, all this is more a substitute for standard residual diagnostics, not R2, which is a measure of how well you explain the target variable. For R2, you can simply calculated R2 or RMSE over the posterior predictive distributions, whatever you like best, however, with all the caveats that arise for mixed models, i.e. you have to consider what you mean by "explain", does a random effect "explain" the data or not - this is again particularly apparent in state-space models, where you can get your fitted states very close to the data, even if the model has basically no clue why the data moves this way.
Metric as straightforward as R^2 for Bayesian models
To check model adequacy, hierarchical Bayesian models are usually evaluated exactly like in DHARMa - you simulated from the fitted model and calculate the quantile residuals. The only difference to DH
Metric as straightforward as R^2 for Bayesian models To check model adequacy, hierarchical Bayesian models are usually evaluated exactly like in DHARMa - you simulated from the fitted model and calculate the quantile residuals. The only difference to DHARMa is that you vary parameters as well while doing the simulations. The approach is explained in many textbooks. Keywords are "posterior predictive simulations", "posterior model checks", or "Bayesian p-values". A few notes As for mixed models, the question arises how many levels of the hierarchy your re-simulate. Especially state-space population models look great when re-simulating only the final observation model, but if you re-simulate the process model as well, it often looks very very different -> good reason to be skeptical when people only show the final fit of the SSMs, this can look great even if the model is horribly wrong. The distributional theory for these residuals is not quite clear for complex models - for GLMMs, all simulations I did so far showed that simulated quantile residuals are with good approximation flat, but this may not be so for any complex model structure. In doubt, run a test on a properly specified model. DHARMa has a function to input posterior predictive simulations (createDHARMa), so that you can use all tools of DHARMa together with hierarchical Bayesian models as well However, all this is more a substitute for standard residual diagnostics, not R2, which is a measure of how well you explain the target variable. For R2, you can simply calculated R2 or RMSE over the posterior predictive distributions, whatever you like best, however, with all the caveats that arise for mixed models, i.e. you have to consider what you mean by "explain", does a random effect "explain" the data or not - this is again particularly apparent in state-space models, where you can get your fitted states very close to the data, even if the model has basically no clue why the data moves this way.
Metric as straightforward as R^2 for Bayesian models To check model adequacy, hierarchical Bayesian models are usually evaluated exactly like in DHARMa - you simulated from the fitted model and calculate the quantile residuals. The only difference to DH
47,178
How to pool c-statistic/AUROC (or any bounded variable) after using multiple imputation techniques?
The c-index is a useful measure of predictive discrimination because it is easy to interpret and at least moderately sensitive. It is not a full-information proper accuracy scoring rule. It is not sensitive enough for comparing two models. So I suggest you obtain the best model using all the partial information available (e.g., multiple imputation with the number of imputations being at least the percentage of records that are incomplete), then attempt to quantify the value of that single model. That is easier said than done, but you can start with the overall Wald statistic for the global null hypothesis that none of the predictors are associated with $Y$. There are a few papers showing how to derive a unitless discrimination index from the Wald $\chi^2$ statistic. Also take a quick look at the $g$-index in my Regression Modeling Strategies book and notes.
How to pool c-statistic/AUROC (or any bounded variable) after using multiple imputation techniques?
The c-index is a useful measure of predictive discrimination because it is easy to interpret and at least moderately sensitive. It is not a full-information proper accuracy scoring rule. It is not s
How to pool c-statistic/AUROC (or any bounded variable) after using multiple imputation techniques? The c-index is a useful measure of predictive discrimination because it is easy to interpret and at least moderately sensitive. It is not a full-information proper accuracy scoring rule. It is not sensitive enough for comparing two models. So I suggest you obtain the best model using all the partial information available (e.g., multiple imputation with the number of imputations being at least the percentage of records that are incomplete), then attempt to quantify the value of that single model. That is easier said than done, but you can start with the overall Wald statistic for the global null hypothesis that none of the predictors are associated with $Y$. There are a few papers showing how to derive a unitless discrimination index from the Wald $\chi^2$ statistic. Also take a quick look at the $g$-index in my Regression Modeling Strategies book and notes.
How to pool c-statistic/AUROC (or any bounded variable) after using multiple imputation techniques? The c-index is a useful measure of predictive discrimination because it is easy to interpret and at least moderately sensitive. It is not a full-information proper accuracy scoring rule. It is not s
47,179
How to pool c-statistic/AUROC (or any bounded variable) after using multiple imputation techniques?
After asking and looking around, I've been pointed at the following reference concerning the meta-analyses of prediction models (in biomedical research) by Debray TPA et al in the British Medical Journal 2016. In appendix 9 the authors provide an explanation of how to pool multiple c-indices across different studies and specify how to obtain the total variance and its components (within and between variance). All of this is based on transforming the values using a logit transformation as a first step. Second, pooling across studies occurs in a similar way as when compared to Rubin's rules for different imputation sets. Finally, the authors back-transform their estimate and confidence interval bounds to the regular scale. As @joe-74 pointed out in his comment, and Debray et al in the reference, it all depends on whether you would assume a normal distribution around the c-index estimate (or other estimate you'd want to pool) and finding a low variance of said estimate. This assumption is necessary in order to avoid the area of the (c-index) scale which is not normally distributed (e.g. near the 1.0 bound). Furthermore, assuming normality will result in a symmetric confidence interval, which suffers the same problems as the estimate itself (i.e. on the bounded scale of concordance between $[0,1]$). To make this clear, the difference in concordant pairs between c-indices of 0.75 and 0.80 is a smaller than the difference between 0.90 and 0.95. Second, to me, the setting of pooling multiple studies or multiple imputation datasets does not matter (please comment if you think otherwise). Consequently, while this may be opinionated (I still do not have a clear reference where the possible bias or error due to pooling without transformation was actually studied), I'd rather not assume this normality for a scale which is inherently non-normal ($[0,1]$ bounded). On a side note, using this strategy, values bounded only on one side (such as the Observed:Expected ratio $[0,∞]$) can be transformed with a log transformation (as mentioned per the Siregar et al reference). To conclude, I would recommend (myself) to logit-transform the c-indices found in the imputation datasets to an unbounded scale and apply Rubin's rules on these transformed values to pool them (including calculating the variance and the confidence interval). And finally, back-transforming the resulting values into the final pooled estimate.
How to pool c-statistic/AUROC (or any bounded variable) after using multiple imputation techniques?
After asking and looking around, I've been pointed at the following reference concerning the meta-analyses of prediction models (in biomedical research) by Debray TPA et al in the British Medical Jour
How to pool c-statistic/AUROC (or any bounded variable) after using multiple imputation techniques? After asking and looking around, I've been pointed at the following reference concerning the meta-analyses of prediction models (in biomedical research) by Debray TPA et al in the British Medical Journal 2016. In appendix 9 the authors provide an explanation of how to pool multiple c-indices across different studies and specify how to obtain the total variance and its components (within and between variance). All of this is based on transforming the values using a logit transformation as a first step. Second, pooling across studies occurs in a similar way as when compared to Rubin's rules for different imputation sets. Finally, the authors back-transform their estimate and confidence interval bounds to the regular scale. As @joe-74 pointed out in his comment, and Debray et al in the reference, it all depends on whether you would assume a normal distribution around the c-index estimate (or other estimate you'd want to pool) and finding a low variance of said estimate. This assumption is necessary in order to avoid the area of the (c-index) scale which is not normally distributed (e.g. near the 1.0 bound). Furthermore, assuming normality will result in a symmetric confidence interval, which suffers the same problems as the estimate itself (i.e. on the bounded scale of concordance between $[0,1]$). To make this clear, the difference in concordant pairs between c-indices of 0.75 and 0.80 is a smaller than the difference between 0.90 and 0.95. Second, to me, the setting of pooling multiple studies or multiple imputation datasets does not matter (please comment if you think otherwise). Consequently, while this may be opinionated (I still do not have a clear reference where the possible bias or error due to pooling without transformation was actually studied), I'd rather not assume this normality for a scale which is inherently non-normal ($[0,1]$ bounded). On a side note, using this strategy, values bounded only on one side (such as the Observed:Expected ratio $[0,∞]$) can be transformed with a log transformation (as mentioned per the Siregar et al reference). To conclude, I would recommend (myself) to logit-transform the c-indices found in the imputation datasets to an unbounded scale and apply Rubin's rules on these transformed values to pool them (including calculating the variance and the confidence interval). And finally, back-transforming the resulting values into the final pooled estimate.
How to pool c-statistic/AUROC (or any bounded variable) after using multiple imputation techniques? After asking and looking around, I've been pointed at the following reference concerning the meta-analyses of prediction models (in biomedical research) by Debray TPA et al in the British Medical Jour
47,180
Exotic distribution
Writing $$x\exp(-ax^2+bx) = \exp\left(\frac{b^2}{4a}\right)x^{2-1}\exp\left(-\left(\frac{x-b/(2a)}{1/\sqrt{a}}\right)^2\right)$$ exhibits this distribution as a Generalized Gamma with scale parameter $1/\sqrt{a}$ and shape parameters $d=2, p=2$ that has been shifted by $\mu=b/(2a)$ and truncated at the left at $b/(2a)$. Because the power of $x$ in the exponential is $p=2$ it can also be called a shifted left-truncated Rayleigh distribution. The raw moments are relatively easy to find using the moment generating function (MGF) $\mathbb{E}(\exp(-tX))$ because the scaling and shifting tell us to change the variable from $x$ to $y=\sqrt{a}(x - b/(2a))$, after which the integral splits into two that are readily evaluated in terms of the standard Normal distribution function $\Phi$: $$\phi(t) \propto 2\sqrt{a} + 2\sqrt{\pi}(b-t)\exp\left(\frac{(b-t)^2}{4a}\right)\Phi\left(\frac{b-t}{\sqrt{2a}}\right).$$ Because the MGF is directly proportional to the density function, the constant of proportionality (which so far has been ignored) can now be found by evaluating $\phi(0)$, because the value of the MGF at zero must equal $1$. In other words, the MGF is $\phi(t)/\phi(0)$.
Exotic distribution
Writing $$x\exp(-ax^2+bx) = \exp\left(\frac{b^2}{4a}\right)x^{2-1}\exp\left(-\left(\frac{x-b/(2a)}{1/\sqrt{a}}\right)^2\right)$$ exhibits this distribution as a Generalized Gamma with scale paramete
Exotic distribution Writing $$x\exp(-ax^2+bx) = \exp\left(\frac{b^2}{4a}\right)x^{2-1}\exp\left(-\left(\frac{x-b/(2a)}{1/\sqrt{a}}\right)^2\right)$$ exhibits this distribution as a Generalized Gamma with scale parameter $1/\sqrt{a}$ and shape parameters $d=2, p=2$ that has been shifted by $\mu=b/(2a)$ and truncated at the left at $b/(2a)$. Because the power of $x$ in the exponential is $p=2$ it can also be called a shifted left-truncated Rayleigh distribution. The raw moments are relatively easy to find using the moment generating function (MGF) $\mathbb{E}(\exp(-tX))$ because the scaling and shifting tell us to change the variable from $x$ to $y=\sqrt{a}(x - b/(2a))$, after which the integral splits into two that are readily evaluated in terms of the standard Normal distribution function $\Phi$: $$\phi(t) \propto 2\sqrt{a} + 2\sqrt{\pi}(b-t)\exp\left(\frac{(b-t)^2}{4a}\right)\Phi\left(\frac{b-t}{\sqrt{2a}}\right).$$ Because the MGF is directly proportional to the density function, the constant of proportionality (which so far has been ignored) can now be found by evaluating $\phi(0)$, because the value of the MGF at zero must equal $1$. In other words, the MGF is $\phi(t)/\phi(0)$.
Exotic distribution Writing $$x\exp(-ax^2+bx) = \exp\left(\frac{b^2}{4a}\right)x^{2-1}\exp\left(-\left(\frac{x-b/(2a)}{1/\sqrt{a}}\right)^2\right)$$ exhibits this distribution as a Generalized Gamma with scale paramete
47,181
Difference Between IV and Control Function in a Non-Linear Model
I would still like others to maybe contribute if they have something substantive to say, but I think this personally cleared the issue up for me: http://www.nber.org/WNE/lect_6_controlfuncs.pdf So, it appears in the non-linear setting the CF approach imposes a linear conditional expectation on the endogenous variable, i.e. $E[u_{2}|z,y_2]$ has a linear conditional expectation. Note: I have listed $u_2$ as the error term in the regression of the endogenous variable, $y_2$ on the exogenous variables $z$. Apparently this assumption is more stringent than simply relying on linear projections as IV does.
Difference Between IV and Control Function in a Non-Linear Model
I would still like others to maybe contribute if they have something substantive to say, but I think this personally cleared the issue up for me: http://www.nber.org/WNE/lect_6_controlfuncs.pdf So, i
Difference Between IV and Control Function in a Non-Linear Model I would still like others to maybe contribute if they have something substantive to say, but I think this personally cleared the issue up for me: http://www.nber.org/WNE/lect_6_controlfuncs.pdf So, it appears in the non-linear setting the CF approach imposes a linear conditional expectation on the endogenous variable, i.e. $E[u_{2}|z,y_2]$ has a linear conditional expectation. Note: I have listed $u_2$ as the error term in the regression of the endogenous variable, $y_2$ on the exogenous variables $z$. Apparently this assumption is more stringent than simply relying on linear projections as IV does.
Difference Between IV and Control Function in a Non-Linear Model I would still like others to maybe contribute if they have something substantive to say, but I think this personally cleared the issue up for me: http://www.nber.org/WNE/lect_6_controlfuncs.pdf So, i
47,182
Difference Between IV and Control Function in a Non-Linear Model
Petrin and Train (2009) is one example of endogeneity being handled with a control function. E.g. a WP here: http://eml.berkeley.edu/~train/petrintrain.pdf I have always found the distinction a bit tricky. I guess in CF you typically invoke more specific assumptions about how two error terms are related. In IV, you rely on an instrument. The classical example covered by Imbens and Wooldridge as well is the Heckman selection model: here, under normality, you get the inverse mill's ratio. Therefore, you can estimate the model even in absence of an instrument, just relying on functional form only (although it is not advisable).
Difference Between IV and Control Function in a Non-Linear Model
Petrin and Train (2009) is one example of endogeneity being handled with a control function. E.g. a WP here: http://eml.berkeley.edu/~train/petrintrain.pdf I have always found the distinction a bit tr
Difference Between IV and Control Function in a Non-Linear Model Petrin and Train (2009) is one example of endogeneity being handled with a control function. E.g. a WP here: http://eml.berkeley.edu/~train/petrintrain.pdf I have always found the distinction a bit tricky. I guess in CF you typically invoke more specific assumptions about how two error terms are related. In IV, you rely on an instrument. The classical example covered by Imbens and Wooldridge as well is the Heckman selection model: here, under normality, you get the inverse mill's ratio. Therefore, you can estimate the model even in absence of an instrument, just relying on functional form only (although it is not advisable).
Difference Between IV and Control Function in a Non-Linear Model Petrin and Train (2009) is one example of endogeneity being handled with a control function. E.g. a WP here: http://eml.berkeley.edu/~train/petrintrain.pdf I have always found the distinction a bit tr
47,183
Is this a valid way to think about p-values?
Would it be accurate to say that a p-value is a random variable whose null distribution is Unif$(0,1)$ which stochastically dominates its distribution under the alternative hypothesis? No, that dominance would be a desirable property, not a definition. Many good (and widely used) tests are biased under some alternatives (it's typical for goodness of fit tests for example). Further, one can easily define "useless" test statistics which don't possess this property anywhere under the alternative. I realized that I have been thinking about p-values in the sense of "if we set significance level $\alpha$, then we expect $\alpha$ proportion of research papers to be false positives" which I now think is wrong. It is wrong for several reasons. Perhaps the most obvious is that almost all point nulls are actually false (and most published hypothesis tests use point nulls). Consequently while rejections are very common in published papers (in some areas, unfortunately, even ubiquitious) few of them will actually be false rejections even in cases where the hypothesis is not rejected in a later attempt to replicate the result.
Is this a valid way to think about p-values?
Would it be accurate to say that a p-value is a random variable whose null distribution is Unif$(0,1)$ which stochastically dominates its distribution under the alternative hypothesis? No, that domi
Is this a valid way to think about p-values? Would it be accurate to say that a p-value is a random variable whose null distribution is Unif$(0,1)$ which stochastically dominates its distribution under the alternative hypothesis? No, that dominance would be a desirable property, not a definition. Many good (and widely used) tests are biased under some alternatives (it's typical for goodness of fit tests for example). Further, one can easily define "useless" test statistics which don't possess this property anywhere under the alternative. I realized that I have been thinking about p-values in the sense of "if we set significance level $\alpha$, then we expect $\alpha$ proportion of research papers to be false positives" which I now think is wrong. It is wrong for several reasons. Perhaps the most obvious is that almost all point nulls are actually false (and most published hypothesis tests use point nulls). Consequently while rejections are very common in published papers (in some areas, unfortunately, even ubiquitious) few of them will actually be false rejections even in cases where the hypothesis is not rejected in a later attempt to replicate the result.
Is this a valid way to think about p-values? Would it be accurate to say that a p-value is a random variable whose null distribution is Unif$(0,1)$ which stochastically dominates its distribution under the alternative hypothesis? No, that domi
47,184
Is this a valid way to think about p-values?
$p$ can indeed be regarded as a random variable (in fact, it's a statistic), and is required to be uniformity distributed on $[0, 1]$ under the null hypothesis. However, no guarantees are made about the distribution of $p$ under the alternative hypothesis. This makes sense when you consider that the alternative hypothesis is, for the typical two-tailed test, extremely weak, so very little can be inferred from it.
Is this a valid way to think about p-values?
$p$ can indeed be regarded as a random variable (in fact, it's a statistic), and is required to be uniformity distributed on $[0, 1]$ under the null hypothesis. However, no guarantees are made about t
Is this a valid way to think about p-values? $p$ can indeed be regarded as a random variable (in fact, it's a statistic), and is required to be uniformity distributed on $[0, 1]$ under the null hypothesis. However, no guarantees are made about the distribution of $p$ under the alternative hypothesis. This makes sense when you consider that the alternative hypothesis is, for the typical two-tailed test, extremely weak, so very little can be inferred from it.
Is this a valid way to think about p-values? $p$ can indeed be regarded as a random variable (in fact, it's a statistic), and is required to be uniformity distributed on $[0, 1]$ under the null hypothesis. However, no guarantees are made about t
47,185
Is this a valid way to think about p-values?
There have been many different definitions of P-values and there will, no doubt, be many more. I do not find yours to be satisfactory because the decision theory-based concept of stochastic dominance seems to fit more with the dichotomous hypothesis test framework than with the significance testing framework that yields a P-value. The hypothesis testing framework utilises rejection regions and the $\alpha$ that you mention in your question, and does not entail calculation of a P-value at all. See these questions and answers for more on this topic: What is the difference between "testing of hypothesis" and "test of significance"? Why are lower p-values not more evidence against the null? Arguments from Johansson 2011 Is it fair to say p-values tell us nothing about the probability null hypotheses are true? Is the "hybrid" between Fisher and Neyman-Pearson approaches to statistical testing really an "incoherent mishmash"? Interpretation of p-value in hypothesis testing
Is this a valid way to think about p-values?
There have been many different definitions of P-values and there will, no doubt, be many more. I do not find yours to be satisfactory because the decision theory-based concept of stochastic dominance
Is this a valid way to think about p-values? There have been many different definitions of P-values and there will, no doubt, be many more. I do not find yours to be satisfactory because the decision theory-based concept of stochastic dominance seems to fit more with the dichotomous hypothesis test framework than with the significance testing framework that yields a P-value. The hypothesis testing framework utilises rejection regions and the $\alpha$ that you mention in your question, and does not entail calculation of a P-value at all. See these questions and answers for more on this topic: What is the difference between "testing of hypothesis" and "test of significance"? Why are lower p-values not more evidence against the null? Arguments from Johansson 2011 Is it fair to say p-values tell us nothing about the probability null hypotheses are true? Is the "hybrid" between Fisher and Neyman-Pearson approaches to statistical testing really an "incoherent mishmash"? Interpretation of p-value in hypothesis testing
Is this a valid way to think about p-values? There have been many different definitions of P-values and there will, no doubt, be many more. I do not find yours to be satisfactory because the decision theory-based concept of stochastic dominance
47,186
Varied Activation Functions in Neural Networks
Clearly you can use different activations in a neural network. An MLP with any activation and a softmax readout layer is one example (for example, multi-class classification). An RNN with LSTM units has at least two activation functions (logistic, tanh and any activations used elsewhere). ReLU activations in the hidden layers and a linear function in the readout layer for a regression problem.
Varied Activation Functions in Neural Networks
Clearly you can use different activations in a neural network. An MLP with any activation and a softmax readout layer is one example (for example, multi-class classification). An RNN with LSTM units h
Varied Activation Functions in Neural Networks Clearly you can use different activations in a neural network. An MLP with any activation and a softmax readout layer is one example (for example, multi-class classification). An RNN with LSTM units has at least two activation functions (logistic, tanh and any activations used elsewhere). ReLU activations in the hidden layers and a linear function in the readout layer for a regression problem.
Varied Activation Functions in Neural Networks Clearly you can use different activations in a neural network. An MLP with any activation and a softmax readout layer is one example (for example, multi-class classification). An RNN with LSTM units h
47,187
Varied Activation Functions in Neural Networks
I believe what is meant by the question is: can we mix different activation functions in a single layer. So imagine we have only one hidden layer with 3 nodes, can I set the first node to have sigmoid, second node to have ReLU, and third node to have tanh? I just thought about this as well, and I believe this should be possible but with the cost of computation time, because then we cannot vectorize the computation for that hidden layer.
Varied Activation Functions in Neural Networks
I believe what is meant by the question is: can we mix different activation functions in a single layer. So imagine we have only one hidden layer with 3 nodes, can I set the first node to have sigmoid
Varied Activation Functions in Neural Networks I believe what is meant by the question is: can we mix different activation functions in a single layer. So imagine we have only one hidden layer with 3 nodes, can I set the first node to have sigmoid, second node to have ReLU, and third node to have tanh? I just thought about this as well, and I believe this should be possible but with the cost of computation time, because then we cannot vectorize the computation for that hidden layer.
Varied Activation Functions in Neural Networks I believe what is meant by the question is: can we mix different activation functions in a single layer. So imagine we have only one hidden layer with 3 nodes, can I set the first node to have sigmoid
47,188
Quantile regression for non linear regression analysis?
Unlike the answer from @Arne Jonas Warnke , I see no need to restrict attention to non-parametric estimators for nonlinear quantile regression. Simply use whatever form of nonlinear function of the parameter vector $\beta$ , namely $f(\beta)$, you have in place of $X\beta$ in https://en.wikipedia.org/wiki/Quantile_regression#Conditional_quantile_and_quantile_regression . Of course, if $f(\beta)$ is a nonlinear function of the parameter vector $\beta$, the quantile regression problem will not be a Linear Programming problem, but it could still be solved with an appropriate nonlinear optimization solver.
Quantile regression for non linear regression analysis?
Unlike the answer from @Arne Jonas Warnke , I see no need to restrict attention to non-parametric estimators for nonlinear quantile regression. Simply use whatever form of nonlinear function of the pa
Quantile regression for non linear regression analysis? Unlike the answer from @Arne Jonas Warnke , I see no need to restrict attention to non-parametric estimators for nonlinear quantile regression. Simply use whatever form of nonlinear function of the parameter vector $\beta$ , namely $f(\beta)$, you have in place of $X\beta$ in https://en.wikipedia.org/wiki/Quantile_regression#Conditional_quantile_and_quantile_regression . Of course, if $f(\beta)$ is a nonlinear function of the parameter vector $\beta$, the quantile regression problem will not be a Linear Programming problem, but it could still be solved with an appropriate nonlinear optimization solver.
Quantile regression for non linear regression analysis? Unlike the answer from @Arne Jonas Warnke , I see no need to restrict attention to non-parametric estimators for nonlinear quantile regression. Simply use whatever form of nonlinear function of the pa
47,189
Quantile regression for non linear regression analysis?
Yes, of course, there are non-parametric estimator for quantile regression, see for example Horrowitz and Lee (2004). But I think there may be some confusion about the meaning of the term linear. See this nice answer here at CrossValidated. The models in the blog post are indeed additive and linear.
Quantile regression for non linear regression analysis?
Yes, of course, there are non-parametric estimator for quantile regression, see for example Horrowitz and Lee (2004). But I think there may be some confusion about the meaning of the term linear. See
Quantile regression for non linear regression analysis? Yes, of course, there are non-parametric estimator for quantile regression, see for example Horrowitz and Lee (2004). But I think there may be some confusion about the meaning of the term linear. See this nice answer here at CrossValidated. The models in the blog post are indeed additive and linear.
Quantile regression for non linear regression analysis? Yes, of course, there are non-parametric estimator for quantile regression, see for example Horrowitz and Lee (2004). But I think there may be some confusion about the meaning of the term linear. See
47,190
Partial exchangeability - Theory and results
This is described by Diaconis (1988; see also Diaconis and Freedman, 1980): In 1938 de Finetti broaden the concept of exchangeability. Consider first the special case with two observations $X_1,X_2,\dots;Y_1,Y_2,\dots$. The $X_i$ might represent binary outcomes for a group of men and $Y_i$ might represent binary outcomes for a group of women. If it were judged that the observable covariate men/women did not matter, all of the variables would be judged exchangeable. Often, the covariate is judged as potentially meaningful, the $X_i$'s are judged exchangeable between themselves and the $Y_i$'s are judged exchangeable between themselves. Mathematically, the joint law must be invariant under permutations within the $X$'s and $Y$'s: $$ \mathcal{L}(X_1,\dots,X_n;Y_1,\dots,Y_m) = \mathcal{L}(X_{\pi(1)},\dots,X_{\pi(n)};Y_{\sigma(1)},\dots,Y_{\sigma(m)}) $$ This must hold for all $n$ and $m$, and permutations $\pi$ and $\sigma$. You could check as well the original paper by de Finetti (1938) for discussion and multiple examples as he has very light and clear style of writing, what makes his papers easy to read. Diaconis, P. (1988). Recent progress on de Finetti’s notions of exchangeability. Bayesian statistics, 3, 111-125. Diaconis, P., & Freedman, D. (1980). De Finetti’s generalizations of exchangeability. Studies in inductive logic and probability, 2, 233-249. De Finetti, B. (1938/1980). On the condition of partial exchangeability. Studies in inductive logic and probability, 2, 193-205.
Partial exchangeability - Theory and results
This is described by Diaconis (1988; see also Diaconis and Freedman, 1980): In 1938 de Finetti broaden the concept of exchangeability. Consider first the special case with two observations $X_1,X
Partial exchangeability - Theory and results This is described by Diaconis (1988; see also Diaconis and Freedman, 1980): In 1938 de Finetti broaden the concept of exchangeability. Consider first the special case with two observations $X_1,X_2,\dots;Y_1,Y_2,\dots$. The $X_i$ might represent binary outcomes for a group of men and $Y_i$ might represent binary outcomes for a group of women. If it were judged that the observable covariate men/women did not matter, all of the variables would be judged exchangeable. Often, the covariate is judged as potentially meaningful, the $X_i$'s are judged exchangeable between themselves and the $Y_i$'s are judged exchangeable between themselves. Mathematically, the joint law must be invariant under permutations within the $X$'s and $Y$'s: $$ \mathcal{L}(X_1,\dots,X_n;Y_1,\dots,Y_m) = \mathcal{L}(X_{\pi(1)},\dots,X_{\pi(n)};Y_{\sigma(1)},\dots,Y_{\sigma(m)}) $$ This must hold for all $n$ and $m$, and permutations $\pi$ and $\sigma$. You could check as well the original paper by de Finetti (1938) for discussion and multiple examples as he has very light and clear style of writing, what makes his papers easy to read. Diaconis, P. (1988). Recent progress on de Finetti’s notions of exchangeability. Bayesian statistics, 3, 111-125. Diaconis, P., & Freedman, D. (1980). De Finetti’s generalizations of exchangeability. Studies in inductive logic and probability, 2, 233-249. De Finetti, B. (1938/1980). On the condition of partial exchangeability. Studies in inductive logic and probability, 2, 193-205.
Partial exchangeability - Theory and results This is described by Diaconis (1988; see also Diaconis and Freedman, 1980): In 1938 de Finetti broaden the concept of exchangeability. Consider first the special case with two observations $X_1,X
47,191
Partial exchangeability - Theory and results
To complete Tim's answer, from the useful references given there: Suppose the quantities $\{X_i\} := \{X_1, X_2, \dotsc\}$ and $\{Y_j\}$ can have values $\{x\}$ and $\{y\}$ from two discrete sets. The assumption of infinite partial exchangeability for their joint probabilities means $$ \mathrm{P}(X_1=x_1, \dotsc, X_n=x_n,\; Y_1=y_1, \dotsc, Y_m=y_m) ={}\\ \mathrm{P}(X_1=x_{\pi(1)}, \dotsc, X_n=x_{\pi(n)},\; Y_1=y_{\sigma(1)}, \dotsc, Y_m=y_{\sigma(m)}),\\ \text{for all $m,n$, and all permutations $\pi,\sigma$ of $\{1,\dotsc,n\}$ and $\{1,\dotsc,m\}$.} $$ Then the probability above can be expressed in this integral form: $$ \mathrm{P}(X_1=x_1, \dotsc, X_n=x_n,\; Y_1=y_1, \dotsc, Y_m=y_m) ={}\\ \iint \prod_{i=1}^n p_{x_i}\; \prod_{j=1}^m q_{y_j}\; f(\mathbf{p},\mathbf{q})\;\mathrm{d}\mathbf{p}\,\mathrm{d}\mathbf{q}, $$ where $\mathbf{p} := \{p_x\}$ and $\mathbf{q} := \{q_y\}$ are distributions over the possible values $\{x\}$ and $\{y\}$, and $f$ is a probability density over all such pairs of distributions. Another useful reference for partial exchangeability, with examples, is Bernardo & Smith's Bayesian Theory (Wiley 2000), especially § 4.6.
Partial exchangeability - Theory and results
To complete Tim's answer, from the useful references given there: Suppose the quantities $\{X_i\} := \{X_1, X_2, \dotsc\}$ and $\{Y_j\}$ can have values $\{x\}$ and $\{y\}$ from two discrete sets. The
Partial exchangeability - Theory and results To complete Tim's answer, from the useful references given there: Suppose the quantities $\{X_i\} := \{X_1, X_2, \dotsc\}$ and $\{Y_j\}$ can have values $\{x\}$ and $\{y\}$ from two discrete sets. The assumption of infinite partial exchangeability for their joint probabilities means $$ \mathrm{P}(X_1=x_1, \dotsc, X_n=x_n,\; Y_1=y_1, \dotsc, Y_m=y_m) ={}\\ \mathrm{P}(X_1=x_{\pi(1)}, \dotsc, X_n=x_{\pi(n)},\; Y_1=y_{\sigma(1)}, \dotsc, Y_m=y_{\sigma(m)}),\\ \text{for all $m,n$, and all permutations $\pi,\sigma$ of $\{1,\dotsc,n\}$ and $\{1,\dotsc,m\}$.} $$ Then the probability above can be expressed in this integral form: $$ \mathrm{P}(X_1=x_1, \dotsc, X_n=x_n,\; Y_1=y_1, \dotsc, Y_m=y_m) ={}\\ \iint \prod_{i=1}^n p_{x_i}\; \prod_{j=1}^m q_{y_j}\; f(\mathbf{p},\mathbf{q})\;\mathrm{d}\mathbf{p}\,\mathrm{d}\mathbf{q}, $$ where $\mathbf{p} := \{p_x\}$ and $\mathbf{q} := \{q_y\}$ are distributions over the possible values $\{x\}$ and $\{y\}$, and $f$ is a probability density over all such pairs of distributions. Another useful reference for partial exchangeability, with examples, is Bernardo & Smith's Bayesian Theory (Wiley 2000), especially § 4.6.
Partial exchangeability - Theory and results To complete Tim's answer, from the useful references given there: Suppose the quantities $\{X_i\} := \{X_1, X_2, \dotsc\}$ and $\{Y_j\}$ can have values $\{x\}$ and $\{y\}$ from two discrete sets. The
47,192
Can chi-square test be used on non-integer observed frequencies?
observed count have decimal points. If you have fractions, you don't have observed counts but something else. Counts actually count things, 0, 1, 2... . The real data is the prediction of males and females according to the job roles and City from Bureau of Labor Statistics Predictions don't have the same properties (including the same uncertainty) as count data. The chi-squared test relies on the data being actual observed counts, not predictions of counts or any other manipulation of counts. This is needed to obtain the correct scaling of $O_i-E_i$ (the denominator is based on particular assumptions that in general won't hold for things that are not counts). As a result, your test won't work - you can't just treat predictions as observed counts. It's irrelevant whether they were rounded integers or not (the only difference of any consequence is that the non-integer values made it obvious you didn't have actual observed counts; if the predictions had been rounded you might never have known there was a problem).
Can chi-square test be used on non-integer observed frequencies?
observed count have decimal points. If you have fractions, you don't have observed counts but something else. Counts actually count things, 0, 1, 2... . The real data is the prediction of males an
Can chi-square test be used on non-integer observed frequencies? observed count have decimal points. If you have fractions, you don't have observed counts but something else. Counts actually count things, 0, 1, 2... . The real data is the prediction of males and females according to the job roles and City from Bureau of Labor Statistics Predictions don't have the same properties (including the same uncertainty) as count data. The chi-squared test relies on the data being actual observed counts, not predictions of counts or any other manipulation of counts. This is needed to obtain the correct scaling of $O_i-E_i$ (the denominator is based on particular assumptions that in general won't hold for things that are not counts). As a result, your test won't work - you can't just treat predictions as observed counts. It's irrelevant whether they were rounded integers or not (the only difference of any consequence is that the non-integer values made it obvious you didn't have actual observed counts; if the predictions had been rounded you might never have known there was a problem).
Can chi-square test be used on non-integer observed frequencies? observed count have decimal points. If you have fractions, you don't have observed counts but something else. Counts actually count things, 0, 1, 2... . The real data is the prediction of males an
47,193
Can chi-square test be used on non-integer observed frequencies?
Even before rounding, parts of your question describes things which seem to me problematic. IMHO, it pays to consider them, as they relate to the cause of rounding. Scaling Say my model just divides everything by 3 The rationale behind this test involves the multinomial distribution, and contains combinatorical terms of the form $${n \choose n_1 \cdot n_k}$$ These terms are not invariant to scaling. I.e., you cannot replace this with $${\alpha n \choose \alpha^k n_1 \cdot n_k} = {\alpha n \choose \alpha n_1 \cdot \alpha n_k}$$ and expect to get the same results. Test Assumptions It's possible your division of 3 is caused by this being an average of three observations. In this case, though, there's a problem with assuming that the test is relevant here: A common rule is 5 or more in all cells of a 2-by-2 table Post the division by 3, this does not hold, and the numbers are not in the range where it can be assumed that this test is applicable.
Can chi-square test be used on non-integer observed frequencies?
Even before rounding, parts of your question describes things which seem to me problematic. IMHO, it pays to consider them, as they relate to the cause of rounding. Scaling Say my model just divides
Can chi-square test be used on non-integer observed frequencies? Even before rounding, parts of your question describes things which seem to me problematic. IMHO, it pays to consider them, as they relate to the cause of rounding. Scaling Say my model just divides everything by 3 The rationale behind this test involves the multinomial distribution, and contains combinatorical terms of the form $${n \choose n_1 \cdot n_k}$$ These terms are not invariant to scaling. I.e., you cannot replace this with $${\alpha n \choose \alpha^k n_1 \cdot n_k} = {\alpha n \choose \alpha n_1 \cdot \alpha n_k}$$ and expect to get the same results. Test Assumptions It's possible your division of 3 is caused by this being an average of three observations. In this case, though, there's a problem with assuming that the test is relevant here: A common rule is 5 or more in all cells of a 2-by-2 table Post the division by 3, this does not hold, and the numbers are not in the range where it can be assumed that this test is applicable.
Can chi-square test be used on non-integer observed frequencies? Even before rounding, parts of your question describes things which seem to me problematic. IMHO, it pays to consider them, as they relate to the cause of rounding. Scaling Say my model just divides
47,194
Can chi-square test be used on non-integer observed frequencies?
What you are doing here is in a manner of speaking called weighting of cases. Let's assume that you are doing a study where you want to find out the prevalence of child abuse in high school population. In the population you have 50% boys and 50% girls, however your sample is 60% boys and 40% girls due to the sampling error. If you assume that the prevalence is higher among girls than boys then your sample estimate would be deflated because the sample does not represent the population well. What you do here is that you employ weights to cases and you will declare that each male participant has the weight of 0.83, and each female participant has the weight of 1.25 so you wil get e.g. 60 male participants * 0,83=50 and 40 female * 1,25=50. When you do this your frequencies can become fractional values and this is quite common in survey based studies. Softwares have issues with this and e.g. SPSS when calculating nonparametric statistics ignores the decimal parts (imagine calculating ranks when each entity has its own weight), and SPSS even ignores the weights when performing CHI Square test. However the logic of chi square is that you are first calculating the difference between the observed and expected value, then you square it to remove the direction and to give more importance to bigger differences, and the you divide this by expected value to return it to original metric and to put it in terms of expected value. From this perspective, if you use the fractional counts, the logic is still preserved. If you want to calculate this, you should check out how your software deals with weighted data, or do it by hand. Be aware that meddling with weights means meddling with statistical power so use caution :)
Can chi-square test be used on non-integer observed frequencies?
What you are doing here is in a manner of speaking called weighting of cases. Let's assume that you are doing a study where you want to find out the prevalence of child abuse in high school population
Can chi-square test be used on non-integer observed frequencies? What you are doing here is in a manner of speaking called weighting of cases. Let's assume that you are doing a study where you want to find out the prevalence of child abuse in high school population. In the population you have 50% boys and 50% girls, however your sample is 60% boys and 40% girls due to the sampling error. If you assume that the prevalence is higher among girls than boys then your sample estimate would be deflated because the sample does not represent the population well. What you do here is that you employ weights to cases and you will declare that each male participant has the weight of 0.83, and each female participant has the weight of 1.25 so you wil get e.g. 60 male participants * 0,83=50 and 40 female * 1,25=50. When you do this your frequencies can become fractional values and this is quite common in survey based studies. Softwares have issues with this and e.g. SPSS when calculating nonparametric statistics ignores the decimal parts (imagine calculating ranks when each entity has its own weight), and SPSS even ignores the weights when performing CHI Square test. However the logic of chi square is that you are first calculating the difference between the observed and expected value, then you square it to remove the direction and to give more importance to bigger differences, and the you divide this by expected value to return it to original metric and to put it in terms of expected value. From this perspective, if you use the fractional counts, the logic is still preserved. If you want to calculate this, you should check out how your software deals with weighted data, or do it by hand. Be aware that meddling with weights means meddling with statistical power so use caution :)
Can chi-square test be used on non-integer observed frequencies? What you are doing here is in a manner of speaking called weighting of cases. Let's assume that you are doing a study where you want to find out the prevalence of child abuse in high school population
47,195
Lagrange Multipler KKT condition
A key concept with optimization in general and the KKT conditions in particular is distinguishing: necessary conditions for an optimum sufficient conditions for an optimum In its most basic form, the KKT conditions are necessary conditions for an optimum. If an optimum exists and certain regularity conditions are satisfied, the optimum must satisfy the KKT conditions. Consider an even simpler case: \begin{equation} \begin{array}{*2{>{\displaystyle}r}} \mbox{maximize (over $x$)} & x^2 \\ \end{array} \end{equation} The KKT condition is $2x = 0$. Every optimum satisfies these conditions, but there is no optimum! For the KKT conditions to be sufficient conditions, more is required! For example, if the optimization problem is convex and Slater's condition is satisfied, then the KKT conditions are also sufficient conditions for an optimum (and every point that satisfies the KKT conditions is an optimum). For example, \begin{equation} \begin{array}{*2{>{\displaystyle}r}} \mbox{minimize (over $x$)} & x^2 \\ \end{array} \end{equation} is a convex, unconstrained problem hence the KKT conditions are sufficient conditions hence the condition $2x = 0$ implies $x=0$ is a solution. Answering your direct question: If functions are complicated, what's the systematic way to confirm that the optimization with inequality constraint functions is solvable using Lagrange multiplier? Unfortunately, there's a bit of nuance to the answer here. There are many different conditions for the optimization problem that imply that the KKT conditions are either necessary or sufficient for an optimum. One of the most useful categories of problems where the KKT conditions are sufficient conditions for an optimum are when the optimization problem is convex and Slater's condition holds. Checkout Stanford Prof. Boyd's course on convex optimization, but the basic idea is that a convex optimization problem can be written as: \begin{equation} \begin{array}{*2{>{\displaystyle}r}} \mbox{minimize (over $\mathbf{x}$)} & f(\mathbf{x}) \\ \mbox{subject to} & \forall_j g_j(\mathbf{x}) \leq 0 \\ & A\mathbf{x} = \mathbf{b} \end{array} \end{equation} where $\mathbf{x}$ is a vector, objective function $f$ is convex in $\mathbf{x}$, constraints $g_j$ are convex in $\mathbf{x}$, and equality constraints are affine. Slater's condition is that there exists a point in relative interior of the feasible set (eg. you don't have constraints like $x^2 \leq 0$ which are only satisfied by a single point). In the case of a convex problem where Slater's condition is satisfied, the optimal pair $(\mathbf{x}, \boldsymbol{\lambda})$ is a saddle point of the Lagrangian. Another useful regularity condition for the KKT conditions to be necessary is the LICQ constraint qualification. The KKT Wikipedia page has a whole list of possible regularity conditions. The mathematics of optimization is a big, broad topic! Anyway, this will hopefully get you going in the right direction! As you're going along, be sure to distinguish: Conditions on your optimization problem that imply the KKT conditions are necessary for an optimum. Conditions on your optimization problem that imply the KKT conditions are sufficient for an optimum.
Lagrange Multipler KKT condition
A key concept with optimization in general and the KKT conditions in particular is distinguishing: necessary conditions for an optimum sufficient conditions for an optimum In its most basic form, th
Lagrange Multipler KKT condition A key concept with optimization in general and the KKT conditions in particular is distinguishing: necessary conditions for an optimum sufficient conditions for an optimum In its most basic form, the KKT conditions are necessary conditions for an optimum. If an optimum exists and certain regularity conditions are satisfied, the optimum must satisfy the KKT conditions. Consider an even simpler case: \begin{equation} \begin{array}{*2{>{\displaystyle}r}} \mbox{maximize (over $x$)} & x^2 \\ \end{array} \end{equation} The KKT condition is $2x = 0$. Every optimum satisfies these conditions, but there is no optimum! For the KKT conditions to be sufficient conditions, more is required! For example, if the optimization problem is convex and Slater's condition is satisfied, then the KKT conditions are also sufficient conditions for an optimum (and every point that satisfies the KKT conditions is an optimum). For example, \begin{equation} \begin{array}{*2{>{\displaystyle}r}} \mbox{minimize (over $x$)} & x^2 \\ \end{array} \end{equation} is a convex, unconstrained problem hence the KKT conditions are sufficient conditions hence the condition $2x = 0$ implies $x=0$ is a solution. Answering your direct question: If functions are complicated, what's the systematic way to confirm that the optimization with inequality constraint functions is solvable using Lagrange multiplier? Unfortunately, there's a bit of nuance to the answer here. There are many different conditions for the optimization problem that imply that the KKT conditions are either necessary or sufficient for an optimum. One of the most useful categories of problems where the KKT conditions are sufficient conditions for an optimum are when the optimization problem is convex and Slater's condition holds. Checkout Stanford Prof. Boyd's course on convex optimization, but the basic idea is that a convex optimization problem can be written as: \begin{equation} \begin{array}{*2{>{\displaystyle}r}} \mbox{minimize (over $\mathbf{x}$)} & f(\mathbf{x}) \\ \mbox{subject to} & \forall_j g_j(\mathbf{x}) \leq 0 \\ & A\mathbf{x} = \mathbf{b} \end{array} \end{equation} where $\mathbf{x}$ is a vector, objective function $f$ is convex in $\mathbf{x}$, constraints $g_j$ are convex in $\mathbf{x}$, and equality constraints are affine. Slater's condition is that there exists a point in relative interior of the feasible set (eg. you don't have constraints like $x^2 \leq 0$ which are only satisfied by a single point). In the case of a convex problem where Slater's condition is satisfied, the optimal pair $(\mathbf{x}, \boldsymbol{\lambda})$ is a saddle point of the Lagrangian. Another useful regularity condition for the KKT conditions to be necessary is the LICQ constraint qualification. The KKT Wikipedia page has a whole list of possible regularity conditions. The mathematics of optimization is a big, broad topic! Anyway, this will hopefully get you going in the right direction! As you're going along, be sure to distinguish: Conditions on your optimization problem that imply the KKT conditions are necessary for an optimum. Conditions on your optimization problem that imply the KKT conditions are sufficient for an optimum.
Lagrange Multipler KKT condition A key concept with optimization in general and the KKT conditions in particular is distinguishing: necessary conditions for an optimum sufficient conditions for an optimum In its most basic form, th
47,196
LDA: Why am I getting the same topic for all points in test set?
My first bet would be that the function words in a corpus of source code differ vastly from those of standard stop lists, and that your model's first topic is indeed capturing standard programming fare: if, int, new, while, etc. Besides building a custom stop list—seeing which words have high probability under the most frequently assigned topics is a good place to start—you might consider fitting a hierarchal topic model, first described in this paper and in more detail in this one. From the first: In our approach, each node in the hierarchy is associated with a topic, where a topic is a distribution across words. A document is generated by choosing a path from the root to a leaf, repeatedly sampling topics along that path, and sampling the words from the selected topics. Thus the organization of topics into a hierarchy aims to capture the breadth of usage of topics across the corpus, reflecting underlying syntactic and semantic notions of generality and specificity. Meaning, using this model, all documents start at the root node, which will include the most common words in the corpus. (See the paper for examples.) This lets you avoid determining a list of stop words manually: The model has nicely captured the function words without using an auxiliary list, a nuisance that most practical applications of language models require. At the next level, it separated the words pertaining to neuroscience abstracts and machine learning abstracts. Finally, it delineated several important subtopics within the two fields. These results suggest that hLDA can be an effective tool in text applications. Implementation here. (Unaware of one in Python.)
LDA: Why am I getting the same topic for all points in test set?
My first bet would be that the function words in a corpus of source code differ vastly from those of standard stop lists, and that your model's first topic is indeed capturing standard programming far
LDA: Why am I getting the same topic for all points in test set? My first bet would be that the function words in a corpus of source code differ vastly from those of standard stop lists, and that your model's first topic is indeed capturing standard programming fare: if, int, new, while, etc. Besides building a custom stop list—seeing which words have high probability under the most frequently assigned topics is a good place to start—you might consider fitting a hierarchal topic model, first described in this paper and in more detail in this one. From the first: In our approach, each node in the hierarchy is associated with a topic, where a topic is a distribution across words. A document is generated by choosing a path from the root to a leaf, repeatedly sampling topics along that path, and sampling the words from the selected topics. Thus the organization of topics into a hierarchy aims to capture the breadth of usage of topics across the corpus, reflecting underlying syntactic and semantic notions of generality and specificity. Meaning, using this model, all documents start at the root node, which will include the most common words in the corpus. (See the paper for examples.) This lets you avoid determining a list of stop words manually: The model has nicely captured the function words without using an auxiliary list, a nuisance that most practical applications of language models require. At the next level, it separated the words pertaining to neuroscience abstracts and machine learning abstracts. Finally, it delineated several important subtopics within the two fields. These results suggest that hLDA can be an effective tool in text applications. Implementation here. (Unaware of one in Python.)
LDA: Why am I getting the same topic for all points in test set? My first bet would be that the function words in a corpus of source code differ vastly from those of standard stop lists, and that your model's first topic is indeed capturing standard programming far
47,197
LDA: Why am I getting the same topic for all points in test set?
I found the problem. As indicated by several comments and the answer, it seemed LDA was doing fine and it was. The only problem was the data was too much for LDA and too noisy. I was training on 750K+ docs and everything was noisy. Upon reducing the data to 30k relevant docs, I was able to achieve much better results.
LDA: Why am I getting the same topic for all points in test set?
I found the problem. As indicated by several comments and the answer, it seemed LDA was doing fine and it was. The only problem was the data was too much for LDA and too noisy. I was training on 750K+
LDA: Why am I getting the same topic for all points in test set? I found the problem. As indicated by several comments and the answer, it seemed LDA was doing fine and it was. The only problem was the data was too much for LDA and too noisy. I was training on 750K+ docs and everything was noisy. Upon reducing the data to 30k relevant docs, I was able to achieve much better results.
LDA: Why am I getting the same topic for all points in test set? I found the problem. As indicated by several comments and the answer, it seemed LDA was doing fine and it was. The only problem was the data was too much for LDA and too noisy. I was training on 750K+
47,198
Predicting future values with hurdle Poisson model
The basic idea is 'success probability of binomial distribution' * 'lambda (= an expected value) of poisson distribution'. But you have to consider that the poisson model in count part never returns 0. I supposed your example data and predicted when width is c(23, 26, 29). library(pscl) data <- data.frame(y = c(8, 0, 3, 7), width = c(34.40, 22.50, 28.34, 32.22)) model <- hurdle(y ~ width, data = data) model # Count model coefficients (truncated poisson with log link): # (Intercept) width # -3.4520 0.1629 # model$coef$count[[1]] (left); model$coef$count[[2]] (right) # Zero hurdle model coefficients (binomial with logit link): # (Intercept) width # -198.851 7.809 # model$coef$zero[[1]] (left); model$coef$zero[[2]] (right) First, you calculate a success probability of a binomial model, phi_zero, (logistic equation). (I attached a taking log version because of predict() uses it.) phi_zero <- 1 / ( 1 + exp(-(model$coef$zero[[1]] + model$coef$zero[[2]] * c(23, 26, 29)))) # p0_zero <- log(phi_zero) Second, you calculate a param (= expected value) of a poisson model, mu, and the > 0 probability, phi_count. mu <- exp(model$coef$count[[1]] + model$coef$count[[2]] * c(23, 26, 29)) phi_count <- ppois(0, lambda = mu, lower.tail = F) # not 0 probability # p0_count <- ppois(0, lambda = mu, lower.tail = F, log.p = T) Finally, you integrate values of both model. phi <- phi_zero / phi_count # because there isn't 0 coming from poisson. rval <- phi * mu # logphi <- p0_zero - p0_count # rval2 <- exp(logphi + log(mu)) rval # [1] 8.051324e-09 2.429582e+00 3.674317e+00 And predict() takes a class hurdle as an argument (see ?predict.hurdle). predict(model, data.frame(width = c(23, 26, 29)), type = "response") # 1 2 3 # 8.051324e-09 2.429582e+00 3.674317e+00 # the same
Predicting future values with hurdle Poisson model
The basic idea is 'success probability of binomial distribution' * 'lambda (= an expected value) of poisson distribution'. But you have to consider that the poisson model in count part never returns 0
Predicting future values with hurdle Poisson model The basic idea is 'success probability of binomial distribution' * 'lambda (= an expected value) of poisson distribution'. But you have to consider that the poisson model in count part never returns 0. I supposed your example data and predicted when width is c(23, 26, 29). library(pscl) data <- data.frame(y = c(8, 0, 3, 7), width = c(34.40, 22.50, 28.34, 32.22)) model <- hurdle(y ~ width, data = data) model # Count model coefficients (truncated poisson with log link): # (Intercept) width # -3.4520 0.1629 # model$coef$count[[1]] (left); model$coef$count[[2]] (right) # Zero hurdle model coefficients (binomial with logit link): # (Intercept) width # -198.851 7.809 # model$coef$zero[[1]] (left); model$coef$zero[[2]] (right) First, you calculate a success probability of a binomial model, phi_zero, (logistic equation). (I attached a taking log version because of predict() uses it.) phi_zero <- 1 / ( 1 + exp(-(model$coef$zero[[1]] + model$coef$zero[[2]] * c(23, 26, 29)))) # p0_zero <- log(phi_zero) Second, you calculate a param (= expected value) of a poisson model, mu, and the > 0 probability, phi_count. mu <- exp(model$coef$count[[1]] + model$coef$count[[2]] * c(23, 26, 29)) phi_count <- ppois(0, lambda = mu, lower.tail = F) # not 0 probability # p0_count <- ppois(0, lambda = mu, lower.tail = F, log.p = T) Finally, you integrate values of both model. phi <- phi_zero / phi_count # because there isn't 0 coming from poisson. rval <- phi * mu # logphi <- p0_zero - p0_count # rval2 <- exp(logphi + log(mu)) rval # [1] 8.051324e-09 2.429582e+00 3.674317e+00 And predict() takes a class hurdle as an argument (see ?predict.hurdle). predict(model, data.frame(width = c(23, 26, 29)), type = "response") # 1 2 3 # 8.051324e-09 2.429582e+00 3.674317e+00 # the same
Predicting future values with hurdle Poisson model The basic idea is 'success probability of binomial distribution' * 'lambda (= an expected value) of poisson distribution'. But you have to consider that the poisson model in count part never returns 0
47,199
Predicting future values with hurdle Poisson model
Hurdle models are also called two-part models. They are useful to implement count data with many zeros. In the first step the probability is computed, that the dependent variable is zero, or a positive number. This table should be interpreted just like a logit regression. Zero hurdle model coefficients (binomial with logit link): (Intercept) width -12.3508 0.4972 Now the algorithm is divided into zeros and ones. The zeros in our case are the cases in which the dependent variable takes on the value 0. The ones in our case are the cases in which the dependent variable takes on a positiv integer. Count model coefficients (truncated poisson with log link): (Intercept) width 0.58915 0.03386 Under the condition that the dependent variable is a positive integer (not zero), you can compute the value of width=34 in the following equation -12.3508 + 34 * 0.4972 To point it out in an example: You want to count the number of cigarettes adults are smoking per day in Germany. You decide to use a count data model, because the number of cigarettes is a count variable As there are many zeros in your dataset (most people in Germany don´t smoke at all) you stick to a hurdle Poisson modell. Now the zero hurdle model coefficients calculate whether the person is actually smoking or not smoking at all. Among those who smoke the Count model coefficient forecast how much cigarettes a smoker is going to smoke per day.
Predicting future values with hurdle Poisson model
Hurdle models are also called two-part models. They are useful to implement count data with many zeros. In the first step the probability is computed, that the dependent variable is zero, or a positiv
Predicting future values with hurdle Poisson model Hurdle models are also called two-part models. They are useful to implement count data with many zeros. In the first step the probability is computed, that the dependent variable is zero, or a positive number. This table should be interpreted just like a logit regression. Zero hurdle model coefficients (binomial with logit link): (Intercept) width -12.3508 0.4972 Now the algorithm is divided into zeros and ones. The zeros in our case are the cases in which the dependent variable takes on the value 0. The ones in our case are the cases in which the dependent variable takes on a positiv integer. Count model coefficients (truncated poisson with log link): (Intercept) width 0.58915 0.03386 Under the condition that the dependent variable is a positive integer (not zero), you can compute the value of width=34 in the following equation -12.3508 + 34 * 0.4972 To point it out in an example: You want to count the number of cigarettes adults are smoking per day in Germany. You decide to use a count data model, because the number of cigarettes is a count variable As there are many zeros in your dataset (most people in Germany don´t smoke at all) you stick to a hurdle Poisson modell. Now the zero hurdle model coefficients calculate whether the person is actually smoking or not smoking at all. Among those who smoke the Count model coefficient forecast how much cigarettes a smoker is going to smoke per day.
Predicting future values with hurdle Poisson model Hurdle models are also called two-part models. They are useful to implement count data with many zeros. In the first step the probability is computed, that the dependent variable is zero, or a positiv
47,200
Different ways of performing the Wilcoxon rank sum test and the interpretation of the resulting W-statistic
The Mann-Whitney U statistic counts 1 every time an observation in one sample is less than an observation in the other sample, across all cross-sample pairs of observations. However, it's arbitrary which sample is regarded as the first sample and which one is regarded as the second sample -- if you swap them, the sum of the statistics you got each time will be the total number of pairs ($U_1+U_2=n_1 n_2$) In your case that's 8 x 16 = 128 pairs, so if you swap the two samples and recalculate, the statistic will change from 10 to 128-10 = 118. Either way this is the same distance from the expected value under the null, $E(U) = n_1 n_2/2=64$. If you think in terms of the Wilcoxon rank sum statistic W (the sum of ranks in sample 1) there's also two possible values depending on which one you call sample 1. However, again they're related to each other in a similar way to the Mann-Whitney statistics above, and indeed they're also related to the Mann-Whitney statistics themselves (by a simple shift). (R calls its statistic W but subtracts the smallest possible sum of ranks, making it exactly equal to the U statistic.) The same thing happens when you do a t-test -- you get a different statistic when you look at $\bar{X}-\bar{Y}$ than when you look at $\bar{Y}-\bar{X}$ -- again again they're equally far from what's expected under the null case (in this case, the null case will have expected statistic 0.
Different ways of performing the Wilcoxon rank sum test and the interpretation of the resulting W-st
The Mann-Whitney U statistic counts 1 every time an observation in one sample is less than an observation in the other sample, across all cross-sample pairs of observations. However, it's arbitrary wh
Different ways of performing the Wilcoxon rank sum test and the interpretation of the resulting W-statistic The Mann-Whitney U statistic counts 1 every time an observation in one sample is less than an observation in the other sample, across all cross-sample pairs of observations. However, it's arbitrary which sample is regarded as the first sample and which one is regarded as the second sample -- if you swap them, the sum of the statistics you got each time will be the total number of pairs ($U_1+U_2=n_1 n_2$) In your case that's 8 x 16 = 128 pairs, so if you swap the two samples and recalculate, the statistic will change from 10 to 128-10 = 118. Either way this is the same distance from the expected value under the null, $E(U) = n_1 n_2/2=64$. If you think in terms of the Wilcoxon rank sum statistic W (the sum of ranks in sample 1) there's also two possible values depending on which one you call sample 1. However, again they're related to each other in a similar way to the Mann-Whitney statistics above, and indeed they're also related to the Mann-Whitney statistics themselves (by a simple shift). (R calls its statistic W but subtracts the smallest possible sum of ranks, making it exactly equal to the U statistic.) The same thing happens when you do a t-test -- you get a different statistic when you look at $\bar{X}-\bar{Y}$ than when you look at $\bar{Y}-\bar{X}$ -- again again they're equally far from what's expected under the null case (in this case, the null case will have expected statistic 0.
Different ways of performing the Wilcoxon rank sum test and the interpretation of the resulting W-st The Mann-Whitney U statistic counts 1 every time an observation in one sample is less than an observation in the other sample, across all cross-sample pairs of observations. However, it's arbitrary wh