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
|
|---|---|---|---|---|---|---|
48,001
|
Brewer's method for sampling with unequal probabilities with n>2
|
My reading of Brewer's procedure is as follows.
To sample the first unit, set $r=n$ and compute
$$
D_1 = \sum_{i=1}^N\frac{P_i(1-P_i)}{(1-nP_i)}
$$
Then sample the first unit with probability
$$P^{(1)}_i = \frac{P_i (1 - P_i)}{D_1 (1-nP_i)}$$Let the index of the first sampled unit be $I_1$.
To sample the second unit, set $r=n-1$ and compute
$$
D_2 = \sum_{i\in\{1,\ldots,N\}, i\notin \{ I_1 \} }\frac{P_i(1-P_i)}{(1-(n-1)P_i)}
$$
Then sample the second unit with probability
$$P^{(2)}_i = \frac{P_i (1 - P_i)}{D_2 (1-(n-1)P_i)}$$ Let the index of the first sampled unit be $I_2$.
etc.
To sample the $k$-th unit, set $r=n-k+1$ and compute
$$
D_k = \sum_{i\in\{1,\ldots,N\}, i\notin \{ I_1, \ldots, I_{k-1} \} }\frac{P_i(1-P_i)}{(1-(n-k+1)P_i)}
$$
Then sample the $k$-th unit with probability
$$P^{(k)}_i = \frac{P_i (1 - P_i)}{D_k (1-(n-k+1)P_i)}$$
B&H 83 refers to Brewer (1975) in Australian J of Statistics which I don't see any way of getting.
|
Brewer's method for sampling with unequal probabilities with n>2
|
My reading of Brewer's procedure is as follows.
To sample the first unit, set $r=n$ and compute
$$
D_1 = \sum_{i=1}^N\frac{P_i(1-P_i)}{(1-nP_i)}
$$
Then sample the first unit with probability
$$P^{
|
Brewer's method for sampling with unequal probabilities with n>2
My reading of Brewer's procedure is as follows.
To sample the first unit, set $r=n$ and compute
$$
D_1 = \sum_{i=1}^N\frac{P_i(1-P_i)}{(1-nP_i)}
$$
Then sample the first unit with probability
$$P^{(1)}_i = \frac{P_i (1 - P_i)}{D_1 (1-nP_i)}$$Let the index of the first sampled unit be $I_1$.
To sample the second unit, set $r=n-1$ and compute
$$
D_2 = \sum_{i\in\{1,\ldots,N\}, i\notin \{ I_1 \} }\frac{P_i(1-P_i)}{(1-(n-1)P_i)}
$$
Then sample the second unit with probability
$$P^{(2)}_i = \frac{P_i (1 - P_i)}{D_2 (1-(n-1)P_i)}$$ Let the index of the first sampled unit be $I_2$.
etc.
To sample the $k$-th unit, set $r=n-k+1$ and compute
$$
D_k = \sum_{i\in\{1,\ldots,N\}, i\notin \{ I_1, \ldots, I_{k-1} \} }\frac{P_i(1-P_i)}{(1-(n-k+1)P_i)}
$$
Then sample the $k$-th unit with probability
$$P^{(k)}_i = \frac{P_i (1 - P_i)}{D_k (1-(n-k+1)P_i)}$$
B&H 83 refers to Brewer (1975) in Australian J of Statistics which I don't see any way of getting.
|
Brewer's method for sampling with unequal probabilities with n>2
My reading of Brewer's procedure is as follows.
To sample the first unit, set $r=n$ and compute
$$
D_1 = \sum_{i=1}^N\frac{P_i(1-P_i)}{(1-nP_i)}
$$
Then sample the first unit with probability
$$P^{
|
48,002
|
Brewer's method for sampling with unequal probabilities with n>2
|
Update: August 19
I've now had a look at both Brewer's 1963 and 1975 articles. The 1975 method is indeed the generalization for (n>2) as Stas stated, with the same draw probabilities for n = 1 & 2.
This has been a very informative topic. I wondered why there were two versions of "Brewer's Method" in Roberto's question.}
The first formula Roberto gave is from "Brewer's Procedure" (Procedure 8) in Brewer and Hanif (1982). As Stas points out, it is based on Brewer (1975). However the second version that Roberto shows is that which Cochran (1977, p. 261) and the SAS manual also call "Brewer's Method" for n = 2. This turns out to be from Brewer (1963). It doesn't appear in Brewer & Hanif (1982) It does, as Procedure 8.
Durbin (1967, p.54) created another method for n = 2 (Method I). It is Procedure 9 in B & H. Durbin was unaware of Brewer (1963), and prior to publication, JNK Rao pointed out to Durbin that the pairwise inclusion probabilities are identical to those in Brewer's 1963 method.
Sampford (1967) extended Brewer's 1963 method to n>2. He gave several suggestions for implementation. That used by SAS is what Sampford called "method c" (p. 502). It is Procedure 11 in B & H, who call it the "Rao-Sampford Rejective" method. It is interesting because all draws are made with replacement; if a duplicate appears, the sample is rejected.
Sampford's method is easy to write down. Define
$$
\lambda_i = p_i/(1-n p_i)
$$
Draw the first unit with probability $p_i$.
Draw all others with probability $\lambda_j/\sum_k^N \lambda_k$, with replacement
If a drawing duplicates any previously selected item, reject the sample and begin again with Step 1.
The joint probabilities $\pi_{ij}$ of inclusion for elements $i$ and $j$ are needed to compute a proper variance estimate for the Horvitz-Thompson ($p_i$ weighted) estimator.. Sampford gives the formula for $\pi_{ij}$ on page 503 of his article and some examples of its calculation in his section 5. See also the SAS SURVEYSELECT manual, p. 8493.
References
Brewer, Kenneth RW 1963. A Model of Systematic Sampling with Unequal Probabilities. Australian Journal of Statistics 5, no. 1: 5-13.
Brewer, Kenneth RW (1975). A Simple Procedure For Sampling $\pi$pswor1. Australian Journal of Statistics, 17(3), 166-172.
Brewer, Kenneth RW, and Muhammad Hanif. 1982. Sampling with unequal probabilities (lecture notes in statistics).
Cochran, William G. 1977. Sampling Techniques. New York: Wiley.
Durbin, J. 1967. Design of multi-stage surveys for the estimation of sampling errors. Applied Statistics 16, no. 2: 152-164.
Sampford, MR. 1967. On sampling without replacement with unequal probabilities of selection. Biometrika 54, no. 3-4: 499-513.
SAS SURVEYSELECT MANUAL http://support.sas.com/documentation/onlinedoc/stat/131/surveyselect.pdf
|
Brewer's method for sampling with unequal probabilities with n>2
|
Update: August 19
I've now had a look at both Brewer's 1963 and 1975 articles. The 1975 method is indeed the generalization for (n>2) as Stas stated, with the same draw probabilities for n = 1 & 2.
T
|
Brewer's method for sampling with unequal probabilities with n>2
Update: August 19
I've now had a look at both Brewer's 1963 and 1975 articles. The 1975 method is indeed the generalization for (n>2) as Stas stated, with the same draw probabilities for n = 1 & 2.
This has been a very informative topic. I wondered why there were two versions of "Brewer's Method" in Roberto's question.}
The first formula Roberto gave is from "Brewer's Procedure" (Procedure 8) in Brewer and Hanif (1982). As Stas points out, it is based on Brewer (1975). However the second version that Roberto shows is that which Cochran (1977, p. 261) and the SAS manual also call "Brewer's Method" for n = 2. This turns out to be from Brewer (1963). It doesn't appear in Brewer & Hanif (1982) It does, as Procedure 8.
Durbin (1967, p.54) created another method for n = 2 (Method I). It is Procedure 9 in B & H. Durbin was unaware of Brewer (1963), and prior to publication, JNK Rao pointed out to Durbin that the pairwise inclusion probabilities are identical to those in Brewer's 1963 method.
Sampford (1967) extended Brewer's 1963 method to n>2. He gave several suggestions for implementation. That used by SAS is what Sampford called "method c" (p. 502). It is Procedure 11 in B & H, who call it the "Rao-Sampford Rejective" method. It is interesting because all draws are made with replacement; if a duplicate appears, the sample is rejected.
Sampford's method is easy to write down. Define
$$
\lambda_i = p_i/(1-n p_i)
$$
Draw the first unit with probability $p_i$.
Draw all others with probability $\lambda_j/\sum_k^N \lambda_k$, with replacement
If a drawing duplicates any previously selected item, reject the sample and begin again with Step 1.
The joint probabilities $\pi_{ij}$ of inclusion for elements $i$ and $j$ are needed to compute a proper variance estimate for the Horvitz-Thompson ($p_i$ weighted) estimator.. Sampford gives the formula for $\pi_{ij}$ on page 503 of his article and some examples of its calculation in his section 5. See also the SAS SURVEYSELECT manual, p. 8493.
References
Brewer, Kenneth RW 1963. A Model of Systematic Sampling with Unequal Probabilities. Australian Journal of Statistics 5, no. 1: 5-13.
Brewer, Kenneth RW (1975). A Simple Procedure For Sampling $\pi$pswor1. Australian Journal of Statistics, 17(3), 166-172.
Brewer, Kenneth RW, and Muhammad Hanif. 1982. Sampling with unequal probabilities (lecture notes in statistics).
Cochran, William G. 1977. Sampling Techniques. New York: Wiley.
Durbin, J. 1967. Design of multi-stage surveys for the estimation of sampling errors. Applied Statistics 16, no. 2: 152-164.
Sampford, MR. 1967. On sampling without replacement with unequal probabilities of selection. Biometrika 54, no. 3-4: 499-513.
SAS SURVEYSELECT MANUAL http://support.sas.com/documentation/onlinedoc/stat/131/surveyselect.pdf
|
Brewer's method for sampling with unequal probabilities with n>2
Update: August 19
I've now had a look at both Brewer's 1963 and 1975 articles. The 1975 method is indeed the generalization for (n>2) as Stas stated, with the same draw probabilities for n = 1 & 2.
T
|
48,003
|
which statistic should I use for inter-rater agreement on nominal data, multiple responses
|
You could use a chance-adjusted agreement index (e.g., Cohen's kappa or Scott's pi) for each category separately. Alternatively, you could use the following approach:
Kramer (1980) proposed a method for assessing inter-rater reliability for tasks in which raters could select multiple categories for each object of measurement. The intuition behind this method is to reframe the problem from one of classification to one of rank ordering. Thus, all selected categories are tied for first place and all non-selected categories are tied for second place. Chance-adjusted agreement can then be calculated using rank correlation coefficients or analysis of variance of the ranks. Naturally, this approach also allows multiple categories to be ranked by raters.
$$
\kappa_0 = \frac{\bar{P} - P_e}{1 - P_e} + \frac{1 - \bar{P}}{Nm_0(1 - P_e)}
$$
where $\bar{P}$ is the average proportion of concordant pairs out of all possible pairs of observations for each subject, $P_e=\sum_j p_j^2$ and $p_j$ is the overall proportion of observations in which response category $j$ was selected, $m_0$ is the number of observations per subject, and $N$ is the number of subjects. It can also be shown that, when only one category is selected, $\kappa_0$ asymptotically approaches Cohen's and Fleiss' kappa coefficients.
A clever solution, but not one that I've ever seen used in an article.
References
Kraemer, H. C. (1980). Extension of the kappa coefficient. Biometrics, 36(2), 207–16.
|
which statistic should I use for inter-rater agreement on nominal data, multiple responses
|
You could use a chance-adjusted agreement index (e.g., Cohen's kappa or Scott's pi) for each category separately. Alternatively, you could use the following approach:
Kramer (1980) proposed a method f
|
which statistic should I use for inter-rater agreement on nominal data, multiple responses
You could use a chance-adjusted agreement index (e.g., Cohen's kappa or Scott's pi) for each category separately. Alternatively, you could use the following approach:
Kramer (1980) proposed a method for assessing inter-rater reliability for tasks in which raters could select multiple categories for each object of measurement. The intuition behind this method is to reframe the problem from one of classification to one of rank ordering. Thus, all selected categories are tied for first place and all non-selected categories are tied for second place. Chance-adjusted agreement can then be calculated using rank correlation coefficients or analysis of variance of the ranks. Naturally, this approach also allows multiple categories to be ranked by raters.
$$
\kappa_0 = \frac{\bar{P} - P_e}{1 - P_e} + \frac{1 - \bar{P}}{Nm_0(1 - P_e)}
$$
where $\bar{P}$ is the average proportion of concordant pairs out of all possible pairs of observations for each subject, $P_e=\sum_j p_j^2$ and $p_j$ is the overall proportion of observations in which response category $j$ was selected, $m_0$ is the number of observations per subject, and $N$ is the number of subjects. It can also be shown that, when only one category is selected, $\kappa_0$ asymptotically approaches Cohen's and Fleiss' kappa coefficients.
A clever solution, but not one that I've ever seen used in an article.
References
Kraemer, H. C. (1980). Extension of the kappa coefficient. Biometrics, 36(2), 207–16.
|
which statistic should I use for inter-rater agreement on nominal data, multiple responses
You could use a chance-adjusted agreement index (e.g., Cohen's kappa or Scott's pi) for each category separately. Alternatively, you could use the following approach:
Kramer (1980) proposed a method f
|
48,004
|
What do the variables mean in the SVM objective function?
|
Those two formulae are different things:
$\frac{1}{2} w^T w + C \sum \xi_i$ is one form of the objective function, the function which is minimized over $w$, $b$, and $\xi_i$ (subject to certain constraints, which are where $b$ comes in) to find the best SVM solution.
Once you've found the model (defined by $w$ and $b$), predictions on new data $x$ are done by finding their distance from the decision hyperplane, $f(x) = w^T x + b$.
$w$ and $b$ define the decision hyperplane, which separates positives from negatives, $\{ x \mid w^T x + b = 0 \}$. So $w$ is perpindicular to that hyperplane. $|w_j|$ is also the weight of the corresponding feature dimension: if $w_j = 0$, that feature is ignored, and if $|w_j|$ is high, that feature is important to the SVM's decision (assuming all the features are scaled similarly).
SVMs are trained by maximizing the margin, which is the amount of space between the decision boundary and the nearest example. If your problem isn't linearly separable, though, there is no perfect decision boundary and so there's no "hard-margin" SVM solution. This is why the "soft-margin" SVM was introduced, which allows some points to be on the wrong side of the margin.
$\xi_i$ is the slack variable defining how much on the wrong side the $i$th training example is. If $\xi_i = 0$, the point was classified correctly and by enough of a margin; if it's between 0 and 1, the point was classified correctly but by less of a margin than the SVM wanted; if it's more than 1, the point was classified incorrectly. ($\xi_i$ isn't allowed to be negative.) Points with $\xi_i > 0$, as well as those with $\xi_i = 0$ closest to the decision boundary, are known as support vectors because they "support" the margin. These are important in a kernel SVM because they're the only ones you need to worry about when predicting on new data.
$C$ is a parameter of the problem that defines how soft the margin should be. As $C \to \infty$, you get a hard SVM; if $C = 0$, the SVM doesn't care about getting the right answer at all and will just choose $w = 0$. In practice, you usually try a few different values of $C$ and see how they perform.
This picture (source) illustrates the different variables, though it's for a kernel SVM; just say $\phi(x) = x$ and it'll be a linear SVM.
|
What do the variables mean in the SVM objective function?
|
Those two formulae are different things:
$\frac{1}{2} w^T w + C \sum \xi_i$ is one form of the objective function, the function which is minimized over $w$, $b$, and $\xi_i$ (subject to certain const
|
What do the variables mean in the SVM objective function?
Those two formulae are different things:
$\frac{1}{2} w^T w + C \sum \xi_i$ is one form of the objective function, the function which is minimized over $w$, $b$, and $\xi_i$ (subject to certain constraints, which are where $b$ comes in) to find the best SVM solution.
Once you've found the model (defined by $w$ and $b$), predictions on new data $x$ are done by finding their distance from the decision hyperplane, $f(x) = w^T x + b$.
$w$ and $b$ define the decision hyperplane, which separates positives from negatives, $\{ x \mid w^T x + b = 0 \}$. So $w$ is perpindicular to that hyperplane. $|w_j|$ is also the weight of the corresponding feature dimension: if $w_j = 0$, that feature is ignored, and if $|w_j|$ is high, that feature is important to the SVM's decision (assuming all the features are scaled similarly).
SVMs are trained by maximizing the margin, which is the amount of space between the decision boundary and the nearest example. If your problem isn't linearly separable, though, there is no perfect decision boundary and so there's no "hard-margin" SVM solution. This is why the "soft-margin" SVM was introduced, which allows some points to be on the wrong side of the margin.
$\xi_i$ is the slack variable defining how much on the wrong side the $i$th training example is. If $\xi_i = 0$, the point was classified correctly and by enough of a margin; if it's between 0 and 1, the point was classified correctly but by less of a margin than the SVM wanted; if it's more than 1, the point was classified incorrectly. ($\xi_i$ isn't allowed to be negative.) Points with $\xi_i > 0$, as well as those with $\xi_i = 0$ closest to the decision boundary, are known as support vectors because they "support" the margin. These are important in a kernel SVM because they're the only ones you need to worry about when predicting on new data.
$C$ is a parameter of the problem that defines how soft the margin should be. As $C \to \infty$, you get a hard SVM; if $C = 0$, the SVM doesn't care about getting the right answer at all and will just choose $w = 0$. In practice, you usually try a few different values of $C$ and see how they perform.
This picture (source) illustrates the different variables, though it's for a kernel SVM; just say $\phi(x) = x$ and it'll be a linear SVM.
|
What do the variables mean in the SVM objective function?
Those two formulae are different things:
$\frac{1}{2} w^T w + C \sum \xi_i$ is one form of the objective function, the function which is minimized over $w$, $b$, and $\xi_i$ (subject to certain const
|
48,005
|
Is binary hypothesis testing a better statistical term than A/B testing?
|
The Wikipedia article has accurate information about A/B testing; binary hypothesis testing is another name for A/B testing. A/B testing and split testing are the most widely accepted terms in the business and marketing community. The exact origins of A/B testing are not well known but can be traced back to Google during the turn of the millennium. "Google engineers ran their first A/B test at the turn of the millennium to determine the optimum number of results to display on a search engine results page."
|
Is binary hypothesis testing a better statistical term than A/B testing?
|
The Wikipedia article has accurate information about A/B testing; binary hypothesis testing is another name for A/B testing. A/B testing and split testing are the most widely accepted terms in the bu
|
Is binary hypothesis testing a better statistical term than A/B testing?
The Wikipedia article has accurate information about A/B testing; binary hypothesis testing is another name for A/B testing. A/B testing and split testing are the most widely accepted terms in the business and marketing community. The exact origins of A/B testing are not well known but can be traced back to Google during the turn of the millennium. "Google engineers ran their first A/B test at the turn of the millennium to determine the optimum number of results to display on a search engine results page."
|
Is binary hypothesis testing a better statistical term than A/B testing?
The Wikipedia article has accurate information about A/B testing; binary hypothesis testing is another name for A/B testing. A/B testing and split testing are the most widely accepted terms in the bu
|
48,006
|
Is binary hypothesis testing a better statistical term than A/B testing?
|
"Binary hypothesis testing" is hypothesis testing when one wants to decide between two hypotheses.
"Two-sample hypothesis testing" is what is known colloquially as A/B testing.
"Paired hypothesis testing" when you compare the same sample before and after an event to find if it had an effect. Similar to A/B testing but not A/B testing.
|
Is binary hypothesis testing a better statistical term than A/B testing?
|
"Binary hypothesis testing" is hypothesis testing when one wants to decide between two hypotheses.
"Two-sample hypothesis testing" is what is known colloquially as A/B testing.
"Paired hypothesis test
|
Is binary hypothesis testing a better statistical term than A/B testing?
"Binary hypothesis testing" is hypothesis testing when one wants to decide between two hypotheses.
"Two-sample hypothesis testing" is what is known colloquially as A/B testing.
"Paired hypothesis testing" when you compare the same sample before and after an event to find if it had an effect. Similar to A/B testing but not A/B testing.
|
Is binary hypothesis testing a better statistical term than A/B testing?
"Binary hypothesis testing" is hypothesis testing when one wants to decide between two hypotheses.
"Two-sample hypothesis testing" is what is known colloquially as A/B testing.
"Paired hypothesis test
|
48,007
|
Is binary hypothesis testing a better statistical term than A/B testing?
|
I agree with the other very good answers. I think, it is mostly engineering backgrounds that prefer the term A/B test and the last years it has become a quite hot term especially within the context of web sites optimisation.
Have in mind that except A/B test you may encounter these terms:
A/B/C tests where you assess a control cohort against 2 alternative cohorts.
A/A tests where you empirically assess the quality and robustness of the statistical test against Type-I errors (the test should return that there's no difference in cohorts).
|
Is binary hypothesis testing a better statistical term than A/B testing?
|
I agree with the other very good answers. I think, it is mostly engineering backgrounds that prefer the term A/B test and the last years it has become a quite hot term especially within the context of
|
Is binary hypothesis testing a better statistical term than A/B testing?
I agree with the other very good answers. I think, it is mostly engineering backgrounds that prefer the term A/B test and the last years it has become a quite hot term especially within the context of web sites optimisation.
Have in mind that except A/B test you may encounter these terms:
A/B/C tests where you assess a control cohort against 2 alternative cohorts.
A/A tests where you empirically assess the quality and robustness of the statistical test against Type-I errors (the test should return that there's no difference in cohorts).
|
Is binary hypothesis testing a better statistical term than A/B testing?
I agree with the other very good answers. I think, it is mostly engineering backgrounds that prefer the term A/B test and the last years it has become a quite hot term especially within the context of
|
48,008
|
How to get percentiles from empirical density in R?
|
The command density(), although very useful for a quick inspection of the KDE, is also very restrictive since it only returns the values on a grid. I prefer to code my own KDE (usually with a Gaussian kernel). This can be obtained as shown below (1-line code):
rm(list=ls())
# Constructing your own KDE
set.seed(123)
sample = rnorm(1000,10,1)
# Bandwidth used by density()
hT = bw.nrd0(sample)
kde <- Vectorize(function(x) mean(dnorm((x-sample)/hT)/hT))
# Comparison
plot(density(sample))
curve(kde,6,13,add=T,col="red")
The corresponding nonparametric estimator of the CDF can be obtained as follows:
# Obtaining the corresponding kernel distribution estimator
KDE <- Vectorize(function(x) mean(pnorm((x-sample)/hT)))
curve(KDE,6,13,col="blue")
Using these functions, you can manually approximate the percentiles if you can provide an interval where the quantile of interest lies:
# Manual calculation of the percentile (requires the probability and an interval containing the quantile)
QKDE <- function(p,Interval){
tempf <- function(t) KDE(t)-p
return(uniroot(tempf,Interval)$root )
}
QKDE(0.5,c(8,12))
This may not be the most efficient way, but it works, and it is fast and accurate. I hope this helps.
|
How to get percentiles from empirical density in R?
|
The command density(), although very useful for a quick inspection of the KDE, is also very restrictive since it only returns the values on a grid. I prefer to code my own KDE (usually with a Gaussian
|
How to get percentiles from empirical density in R?
The command density(), although very useful for a quick inspection of the KDE, is also very restrictive since it only returns the values on a grid. I prefer to code my own KDE (usually with a Gaussian kernel). This can be obtained as shown below (1-line code):
rm(list=ls())
# Constructing your own KDE
set.seed(123)
sample = rnorm(1000,10,1)
# Bandwidth used by density()
hT = bw.nrd0(sample)
kde <- Vectorize(function(x) mean(dnorm((x-sample)/hT)/hT))
# Comparison
plot(density(sample))
curve(kde,6,13,add=T,col="red")
The corresponding nonparametric estimator of the CDF can be obtained as follows:
# Obtaining the corresponding kernel distribution estimator
KDE <- Vectorize(function(x) mean(pnorm((x-sample)/hT)))
curve(KDE,6,13,col="blue")
Using these functions, you can manually approximate the percentiles if you can provide an interval where the quantile of interest lies:
# Manual calculation of the percentile (requires the probability and an interval containing the quantile)
QKDE <- function(p,Interval){
tempf <- function(t) KDE(t)-p
return(uniroot(tempf,Interval)$root )
}
QKDE(0.5,c(8,12))
This may not be the most efficient way, but it works, and it is fast and accurate. I hope this helps.
|
How to get percentiles from empirical density in R?
The command density(), although very useful for a quick inspection of the KDE, is also very restrictive since it only returns the values on a grid. I prefer to code my own KDE (usually with a Gaussian
|
48,009
|
How to get percentiles from empirical density in R?
|
Why re-invent the wheel? I advise you to use the ewcdf function in the spatstat library. If I understand your question correctly, it does exactly what you want:
library(spatstat)
x <- rnorm(100) #data
w <- runif(100) #weights
a1<-ewcdf(x,w) #empricial *weighted* cdf and quantile function
quantile(a1,.2) #calls quantile.ecdf()
#which is different from quantile because of the effects of the weights:
quantile(x,.2)
|
How to get percentiles from empirical density in R?
|
Why re-invent the wheel? I advise you to use the ewcdf function in the spatstat library. If I understand your question correctly, it does exactly what you want:
library(spatstat)
x <- rnorm(100)
|
How to get percentiles from empirical density in R?
Why re-invent the wheel? I advise you to use the ewcdf function in the spatstat library. If I understand your question correctly, it does exactly what you want:
library(spatstat)
x <- rnorm(100) #data
w <- runif(100) #weights
a1<-ewcdf(x,w) #empricial *weighted* cdf and quantile function
quantile(a1,.2) #calls quantile.ecdf()
#which is different from quantile because of the effects of the weights:
quantile(x,.2)
|
How to get percentiles from empirical density in R?
Why re-invent the wheel? I advise you to use the ewcdf function in the spatstat library. If I understand your question correctly, it does exactly what you want:
library(spatstat)
x <- rnorm(100)
|
48,010
|
What are some methods for generating simulated time series data for use in modeling?
|
One possibility is to fit a time series model to the data you are interested in. Then you can resample the residuals from the fitted model and use them to simulate the data. For example, you can fit an ARIMA model, resample the residuals and then generate new data from the fitted ARIMA model. Instead of generating the innovations from a Gaussian distribution you would use the resampled residuals.
You can find further details searching in the literature about bootstrapping time series. See for example this post and the references mentioned there.
You should take care of events that you mention such as drought years or other particular events. Those events may be exceptional for a particular year or may be cyclical patterns observed in the data. You should choose an appropriate intervention variable to capture these effects in the model. Alternatively, you may fit a model for each subsample where the data remain relatively stable with no breaks or changes in the variance.
|
What are some methods for generating simulated time series data for use in modeling?
|
One possibility is to fit a time series model to the data you are interested in. Then you can resample the residuals from the fitted model and use them to simulate the data. For example, you can fit a
|
What are some methods for generating simulated time series data for use in modeling?
One possibility is to fit a time series model to the data you are interested in. Then you can resample the residuals from the fitted model and use them to simulate the data. For example, you can fit an ARIMA model, resample the residuals and then generate new data from the fitted ARIMA model. Instead of generating the innovations from a Gaussian distribution you would use the resampled residuals.
You can find further details searching in the literature about bootstrapping time series. See for example this post and the references mentioned there.
You should take care of events that you mention such as drought years or other particular events. Those events may be exceptional for a particular year or may be cyclical patterns observed in the data. You should choose an appropriate intervention variable to capture these effects in the model. Alternatively, you may fit a model for each subsample where the data remain relatively stable with no breaks or changes in the variance.
|
What are some methods for generating simulated time series data for use in modeling?
One possibility is to fit a time series model to the data you are interested in. Then you can resample the residuals from the fitted model and use them to simulate the data. For example, you can fit a
|
48,011
|
What are some methods for generating simulated time series data for use in modeling?
|
I suggest you first determine that you wanna predict for one day, one month or one year, next think about situation that effect in your goal variable, and if you could use variable from external database like temperature, and as our friend says use time-series models. I think preparation data is more important modeling. don't forget that do smoothing on your data.
|
What are some methods for generating simulated time series data for use in modeling?
|
I suggest you first determine that you wanna predict for one day, one month or one year, next think about situation that effect in your goal variable, and if you could use variable from external datab
|
What are some methods for generating simulated time series data for use in modeling?
I suggest you first determine that you wanna predict for one day, one month or one year, next think about situation that effect in your goal variable, and if you could use variable from external database like temperature, and as our friend says use time-series models. I think preparation data is more important modeling. don't forget that do smoothing on your data.
|
What are some methods for generating simulated time series data for use in modeling?
I suggest you first determine that you wanna predict for one day, one month or one year, next think about situation that effect in your goal variable, and if you could use variable from external datab
|
48,012
|
Ratio of correlated sample variances (gamma distributed)
|
If we assume that the underlying normals are jointly normal, then the result is very simple.
This answer uses results from A. H. Joarder (2007/2009), Moments of the product and ratio of two correlated chi-square variables (open access).
We have
$$r\equiv \frac{s_y^2}{s_x^2} = \frac {\sigma^2_y}{\sigma^2_x}\frac{(n-1)s_y^2/\sigma^2_y}{(n-1)s_x^2/\sigma^2_x}= \frac {\sigma^2_y}{\sigma^2_x} \frac {U_y}{U_x},\;\; U_y \sim \mathcal \chi^2_{(n-1)},\;\; U_x \sim \mathcal \chi^2_{(n-1)}$$
So
$$E(r) = \frac {\sigma^2_y}{\sigma^2_x} E\left(\frac {U_y}{U_x}\right)$$
In other words, we need the expected value (first raw moment) of the ratio of two correlated chi-squares with equal degrees of freedom.
Note that standardizing the normals does not affect their correlation coefficient, denote it simply $\rho \in (-1,1)$. Then according to the above paper (which references another paper), $$\operatorname{Corr}(U_y, U_x) = \rho^2$$
and by Corollary 3.8 p. 590, if $n-1 >2$ (i.e we need a sample size at least equal to $4$) we have
$$E\left(\frac {U_y}{U_x}\right) = \frac {n-1 -2\rho^2}{n-1-2} = \frac {n-1 -2\rho^2}{n-3}$$
So
$$E(r) = \frac {\sigma^2_y}{\sigma^2_x}\frac {n-1 -2\rho^2}{n-3}$$
The paper contains also expressions for the next three raw moments, increasing slightly the requirement on the size of the sample. Results appear to depend on the two chi-squares having the same degrees of freedom.
|
Ratio of correlated sample variances (gamma distributed)
|
If we assume that the underlying normals are jointly normal, then the result is very simple.
This answer uses results from A. H. Joarder (2007/2009), Moments of the product and ratio of two correlated
|
Ratio of correlated sample variances (gamma distributed)
If we assume that the underlying normals are jointly normal, then the result is very simple.
This answer uses results from A. H. Joarder (2007/2009), Moments of the product and ratio of two correlated chi-square variables (open access).
We have
$$r\equiv \frac{s_y^2}{s_x^2} = \frac {\sigma^2_y}{\sigma^2_x}\frac{(n-1)s_y^2/\sigma^2_y}{(n-1)s_x^2/\sigma^2_x}= \frac {\sigma^2_y}{\sigma^2_x} \frac {U_y}{U_x},\;\; U_y \sim \mathcal \chi^2_{(n-1)},\;\; U_x \sim \mathcal \chi^2_{(n-1)}$$
So
$$E(r) = \frac {\sigma^2_y}{\sigma^2_x} E\left(\frac {U_y}{U_x}\right)$$
In other words, we need the expected value (first raw moment) of the ratio of two correlated chi-squares with equal degrees of freedom.
Note that standardizing the normals does not affect their correlation coefficient, denote it simply $\rho \in (-1,1)$. Then according to the above paper (which references another paper), $$\operatorname{Corr}(U_y, U_x) = \rho^2$$
and by Corollary 3.8 p. 590, if $n-1 >2$ (i.e we need a sample size at least equal to $4$) we have
$$E\left(\frac {U_y}{U_x}\right) = \frac {n-1 -2\rho^2}{n-1-2} = \frac {n-1 -2\rho^2}{n-3}$$
So
$$E(r) = \frac {\sigma^2_y}{\sigma^2_x}\frac {n-1 -2\rho^2}{n-3}$$
The paper contains also expressions for the next three raw moments, increasing slightly the requirement on the size of the sample. Results appear to depend on the two chi-squares having the same degrees of freedom.
|
Ratio of correlated sample variances (gamma distributed)
If we assume that the underlying normals are jointly normal, then the result is very simple.
This answer uses results from A. H. Joarder (2007/2009), Moments of the product and ratio of two correlated
|
48,013
|
Product of Gamma by Beta rv
|
Given:
$X \sim \text{Beta}(a,b)$ with pdf $f(x)$:
$Y \sim \text{Gamma}(k,\theta)$ with pdf $g(y)$:
Solution: Then, the pdf of the product $Z = X Y$ can be automatically derived via:
where I am using the TransformProduct function from the mathStatica package for Mathematica, and where Hypergeometric1F1 denotes the Kummer confluent hypergeometric function: http://reference.wolfram.com/mathematica/ref/Hypergeometric1F1.html
This formulation works nicely, except for certain combinations of integer values of the parameters (indeterminate - please see discussion below). [If say $a = 4$ and $k = 3$, just enter $k$ as 3.0000001 and it will side-step the issue.]
Quick Monte Carlo check
It is always a good idea to check symbolic solutions with Monte Carlo methods. Here is a quick comparison of the exact theoretical solution derived above (dashed RED curve) against an empirical Monte Carlo simulation of the pdf of the product (squiggly BLUE), when ${a = 3, b = 6, k = 2.2, \theta = 5}$
All done.
|
Product of Gamma by Beta rv
|
Given:
$X \sim \text{Beta}(a,b)$ with pdf $f(x)$:
$Y \sim \text{Gamma}(k,\theta)$ with pdf $g(y)$:
Solution: Then, the pdf of the product $Z = X Y$ can be automatically derived via:
where I am
|
Product of Gamma by Beta rv
Given:
$X \sim \text{Beta}(a,b)$ with pdf $f(x)$:
$Y \sim \text{Gamma}(k,\theta)$ with pdf $g(y)$:
Solution: Then, the pdf of the product $Z = X Y$ can be automatically derived via:
where I am using the TransformProduct function from the mathStatica package for Mathematica, and where Hypergeometric1F1 denotes the Kummer confluent hypergeometric function: http://reference.wolfram.com/mathematica/ref/Hypergeometric1F1.html
This formulation works nicely, except for certain combinations of integer values of the parameters (indeterminate - please see discussion below). [If say $a = 4$ and $k = 3$, just enter $k$ as 3.0000001 and it will side-step the issue.]
Quick Monte Carlo check
It is always a good idea to check symbolic solutions with Monte Carlo methods. Here is a quick comparison of the exact theoretical solution derived above (dashed RED curve) against an empirical Monte Carlo simulation of the pdf of the product (squiggly BLUE), when ${a = 3, b = 6, k = 2.2, \theta = 5}$
All done.
|
Product of Gamma by Beta rv
Given:
$X \sim \text{Beta}(a,b)$ with pdf $f(x)$:
$Y \sim \text{Gamma}(k,\theta)$ with pdf $g(y)$:
Solution: Then, the pdf of the product $Z = X Y$ can be automatically derived via:
where I am
|
48,014
|
Product of Gamma by Beta rv
|
This distribution is called the Gamma-Inverse Beta distribution in this paper. It is available in the R package brr.
nsims <- 1e6
alpha <- 3
beta <- 5
K <- 6
theta <- 4
sims <- rgamma(nsims, shape = K, rate = theta) * rbeta(nsims, alpha, beta)
plot(density(sims, to=3))
curve(brr::dGIB(x, K, beta, alpha, theta), # note that alpha and beta are swapped
add = TRUE, col = "red", lwd = 2, lty = "dashed")
Here is its density function:
> brr::dGIB
function (x, a, alpha, beta, rho)
{
exp(lnpoch(beta, alpha) - lngamma(a)) * rho^a * x^(a - 1) *
exp(-rho * x) * hyperg_U(alpha, a - beta + 1, rho * x)
}
$$
\frac{{(\beta)}_\alpha}{\Gamma(a)}\rho^a x^{a-1} \exp(-\rho x) U(\alpha, a-\beta+1, \rho x), \qquad x > 0
$$
where $U$ is the Tricomi hypergeometric function.
There's a generalization of this distribution to random matrices. It is a type II confluent hypergeometric function distribution of kind two (see Gupta & Nagar's book Matrix variate distributions).
library(matrixsampling)
sims2 <- rmatrixCHIIkind2(20000, nu = K, alpha = beta,
beta = K+1-alpha, theta = 1/theta, p = 1)
lines(density(sims2, to=3), col = "orange", lwd = 2, lty = "dashed")
The mgf is given in Gupta & Nagar's book. With your notations, this gives
$$
\textrm{mgf}(t) = {}_2\!F_1(\alpha, K, \alpha+\beta, t/\theta).
$$
library(gsl)
hyperg_2F1(alpha, K, beta+alpha, 0.2/theta)
## [1] 1.121871
mean(exp(0.2*sims))
## [1] 1.121846
|
Product of Gamma by Beta rv
|
This distribution is called the Gamma-Inverse Beta distribution in this paper. It is available in the R package brr.
nsims <- 1e6
alpha <- 3
beta <- 5
K <- 6
theta <- 4
sims <- rgamma(nsims, shape =
|
Product of Gamma by Beta rv
This distribution is called the Gamma-Inverse Beta distribution in this paper. It is available in the R package brr.
nsims <- 1e6
alpha <- 3
beta <- 5
K <- 6
theta <- 4
sims <- rgamma(nsims, shape = K, rate = theta) * rbeta(nsims, alpha, beta)
plot(density(sims, to=3))
curve(brr::dGIB(x, K, beta, alpha, theta), # note that alpha and beta are swapped
add = TRUE, col = "red", lwd = 2, lty = "dashed")
Here is its density function:
> brr::dGIB
function (x, a, alpha, beta, rho)
{
exp(lnpoch(beta, alpha) - lngamma(a)) * rho^a * x^(a - 1) *
exp(-rho * x) * hyperg_U(alpha, a - beta + 1, rho * x)
}
$$
\frac{{(\beta)}_\alpha}{\Gamma(a)}\rho^a x^{a-1} \exp(-\rho x) U(\alpha, a-\beta+1, \rho x), \qquad x > 0
$$
where $U$ is the Tricomi hypergeometric function.
There's a generalization of this distribution to random matrices. It is a type II confluent hypergeometric function distribution of kind two (see Gupta & Nagar's book Matrix variate distributions).
library(matrixsampling)
sims2 <- rmatrixCHIIkind2(20000, nu = K, alpha = beta,
beta = K+1-alpha, theta = 1/theta, p = 1)
lines(density(sims2, to=3), col = "orange", lwd = 2, lty = "dashed")
The mgf is given in Gupta & Nagar's book. With your notations, this gives
$$
\textrm{mgf}(t) = {}_2\!F_1(\alpha, K, \alpha+\beta, t/\theta).
$$
library(gsl)
hyperg_2F1(alpha, K, beta+alpha, 0.2/theta)
## [1] 1.121871
mean(exp(0.2*sims))
## [1] 1.121846
|
Product of Gamma by Beta rv
This distribution is called the Gamma-Inverse Beta distribution in this paper. It is available in the R package brr.
nsims <- 1e6
alpha <- 3
beta <- 5
K <- 6
theta <- 4
sims <- rgamma(nsims, shape =
|
48,015
|
What's the difference between autoencoders and deep autoencoders?
|
Autoencoder is basically a technique to find fundamental features representing the input images. A simple autoencoder will have 1 hidden layer between the input and output, wheras a deep autoencoder will have multiple hidden layers (the number of hidden layer depends on your configuration). Refering the first figure below (deep autoencoder), the demsion of the input image (e.g. size=100x100 pixels) is reduced to 2000,1000,500,30(e.g. size = 10x3) respectively; this part is called encoder. Then, the reduced coder layer is reconstruced back to the original image; this part is called the decoder. Typically, you may use the features produced in any layer of the encoder (i.e. 2000,1000,500, or 30) for building a classifier (e.g. softmax classifier). And this classifier performance is generally better than a classifier using original features without any decoding.
You can imagine each hidden layer represent some form of fundamental features that construct the next layer of features. (See below figure; the first layer learn the colour formation; the second layer learns the edges; the third layer learn different parts of face; the fourth layer learn combination of parts to represent face)
References:
Jones, N. (2014). Computer science: The learning machines. Nature, 505(7482), 146-148. doi:10.1038/505146a
Hinton, G., & Salakhutdinov, R. (2006). Reducing the dimensionality of data with neural networks. Science, 313(5786), 504--507.
A good tutorial learning deep learning:
http://ufldl.stanford.edu/wiki/index.php/UFLDL_Tutorial
A github for sample solutions for the UFLDL tutorial:
https://github.com/johnny5550822/Ho-UFLDL-tutorial
|
What's the difference between autoencoders and deep autoencoders?
|
Autoencoder is basically a technique to find fundamental features representing the input images. A simple autoencoder will have 1 hidden layer between the input and output, wheras a deep autoencoder w
|
What's the difference between autoencoders and deep autoencoders?
Autoencoder is basically a technique to find fundamental features representing the input images. A simple autoencoder will have 1 hidden layer between the input and output, wheras a deep autoencoder will have multiple hidden layers (the number of hidden layer depends on your configuration). Refering the first figure below (deep autoencoder), the demsion of the input image (e.g. size=100x100 pixels) is reduced to 2000,1000,500,30(e.g. size = 10x3) respectively; this part is called encoder. Then, the reduced coder layer is reconstruced back to the original image; this part is called the decoder. Typically, you may use the features produced in any layer of the encoder (i.e. 2000,1000,500, or 30) for building a classifier (e.g. softmax classifier). And this classifier performance is generally better than a classifier using original features without any decoding.
You can imagine each hidden layer represent some form of fundamental features that construct the next layer of features. (See below figure; the first layer learn the colour formation; the second layer learns the edges; the third layer learn different parts of face; the fourth layer learn combination of parts to represent face)
References:
Jones, N. (2014). Computer science: The learning machines. Nature, 505(7482), 146-148. doi:10.1038/505146a
Hinton, G., & Salakhutdinov, R. (2006). Reducing the dimensionality of data with neural networks. Science, 313(5786), 504--507.
A good tutorial learning deep learning:
http://ufldl.stanford.edu/wiki/index.php/UFLDL_Tutorial
A github for sample solutions for the UFLDL tutorial:
https://github.com/johnny5550822/Ho-UFLDL-tutorial
|
What's the difference between autoencoders and deep autoencoders?
Autoencoder is basically a technique to find fundamental features representing the input images. A simple autoencoder will have 1 hidden layer between the input and output, wheras a deep autoencoder w
|
48,016
|
How to transform an accuracy distribution for a violin plot
|
I have various takes on this.
Don't expect too much from transformation. I read your results as saying that the upper quartile (**not* usually called the first quartile) is 1; hence >25% of the values tie at 1 and you have a spike in the distribution. Any one-to-one transformation will inevitably map a spike to a spike. There's no escape from that. (Also, see #4: I don't view this kind of visualization as a good idea in the presence of a spike, but there is some statistical taste and judgment in that view.) [EDIT: The original was edited to stating that it's the lower quartile that is 1. This intensifies #1 mightily.]
Log transformation is definitely inappropriate as it will stretch your tail out further. Its inverse, say exp(), won't help much here as it is too near linear over this narrow range. Some high power, say fourth or higher, should make the distribution a little more symmetric, but can't solve #1.
Why do you think you need a transformation? The results are as they are. Thinking you need a transformation often arises from a misconception that (e.g.) data must be nearly normal to do much with them, but that's an exaggeration. If you spell out analyses you plan downstream from this, there should be better advice forthcoming.
I don't find the visualizations at all compelling, if only because it's hard to read off the precise differences between the distributions. I would try very fine binning, e.g. intervals of 0.01, and then look at histograms using a log frequency scale. In my view, an honest visualization would show spikes as such, not smooth over them.
|
How to transform an accuracy distribution for a violin plot
|
I have various takes on this.
Don't expect too much from transformation. I read your results as saying that the upper quartile (**not* usually called the first quartile) is 1; hence >25% of the valu
|
How to transform an accuracy distribution for a violin plot
I have various takes on this.
Don't expect too much from transformation. I read your results as saying that the upper quartile (**not* usually called the first quartile) is 1; hence >25% of the values tie at 1 and you have a spike in the distribution. Any one-to-one transformation will inevitably map a spike to a spike. There's no escape from that. (Also, see #4: I don't view this kind of visualization as a good idea in the presence of a spike, but there is some statistical taste and judgment in that view.) [EDIT: The original was edited to stating that it's the lower quartile that is 1. This intensifies #1 mightily.]
Log transformation is definitely inappropriate as it will stretch your tail out further. Its inverse, say exp(), won't help much here as it is too near linear over this narrow range. Some high power, say fourth or higher, should make the distribution a little more symmetric, but can't solve #1.
Why do you think you need a transformation? The results are as they are. Thinking you need a transformation often arises from a misconception that (e.g.) data must be nearly normal to do much with them, but that's an exaggeration. If you spell out analyses you plan downstream from this, there should be better advice forthcoming.
I don't find the visualizations at all compelling, if only because it's hard to read off the precise differences between the distributions. I would try very fine binning, e.g. intervals of 0.01, and then look at histograms using a log frequency scale. In my view, an honest visualization would show spikes as such, not smooth over them.
|
How to transform an accuracy distribution for a violin plot
I have various takes on this.
Don't expect too much from transformation. I read your results as saying that the upper quartile (**not* usually called the first quartile) is 1; hence >25% of the valu
|
48,017
|
Statistics of 7 game playoff series
|
For a team to win [the series] in game N, they must have won exactly 3 of the first N-1 games. For game seven, there are $\binom{6}{3} = 20$ ways to do that. There are 2 possible outcomes for game seven, and 20 possible combinations of wins for each of the teams that can win, so 40 possible outcomes. For an N-game series a best-of-seven series to end in N games, the number of possibilities is $2 \binom{N-1}{3}$.
Indeed the order doesn't matter, if you're already given the number of games played. Only the last game matters, and the winner must have 3 previous wins, in any order.
|
Statistics of 7 game playoff series
|
For a team to win [the series] in game N, they must have won exactly 3 of the first N-1 games. For game seven, there are $\binom{6}{3} = 20$ ways to do that. There are 2 possible outcomes for game sev
|
Statistics of 7 game playoff series
For a team to win [the series] in game N, they must have won exactly 3 of the first N-1 games. For game seven, there are $\binom{6}{3} = 20$ ways to do that. There are 2 possible outcomes for game seven, and 20 possible combinations of wins for each of the teams that can win, so 40 possible outcomes. For an N-game series a best-of-seven series to end in N games, the number of possibilities is $2 \binom{N-1}{3}$.
Indeed the order doesn't matter, if you're already given the number of games played. Only the last game matters, and the winner must have 3 previous wins, in any order.
|
Statistics of 7 game playoff series
For a team to win [the series] in game N, they must have won exactly 3 of the first N-1 games. For game seven, there are $\binom{6}{3} = 20$ ways to do that. There are 2 possible outcomes for game sev
|
48,018
|
Statistics of 7 game playoff series
|
If p is the probability of winning a single game, and N is the number of games one needs to win the series, then the probability "P" of winning the series is given by:
$$
P = \frac{p^N}{\left(N-1\right)!}\cdot\sum_{i=0}^{N-1}\left[\left(\prod_{j=1}^{N-1}\left(i+j\right)\right)(1-p)^i\right]
$$
Think of the way a game plays out with points going to each player as a path. Each path that leads to a win has a probability given by the product of the probabilities for the number of wins and losses. The following image tries to illustrate an example.
The pattern for the coefficients is given by (i+N-1) choose (i) where "i" is the number of points the opponent has scored and N is the number of points for the win.
Remember the choose formula is:
$$
nCr = \frac{n!}{r!\left(n-r\right)!}
$$
so for us:
$$
nCr = \frac{\left(i+N-1\right)!}{i!\left(N-1\right)!}=\frac{\left(i+1\right)...\left(i+N-1\right)}{\left(N-1\right)!}=\frac{\prod_{j=1}^{N-1}\left(i+j\right)}{\left(N-1\right)!}
$$
|
Statistics of 7 game playoff series
|
If p is the probability of winning a single game, and N is the number of games one needs to win the series, then the probability "P" of winning the series is given by:
$$
P = \frac{p^N}{\left(N-1\righ
|
Statistics of 7 game playoff series
If p is the probability of winning a single game, and N is the number of games one needs to win the series, then the probability "P" of winning the series is given by:
$$
P = \frac{p^N}{\left(N-1\right)!}\cdot\sum_{i=0}^{N-1}\left[\left(\prod_{j=1}^{N-1}\left(i+j\right)\right)(1-p)^i\right]
$$
Think of the way a game plays out with points going to each player as a path. Each path that leads to a win has a probability given by the product of the probabilities for the number of wins and losses. The following image tries to illustrate an example.
The pattern for the coefficients is given by (i+N-1) choose (i) where "i" is the number of points the opponent has scored and N is the number of points for the win.
Remember the choose formula is:
$$
nCr = \frac{n!}{r!\left(n-r\right)!}
$$
so for us:
$$
nCr = \frac{\left(i+N-1\right)!}{i!\left(N-1\right)!}=\frac{\left(i+1\right)...\left(i+N-1\right)}{\left(N-1\right)!}=\frac{\prod_{j=1}^{N-1}\left(i+j\right)}{\left(N-1\right)!}
$$
|
Statistics of 7 game playoff series
If p is the probability of winning a single game, and N is the number of games one needs to win the series, then the probability "P" of winning the series is given by:
$$
P = \frac{p^N}{\left(N-1\righ
|
48,019
|
Statistics of 7 game playoff series
|
An alternate way to look at would be a binomial distribution: You need x=3 (exactly 3 successes) in n = 6 (trails) , so if the probability of winning a game is .5 (both teams equally likely) , binomial would say:
P(x=3) = 6C3 * (.5)^3 * (.5)^3 = .3125
This would mean there is 31.25% chance of going to a 7 game series.
And the probability you win in the 7th game , would follow negative binomial, how many trails = 7 for 4 success, 7-1 C 4-1 * (.5)^3 * (.5)^4
|
Statistics of 7 game playoff series
|
An alternate way to look at would be a binomial distribution: You need x=3 (exactly 3 successes) in n = 6 (trails) , so if the probability of winning a game is .5 (both teams equally likely) , binomia
|
Statistics of 7 game playoff series
An alternate way to look at would be a binomial distribution: You need x=3 (exactly 3 successes) in n = 6 (trails) , so if the probability of winning a game is .5 (both teams equally likely) , binomial would say:
P(x=3) = 6C3 * (.5)^3 * (.5)^3 = .3125
This would mean there is 31.25% chance of going to a 7 game series.
And the probability you win in the 7th game , would follow negative binomial, how many trails = 7 for 4 success, 7-1 C 4-1 * (.5)^3 * (.5)^4
|
Statistics of 7 game playoff series
An alternate way to look at would be a binomial distribution: You need x=3 (exactly 3 successes) in n = 6 (trails) , so if the probability of winning a game is .5 (both teams equally likely) , binomia
|
48,020
|
Statistics of 7 game playoff series
|
Regarding the discrepancy in real-life results, OP noted "I'd guess that the discrepancy comes from the outcome of each game having being biased toward a win for one team or the other (indeed, teams are usually seeded in the first round so that the leading qualifying team plays the team that barely qualified, second place plays second last, and so on." ...
I'll note that even a random ordering would result in such a phenomenon, as many of the games would pair off teams with different levels of skill. In fact, the only system I can think of where the real results would match the theory would be one where #1 is paired off with #2 etc AND where the pairs are coincidentally evenly matched (or the league gives home-arena advantage to the underdog). But even then, the second round would almost certainly feature mis-matched teams even if randomly assigned.
In other words, the theoretical results will always represent a best-case scenario.
|
Statistics of 7 game playoff series
|
Regarding the discrepancy in real-life results, OP noted "I'd guess that the discrepancy comes from the outcome of each game having being biased toward a win for one team or the other (indeed, teams a
|
Statistics of 7 game playoff series
Regarding the discrepancy in real-life results, OP noted "I'd guess that the discrepancy comes from the outcome of each game having being biased toward a win for one team or the other (indeed, teams are usually seeded in the first round so that the leading qualifying team plays the team that barely qualified, second place plays second last, and so on." ...
I'll note that even a random ordering would result in such a phenomenon, as many of the games would pair off teams with different levels of skill. In fact, the only system I can think of where the real results would match the theory would be one where #1 is paired off with #2 etc AND where the pairs are coincidentally evenly matched (or the league gives home-arena advantage to the underdog). But even then, the second round would almost certainly feature mis-matched teams even if randomly assigned.
In other words, the theoretical results will always represent a best-case scenario.
|
Statistics of 7 game playoff series
Regarding the discrepancy in real-life results, OP noted "I'd guess that the discrepancy comes from the outcome of each game having being biased toward a win for one team or the other (indeed, teams a
|
48,021
|
Probability of data point being from distribution in normal mixtures
|
Let's call the estimates from population 1 and population 2 to be
$\mu_1$ and $\mu_2$ for the means, $\sigma_1$ and $\sigma_2$ for the sd's. Also, let's define $p$ to be the estimated proportion of observations from population 1.
Then, for each observation $x_i$, the estimated probability of belonging to population 1 is
$= \dfrac{p*N( x_i ; \mu_1, \sigma_1)}{p*N( x_i ; \mu_1, \sigma_1) +(1-p)*N( x_i ; \mu_2, \sigma_2)}$
where $N( x_i ; \mu_1, \sigma_1)$ is the normal density. If using JMP, you could evaluate the normal density with
Normal.Density( (x_i - mu_1) / sigma_1) )
since the normal density function in JMP only accepts arguments for the standard normal distribution.
The estimated probability of belonging to population 2 would then of course be 1 minus the estimated probability of belonging to population 1.
|
Probability of data point being from distribution in normal mixtures
|
Let's call the estimates from population 1 and population 2 to be
$\mu_1$ and $\mu_2$ for the means, $\sigma_1$ and $\sigma_2$ for the sd's. Also, let's define $p$ to be the estimated proportion of
|
Probability of data point being from distribution in normal mixtures
Let's call the estimates from population 1 and population 2 to be
$\mu_1$ and $\mu_2$ for the means, $\sigma_1$ and $\sigma_2$ for the sd's. Also, let's define $p$ to be the estimated proportion of observations from population 1.
Then, for each observation $x_i$, the estimated probability of belonging to population 1 is
$= \dfrac{p*N( x_i ; \mu_1, \sigma_1)}{p*N( x_i ; \mu_1, \sigma_1) +(1-p)*N( x_i ; \mu_2, \sigma_2)}$
where $N( x_i ; \mu_1, \sigma_1)$ is the normal density. If using JMP, you could evaluate the normal density with
Normal.Density( (x_i - mu_1) / sigma_1) )
since the normal density function in JMP only accepts arguments for the standard normal distribution.
The estimated probability of belonging to population 2 would then of course be 1 minus the estimated probability of belonging to population 1.
|
Probability of data point being from distribution in normal mixtures
Let's call the estimates from population 1 and population 2 to be
$\mu_1$ and $\mu_2$ for the means, $\sigma_1$ and $\sigma_2$ for the sd's. Also, let's define $p$ to be the estimated proportion of
|
48,022
|
Can the union (or) probability of many non-mutually exclusive events be calculated recursively?
|
As @HaoYe's comment points out, your recursion via divide-and-conquer is not
quite right: it is not the case that
$$P(A_1\cup A_2\cup A_3\cup A_4) = P( A_1 \cup A_2) + P( A_3 \cup A_4) - P( A_1 \cup A_2) * P( A_3 \cup A_4)$$
but rather that
$$P(A_1\cup A_2\cup A_3\cup A_4) = P( A_1 \cup A_2) + P( A_3 \cup A_4) - P\left(( A_1 \cup A_2) \cap ( A_3 \cup A_4)\right).$$
In any case, the principle of inclusion/exclusion gives a very pretty formula
that rarely can be used in practice because the probabilities of all those
various intersections are not easy to determine. One case where the probabilities
can be calculated is when the $n$ events are mutually independent, but
in this special case, the general formula should not be used at all!
For $n$ mutually independent events $A_1, A_2, \ldots, A_n$, use DeMorgan's theorem to write
$$P\left(\bigcup_{i=1}^n A_i\right) = 1 - P\left(\bigcap_{i=1}^n A_i^c\right)
= 1 - \prod_{i=1}^n P(A_i^c)= 1 - \prod_{i=1}^n \left[1 - P(A_i)\right]
\tag{1}$$
and calculate $P(A_1\cup A_2\cup\cdots\cup A_n)$ using $n-1$ multiplications
and $n+1$ subtractions. In other words, for Heaven's sake, resist the
temptation to multiply out those terms in square brackets on the right
because you will end up with the inclusion/exclusion formula which you
should try to avoid at all costs.
|
Can the union (or) probability of many non-mutually exclusive events be calculated recursively?
|
As @HaoYe's comment points out, your recursion via divide-and-conquer is not
quite right: it is not the case that
$$P(A_1\cup A_2\cup A_3\cup A_4) = P( A_1 \cup A_2) + P( A_3 \cup A_4) - P( A_1 \cup
|
Can the union (or) probability of many non-mutually exclusive events be calculated recursively?
As @HaoYe's comment points out, your recursion via divide-and-conquer is not
quite right: it is not the case that
$$P(A_1\cup A_2\cup A_3\cup A_4) = P( A_1 \cup A_2) + P( A_3 \cup A_4) - P( A_1 \cup A_2) * P( A_3 \cup A_4)$$
but rather that
$$P(A_1\cup A_2\cup A_3\cup A_4) = P( A_1 \cup A_2) + P( A_3 \cup A_4) - P\left(( A_1 \cup A_2) \cap ( A_3 \cup A_4)\right).$$
In any case, the principle of inclusion/exclusion gives a very pretty formula
that rarely can be used in practice because the probabilities of all those
various intersections are not easy to determine. One case where the probabilities
can be calculated is when the $n$ events are mutually independent, but
in this special case, the general formula should not be used at all!
For $n$ mutually independent events $A_1, A_2, \ldots, A_n$, use DeMorgan's theorem to write
$$P\left(\bigcup_{i=1}^n A_i\right) = 1 - P\left(\bigcap_{i=1}^n A_i^c\right)
= 1 - \prod_{i=1}^n P(A_i^c)= 1 - \prod_{i=1}^n \left[1 - P(A_i)\right]
\tag{1}$$
and calculate $P(A_1\cup A_2\cup\cdots\cup A_n)$ using $n-1$ multiplications
and $n+1$ subtractions. In other words, for Heaven's sake, resist the
temptation to multiply out those terms in square brackets on the right
because you will end up with the inclusion/exclusion formula which you
should try to avoid at all costs.
|
Can the union (or) probability of many non-mutually exclusive events be calculated recursively?
As @HaoYe's comment points out, your recursion via divide-and-conquer is not
quite right: it is not the case that
$$P(A_1\cup A_2\cup A_3\cup A_4) = P( A_1 \cup A_2) + P( A_3 \cup A_4) - P( A_1 \cup
|
48,023
|
Can the union (or) probability of many non-mutually exclusive events be calculated recursively?
|
Nothing wrong with this approach. If you use floating point, you will want to or (add up) the two smallest remaining probabilities in each step in order to minimize the effect of rounding errors (floating point is most accurate when the values you add are of similar magnitude).
PS. Since (a or b or c or d) = ((a or b) or (c or d)), you don't need any literature reference. The correctness follows directly from associativity of OR.
|
Can the union (or) probability of many non-mutually exclusive events be calculated recursively?
|
Nothing wrong with this approach. If you use floating point, you will want to or (add up) the two smallest remaining probabilities in each step in order to minimize the effect of rounding errors (floa
|
Can the union (or) probability of many non-mutually exclusive events be calculated recursively?
Nothing wrong with this approach. If you use floating point, you will want to or (add up) the two smallest remaining probabilities in each step in order to minimize the effect of rounding errors (floating point is most accurate when the values you add are of similar magnitude).
PS. Since (a or b or c or d) = ((a or b) or (c or d)), you don't need any literature reference. The correctness follows directly from associativity of OR.
|
Can the union (or) probability of many non-mutually exclusive events be calculated recursively?
Nothing wrong with this approach. If you use floating point, you will want to or (add up) the two smallest remaining probabilities in each step in order to minimize the effect of rounding errors (floa
|
48,024
|
Dealing with missing data - glmer in lme4 package
|
Turning my comments into an answer as they seem to have answered your question...
Just exclude the actual missing data. If you format your data with columns ID, Day, environmental variables, response, everything should be fine to just omit the rows where an ID is missing a measurement on a certain day, still keeping the other measurements on those IDs.
For inference, you'll get the best accuracy using bootstrapped estimates, (lme4::confint() with method = "boot" works well -- you'll need to install the boot package for this to work). If you want more info on that, I'd recommend Faraway's Extending the Linear Model with R, section 8.2. The lme4 package has been considerably updated since Faraway's book's printing, you can see the accompanying transition guide. The principles, of course, remain the same.
|
Dealing with missing data - glmer in lme4 package
|
Turning my comments into an answer as they seem to have answered your question...
Just exclude the actual missing data. If you format your data with columns ID, Day, environmental variables, response,
|
Dealing with missing data - glmer in lme4 package
Turning my comments into an answer as they seem to have answered your question...
Just exclude the actual missing data. If you format your data with columns ID, Day, environmental variables, response, everything should be fine to just omit the rows where an ID is missing a measurement on a certain day, still keeping the other measurements on those IDs.
For inference, you'll get the best accuracy using bootstrapped estimates, (lme4::confint() with method = "boot" works well -- you'll need to install the boot package for this to work). If you want more info on that, I'd recommend Faraway's Extending the Linear Model with R, section 8.2. The lme4 package has been considerably updated since Faraway's book's printing, you can see the accompanying transition guide. The principles, of course, remain the same.
|
Dealing with missing data - glmer in lme4 package
Turning my comments into an answer as they seem to have answered your question...
Just exclude the actual missing data. If you format your data with columns ID, Day, environmental variables, response,
|
48,025
|
Dealing with missing data - glmer in lme4 package
|
You must create an indicator variable as control in your model: 1 for acoustic receiver in the missing day and 0 for complete data. Repeat the code for the same acoustic receiver in all its observed and unobserved days (in wide format data base, before converting to long format). You can do it for any missing day or one indicator variable for each missing day separately or grouping days as you consider important. If the indicator variable has no statistic significance, missing data is unimportatnt for the model, but statistic significance shows that the nonobservation is due your dependent variable or vice-versa.
|
Dealing with missing data - glmer in lme4 package
|
You must create an indicator variable as control in your model: 1 for acoustic receiver in the missing day and 0 for complete data. Repeat the code for the same acoustic receiver in all its observed a
|
Dealing with missing data - glmer in lme4 package
You must create an indicator variable as control in your model: 1 for acoustic receiver in the missing day and 0 for complete data. Repeat the code for the same acoustic receiver in all its observed and unobserved days (in wide format data base, before converting to long format). You can do it for any missing day or one indicator variable for each missing day separately or grouping days as you consider important. If the indicator variable has no statistic significance, missing data is unimportatnt for the model, but statistic significance shows that the nonobservation is due your dependent variable or vice-versa.
|
Dealing with missing data - glmer in lme4 package
You must create an indicator variable as control in your model: 1 for acoustic receiver in the missing day and 0 for complete data. Repeat the code for the same acoustic receiver in all its observed a
|
48,026
|
can an ARMA process with complex unit roots be made stationary by differencing?
|
Yes, it is possible to render the process stationary regardless of whether the
non-stationary cycles are related to real or complex roots.
For example, the following seasonal random walk:
$$
y_t = y_{t-4} + \epsilon_t \quad \epsilon_t \sim NID(0, \sigma^2) \,,
$$
contains four unit roots: $\pm 1, \pm i$ (i.e., 2 real and 2 complex roots). Applying the filter $(1 - L^4)$ (where $L$ is the lag operator such that $L^i y_t = y_{t-i}$) the non-stationary cycles are removed from the series $y_t$, which is not surprising since all we did is moving $y_{t-4}$ to the left-hand-side of the equation so that we get that the filtered series is $y_t - y_{t-4} = \epsilon_t$.
The seasonal differencing filter is commonly used when working with
ARIMA models. It is illuminating to write the seasonal differencing filter factorized as follows (for a quarterly series in this example):
$$
(1 - L^4)y_t = (1-L)(1+L)(1+L^2)y_t = \epsilon_t \,.
$$
The factor $(1-L)$ contains the root $1$, $(1+L)$ the root $-1$ and
$(1+L^2)$ the complex roots $\pm i$. Thus, applying the filter $(1+L^2)$ we
remove only those cycles related to the complex roots.
The first graphic in the plot below shows the sample spectrum of a simulated random walk. It contains a spike at cycles of frequencies $0$ (related to the root $1$), $\pi/2$ and $3\pi/2$ (related to roots $\pm i$) and $\pi$ (related to the root $-1$). In the second graphic, the cycles related to the complex roots have been removed by the filter $(1+L^2)$; the spike at the middle of the periodogram is not present, confirming that the contribution of those cycles to the whole series is negligible.
The plot can be reproduced with the following R code:
set.seed(125)
x <- diffinv(rnorm(100), 4)[-seq(4)]
par(mfrow = c(2,1))
spectrum(x, span = c(3,3), main = paste("Periodogram of a seasonal random walk", dQuote("x")))
spectrum(na.omit(filter(x, filter = c(1,0,1), method = "conv", sides = 1)),
span = c(3,3), main = expression(paste("Periodogram of ", (1+L^2), "x")))
|
can an ARMA process with complex unit roots be made stationary by differencing?
|
Yes, it is possible to render the process stationary regardless of whether the
non-stationary cycles are related to real or complex roots.
For example, the following seasonal random walk:
$$
y_t = y_{
|
can an ARMA process with complex unit roots be made stationary by differencing?
Yes, it is possible to render the process stationary regardless of whether the
non-stationary cycles are related to real or complex roots.
For example, the following seasonal random walk:
$$
y_t = y_{t-4} + \epsilon_t \quad \epsilon_t \sim NID(0, \sigma^2) \,,
$$
contains four unit roots: $\pm 1, \pm i$ (i.e., 2 real and 2 complex roots). Applying the filter $(1 - L^4)$ (where $L$ is the lag operator such that $L^i y_t = y_{t-i}$) the non-stationary cycles are removed from the series $y_t$, which is not surprising since all we did is moving $y_{t-4}$ to the left-hand-side of the equation so that we get that the filtered series is $y_t - y_{t-4} = \epsilon_t$.
The seasonal differencing filter is commonly used when working with
ARIMA models. It is illuminating to write the seasonal differencing filter factorized as follows (for a quarterly series in this example):
$$
(1 - L^4)y_t = (1-L)(1+L)(1+L^2)y_t = \epsilon_t \,.
$$
The factor $(1-L)$ contains the root $1$, $(1+L)$ the root $-1$ and
$(1+L^2)$ the complex roots $\pm i$. Thus, applying the filter $(1+L^2)$ we
remove only those cycles related to the complex roots.
The first graphic in the plot below shows the sample spectrum of a simulated random walk. It contains a spike at cycles of frequencies $0$ (related to the root $1$), $\pi/2$ and $3\pi/2$ (related to roots $\pm i$) and $\pi$ (related to the root $-1$). In the second graphic, the cycles related to the complex roots have been removed by the filter $(1+L^2)$; the spike at the middle of the periodogram is not present, confirming that the contribution of those cycles to the whole series is negligible.
The plot can be reproduced with the following R code:
set.seed(125)
x <- diffinv(rnorm(100), 4)[-seq(4)]
par(mfrow = c(2,1))
spectrum(x, span = c(3,3), main = paste("Periodogram of a seasonal random walk", dQuote("x")))
spectrum(na.omit(filter(x, filter = c(1,0,1), method = "conv", sides = 1)),
span = c(3,3), main = expression(paste("Periodogram of ", (1+L^2), "x")))
|
can an ARMA process with complex unit roots be made stationary by differencing?
Yes, it is possible to render the process stationary regardless of whether the
non-stationary cycles are related to real or complex roots.
For example, the following seasonal random walk:
$$
y_t = y_{
|
48,027
|
What is this kind of tabular relation diagram called?
|
I would use the term binary heat map - although I'm not sure if there is a unified term. (There are probably other names used in various fields of application.) Heat maps more often display continuous attributes in cells via a color ramp, but there are plenty of matrix like representations of binary data. For instance Bertin in Semiologie talks about reordering the matrix to make certain patterns clearer.
For Bertin's examples (and older ones) see:
Wilkinson, L. and Friendly, M. (2009). The history of the cluster heat map. The American Statistician, 63(2):179-184. Online PDF Pre-print
Here is an example figure taken from Wilkinson & Friendly (2009) but is originally from the work of Bertin:
|
What is this kind of tabular relation diagram called?
|
I would use the term binary heat map - although I'm not sure if there is a unified term. (There are probably other names used in various fields of application.) Heat maps more often display continuous
|
What is this kind of tabular relation diagram called?
I would use the term binary heat map - although I'm not sure if there is a unified term. (There are probably other names used in various fields of application.) Heat maps more often display continuous attributes in cells via a color ramp, but there are plenty of matrix like representations of binary data. For instance Bertin in Semiologie talks about reordering the matrix to make certain patterns clearer.
For Bertin's examples (and older ones) see:
Wilkinson, L. and Friendly, M. (2009). The history of the cluster heat map. The American Statistician, 63(2):179-184. Online PDF Pre-print
Here is an example figure taken from Wilkinson & Friendly (2009) but is originally from the work of Bertin:
|
What is this kind of tabular relation diagram called?
I would use the term binary heat map - although I'm not sure if there is a unified term. (There are probably other names used in various fields of application.) Heat maps more often display continuous
|
48,028
|
What is this kind of tabular relation diagram called?
|
I think this is somewhat harder to answer than it would otherwise be because it's a very simple and commonly used style of chart. My answer may not be universally applicable, and other terms are likely to exist for the exact same layout, but I'm finding a lot of similar results in a Google image search for "comparison chart"...so without further references for support (haven't been able to find any yet), I'd recommend calling it a comparison chart. For comparison, another result from my image search:
http://www.utm.utoronto.ca/housing/sites/files/housing/public/users/beamsone/Comparison_chart.jpg
This one is a little more complex, in that it has three kinds of dots (see the legend in the top left corner) and numeric entries on the bottom row. The University of Toronto titles this as a comparison chart.
|
What is this kind of tabular relation diagram called?
|
I think this is somewhat harder to answer than it would otherwise be because it's a very simple and commonly used style of chart. My answer may not be universally applicable, and other terms are likel
|
What is this kind of tabular relation diagram called?
I think this is somewhat harder to answer than it would otherwise be because it's a very simple and commonly used style of chart. My answer may not be universally applicable, and other terms are likely to exist for the exact same layout, but I'm finding a lot of similar results in a Google image search for "comparison chart"...so without further references for support (haven't been able to find any yet), I'd recommend calling it a comparison chart. For comparison, another result from my image search:
http://www.utm.utoronto.ca/housing/sites/files/housing/public/users/beamsone/Comparison_chart.jpg
This one is a little more complex, in that it has three kinds of dots (see the legend in the top left corner) and numeric entries on the bottom row. The University of Toronto titles this as a comparison chart.
|
What is this kind of tabular relation diagram called?
I think this is somewhat harder to answer than it would otherwise be because it's a very simple and commonly used style of chart. My answer may not be universally applicable, and other terms are likel
|
48,029
|
How do I use math to predict the next number in the series?
|
If observations are independent, and if values must either be 1 or 0, with no additional prior information, you may simply assume that the probability that the next value is 1 is equal to the proportion of 1s in the observations.
If you wish to calculate a confidence interval around this estimate, this could reasonably be modeled as a Bernoulli trial with probability $p=19/22\simeq0.86$ And a 95% confidence interval of $[65\%,97\%]$ (CI calculated as the Clopper-Pearson interval).
This model is analogous to expecting heads from a coin that has landed on heads in 19 of 22 flips, or drawing a white pebble from a bag where the previous 22 draws gave 19 white + 3 nonwhite pebbles (if the pebbles are put back each time, or if there are infinite well mixed pebbles).
See also https://stats.stackexchange.com/a/6184/1381 for information and alternative methods for computing confidence intervals for Bernoulli trials.
Given the number of up votes on the OP, perhaps there is a less trivial solution, but I suspect that it just looks like it would be interesting if the observations were related, and order mattered, rather than being independent.
|
How do I use math to predict the next number in the series?
|
If observations are independent, and if values must either be 1 or 0, with no additional prior information, you may simply assume that the probability that the next value is 1 is equal to the proporti
|
How do I use math to predict the next number in the series?
If observations are independent, and if values must either be 1 or 0, with no additional prior information, you may simply assume that the probability that the next value is 1 is equal to the proportion of 1s in the observations.
If you wish to calculate a confidence interval around this estimate, this could reasonably be modeled as a Bernoulli trial with probability $p=19/22\simeq0.86$ And a 95% confidence interval of $[65\%,97\%]$ (CI calculated as the Clopper-Pearson interval).
This model is analogous to expecting heads from a coin that has landed on heads in 19 of 22 flips, or drawing a white pebble from a bag where the previous 22 draws gave 19 white + 3 nonwhite pebbles (if the pebbles are put back each time, or if there are infinite well mixed pebbles).
See also https://stats.stackexchange.com/a/6184/1381 for information and alternative methods for computing confidence intervals for Bernoulli trials.
Given the number of up votes on the OP, perhaps there is a less trivial solution, but I suspect that it just looks like it would be interesting if the observations were related, and order mattered, rather than being independent.
|
How do I use math to predict the next number in the series?
If observations are independent, and if values must either be 1 or 0, with no additional prior information, you may simply assume that the probability that the next value is 1 is equal to the proporti
|
48,030
|
p-value for weighted Pearson correlation coefficient
|
The $P$-value reported for a correlation depends on the sample correlation, the sample size, and a bundle of assumptions not always checked (independence being, in my experience, least checked of all). But there is a difference between a crude $t$-based $P$-value based on a null hypothesis of zero correlation and a more general $P$-value based on Fisher's $z$ transformation.
I don't think there is an answer to this independent of what the weights are. If weighting means that you are combining data from different subsamples, then the weights have implications for the sample size that should be used; at the same time correlations based on weighted combinations would not necessarily have the same distribution as the correlation distribution based on raw data.
At the same time, it is difficult to get agitated about this. If correlations have a point it is that they measure strength of relationship; if you are seriously in doubt that they are significantly different from zero, then it is arguable that you just have inadequately small samples and being precise about that problem is secondary.
It's likely that this misreads your problem, in which case you may have to give much more detail.
If getting really reliable $P$-values for weighted correlations is important to you, it is possible that you need to get a handle on it through simulation, including simulation of the weighting process if that is variable too.
|
p-value for weighted Pearson correlation coefficient
|
The $P$-value reported for a correlation depends on the sample correlation, the sample size, and a bundle of assumptions not always checked (independence being, in my experience, least checked of all)
|
p-value for weighted Pearson correlation coefficient
The $P$-value reported for a correlation depends on the sample correlation, the sample size, and a bundle of assumptions not always checked (independence being, in my experience, least checked of all). But there is a difference between a crude $t$-based $P$-value based on a null hypothesis of zero correlation and a more general $P$-value based on Fisher's $z$ transformation.
I don't think there is an answer to this independent of what the weights are. If weighting means that you are combining data from different subsamples, then the weights have implications for the sample size that should be used; at the same time correlations based on weighted combinations would not necessarily have the same distribution as the correlation distribution based on raw data.
At the same time, it is difficult to get agitated about this. If correlations have a point it is that they measure strength of relationship; if you are seriously in doubt that they are significantly different from zero, then it is arguable that you just have inadequately small samples and being precise about that problem is secondary.
It's likely that this misreads your problem, in which case you may have to give much more detail.
If getting really reliable $P$-values for weighted correlations is important to you, it is possible that you need to get a handle on it through simulation, including simulation of the weighting process if that is variable too.
|
p-value for weighted Pearson correlation coefficient
The $P$-value reported for a correlation depends on the sample correlation, the sample size, and a bundle of assumptions not always checked (independence being, in my experience, least checked of all)
|
48,031
|
p-value for weighted Pearson correlation coefficient
|
I haven't yet sit down to work the math, but from the few simulations I run it seems that replacing the number of samples $n$ in the formulas with the effective number of samples $n_\text{eff}$ yields very good approximations.
$n_\text{eff} = \exp(H)$, where $H=-\sum_{i=1}^n w_i \ln w_i$ is the entropy of weights (normalized to $\sum_{i=1}^n w_i = 1$).
For example:
$t = r\sqrt{\frac{n_\text{eff}-2}{1-r^2}}$ follows approximately $t$-distribution with $n_\text{eff}-2$ d.o.f.,
$F(r) = \frac{1}{2}\ln\left(\frac{1+r}{1-r}\right)$ follows approximately normal distribution with mean $F(\rho)$ and std. $\frac{1}{\sqrt{n_\text{eff}-3}}$.
But the point should be made that even the unweighted formulas for $p$-values are approximations assuming normal data etc. Bootstrap or permutation tests might be more reliable and they work with Spearman's weighted correlation as well.
|
p-value for weighted Pearson correlation coefficient
|
I haven't yet sit down to work the math, but from the few simulations I run it seems that replacing the number of samples $n$ in the formulas with the effective number of samples $n_\text{eff}$ yields
|
p-value for weighted Pearson correlation coefficient
I haven't yet sit down to work the math, but from the few simulations I run it seems that replacing the number of samples $n$ in the formulas with the effective number of samples $n_\text{eff}$ yields very good approximations.
$n_\text{eff} = \exp(H)$, where $H=-\sum_{i=1}^n w_i \ln w_i$ is the entropy of weights (normalized to $\sum_{i=1}^n w_i = 1$).
For example:
$t = r\sqrt{\frac{n_\text{eff}-2}{1-r^2}}$ follows approximately $t$-distribution with $n_\text{eff}-2$ d.o.f.,
$F(r) = \frac{1}{2}\ln\left(\frac{1+r}{1-r}\right)$ follows approximately normal distribution with mean $F(\rho)$ and std. $\frac{1}{\sqrt{n_\text{eff}-3}}$.
But the point should be made that even the unweighted formulas for $p$-values are approximations assuming normal data etc. Bootstrap or permutation tests might be more reliable and they work with Spearman's weighted correlation as well.
|
p-value for weighted Pearson correlation coefficient
I haven't yet sit down to work the math, but from the few simulations I run it seems that replacing the number of samples $n$ in the formulas with the effective number of samples $n_\text{eff}$ yields
|
48,032
|
Inference with only left-censored data
|
How much you can conclude depends on the assumptions you are willing to make about the underlying distribution. Even with no assumptions, though, you can still conclude something, although it might not be a whole lot. For example, the sample data are not plausibly consistent with an underlying distribution whose mean is $100$ and standard deviation is $10$: Chebyshev's inequality tells us these data must have extremely low likelihood in that case.
The most general answer will be given in the form of a p-box. This is a simple device to describe a range of distribution functions. It consists of two graphs, one lying above the other, which thereby determine a region $\mathcal P$ in Cartesian coordinates. Any CDF whose graph would lie entirely within $\mathcal P$ is an element of that p-box.
As an example, let's construct a (nonparametric) 90%-confidence p-box for the sample data, $(\lt 5, \lt 5, \lt 5, \lt 10, \lt 10, \lt 10)$. This p-box should be as "small as possible" (in some sense) while containing any distribution law $F$ for which the probability of the data, given $F$, is at least $1 - 90/100 = 1/10$. Let us (temporarily) call these the "plausible laws."
"As small as possible" can be rigorously defined. Let $\mathbb{P}$ be the set of all distribution functions. Associated with any subset $\Omega\subset \mathbb{P}$ is the set $C(\Omega)$ consisting of all points $(x,y)$ such that $x$ is a real number and there exist $F,G\in \Omega$ with $F(x) \le y \le G(x)$. Letting $\Omega$ be the set of plausible laws, we take the p-box to be $C(\Omega)$.
These data, which have no quantified results at all, tell us just two things about the plausible laws. When a sample $X_1, X_2, \ldots, X_6$ is taken from such a law $F$, then (1) it should be unlikely that one or more of the $X_i$ equal $10$ or greater and (2) it should be unlikely that four or more of the $X_i$ should equal $5$ or greater. These are binomial events governed by the parameters $p=F(10)$ and $q=F(5)$, respectively. Interpreting "unlikely" as being a chance of $100-90 = 10\%$ or less, these criteria uniquely determine $p$ and $q$.
For these data, $p = (1/10)^{1/6} \approx 0.681$ and $q \approx 0.201$.
The p-box therefore contains the graphs of all distribution laws $F$ for which (1) $q \le F(5) \le 1$ and (2) $p \le F(10) \le 1$. A part of this p-box (between $x=0$ and $x=15$) is shaded in gray:
Within this p-box I have drawn the graphs of some distributions that come close to its boundary. All three are two-parameter Exponential distributions. The dark red one is determined by the two corners it passes through. The other two (dashed gray ones) show a distribution with a large standard deviation and one with a small standard deviation.
These illustrations should make it clear that if you wished to construct a parametric p-box encompassing only two-parameter Exponential distributions, then it would exclude the region between the thick red curve and the lower line segment between $x=5$ and $x=10$, but it would have to include everything else. We don't necessarily achieve a lot by making a strong parametric assumption in this example.
What happens when the amount of data increases? Suppose as you collect more data that all results continue to be either $\lt 5$ or $\lt 10$ and that their proportions remain roughly 1:1. Then the value of $p$ approaches $1.0$--there can't be much of a chance of observing anything greater than $10$--and the value of $q$ approaches $1/2$, the proportion of $\lt 5$s in the population. Making an Exponential distribution assumption allows you to conclude a little more: the chance of observing anything above $5$ grows vanishingly small, too. Here is the situation upon observing $3000$ values of "$\lt 5$" and $3000$ values of "$\lt 10$":
Nevertheless, there is a huge set of possible distributions consistent with such data, even when the dataset becomes enormous. Intuitively this should be clear: for example, any distribution supported on a set of numbers less than $5$ will be consistent with such data and its graph will fit within this p-box.
This approach to data analysis is not as powerful as, say, a Bayesian analysis. However, it requires minimal assumptions: we only suppose that the data are identically and independently distributed. There is no need to adopt a prior and justify your choice of it, for instance. (Such checking is rather difficult when all the data are censored!) If the p-box is sufficiently narrow to let you draw a firm conclusion, then you're done and you know your conclusion is extremely robust. Otherwise, the p-box can be a useful tool to help you explore the impact of potential additional assumptions on your conclusions.
Here is some R code to play with.
k1 <- 3; k2 <- 3 # Counts
x1 <- 5; x2 <- 10 # Quantitation limits
confidence <- 90/100
#
# Find p and q.
#
x <- c(rep(x1, k1), rep(x2, k2))
n <- length(x)
alpha <- 1 - confidence
p <- uniroot(function(p) pbinom(n-1, n, p) - confidence, c(0,1))$root
q <- uniroot(function(p) pbinom(k1-1, n, p) - confidence, c(0,1))$root
#
# Plot the p-box.
#
plot(c(0, 15), c(0, 1), type="n", bty="n", xlab="X", ylab="Probability")
rect(0, 0, x1, 1, col=gray(.975), border=NA)
rect(x1, q, x2, 1, col=gray(.975), border=NA)
rect(x2, p, 15, 1, col=gray(.975), border=NA)
#
# Show a parametric solution.
#
F.inv <- qexp; F <- pexp # Exponential distribution family
F.p <- F.inv(p); F.q <- F.inv(q)
sigma <- (x2 - x1) / (F.p - F.q) # Scale parameter
mu <- x2 - sigma*F.p # Offset parameter
curve(F((x - mu)/sigma), add=TRUE, col="Red", lwd=2)
f <- stepfun(c(x1, x2), c(0, q, p)) # Lower limit of the p-box
plot(f, add=TRUE, verticals=FALSE)
curve(1 + 0*x, add=TRUE) # Upper limit of the p-box
|
Inference with only left-censored data
|
How much you can conclude depends on the assumptions you are willing to make about the underlying distribution. Even with no assumptions, though, you can still conclude something, although it might n
|
Inference with only left-censored data
How much you can conclude depends on the assumptions you are willing to make about the underlying distribution. Even with no assumptions, though, you can still conclude something, although it might not be a whole lot. For example, the sample data are not plausibly consistent with an underlying distribution whose mean is $100$ and standard deviation is $10$: Chebyshev's inequality tells us these data must have extremely low likelihood in that case.
The most general answer will be given in the form of a p-box. This is a simple device to describe a range of distribution functions. It consists of two graphs, one lying above the other, which thereby determine a region $\mathcal P$ in Cartesian coordinates. Any CDF whose graph would lie entirely within $\mathcal P$ is an element of that p-box.
As an example, let's construct a (nonparametric) 90%-confidence p-box for the sample data, $(\lt 5, \lt 5, \lt 5, \lt 10, \lt 10, \lt 10)$. This p-box should be as "small as possible" (in some sense) while containing any distribution law $F$ for which the probability of the data, given $F$, is at least $1 - 90/100 = 1/10$. Let us (temporarily) call these the "plausible laws."
"As small as possible" can be rigorously defined. Let $\mathbb{P}$ be the set of all distribution functions. Associated with any subset $\Omega\subset \mathbb{P}$ is the set $C(\Omega)$ consisting of all points $(x,y)$ such that $x$ is a real number and there exist $F,G\in \Omega$ with $F(x) \le y \le G(x)$. Letting $\Omega$ be the set of plausible laws, we take the p-box to be $C(\Omega)$.
These data, which have no quantified results at all, tell us just two things about the plausible laws. When a sample $X_1, X_2, \ldots, X_6$ is taken from such a law $F$, then (1) it should be unlikely that one or more of the $X_i$ equal $10$ or greater and (2) it should be unlikely that four or more of the $X_i$ should equal $5$ or greater. These are binomial events governed by the parameters $p=F(10)$ and $q=F(5)$, respectively. Interpreting "unlikely" as being a chance of $100-90 = 10\%$ or less, these criteria uniquely determine $p$ and $q$.
For these data, $p = (1/10)^{1/6} \approx 0.681$ and $q \approx 0.201$.
The p-box therefore contains the graphs of all distribution laws $F$ for which (1) $q \le F(5) \le 1$ and (2) $p \le F(10) \le 1$. A part of this p-box (between $x=0$ and $x=15$) is shaded in gray:
Within this p-box I have drawn the graphs of some distributions that come close to its boundary. All three are two-parameter Exponential distributions. The dark red one is determined by the two corners it passes through. The other two (dashed gray ones) show a distribution with a large standard deviation and one with a small standard deviation.
These illustrations should make it clear that if you wished to construct a parametric p-box encompassing only two-parameter Exponential distributions, then it would exclude the region between the thick red curve and the lower line segment between $x=5$ and $x=10$, but it would have to include everything else. We don't necessarily achieve a lot by making a strong parametric assumption in this example.
What happens when the amount of data increases? Suppose as you collect more data that all results continue to be either $\lt 5$ or $\lt 10$ and that their proportions remain roughly 1:1. Then the value of $p$ approaches $1.0$--there can't be much of a chance of observing anything greater than $10$--and the value of $q$ approaches $1/2$, the proportion of $\lt 5$s in the population. Making an Exponential distribution assumption allows you to conclude a little more: the chance of observing anything above $5$ grows vanishingly small, too. Here is the situation upon observing $3000$ values of "$\lt 5$" and $3000$ values of "$\lt 10$":
Nevertheless, there is a huge set of possible distributions consistent with such data, even when the dataset becomes enormous. Intuitively this should be clear: for example, any distribution supported on a set of numbers less than $5$ will be consistent with such data and its graph will fit within this p-box.
This approach to data analysis is not as powerful as, say, a Bayesian analysis. However, it requires minimal assumptions: we only suppose that the data are identically and independently distributed. There is no need to adopt a prior and justify your choice of it, for instance. (Such checking is rather difficult when all the data are censored!) If the p-box is sufficiently narrow to let you draw a firm conclusion, then you're done and you know your conclusion is extremely robust. Otherwise, the p-box can be a useful tool to help you explore the impact of potential additional assumptions on your conclusions.
Here is some R code to play with.
k1 <- 3; k2 <- 3 # Counts
x1 <- 5; x2 <- 10 # Quantitation limits
confidence <- 90/100
#
# Find p and q.
#
x <- c(rep(x1, k1), rep(x2, k2))
n <- length(x)
alpha <- 1 - confidence
p <- uniroot(function(p) pbinom(n-1, n, p) - confidence, c(0,1))$root
q <- uniroot(function(p) pbinom(k1-1, n, p) - confidence, c(0,1))$root
#
# Plot the p-box.
#
plot(c(0, 15), c(0, 1), type="n", bty="n", xlab="X", ylab="Probability")
rect(0, 0, x1, 1, col=gray(.975), border=NA)
rect(x1, q, x2, 1, col=gray(.975), border=NA)
rect(x2, p, 15, 1, col=gray(.975), border=NA)
#
# Show a parametric solution.
#
F.inv <- qexp; F <- pexp # Exponential distribution family
F.p <- F.inv(p); F.q <- F.inv(q)
sigma <- (x2 - x1) / (F.p - F.q) # Scale parameter
mu <- x2 - sigma*F.p # Offset parameter
curve(F((x - mu)/sigma), add=TRUE, col="Red", lwd=2)
f <- stepfun(c(x1, x2), c(0, q, p)) # Lower limit of the p-box
plot(f, add=TRUE, verticals=FALSE)
curve(1 + 0*x, add=TRUE) # Upper limit of the p-box
|
Inference with only left-censored data
How much you can conclude depends on the assumptions you are willing to make about the underlying distribution. Even with no assumptions, though, you can still conclude something, although it might n
|
48,033
|
Inference with only left-censored data
|
I can think of one solution, but I'm open to others.
In the paper linked, the use the formula:
$$F(Z_i) = \prod_{i=1}^j \frac{R_i - n_i}{R_i} $$
The term being multiplied, $\frac{R_i - n_i}{R_i}$, is a pointwise estimate of the rate at time $i$. For low $R_i$ size, or when $n_i = R_i$ or $n_i = 0$, this produces somewhat pathological results (see my complaints above). Instead we can treat this estimation as a Bayesian beta-binomial problem: Given prior $Beta(\alpha, \beta)$, we observe $n_i$ deaths in $R_i$ opportunities and update our prior to $Beta(\alpha + n_i, \beta + R_i - n_i)$. (I suggest keep $\alpha, \beta$ very low as to not introduce a strong bias in the final product).
We then sample from each posterior conversion rate and form the product:
$$F(Z_i) = \prod_{i=1}^j (1 - S_i) $$
where $S_i \sim Beta(\alpha + n_i, \beta + R_i - n_i)$. Doing this many times, we can reconstruct the posterior CDF.
Why does this work? Even if $n_i = 0$, $S_i$ is still slightly greater than 0, though not too much greater. If I have time later this week, I'll do some simulations.
|
Inference with only left-censored data
|
I can think of one solution, but I'm open to others.
In the paper linked, the use the formula:
$$F(Z_i) = \prod_{i=1}^j \frac{R_i - n_i}{R_i} $$
The term being multiplied, $\frac{R_i - n_i}{R_i}$, is
|
Inference with only left-censored data
I can think of one solution, but I'm open to others.
In the paper linked, the use the formula:
$$F(Z_i) = \prod_{i=1}^j \frac{R_i - n_i}{R_i} $$
The term being multiplied, $\frac{R_i - n_i}{R_i}$, is a pointwise estimate of the rate at time $i$. For low $R_i$ size, or when $n_i = R_i$ or $n_i = 0$, this produces somewhat pathological results (see my complaints above). Instead we can treat this estimation as a Bayesian beta-binomial problem: Given prior $Beta(\alpha, \beta)$, we observe $n_i$ deaths in $R_i$ opportunities and update our prior to $Beta(\alpha + n_i, \beta + R_i - n_i)$. (I suggest keep $\alpha, \beta$ very low as to not introduce a strong bias in the final product).
We then sample from each posterior conversion rate and form the product:
$$F(Z_i) = \prod_{i=1}^j (1 - S_i) $$
where $S_i \sim Beta(\alpha + n_i, \beta + R_i - n_i)$. Doing this many times, we can reconstruct the posterior CDF.
Why does this work? Even if $n_i = 0$, $S_i$ is still slightly greater than 0, though not too much greater. If I have time later this week, I'll do some simulations.
|
Inference with only left-censored data
I can think of one solution, but I'm open to others.
In the paper linked, the use the formula:
$$F(Z_i) = \prod_{i=1}^j \frac{R_i - n_i}{R_i} $$
The term being multiplied, $\frac{R_i - n_i}{R_i}$, is
|
48,034
|
Does the estimated overdispersion parameter of Negative Binomial depend on mean
|
I'll begin by noting that there are actually quite a few different estimators of the dispersion parameter of a negative binomial out there, and that my discussion here is limited by those estimators that I am familar with. To answer your question:
In the maximum likelihood case - the answer is yes. For other cases the answer may be no. I'll start with a discussion of the maximum likelihood case. It is not too hard to see that the maximum likelihood estimate of $\psi$ will depend on $\mu$. Just take the first derivative with respect to $\psi$ and note that even though the first derivative has no closed form solution at zero, it's value still depends on $\mu$.
Another method that can estimate $\psi$ is known as conditional maximum likelihood. The sum of iid Negative Binomial data is also negative binomial.
It can further be shown that the sum is a sufficient statistic for $\mu$ so that we can form an exact conditional likelihood for $\psi$ independent of the value of $\mu$. For more details see section 4 in:
http://biostatistics.oxfordjournals.org/content/9/2/321.full.pdf+html
The conditional maximum likelihood estimate has been shown to be less biased than the maximum likelihood estimate whereas the maximum likelihood underestimates the true dispersion. This makes sense intuitively since, just as in the normal case, the maximum likelihood estimate of the dispersion parameter depends on the estimated mean, but makes no adjustments to correct for the fact that the mean is estimated from the same data.
So, I would recommend using conditional maximum likelihood over MLE's in small sample problems or do a search for some bias correction technique on the maximum likelihood estimates. For large samples though you might just as well use the maximum likelihood estimates since it won't make much of a difference though.
|
Does the estimated overdispersion parameter of Negative Binomial depend on mean
|
I'll begin by noting that there are actually quite a few different estimators of the dispersion parameter of a negative binomial out there, and that my discussion here is limited by those estimators t
|
Does the estimated overdispersion parameter of Negative Binomial depend on mean
I'll begin by noting that there are actually quite a few different estimators of the dispersion parameter of a negative binomial out there, and that my discussion here is limited by those estimators that I am familar with. To answer your question:
In the maximum likelihood case - the answer is yes. For other cases the answer may be no. I'll start with a discussion of the maximum likelihood case. It is not too hard to see that the maximum likelihood estimate of $\psi$ will depend on $\mu$. Just take the first derivative with respect to $\psi$ and note that even though the first derivative has no closed form solution at zero, it's value still depends on $\mu$.
Another method that can estimate $\psi$ is known as conditional maximum likelihood. The sum of iid Negative Binomial data is also negative binomial.
It can further be shown that the sum is a sufficient statistic for $\mu$ so that we can form an exact conditional likelihood for $\psi$ independent of the value of $\mu$. For more details see section 4 in:
http://biostatistics.oxfordjournals.org/content/9/2/321.full.pdf+html
The conditional maximum likelihood estimate has been shown to be less biased than the maximum likelihood estimate whereas the maximum likelihood underestimates the true dispersion. This makes sense intuitively since, just as in the normal case, the maximum likelihood estimate of the dispersion parameter depends on the estimated mean, but makes no adjustments to correct for the fact that the mean is estimated from the same data.
So, I would recommend using conditional maximum likelihood over MLE's in small sample problems or do a search for some bias correction technique on the maximum likelihood estimates. For large samples though you might just as well use the maximum likelihood estimates since it won't make much of a difference though.
|
Does the estimated overdispersion parameter of Negative Binomial depend on mean
I'll begin by noting that there are actually quite a few different estimators of the dispersion parameter of a negative binomial out there, and that my discussion here is limited by those estimators t
|
48,035
|
Does the estimated overdispersion parameter of Negative Binomial depend on mean
|
I guess I find the answer via looking at the off diagonal of the Fisher information matrix.
$P(X=x) = \frac{\Gamma(x + \psi)}{\Gamma(\psi)\Gamma(x+1)} \frac{\psi^\psi\mu^x}{(\psi+\mu)^{(\psi+x)}}$
$\log L = n\psi \log\psi - n\log\Gamma(\psi)+\Sigma_{i=1}^n\log\Gamma(x_i+\psi)+\Sigma_{i=1}^nx_i\log\mu-\Sigma_{i=1}^n(\psi+x_i)\log(\psi+\mu) - \Sigma_{i=1}^n \log\Gamma(x_i+1)$
$E(-\frac{\partial^2\ell}{\partial\mu\partial\psi}) = E[\Sigma_{i=1}^n\frac{(\psi+\mu)-(\psi+x_i)}{(\psi+\mu)^2}]=0 $
The off diagonal of the Fisher information matrix is $0$. This indicates there is no correlation between the two.
|
Does the estimated overdispersion parameter of Negative Binomial depend on mean
|
I guess I find the answer via looking at the off diagonal of the Fisher information matrix.
$P(X=x) = \frac{\Gamma(x + \psi)}{\Gamma(\psi)\Gamma(x+1)} \frac{\psi^\psi\mu^x}{(\psi+\mu)^{(\psi+x)}}$
$\l
|
Does the estimated overdispersion parameter of Negative Binomial depend on mean
I guess I find the answer via looking at the off diagonal of the Fisher information matrix.
$P(X=x) = \frac{\Gamma(x + \psi)}{\Gamma(\psi)\Gamma(x+1)} \frac{\psi^\psi\mu^x}{(\psi+\mu)^{(\psi+x)}}$
$\log L = n\psi \log\psi - n\log\Gamma(\psi)+\Sigma_{i=1}^n\log\Gamma(x_i+\psi)+\Sigma_{i=1}^nx_i\log\mu-\Sigma_{i=1}^n(\psi+x_i)\log(\psi+\mu) - \Sigma_{i=1}^n \log\Gamma(x_i+1)$
$E(-\frac{\partial^2\ell}{\partial\mu\partial\psi}) = E[\Sigma_{i=1}^n\frac{(\psi+\mu)-(\psi+x_i)}{(\psi+\mu)^2}]=0 $
The off diagonal of the Fisher information matrix is $0$. This indicates there is no correlation between the two.
|
Does the estimated overdispersion parameter of Negative Binomial depend on mean
I guess I find the answer via looking at the off diagonal of the Fisher information matrix.
$P(X=x) = \frac{\Gamma(x + \psi)}{\Gamma(\psi)\Gamma(x+1)} \frac{\psi^\psi\mu^x}{(\psi+\mu)^{(\psi+x)}}$
$\l
|
48,036
|
When plotting clustering results in the PCA coordinates, does one do PCA or clustering first?
|
It is hard to see how you could do PCA on clusters; it is quite common to do PCA prior to clustering, particularly when you have a lot of variables. You can then use the PCs as variables.
You might be getting confused between a different two alternatives:
1) Do PCA on the data, then do k-means on the PCs, then plot the results
2) Do k-means on the data, do PCA on the data, then plot the clusters in terms of means on the PCs.
Both of these seem reasonable to me; the first may be better when there are many variables or when k-means on the data doesn't yield anything useful.
The former condenses the data in order to do cluster analysis. The latter condenses the data in order to visualize cluster analysis.
|
When plotting clustering results in the PCA coordinates, does one do PCA or clustering first?
|
It is hard to see how you could do PCA on clusters; it is quite common to do PCA prior to clustering, particularly when you have a lot of variables. You can then use the PCs as variables.
You might be
|
When plotting clustering results in the PCA coordinates, does one do PCA or clustering first?
It is hard to see how you could do PCA on clusters; it is quite common to do PCA prior to clustering, particularly when you have a lot of variables. You can then use the PCs as variables.
You might be getting confused between a different two alternatives:
1) Do PCA on the data, then do k-means on the PCs, then plot the results
2) Do k-means on the data, do PCA on the data, then plot the clusters in terms of means on the PCs.
Both of these seem reasonable to me; the first may be better when there are many variables or when k-means on the data doesn't yield anything useful.
The former condenses the data in order to do cluster analysis. The latter condenses the data in order to visualize cluster analysis.
|
When plotting clustering results in the PCA coordinates, does one do PCA or clustering first?
It is hard to see how you could do PCA on clusters; it is quite common to do PCA prior to clustering, particularly when you have a lot of variables. You can then use the PCs as variables.
You might be
|
48,037
|
Prediction with scikit and an precomputed kernel (SVM)
|
It seems that gram matrix that you use for predictions is wrong.
Once you fit the SVM its prediction for $x$ is: $ y = \text{sign} \langle w,\phi(x)\rangle $
It sure is possible that one cannot compute $\phi(x)$ but needs to use a pre-computed gram matrix instead. Substitute $ w = \sum_i^m\alpha_i\phi(x_i)$
into the above prediction expression:
$$
y = \text{sign } \langle \sum_i^m\alpha\phi(x_i),\phi(x) \rangle = \text{sign } \sum_i^m\alpha_i\langle\phi(x_i),\phi(x) \rangle = \text{sign } \sum_i^m\alpha_i K(x_i,x) \rangle = \text{sign } (Xx)^T\alpha = \text{sign } {G}\alpha
$$
Where $X$ is the design matrix for the training data (row $i$ of $X$ is $\phi(x_i)$) and gram matrix $G=(Xx)^T$ (note that G is not symmetric)
You can use this as a reference:
from sklearn.datasets import load_digits
from sklearn.svm import SVC
from sklearn.utils import shuffle
from sklearn.metrics import accuracy_score
import numpy as np
digits = load_digits()
X, y = shuffle(digits.data, digits.target)
X_train, X_test = X[:1000, :], X[100:, :]
y_train, y_test = y[:1000], y[100:]
svc = SVC(kernel='precomputed')
kernel_train = np.dot(X_train, X_train.T) # linear kernel
svc.fit(kernel_train, y_train)
#kernel_test = np.dot(X_test, X_train[svc.support_, :].T)
kernel_test = np.dot(X_test, X_train.T)
y_pred = svc.predict(kernel_test)
print 'accuracy score: %0.3f' % accuracy_score(y_test, y_pred)
|
Prediction with scikit and an precomputed kernel (SVM)
|
It seems that gram matrix that you use for predictions is wrong.
Once you fit the SVM its prediction for $x$ is: $ y = \text{sign} \langle w,\phi(x)\rangle $
It sure is possible that one cannot comput
|
Prediction with scikit and an precomputed kernel (SVM)
It seems that gram matrix that you use for predictions is wrong.
Once you fit the SVM its prediction for $x$ is: $ y = \text{sign} \langle w,\phi(x)\rangle $
It sure is possible that one cannot compute $\phi(x)$ but needs to use a pre-computed gram matrix instead. Substitute $ w = \sum_i^m\alpha_i\phi(x_i)$
into the above prediction expression:
$$
y = \text{sign } \langle \sum_i^m\alpha\phi(x_i),\phi(x) \rangle = \text{sign } \sum_i^m\alpha_i\langle\phi(x_i),\phi(x) \rangle = \text{sign } \sum_i^m\alpha_i K(x_i,x) \rangle = \text{sign } (Xx)^T\alpha = \text{sign } {G}\alpha
$$
Where $X$ is the design matrix for the training data (row $i$ of $X$ is $\phi(x_i)$) and gram matrix $G=(Xx)^T$ (note that G is not symmetric)
You can use this as a reference:
from sklearn.datasets import load_digits
from sklearn.svm import SVC
from sklearn.utils import shuffle
from sklearn.metrics import accuracy_score
import numpy as np
digits = load_digits()
X, y = shuffle(digits.data, digits.target)
X_train, X_test = X[:1000, :], X[100:, :]
y_train, y_test = y[:1000], y[100:]
svc = SVC(kernel='precomputed')
kernel_train = np.dot(X_train, X_train.T) # linear kernel
svc.fit(kernel_train, y_train)
#kernel_test = np.dot(X_test, X_train[svc.support_, :].T)
kernel_test = np.dot(X_test, X_train.T)
y_pred = svc.predict(kernel_test)
print 'accuracy score: %0.3f' % accuracy_score(y_test, y_pred)
|
Prediction with scikit and an precomputed kernel (SVM)
It seems that gram matrix that you use for predictions is wrong.
Once you fit the SVM its prediction for $x$ is: $ y = \text{sign} \langle w,\phi(x)\rangle $
It sure is possible that one cannot comput
|
48,038
|
Prediction with scikit and an precomputed kernel (SVM)
|
I find that I usually get that error from training/vectorizing outside the kfold loop.
vec.fit_transform(), vec.fit_transform(), clf.fit(), clf.pred() - all four of those function calls has to be inside to loop, to make sure all matricies gets the correct shapes.
Is your testing algo setup something like this?:
k_folds = sklearn.cross_validation.StratifiedKFold(list_of_annotations, k=5)
for train_index, test_index in k_folds:
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
vec = TfidfVectorizer()
--> X_train_matrix = vec.fit_transform(X_train)
--> X_test_matrix = vec.transform(X_test)
clf = svm.SVC()
--> clf.fit(X_train_matrix, y_train)
--> y_pred = clf.predict(X_test_matrix)
precision, recall, fscore, support = precision_recall_fscore_support(y_test, y_pred)
# print/save accuracy scores
|
Prediction with scikit and an precomputed kernel (SVM)
|
I find that I usually get that error from training/vectorizing outside the kfold loop.
vec.fit_transform(), vec.fit_transform(), clf.fit(), clf.pred() - all four of those function calls has to be insi
|
Prediction with scikit and an precomputed kernel (SVM)
I find that I usually get that error from training/vectorizing outside the kfold loop.
vec.fit_transform(), vec.fit_transform(), clf.fit(), clf.pred() - all four of those function calls has to be inside to loop, to make sure all matricies gets the correct shapes.
Is your testing algo setup something like this?:
k_folds = sklearn.cross_validation.StratifiedKFold(list_of_annotations, k=5)
for train_index, test_index in k_folds:
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
vec = TfidfVectorizer()
--> X_train_matrix = vec.fit_transform(X_train)
--> X_test_matrix = vec.transform(X_test)
clf = svm.SVC()
--> clf.fit(X_train_matrix, y_train)
--> y_pred = clf.predict(X_test_matrix)
precision, recall, fscore, support = precision_recall_fscore_support(y_test, y_pred)
# print/save accuracy scores
|
Prediction with scikit and an precomputed kernel (SVM)
I find that I usually get that error from training/vectorizing outside the kfold loop.
vec.fit_transform(), vec.fit_transform(), clf.fit(), clf.pred() - all four of those function calls has to be insi
|
48,039
|
CDF and logistic regression
|
There are several issues here. The biggest is that the thinking behind the code for generating the blue points in the second plot is confused. I can't make any sense of what the logic is supposed to be. The $x$ values are the same as your data, but the $y$ values are the number of wins up to that point on the $x$ axis divided by the total number of wins. This really makes no sense. You aren't even dividing by the total number of games, which means you don't have the cumulative probability at that point (although that still wouldn't make sense). This also makes you wonder why the last blue point isn't at $1.0$. Actually it is, but the last point is at $x=55$, which is excluded by your argument xlim=c(-10,50).
At any rate, if you want to get a non-parametric estimate of what the underlying function might be, you could plot a lowess line:
plot(ravenWinNum~ravenScore, data=ravensData)
lines(with(ravensData, lowess(ravenWinNum~ravenScore)))
What is clear from this figure, is that there is a curvilinear relationship between the score and the probability of winning (at least in these data, we can debate whether that makes any theoretical sense). If you thought about it, it was clear from the plot of the raw data in that there are increasing numbers of wins at both the low end and high end of $x$; the losses are in the center. A very simple way to fit a curvilinear relationship is to add a squared term:
lr.Ravens2 <- glm(ravenWinNum~ravenScore+I(ravenScore^2), data=ravensData,
family=binomial)
We can test these models as a whole by assessing their deviance against the null deviance and comparing the result to a chi-squared distribution with the number of degrees of freedom consumed. We do this because we want to think of both the linear term and the squared term together as a unit. This method of testing the model as a whole is analogous to the global $F$-test that comes with a multiple regression model.
# here is the test of the model with the squared term as a whole
1-pchisq(24.435-16.875, df=2)
[1] 0.02282269
# here is the test of your model
1-pchisq(24.435-20.895, df=1)
[1] 0.05990546
# this is the test of the improvement due to adding the squared term
1-pchisq(20.895-16.875, df=1)
[1] 0.04496371
I wouldn't make too much of the arbitrary threshold of significance at $.05$, but we see that the initial model is not significant by conventional standards, or at least is slightly less significant. (Given that you have so few data, I would think a higher $\alpha$ is fine.) The model that includes the squared term as well is more significant, even though it uses up another of your precious few degrees of freedom. The AIC is lower as well: the first model has $AIC=24.895$, whereas the second model has $AIC=22.875$. The last of the tests listed shows that the addition of the squared term yields a significant improvement in fit.
The implication of the fact that there is a curvilinear relationship between $x$ and $y$ is that the function that maps the conditional probability that $y_i=1$ given $x_i$ cannot be equated to a cumulative probability distribution that takes $x$ as its quantiles.
For completeness, here is the same plot with the model's predicted probabilities overlaid:
We see that the predicted probabilities mirror the lowess line reasonably well. Of course, they don't match perfectly, but there is no reason to believe that the lowess line is exactly correct; it just provides a non-parametric approximation of whatever the underlying function is.
Having addressed the specific example in your question, it is worth addressing the assumption underlying the question more broadly. What is the relationship between logistic regression and a cumulative distribution function (CDF)?
There can be a connection between binomial regression and a CDF. For example, when the probit link is used, the conditional probability of 'success' ($\pi_i(Y_i=1|X=x_i)$) is transformed via the inverse of the normal CDF. (For more about that, it may help to read my answer here: difference between logit and probit models.) But there are a couple of points to be made here. First, as @FrankHarrell and @Glen_b note, binomial (e.g., logistic) regression is about modeling conditional probabilities at each point.
Second, although the fitted function can look sort of like a CDF when the conditions are just right, it will never actually be a function (scaled, shifted, etc.) of the CDF of your $X$ data. Your own data serve as an example of the function not even looking like a CDF because you have a polynomial relationship. But it is true even when the function does look like a CDF. The easiest way to understand this is that your last (highest $x$ valued) point will always be 100% of the way through your data, but the fitted function will never reach $\hat p_i=1.0$, it can only approach that value as $X$ (the variable, not your data) approaches infinity. As a result, you should not think of a function of the CDF of your $x$ data as the values the logistic regression is supposed to approximate.
|
CDF and logistic regression
|
There are several issues here. The biggest is that the thinking behind the code for generating the blue points in the second plot is confused. I can't make any sense of what the logic is supposed to
|
CDF and logistic regression
There are several issues here. The biggest is that the thinking behind the code for generating the blue points in the second plot is confused. I can't make any sense of what the logic is supposed to be. The $x$ values are the same as your data, but the $y$ values are the number of wins up to that point on the $x$ axis divided by the total number of wins. This really makes no sense. You aren't even dividing by the total number of games, which means you don't have the cumulative probability at that point (although that still wouldn't make sense). This also makes you wonder why the last blue point isn't at $1.0$. Actually it is, but the last point is at $x=55$, which is excluded by your argument xlim=c(-10,50).
At any rate, if you want to get a non-parametric estimate of what the underlying function might be, you could plot a lowess line:
plot(ravenWinNum~ravenScore, data=ravensData)
lines(with(ravensData, lowess(ravenWinNum~ravenScore)))
What is clear from this figure, is that there is a curvilinear relationship between the score and the probability of winning (at least in these data, we can debate whether that makes any theoretical sense). If you thought about it, it was clear from the plot of the raw data in that there are increasing numbers of wins at both the low end and high end of $x$; the losses are in the center. A very simple way to fit a curvilinear relationship is to add a squared term:
lr.Ravens2 <- glm(ravenWinNum~ravenScore+I(ravenScore^2), data=ravensData,
family=binomial)
We can test these models as a whole by assessing their deviance against the null deviance and comparing the result to a chi-squared distribution with the number of degrees of freedom consumed. We do this because we want to think of both the linear term and the squared term together as a unit. This method of testing the model as a whole is analogous to the global $F$-test that comes with a multiple regression model.
# here is the test of the model with the squared term as a whole
1-pchisq(24.435-16.875, df=2)
[1] 0.02282269
# here is the test of your model
1-pchisq(24.435-20.895, df=1)
[1] 0.05990546
# this is the test of the improvement due to adding the squared term
1-pchisq(20.895-16.875, df=1)
[1] 0.04496371
I wouldn't make too much of the arbitrary threshold of significance at $.05$, but we see that the initial model is not significant by conventional standards, or at least is slightly less significant. (Given that you have so few data, I would think a higher $\alpha$ is fine.) The model that includes the squared term as well is more significant, even though it uses up another of your precious few degrees of freedom. The AIC is lower as well: the first model has $AIC=24.895$, whereas the second model has $AIC=22.875$. The last of the tests listed shows that the addition of the squared term yields a significant improvement in fit.
The implication of the fact that there is a curvilinear relationship between $x$ and $y$ is that the function that maps the conditional probability that $y_i=1$ given $x_i$ cannot be equated to a cumulative probability distribution that takes $x$ as its quantiles.
For completeness, here is the same plot with the model's predicted probabilities overlaid:
We see that the predicted probabilities mirror the lowess line reasonably well. Of course, they don't match perfectly, but there is no reason to believe that the lowess line is exactly correct; it just provides a non-parametric approximation of whatever the underlying function is.
Having addressed the specific example in your question, it is worth addressing the assumption underlying the question more broadly. What is the relationship between logistic regression and a cumulative distribution function (CDF)?
There can be a connection between binomial regression and a CDF. For example, when the probit link is used, the conditional probability of 'success' ($\pi_i(Y_i=1|X=x_i)$) is transformed via the inverse of the normal CDF. (For more about that, it may help to read my answer here: difference between logit and probit models.) But there are a couple of points to be made here. First, as @FrankHarrell and @Glen_b note, binomial (e.g., logistic) regression is about modeling conditional probabilities at each point.
Second, although the fitted function can look sort of like a CDF when the conditions are just right, it will never actually be a function (scaled, shifted, etc.) of the CDF of your $X$ data. Your own data serve as an example of the function not even looking like a CDF because you have a polynomial relationship. But it is true even when the function does look like a CDF. The easiest way to understand this is that your last (highest $x$ valued) point will always be 100% of the way through your data, but the fitted function will never reach $\hat p_i=1.0$, it can only approach that value as $X$ (the variable, not your data) approaches infinity. As a result, you should not think of a function of the CDF of your $x$ data as the values the logistic regression is supposed to approximate.
|
CDF and logistic regression
There are several issues here. The biggest is that the thinking behind the code for generating the blue points in the second plot is confused. I can't make any sense of what the logic is supposed to
|
48,040
|
CDF and logistic regression
|
It would be good to study a standard text on logistic regression. Among other things, you are confusing full conditioning ($Pr[Y=1 | X=x]$ as the logistic model estimates) with partial conditioning ($Pr[Y=1 | X \leq x]$). But more importantly, the model you have fitted is non-stochastic, i.e., the winner is determined with certainty from the two scores.
|
CDF and logistic regression
|
It would be good to study a standard text on logistic regression. Among other things, you are confusing full conditioning ($Pr[Y=1 | X=x]$ as the logistic model estimates) with partial conditioning (
|
CDF and logistic regression
It would be good to study a standard text on logistic regression. Among other things, you are confusing full conditioning ($Pr[Y=1 | X=x]$ as the logistic model estimates) with partial conditioning ($Pr[Y=1 | X \leq x]$). But more importantly, the model you have fitted is non-stochastic, i.e., the winner is determined with certainty from the two scores.
|
CDF and logistic regression
It would be good to study a standard text on logistic regression. Among other things, you are confusing full conditioning ($Pr[Y=1 | X=x]$ as the logistic model estimates) with partial conditioning (
|
48,041
|
CDF and logistic regression
|
What the model gives is an estimate of the conditional (population) proportion of times $Y=1$ at each $x$.
If you plot the actual fitted model against the data it was fitted to:
plot(ravenWinNum~ravenScore, data=ravensData)
points(logRegRavens$fitted~ravenScore,ravensData,col=4,pch=16,cex=.8)
... it doesn't seem like a poor fit at all.
The two things you appear to be comparing don't seem to be comparable, but perhaps you could more clearly explain why they should be.
|
CDF and logistic regression
|
What the model gives is an estimate of the conditional (population) proportion of times $Y=1$ at each $x$.
If you plot the actual fitted model against the data it was fitted to:
plot(ravenWinNum~rave
|
CDF and logistic regression
What the model gives is an estimate of the conditional (population) proportion of times $Y=1$ at each $x$.
If you plot the actual fitted model against the data it was fitted to:
plot(ravenWinNum~ravenScore, data=ravensData)
points(logRegRavens$fitted~ravenScore,ravensData,col=4,pch=16,cex=.8)
... it doesn't seem like a poor fit at all.
The two things you appear to be comparing don't seem to be comparable, but perhaps you could more clearly explain why they should be.
|
CDF and logistic regression
What the model gives is an estimate of the conditional (population) proportion of times $Y=1$ at each $x$.
If you plot the actual fitted model against the data it was fitted to:
plot(ravenWinNum~rave
|
48,042
|
Residual Vs. Fitted Plot with Outliers
|
The fitted values can be outlying because of two reasons:
The predictor values are outlying
The predictor values are quite normal compared to the other predictor variables, however the outcome is outlying because of an extreme error term.
In this case I would study the Cooks distance. If it shows the outlying outcome variables are due to a combination of predictor variables with a high Cooks distance, you might suspect there is something wrong.
And given the four predictor plots, I suspect the outlying outcomes are due to extreme values of factor 1 in combination with factor 3 (which will also result in a high Cooks Distance), and so you might question if your linear model still holds in that region.
Hope this helps and that I did not say anything foolish.
|
Residual Vs. Fitted Plot with Outliers
|
The fitted values can be outlying because of two reasons:
The predictor values are outlying
The predictor values are quite normal compared to the other predictor variables, however the outcome is ou
|
Residual Vs. Fitted Plot with Outliers
The fitted values can be outlying because of two reasons:
The predictor values are outlying
The predictor values are quite normal compared to the other predictor variables, however the outcome is outlying because of an extreme error term.
In this case I would study the Cooks distance. If it shows the outlying outcome variables are due to a combination of predictor variables with a high Cooks distance, you might suspect there is something wrong.
And given the four predictor plots, I suspect the outlying outcomes are due to extreme values of factor 1 in combination with factor 3 (which will also result in a high Cooks Distance), and so you might question if your linear model still holds in that region.
Hope this helps and that I did not say anything foolish.
|
Residual Vs. Fitted Plot with Outliers
The fitted values can be outlying because of two reasons:
The predictor values are outlying
The predictor values are quite normal compared to the other predictor variables, however the outcome is ou
|
48,043
|
Determining similar users from hierarchical clustering
|
If you have done a hierarchical clustering, it outputs a progressive series of more inclusive clusters. If you want to use the hierarchical clustering to determine which users are similar, you can simply look at the returned dendrogram to see which users are joined at the lowest levels. The cophenetic distance makes this idea concrete. It is the inter-group distance when the clusters containing two objects are merged into a single cluster. To see this, here is a simple demonstration in R:
set.seed(9) # this makes the example exactly reproducible
x1 = runif(10) # these data are simple uniform on 2 dimensions
x2 = runif(10) # (i.e., they actually have no cluster structure)
Here is what these data look like:
These are the Euclidean distances between all points:
round(dist(cbind(x1, x2)), digits=3)
1 2 3 4 5 6 7 8 9
2 0.226
3 0.766 0.894
4 0.184 0.350 0.582
5 0.436 0.641 0.457 0.298
6 0.393 0.504 0.390 0.216 0.310
7 0.331 0.538 0.515 0.202 0.105 0.275
8 0.872 1.028 0.187 0.693 0.490 0.531 0.575
9 0.508 0.733 0.699 0.457 0.262 0.553 0.281 0.687
10 0.856 1.082 0.877 0.799 0.548 0.858 0.608 0.790 0.350
Here I run a hierarchical clustering:
HC = hclust(dist(cbind(x1, x2)), method="complete")
Here is what the hierarchical clustering looks like:
To get the cophenetic distance between two points, you follow the lines from those points upwards until the two paths meet. The y-value of the horizontal line where the two paths come together is the cophenetic distance between those two points. This is the distance between the two largest clusters that contain each of the points, but not the other. This is simplest to see at the bottom when each cluster contains only 1 point. For example, the smallest cophenetic distance is between 5 & 7 ($d_c = .105$). Cases like that, where you are joining only two initial points, the cophenetic distance is necessarily equal to the original distance that you used to form the hierarchical clustering, so it isn't very interesting. Perhaps a more interesting case is the cophenetic distance between 3 & 5. Although the original distance between these two points is their Euclidean distance ($d_E = .457$), their cophenetic distance is the distance between the two clusters of which those points are members, just before the clusters are merged into a larger cluster in the hierarchy that encompasses them both. For points 3 & 5, those clusters are {3, 8} & {5, 7, 9, 10}, respectively. The cophenetic distance between those clusters is the complete linkage distance (the maximum distance between any two points in the lower-level clusters) because that's the method I used to form the clustering (i.e., $d_c(3,5) = .877 = d_E(3,10) = .877$).
These are the cophenetic distances between all points based on the output of the hierarchical clustering:
round(cophenetic(HC), digits=3)
1 2 3 4 5 6 7 8 9
2 0.350
3 1.082 1.082
4 0.184 0.350 1.082
5 1.082 1.082 0.877 1.082
6 0.504 0.504 1.082 0.504 1.082
7 1.082 1.082 0.877 1.082 0.105 1.082
8 1.082 1.082 0.187 1.082 0.877 1.082 0.877
9 1.082 1.082 0.877 1.082 0.281 1.082 0.281 0.877
10 1.082 1.082 0.877 1.082 0.608 1.082 0.608 0.877 0.608
We can examine the relationship between the two types of distances by correlating them, and by making a scatterplot of the two distances for each unique pair of points:
cor(cophenetic(HC), dist(cbind(x1, x2)))
[1] 0.5726733
We see that there is a fairly strong correlation ($r = .57$), but we can see other things as well. The points only exist in the upper / left triangular half of the plot because the cophenetic distance cannot be less than the original distance. Cophenetic distances only occur in discrete values and there are lots of ties. At the top of the scatterplot on the left, we also notice that there are some points whose Euclidean distances are quite small, but whose cophenetic distance is quite large (e.g., 4 & 7, with $d_E = .202$ & $d_c = 1.082$).
Note that the cophenetic distances you get will depend on the method used in the hierarchical clustering (here complete) and the underlying distance metric (here Euclidean). If you only want to know which users are most similar, this may or may not help you. First (crucially) determine which distance metric (Euclidean, Jaccard, etc.) best captures the sense of similarity you want to measure, and then that the clustering method is appropriate. Whether the clustering's cophenetic distance should be used depends on whether you think the user's cluster membership should take precedence in some ontological sense.
|
Determining similar users from hierarchical clustering
|
If you have done a hierarchical clustering, it outputs a progressive series of more inclusive clusters. If you want to use the hierarchical clustering to determine which users are similar, you can si
|
Determining similar users from hierarchical clustering
If you have done a hierarchical clustering, it outputs a progressive series of more inclusive clusters. If you want to use the hierarchical clustering to determine which users are similar, you can simply look at the returned dendrogram to see which users are joined at the lowest levels. The cophenetic distance makes this idea concrete. It is the inter-group distance when the clusters containing two objects are merged into a single cluster. To see this, here is a simple demonstration in R:
set.seed(9) # this makes the example exactly reproducible
x1 = runif(10) # these data are simple uniform on 2 dimensions
x2 = runif(10) # (i.e., they actually have no cluster structure)
Here is what these data look like:
These are the Euclidean distances between all points:
round(dist(cbind(x1, x2)), digits=3)
1 2 3 4 5 6 7 8 9
2 0.226
3 0.766 0.894
4 0.184 0.350 0.582
5 0.436 0.641 0.457 0.298
6 0.393 0.504 0.390 0.216 0.310
7 0.331 0.538 0.515 0.202 0.105 0.275
8 0.872 1.028 0.187 0.693 0.490 0.531 0.575
9 0.508 0.733 0.699 0.457 0.262 0.553 0.281 0.687
10 0.856 1.082 0.877 0.799 0.548 0.858 0.608 0.790 0.350
Here I run a hierarchical clustering:
HC = hclust(dist(cbind(x1, x2)), method="complete")
Here is what the hierarchical clustering looks like:
To get the cophenetic distance between two points, you follow the lines from those points upwards until the two paths meet. The y-value of the horizontal line where the two paths come together is the cophenetic distance between those two points. This is the distance between the two largest clusters that contain each of the points, but not the other. This is simplest to see at the bottom when each cluster contains only 1 point. For example, the smallest cophenetic distance is between 5 & 7 ($d_c = .105$). Cases like that, where you are joining only two initial points, the cophenetic distance is necessarily equal to the original distance that you used to form the hierarchical clustering, so it isn't very interesting. Perhaps a more interesting case is the cophenetic distance between 3 & 5. Although the original distance between these two points is their Euclidean distance ($d_E = .457$), their cophenetic distance is the distance between the two clusters of which those points are members, just before the clusters are merged into a larger cluster in the hierarchy that encompasses them both. For points 3 & 5, those clusters are {3, 8} & {5, 7, 9, 10}, respectively. The cophenetic distance between those clusters is the complete linkage distance (the maximum distance between any two points in the lower-level clusters) because that's the method I used to form the clustering (i.e., $d_c(3,5) = .877 = d_E(3,10) = .877$).
These are the cophenetic distances between all points based on the output of the hierarchical clustering:
round(cophenetic(HC), digits=3)
1 2 3 4 5 6 7 8 9
2 0.350
3 1.082 1.082
4 0.184 0.350 1.082
5 1.082 1.082 0.877 1.082
6 0.504 0.504 1.082 0.504 1.082
7 1.082 1.082 0.877 1.082 0.105 1.082
8 1.082 1.082 0.187 1.082 0.877 1.082 0.877
9 1.082 1.082 0.877 1.082 0.281 1.082 0.281 0.877
10 1.082 1.082 0.877 1.082 0.608 1.082 0.608 0.877 0.608
We can examine the relationship between the two types of distances by correlating them, and by making a scatterplot of the two distances for each unique pair of points:
cor(cophenetic(HC), dist(cbind(x1, x2)))
[1] 0.5726733
We see that there is a fairly strong correlation ($r = .57$), but we can see other things as well. The points only exist in the upper / left triangular half of the plot because the cophenetic distance cannot be less than the original distance. Cophenetic distances only occur in discrete values and there are lots of ties. At the top of the scatterplot on the left, we also notice that there are some points whose Euclidean distances are quite small, but whose cophenetic distance is quite large (e.g., 4 & 7, with $d_E = .202$ & $d_c = 1.082$).
Note that the cophenetic distances you get will depend on the method used in the hierarchical clustering (here complete) and the underlying distance metric (here Euclidean). If you only want to know which users are most similar, this may or may not help you. First (crucially) determine which distance metric (Euclidean, Jaccard, etc.) best captures the sense of similarity you want to measure, and then that the clustering method is appropriate. Whether the clustering's cophenetic distance should be used depends on whether you think the user's cluster membership should take precedence in some ontological sense.
|
Determining similar users from hierarchical clustering
If you have done a hierarchical clustering, it outputs a progressive series of more inclusive clusters. If you want to use the hierarchical clustering to determine which users are similar, you can si
|
48,044
|
Interpreting Principal Component Analysis output
|
You appear to be assuming that the largest eigenvalue necessarily can be paired with the largest coefficient within the eigenvectors. That would be wrong.
The question clearly transcends software choice. Here is a fairly silly PCA on five measures of car size using Stata's auto dataset. I used a correlation matrix as starting point, the only sensible option given quite different units of measurement.
. pca headroom trunk weight length displacement
Principal components/correlation Number of obs = 74
Number of comp. = 5
Trace = 5
Rotation: (unrotated = principal) Rho = 1.0000
--------------------------------------------------------------------------
Component | Eigenvalue Difference Proportion Cumulative
-------------+------------------------------------------------------------
Comp1 | 3.76201 3.026 0.7524 0.7524
Comp2 | .736006 .427915 0.1472 0.8996
Comp3 | .308091 .155465 0.0616 0.9612
Comp4 | .152627 .111357 0.0305 0.9917
Comp5 | .0412693 . 0.0083 1.0000
--------------------------------------------------------------------------
Principal components (eigenvectors)
----------------------------------------------------------------
Variable | Comp1 Comp2 Comp3 Comp4 Comp5
-------------+--------------------------------------------------
headroom | 0.3587 0.7640 0.5224 -0.1209 0.0130
trunk | 0.4334 0.3665 -0.7676 0.2914 0.0612
weight | 0.4842 -0.3329 0.0737 -0.2669 0.7603
length | 0.4863 -0.2372 -0.1050 -0.5745 -0.6051
displacement | 0.4610 -0.3390 0.3484 0.7065 -0.2279
----------------------------------------------------------------
(Output truncated.)
The first component picks up on the fact that as all variables are measures of size, they are well correlated. So to first approximation the coefficients are equal; that's to be expected when all the variables hang together. The remaining components in effect pick up the idiosyncratic contribution of each of the original variables. That is not inevitable, but it works out quite simply for this example. But, to your point, you can see that the largest coefficients, say those above 0.7 in absolute value, are associated with components 2 to 5. There is nothing to stop the largest coefficient being associated with the last component.
(UPDATE) The eigenvectors are informative, but it is also helpful to calculate the components themselves as new variables and then look at their correlations with the original variables. Here they are:
pc1 pc2 pc3 pc4 pc5
headroom 0.6958 0.6554 0.2900 -0.0472 0.0026
trunk 0.8405 0.3144 -0.4261 0.1138 0.0124
weight 0.9392 -0.2856 0.0409 -0.1043 0.1545
length 0.9432 -0.2035 -0.0583 -0.2245 -0.1229
displacement 0.8942 -0.2909 0.1934 0.2760 -0.0463
Here trunk is the variable most strongly correlated with pc3, but negatively. A story on why that happens would depend on looking at the data and the PCs. I don't care enough about the example to do that here, but it would be good practice.
Although I produced the example with a little prior thought, and it is suitable for your question, and it is based on real data, it is also salutary: interpreting the PCs may be no easier than interpreting something more direct such as scatter plots and correlations. However, not every PCA application depends on ability to interpret PCs as having substantive meaning, and much of the literature warns against doing that in any case. For some purposes, the whole point is a mechanistic reordering of the information in the data.
|
Interpreting Principal Component Analysis output
|
You appear to be assuming that the largest eigenvalue necessarily can be paired with the largest coefficient within the eigenvectors. That would be wrong.
The question clearly transcends software cho
|
Interpreting Principal Component Analysis output
You appear to be assuming that the largest eigenvalue necessarily can be paired with the largest coefficient within the eigenvectors. That would be wrong.
The question clearly transcends software choice. Here is a fairly silly PCA on five measures of car size using Stata's auto dataset. I used a correlation matrix as starting point, the only sensible option given quite different units of measurement.
. pca headroom trunk weight length displacement
Principal components/correlation Number of obs = 74
Number of comp. = 5
Trace = 5
Rotation: (unrotated = principal) Rho = 1.0000
--------------------------------------------------------------------------
Component | Eigenvalue Difference Proportion Cumulative
-------------+------------------------------------------------------------
Comp1 | 3.76201 3.026 0.7524 0.7524
Comp2 | .736006 .427915 0.1472 0.8996
Comp3 | .308091 .155465 0.0616 0.9612
Comp4 | .152627 .111357 0.0305 0.9917
Comp5 | .0412693 . 0.0083 1.0000
--------------------------------------------------------------------------
Principal components (eigenvectors)
----------------------------------------------------------------
Variable | Comp1 Comp2 Comp3 Comp4 Comp5
-------------+--------------------------------------------------
headroom | 0.3587 0.7640 0.5224 -0.1209 0.0130
trunk | 0.4334 0.3665 -0.7676 0.2914 0.0612
weight | 0.4842 -0.3329 0.0737 -0.2669 0.7603
length | 0.4863 -0.2372 -0.1050 -0.5745 -0.6051
displacement | 0.4610 -0.3390 0.3484 0.7065 -0.2279
----------------------------------------------------------------
(Output truncated.)
The first component picks up on the fact that as all variables are measures of size, they are well correlated. So to first approximation the coefficients are equal; that's to be expected when all the variables hang together. The remaining components in effect pick up the idiosyncratic contribution of each of the original variables. That is not inevitable, but it works out quite simply for this example. But, to your point, you can see that the largest coefficients, say those above 0.7 in absolute value, are associated with components 2 to 5. There is nothing to stop the largest coefficient being associated with the last component.
(UPDATE) The eigenvectors are informative, but it is also helpful to calculate the components themselves as new variables and then look at their correlations with the original variables. Here they are:
pc1 pc2 pc3 pc4 pc5
headroom 0.6958 0.6554 0.2900 -0.0472 0.0026
trunk 0.8405 0.3144 -0.4261 0.1138 0.0124
weight 0.9392 -0.2856 0.0409 -0.1043 0.1545
length 0.9432 -0.2035 -0.0583 -0.2245 -0.1229
displacement 0.8942 -0.2909 0.1934 0.2760 -0.0463
Here trunk is the variable most strongly correlated with pc3, but negatively. A story on why that happens would depend on looking at the data and the PCs. I don't care enough about the example to do that here, but it would be good practice.
Although I produced the example with a little prior thought, and it is suitable for your question, and it is based on real data, it is also salutary: interpreting the PCs may be no easier than interpreting something more direct such as scatter plots and correlations. However, not every PCA application depends on ability to interpret PCs as having substantive meaning, and much of the literature warns against doing that in any case. For some purposes, the whole point is a mechanistic reordering of the information in the data.
|
Interpreting Principal Component Analysis output
You appear to be assuming that the largest eigenvalue necessarily can be paired with the largest coefficient within the eigenvectors. That would be wrong.
The question clearly transcends software cho
|
48,045
|
Why is the state-action value function required when the model is unknown?
|
The $V(s)$'s are sufficient to determine a policy precisely because you have access to the model. In particular you have access to information about the transition structure of the MDP (you know how to look ahead). Without a model you might know you want to get to $s$, but you don't know what actions to take to get there. Q values eliminate the need to estimate the underlying model by just learning what actions are good to take in a state.
This is discussed in the survey by Szepesvari on page 14 where it is noted that knowing either $Q^*$ or $V^*$, $P$ and $r$ suffice for an RL agent to act optimally. Using their notation, $P$ and $r$ are essentially the model.
|
Why is the state-action value function required when the model is unknown?
|
The $V(s)$'s are sufficient to determine a policy precisely because you have access to the model. In particular you have access to information about the transition structure of the MDP (you know how t
|
Why is the state-action value function required when the model is unknown?
The $V(s)$'s are sufficient to determine a policy precisely because you have access to the model. In particular you have access to information about the transition structure of the MDP (you know how to look ahead). Without a model you might know you want to get to $s$, but you don't know what actions to take to get there. Q values eliminate the need to estimate the underlying model by just learning what actions are good to take in a state.
This is discussed in the survey by Szepesvari on page 14 where it is noted that knowing either $Q^*$ or $V^*$, $P$ and $r$ suffice for an RL agent to act optimally. Using their notation, $P$ and $r$ are essentially the model.
|
Why is the state-action value function required when the model is unknown?
The $V(s)$'s are sufficient to determine a policy precisely because you have access to the model. In particular you have access to information about the transition structure of the MDP (you know how t
|
48,046
|
Is this a decent summary of the kernel trick?
|
Yes. Simply put, $k(x,y) = <\Phi(x), \Phi(y)>$ is the kernel trick. Inner product in the feature space is the evaluation of kernel in the input space.
|
Is this a decent summary of the kernel trick?
|
Yes. Simply put, $k(x,y) = <\Phi(x), \Phi(y)>$ is the kernel trick. Inner product in the feature space is the evaluation of kernel in the input space.
|
Is this a decent summary of the kernel trick?
Yes. Simply put, $k(x,y) = <\Phi(x), \Phi(y)>$ is the kernel trick. Inner product in the feature space is the evaluation of kernel in the input space.
|
Is this a decent summary of the kernel trick?
Yes. Simply put, $k(x,y) = <\Phi(x), \Phi(y)>$ is the kernel trick. Inner product in the feature space is the evaluation of kernel in the input space.
|
48,047
|
Is this a decent summary of the kernel trick?
|
There are plenty of references. For example here or less technical but still nicely explained. It is the other way around, problems that can be expressed in terms of dot products are amenable to be "kernelized", i.e. one can apply the kernel trick yielding to better versions of the algorithms.
A really nice paper reviewing applications of kernelization is this one. Happy reading
|
Is this a decent summary of the kernel trick?
|
There are plenty of references. For example here or less technical but still nicely explained. It is the other way around, problems that can be expressed in terms of dot products are amenable to be "
|
Is this a decent summary of the kernel trick?
There are plenty of references. For example here or less technical but still nicely explained. It is the other way around, problems that can be expressed in terms of dot products are amenable to be "kernelized", i.e. one can apply the kernel trick yielding to better versions of the algorithms.
A really nice paper reviewing applications of kernelization is this one. Happy reading
|
Is this a decent summary of the kernel trick?
There are plenty of references. For example here or less technical but still nicely explained. It is the other way around, problems that can be expressed in terms of dot products are amenable to be "
|
48,048
|
Relationships between t distributions and normal distributions
|
I'll let someone else address your first question, but regarding the second bullet point, @Glen_b is right: the $t$ distribution is the posterior, not the prior. The problem here is that there is an ambiguity in the text concerning what phrases are being joined by the "and". Consider these two possibilities:
The t distribution is $($the marginal posterior distribution for the normal mean with unknown variance$)$ and [it is also the] conjugate prior distribution...
vs
The t distribution is the marginal posterior distribution for the normal mean $($with unknown variance and [when the] conjugate prior distribution [had been used]$)$...
The correct interpretation is #2.
|
Relationships between t distributions and normal distributions
|
I'll let someone else address your first question, but regarding the second bullet point, @Glen_b is right: the $t$ distribution is the posterior, not the prior. The problem here is that there is an
|
Relationships between t distributions and normal distributions
I'll let someone else address your first question, but regarding the second bullet point, @Glen_b is right: the $t$ distribution is the posterior, not the prior. The problem here is that there is an ambiguity in the text concerning what phrases are being joined by the "and". Consider these two possibilities:
The t distribution is $($the marginal posterior distribution for the normal mean with unknown variance$)$ and [it is also the] conjugate prior distribution...
vs
The t distribution is the marginal posterior distribution for the normal mean $($with unknown variance and [when the] conjugate prior distribution [had been used]$)$...
The correct interpretation is #2.
|
Relationships between t distributions and normal distributions
I'll let someone else address your first question, but regarding the second bullet point, @Glen_b is right: the $t$ distribution is the posterior, not the prior. The problem here is that there is an
|
48,049
|
Relationships between t distributions and normal distributions
|
Getting away from the heavy duty math and talking in plain English, I just think of the t distribution as a Normal distribution adjusted for greater uncertainty associated with small samples (low DFs in the table). As a result, the t distribution has wider or fatter tails than the Normal Distribution resulting in much wider Confidence Intervals (reflecting the greater uncertainty with small samples). Once n ~ 60 or more, the two distributions become undistinguishable. And, if you conduct hypothesis testing with either the t distribution or the Normal distribution you will get essentially the same p values.
|
Relationships between t distributions and normal distributions
|
Getting away from the heavy duty math and talking in plain English, I just think of the t distribution as a Normal distribution adjusted for greater uncertainty associated with small samples (low DFs
|
Relationships between t distributions and normal distributions
Getting away from the heavy duty math and talking in plain English, I just think of the t distribution as a Normal distribution adjusted for greater uncertainty associated with small samples (low DFs in the table). As a result, the t distribution has wider or fatter tails than the Normal Distribution resulting in much wider Confidence Intervals (reflecting the greater uncertainty with small samples). Once n ~ 60 or more, the two distributions become undistinguishable. And, if you conduct hypothesis testing with either the t distribution or the Normal distribution you will get essentially the same p values.
|
Relationships between t distributions and normal distributions
Getting away from the heavy duty math and talking in plain English, I just think of the t distribution as a Normal distribution adjusted for greater uncertainty associated with small samples (low DFs
|
48,050
|
Why use d-prime instead of percent correct?
|
D' is a measure of sensitivity, whereas proportion correct is affected by both sensitivity and bias.
In the special case of two balanced classes (same number of signal and noise trials) and zero bias, D' is monotonically mapped to proportion correct, offering no additional insight. However, if the two classes are not completely balanced or the bias isn't zero, the two measures can considerably depart. Consider these two examples:
A dataset with 70% signal trials and 30% noise trials. An observer / classifier always responding 'signal' will have 0.7 proportion correct but zero D'.
A dataset with balanced classes and a classifier with D'=1. A zero bias would produce a maximal proportion correct and any increase / decrease in the bias are excepted to decrease the proportion correct (think of the case of extreme biases).
|
Why use d-prime instead of percent correct?
|
D' is a measure of sensitivity, whereas proportion correct is affected by both sensitivity and bias.
In the special case of two balanced classes (same number of signal and noise trials) and zero bias
|
Why use d-prime instead of percent correct?
D' is a measure of sensitivity, whereas proportion correct is affected by both sensitivity and bias.
In the special case of two balanced classes (same number of signal and noise trials) and zero bias, D' is monotonically mapped to proportion correct, offering no additional insight. However, if the two classes are not completely balanced or the bias isn't zero, the two measures can considerably depart. Consider these two examples:
A dataset with 70% signal trials and 30% noise trials. An observer / classifier always responding 'signal' will have 0.7 proportion correct but zero D'.
A dataset with balanced classes and a classifier with D'=1. A zero bias would produce a maximal proportion correct and any increase / decrease in the bias are excepted to decrease the proportion correct (think of the case of extreme biases).
|
Why use d-prime instead of percent correct?
D' is a measure of sensitivity, whereas proportion correct is affected by both sensitivity and bias.
In the special case of two balanced classes (same number of signal and noise trials) and zero bias
|
48,051
|
Meta-analysis of means and medians in R?
|
I thought I would summarize people's suggestions and what I found on my own. It looks like there are meta-analysis methods for analyzing means but not for analyzing medians. These are some sources that are useful for meta-analyzing means:
http://www.stat.rutgers.edu/home/gyang/researches/gmetaRpackage/gmeta.tutorial_2.2-3.pdf
http://www.medicine.mcgill.ca/epidemiology/joseph/pbelisle/forest-plot.html
I was mostly interested in analyzing medians because BLL measurements are almost always highly skewed. However, provided the sample sizes of individual studies are not small, and you are meta-analyzing many studies, the central limit theorem allows you to collapse the individual study means into an overall mean. See the following paper for more explanation: Julian P. T. Higgins et al., Meta-analysis of skewed data: Combining results reported on log-transformed or raw scales, Statist. Med. 2008; 27:6072–6092.
|
Meta-analysis of means and medians in R?
|
I thought I would summarize people's suggestions and what I found on my own. It looks like there are meta-analysis methods for analyzing means but not for analyzing medians. These are some sources tha
|
Meta-analysis of means and medians in R?
I thought I would summarize people's suggestions and what I found on my own. It looks like there are meta-analysis methods for analyzing means but not for analyzing medians. These are some sources that are useful for meta-analyzing means:
http://www.stat.rutgers.edu/home/gyang/researches/gmetaRpackage/gmeta.tutorial_2.2-3.pdf
http://www.medicine.mcgill.ca/epidemiology/joseph/pbelisle/forest-plot.html
I was mostly interested in analyzing medians because BLL measurements are almost always highly skewed. However, provided the sample sizes of individual studies are not small, and you are meta-analyzing many studies, the central limit theorem allows you to collapse the individual study means into an overall mean. See the following paper for more explanation: Julian P. T. Higgins et al., Meta-analysis of skewed data: Combining results reported on log-transformed or raw scales, Statist. Med. 2008; 27:6072–6092.
|
Meta-analysis of means and medians in R?
I thought I would summarize people's suggestions and what I found on my own. It looks like there are meta-analysis methods for analyzing means but not for analyzing medians. These are some sources tha
|
48,052
|
Meta-analysis of means and medians in R?
|
If you have medians and range, then you can get the formula for converting to mean and SD from this sentinel paper by Hozo et al., 2005 (http://www.biomedcentral.com/1471-2288/5/13).
|
Meta-analysis of means and medians in R?
|
If you have medians and range, then you can get the formula for converting to mean and SD from this sentinel paper by Hozo et al., 2005 (http://www.biomedcentral.com/1471-2288/5/13).
|
Meta-analysis of means and medians in R?
If you have medians and range, then you can get the formula for converting to mean and SD from this sentinel paper by Hozo et al., 2005 (http://www.biomedcentral.com/1471-2288/5/13).
|
Meta-analysis of means and medians in R?
If you have medians and range, then you can get the formula for converting to mean and SD from this sentinel paper by Hozo et al., 2005 (http://www.biomedcentral.com/1471-2288/5/13).
|
48,053
|
Meta-analysis of means and medians in R?
|
I came through a useful paper by Wan et al, 2014 and I thought it will be very useful for people interested in doing meta-analysis and are reading this post. The paper has formulas for converting median, range and/or IQR to mean and standard deviations (Click here for the paper). The method presented has improvements over the Hozo et al, 2005.
|
Meta-analysis of means and medians in R?
|
I came through a useful paper by Wan et al, 2014 and I thought it will be very useful for people interested in doing meta-analysis and are reading this post. The paper has formulas for converting medi
|
Meta-analysis of means and medians in R?
I came through a useful paper by Wan et al, 2014 and I thought it will be very useful for people interested in doing meta-analysis and are reading this post. The paper has formulas for converting median, range and/or IQR to mean and standard deviations (Click here for the paper). The method presented has improvements over the Hozo et al, 2005.
|
Meta-analysis of means and medians in R?
I came through a useful paper by Wan et al, 2014 and I thought it will be very useful for people interested in doing meta-analysis and are reading this post. The paper has formulas for converting medi
|
48,054
|
Meta-analysis of means and medians in R?
|
Since this question was posted and answered there has been more work in this area. In two papers McGrath and colleagues discuss working directly with the medians and compare this with the transformation methods referenced in other answers. Their papers are "One-sample aggregate data meta-analysis of medians" available here and "Two-sample aggregate data meta-analysis of medians" available here. These are pre-prints and I believe the first at least may be in press.
The two papers are too long to summarise here but in the first paper on summarising in the one-sample case in a nutshell they show that in their simulations working directly with the median is superior to transforming to the mean. They also use an example data-set where the methods give very different results: delay times in care seeking in China. In the second paper things are more complex but it seems that if the majority of the primary studies have presented medians then a median based method is better and if the majority have presented means then the converse applies. They also present methods based on linear quantile mixed models and methods using the quantiles from each primary study to estimate the underlying unknown distribution in each study.
The methods have been provided in an R package metamedian available from CRAN here
Perhaps also worth noting here that they also reference a later paper with a better transformation method by Luo and colleagues entitled "Optimally estimating the sample mean from the sample size, median, mid-range, and/or mid-quartile range" available here
|
Meta-analysis of means and medians in R?
|
Since this question was posted and answered there has been more work in this area. In two papers McGrath and colleagues discuss working directly with the medians and compare this with the transformati
|
Meta-analysis of means and medians in R?
Since this question was posted and answered there has been more work in this area. In two papers McGrath and colleagues discuss working directly with the medians and compare this with the transformation methods referenced in other answers. Their papers are "One-sample aggregate data meta-analysis of medians" available here and "Two-sample aggregate data meta-analysis of medians" available here. These are pre-prints and I believe the first at least may be in press.
The two papers are too long to summarise here but in the first paper on summarising in the one-sample case in a nutshell they show that in their simulations working directly with the median is superior to transforming to the mean. They also use an example data-set where the methods give very different results: delay times in care seeking in China. In the second paper things are more complex but it seems that if the majority of the primary studies have presented medians then a median based method is better and if the majority have presented means then the converse applies. They also present methods based on linear quantile mixed models and methods using the quantiles from each primary study to estimate the underlying unknown distribution in each study.
The methods have been provided in an R package metamedian available from CRAN here
Perhaps also worth noting here that they also reference a later paper with a better transformation method by Luo and colleagues entitled "Optimally estimating the sample mean from the sample size, median, mid-range, and/or mid-quartile range" available here
|
Meta-analysis of means and medians in R?
Since this question was posted and answered there has been more work in this area. In two papers McGrath and colleagues discuss working directly with the medians and compare this with the transformati
|
48,055
|
Statistical test for uniform distribution
|
To test $U(0,10)$ with $n=5$?
Not with much reliability, unless it's extremely nonuniform.
If you're expecting U-shaped alternatives, you might consider say an Anderson-Darling test, (it usually shows up well in power studies, so it's a good one to keep in mind more generally) -- but the power at $n=5$ is going to be quite low.
It's substantially more powerful than the Kolmogorov-Smirnov test on U-shaped alternatives.
With hill-shaped alternatives (like a beta(3,3), say), at n=5 the Anderson-Darling is very biased (i.e. has much less than $\alpha$ probability to reject), so it's not a great choice there, and the Kolmogorov-Smirnov test does better (though it, too, is biased - which means you have more power against a beta(3,3) by rolling a 20 sided die and rejecting when it comes up with a '1').
Here's an idea of how serious the bias problem is at n=5 (here I used a significance level of 10%, since $n$ is so small):
With a skew alternative that "piles up" probability at one end (such as a beta(2,1)), the power of the two tests is reasonable - somewhat like the power for the U-shape case, but the power of the two is more similar.
With those problems in mind, here are some followup questions:
Why are you testing uniformity?
Do you have any sense of likely alternatives?
(If you can narrow down the alternatives, you may be able to construct a test that has at least a little bit of power.)
What are the relative costs of the two types of error?
|
Statistical test for uniform distribution
|
To test $U(0,10)$ with $n=5$?
Not with much reliability, unless it's extremely nonuniform.
If you're expecting U-shaped alternatives, you might consider say an Anderson-Darling test, (it usually show
|
Statistical test for uniform distribution
To test $U(0,10)$ with $n=5$?
Not with much reliability, unless it's extremely nonuniform.
If you're expecting U-shaped alternatives, you might consider say an Anderson-Darling test, (it usually shows up well in power studies, so it's a good one to keep in mind more generally) -- but the power at $n=5$ is going to be quite low.
It's substantially more powerful than the Kolmogorov-Smirnov test on U-shaped alternatives.
With hill-shaped alternatives (like a beta(3,3), say), at n=5 the Anderson-Darling is very biased (i.e. has much less than $\alpha$ probability to reject), so it's not a great choice there, and the Kolmogorov-Smirnov test does better (though it, too, is biased - which means you have more power against a beta(3,3) by rolling a 20 sided die and rejecting when it comes up with a '1').
Here's an idea of how serious the bias problem is at n=5 (here I used a significance level of 10%, since $n$ is so small):
With a skew alternative that "piles up" probability at one end (such as a beta(2,1)), the power of the two tests is reasonable - somewhat like the power for the U-shape case, but the power of the two is more similar.
With those problems in mind, here are some followup questions:
Why are you testing uniformity?
Do you have any sense of likely alternatives?
(If you can narrow down the alternatives, you may be able to construct a test that has at least a little bit of power.)
What are the relative costs of the two types of error?
|
Statistical test for uniform distribution
To test $U(0,10)$ with $n=5$?
Not with much reliability, unless it's extremely nonuniform.
If you're expecting U-shaped alternatives, you might consider say an Anderson-Darling test, (it usually show
|
48,056
|
When is a sample proportion p hat instead of x bar
|
Both questions are essentially applications of the Central Limit Theorem, which says (informally) that "the value of a sum over many samples from a common population will tend to a normal distribution as the number of samples becomes large".
The two questions differ in the type of data that they treat. The "xbar" question concerns temperature, which is a continuous measurement (e.g. a decimal number). The "phat" question implicitly concerns a binary measurement (true/false, e.g. each student either invests or does not).
Commonly a measurement of a random variable will be denoted by $x$. For a random sample $x_1,\ldots,x_N$ the sample mean will then be denoted by $\bar{x}=\frac{1}{N}\sum_ix_i$. This applies directly to the "xbar" question. Here each $x_i$ is a temperature measurement, and the question asks about the sampling distribution of $\bar{x}$. (This arises when $\bar{x}$ is computed many times over different samples, each of size $N$).
For the "phat" question, the notation and logic is consistent with this, but the connection is a little more involved. In this case each $x_i$ will correspond to an individual student, who either invests ($x=1$) or does not ($x=0$). The probability that a student will invest would commonly be denoted by $p$ ($=30\%$ in this case). These conventions of $\Pr[\text{true}]=p$ and $\{\text{true,false}\}=\{1,0\}$ are standard for the case of a binary random variable.
Now imagine we do not know the value of $p$, but wish to estimate it from a random sample of students $x_1,\ldots,x_N$. For a single student the expected value of $x_i$ is $p$, denoted $\mathbb{E}[x]=p$ (see also here). Similarly, by the properties of expectation, for the sample we have $\mathbb{E}[\bar{x}]=p$. So here the sample mean $\bar{x}$ provides an estimate of the population parameter $p$. In statistics it is standard practice to denote an estimate of a population parameter by using a "hat", so here we it makes sense to denote the sample mean as $\hat{p}$.
(For the "xbar" problem the comparable notation would be $\bar{x}=\hat{\mu}$, as there $x$ is normal rather than Bernoulli.)
|
When is a sample proportion p hat instead of x bar
|
Both questions are essentially applications of the Central Limit Theorem, which says (informally) that "the value of a sum over many samples from a common population will tend to a normal distribution
|
When is a sample proportion p hat instead of x bar
Both questions are essentially applications of the Central Limit Theorem, which says (informally) that "the value of a sum over many samples from a common population will tend to a normal distribution as the number of samples becomes large".
The two questions differ in the type of data that they treat. The "xbar" question concerns temperature, which is a continuous measurement (e.g. a decimal number). The "phat" question implicitly concerns a binary measurement (true/false, e.g. each student either invests or does not).
Commonly a measurement of a random variable will be denoted by $x$. For a random sample $x_1,\ldots,x_N$ the sample mean will then be denoted by $\bar{x}=\frac{1}{N}\sum_ix_i$. This applies directly to the "xbar" question. Here each $x_i$ is a temperature measurement, and the question asks about the sampling distribution of $\bar{x}$. (This arises when $\bar{x}$ is computed many times over different samples, each of size $N$).
For the "phat" question, the notation and logic is consistent with this, but the connection is a little more involved. In this case each $x_i$ will correspond to an individual student, who either invests ($x=1$) or does not ($x=0$). The probability that a student will invest would commonly be denoted by $p$ ($=30\%$ in this case). These conventions of $\Pr[\text{true}]=p$ and $\{\text{true,false}\}=\{1,0\}$ are standard for the case of a binary random variable.
Now imagine we do not know the value of $p$, but wish to estimate it from a random sample of students $x_1,\ldots,x_N$. For a single student the expected value of $x_i$ is $p$, denoted $\mathbb{E}[x]=p$ (see also here). Similarly, by the properties of expectation, for the sample we have $\mathbb{E}[\bar{x}]=p$. So here the sample mean $\bar{x}$ provides an estimate of the population parameter $p$. In statistics it is standard practice to denote an estimate of a population parameter by using a "hat", so here we it makes sense to denote the sample mean as $\hat{p}$.
(For the "xbar" problem the comparable notation would be $\bar{x}=\hat{\mu}$, as there $x$ is normal rather than Bernoulli.)
|
When is a sample proportion p hat instead of x bar
Both questions are essentially applications of the Central Limit Theorem, which says (informally) that "the value of a sum over many samples from a common population will tend to a normal distribution
|
48,057
|
When is a sample proportion p hat instead of x bar
|
Below one could be a handy tip. The image clearly distinguishes between sample mean and sample proportions.
Source
Source info: UF Biostatistics Open learning textbook, Module 9, Sampling Distribution of the Sample Mean (in case link dies out in future)
|
When is a sample proportion p hat instead of x bar
|
Below one could be a handy tip. The image clearly distinguishes between sample mean and sample proportions.
Source
Source info: UF Biostatistics Open learning textbook, Module 9, Sampling Distributi
|
When is a sample proportion p hat instead of x bar
Below one could be a handy tip. The image clearly distinguishes between sample mean and sample proportions.
Source
Source info: UF Biostatistics Open learning textbook, Module 9, Sampling Distribution of the Sample Mean (in case link dies out in future)
|
When is a sample proportion p hat instead of x bar
Below one could be a handy tip. The image clearly distinguishes between sample mean and sample proportions.
Source
Source info: UF Biostatistics Open learning textbook, Module 9, Sampling Distributi
|
48,058
|
ROC graph interpretation
|
The accuracy is the ratio of correct results (true positives and true negatives) to total number of tests. If you classify the first six results in the table are "positive" and the rest are "negative", that gives 5 true positives and 9 true negatives. The accuracy is 14/20, which is higher than any other threshold point on the curve.
If you use this classification rule, 5/6 of the data you classify as "positive" are correct, but only 9/14 of those you classify as "negative" are really negative. Seeing an observation classified as "positive" is more trustworthy than seeing a "negative" classification.
A decision rule that classifies scores $\geq .54$ as "positive" is the threshold that chooses the top 6 scores in this sample.
A balanced distribution of the score would imply that true negatives get high scores just as often as true positives get low scores. And in this example it looks like we're assuming that the proportions are .50-.50 positive and negative.
|
ROC graph interpretation
|
The accuracy is the ratio of correct results (true positives and true negatives) to total number of tests. If you classify the first six results in the table are "positive" and the rest are "negative"
|
ROC graph interpretation
The accuracy is the ratio of correct results (true positives and true negatives) to total number of tests. If you classify the first six results in the table are "positive" and the rest are "negative", that gives 5 true positives and 9 true negatives. The accuracy is 14/20, which is higher than any other threshold point on the curve.
If you use this classification rule, 5/6 of the data you classify as "positive" are correct, but only 9/14 of those you classify as "negative" are really negative. Seeing an observation classified as "positive" is more trustworthy than seeing a "negative" classification.
A decision rule that classifies scores $\geq .54$ as "positive" is the threshold that chooses the top 6 scores in this sample.
A balanced distribution of the score would imply that true negatives get high scores just as often as true positives get low scores. And in this example it looks like we're assuming that the proportions are .50-.50 positive and negative.
|
ROC graph interpretation
The accuracy is the ratio of correct results (true positives and true negatives) to total number of tests. If you classify the first six results in the table are "positive" and the rest are "negative"
|
48,059
|
ROC graph interpretation
|
My understanding is that these are not mathematical assessments. One way to get a best point on the curve is to find the one most protruding in the 10:45 clock direction. But that's assuming you care about fpr equally as tpr, which is not always the case. All subsequent statements are based on this choice.
|
ROC graph interpretation
|
My understanding is that these are not mathematical assessments. One way to get a best point on the curve is to find the one most protruding in the 10:45 clock direction. But that's assuming you care
|
ROC graph interpretation
My understanding is that these are not mathematical assessments. One way to get a best point on the curve is to find the one most protruding in the 10:45 clock direction. But that's assuming you care about fpr equally as tpr, which is not always the case. All subsequent statements are based on this choice.
|
ROC graph interpretation
My understanding is that these are not mathematical assessments. One way to get a best point on the curve is to find the one most protruding in the 10:45 clock direction. But that's assuming you care
|
48,060
|
How do i predict with standard errors using betareg package in R?
|
I've thought about two alternatives to get the prediction interval of the mean of the response:
The paper Ferrari, S.L.P., and Cribari-Neto, F. (2004). Beta Regression for Modeling Rates and Proportions. Journal of Applied Statistics, 31(7), 799–815. (which is in the betareg function references) presents the math formula (in Appendix B) to calculate the exact interval for a given confidence value. But it doesn't seem easy to implement.
Estimate prediction interval through bootstrapping.
|
How do i predict with standard errors using betareg package in R?
|
I've thought about two alternatives to get the prediction interval of the mean of the response:
The paper Ferrari, S.L.P., and Cribari-Neto, F. (2004). Beta Regression for Modeling Rates and Proporti
|
How do i predict with standard errors using betareg package in R?
I've thought about two alternatives to get the prediction interval of the mean of the response:
The paper Ferrari, S.L.P., and Cribari-Neto, F. (2004). Beta Regression for Modeling Rates and Proportions. Journal of Applied Statistics, 31(7), 799–815. (which is in the betareg function references) presents the math formula (in Appendix B) to calculate the exact interval for a given confidence value. But it doesn't seem easy to implement.
Estimate prediction interval through bootstrapping.
|
How do i predict with standard errors using betareg package in R?
I've thought about two alternatives to get the prediction interval of the mean of the response:
The paper Ferrari, S.L.P., and Cribari-Neto, F. (2004). Beta Regression for Modeling Rates and Proporti
|
48,061
|
How do i predict with standard errors using betareg package in R?
|
I have used the package 'effects' and the function allEffects()
BetaReg <- betareg(Value~x, data = Data)
Effects <- as.data.frame(allEffects(BetaReg, xlevels=list(x=BetaReg$x)))$x
Effects
I think it is correct (looks about right on a graph) :)
|
How do i predict with standard errors using betareg package in R?
|
I have used the package 'effects' and the function allEffects()
BetaReg <- betareg(Value~x, data = Data)
Effects <- as.data.frame(allEffects(BetaReg, xlevels=list(x=BetaReg$x)))$x
Effects
I think it
|
How do i predict with standard errors using betareg package in R?
I have used the package 'effects' and the function allEffects()
BetaReg <- betareg(Value~x, data = Data)
Effects <- as.data.frame(allEffects(BetaReg, xlevels=list(x=BetaReg$x)))$x
Effects
I think it is correct (looks about right on a graph) :)
|
How do i predict with standard errors using betareg package in R?
I have used the package 'effects' and the function allEffects()
BetaReg <- betareg(Value~x, data = Data)
Effects <- as.data.frame(allEffects(BetaReg, xlevels=list(x=BetaReg$x)))$x
Effects
I think it
|
48,062
|
Express product as convolution? Or, given $f(s)$, find $g$ satisfying $f(s)=\mathbb{E}[g(X)]$ where $X\sim \mathcal{N}(0,s^2)$
|
The short answer is yes and what you want to do is work on the topological group $\mathbb{R}^*$ equipped with the Haar measure $\mu(A) = \int_A \frac{1}{|x|}dx$.
It essentially computes what you computed with log because $e^x : \mathbb{R} \rightarrow \mathbb{R}^*_{\geq 0}$ is a map of topological groups. It takes the interval $[a,b]$ to $[e^a,e^b]$. The size of $[e^a, e^b]$ in $\mathbb{R}^*$ with the Haar measure above is $b=log(e^b)-log(e^a)=a$ which is the measure of $[a,b]$ in $\mathbb{R}$.
Take $\Psi (y) = \frac{1}{|y|}\phi(\frac{1}{y})$. To compute $f(\sigma)$ as a convolution consider
$$\begin{eqnarray*}
f(\sigma) &=& \frac{1}{\sigma}\int_{-\infty}^{\infty} g(x)\phi(\frac{x}{\sigma})dx\\
&=& \frac{1}{\sigma}\int_{-\infty}^{\infty}g(x)\Psi(\frac{\sigma}{x})\frac{\sigma}{|x|}dx\\
&=& \int_{\mathbb{R}^*}g(x)\Psi(\sigma x^{-1})d\mu\\
&=& (g * \Psi)(\sigma).
\end{eqnarray*}$$
Now you can try the same strategy for computing $g$ by using Fourier theory for $\mathbb{R}^*$.
|
Express product as convolution? Or, given $f(s)$, find $g$ satisfying $f(s)=\mathbb{E}[g(X)]$ where
|
The short answer is yes and what you want to do is work on the topological group $\mathbb{R}^*$ equipped with the Haar measure $\mu(A) = \int_A \frac{1}{|x|}dx$.
It essentially computes what you comp
|
Express product as convolution? Or, given $f(s)$, find $g$ satisfying $f(s)=\mathbb{E}[g(X)]$ where $X\sim \mathcal{N}(0,s^2)$
The short answer is yes and what you want to do is work on the topological group $\mathbb{R}^*$ equipped with the Haar measure $\mu(A) = \int_A \frac{1}{|x|}dx$.
It essentially computes what you computed with log because $e^x : \mathbb{R} \rightarrow \mathbb{R}^*_{\geq 0}$ is a map of topological groups. It takes the interval $[a,b]$ to $[e^a,e^b]$. The size of $[e^a, e^b]$ in $\mathbb{R}^*$ with the Haar measure above is $b=log(e^b)-log(e^a)=a$ which is the measure of $[a,b]$ in $\mathbb{R}$.
Take $\Psi (y) = \frac{1}{|y|}\phi(\frac{1}{y})$. To compute $f(\sigma)$ as a convolution consider
$$\begin{eqnarray*}
f(\sigma) &=& \frac{1}{\sigma}\int_{-\infty}^{\infty} g(x)\phi(\frac{x}{\sigma})dx\\
&=& \frac{1}{\sigma}\int_{-\infty}^{\infty}g(x)\Psi(\frac{\sigma}{x})\frac{\sigma}{|x|}dx\\
&=& \int_{\mathbb{R}^*}g(x)\Psi(\sigma x^{-1})d\mu\\
&=& (g * \Psi)(\sigma).
\end{eqnarray*}$$
Now you can try the same strategy for computing $g$ by using Fourier theory for $\mathbb{R}^*$.
|
Express product as convolution? Or, given $f(s)$, find $g$ satisfying $f(s)=\mathbb{E}[g(X)]$ where
The short answer is yes and what you want to do is work on the topological group $\mathbb{R}^*$ equipped with the Haar measure $\mu(A) = \int_A \frac{1}{|x|}dx$.
It essentially computes what you comp
|
48,063
|
How to conditionally run element of JAGS script based on user supplied variable?
|
Here is one example of implementing a basic macro substitution system for JAGS scripts.
Explanation of the system
Define a function that takes as arguments any optional elements of the script.
For any aspects of the script that vary across argument values, record a macro token. This should be some unique text. Starting and ending with some symbols may assist to make this unambiguous.
For each macro token include code for what the replacement string should be under all possible combinations of the function arguments.
Replace the macro tokens with appropriate placement text based on arguments.
The code below provides one example of how macros could be specified and how to apply the macros to the raw script (suggestions for doing this more elegantly are welcome).
The function returns a replaced model string that could if necessary be passed to a textConnection function for use with rjags.
I like this system for a few reasons:
the raw script is easy to read
the resulting script has proper indentation
you don't have to worry about errors related to commands appearing on the same line
Example
Specifically, this example, aims to allow the user to fit a particular type of multilevel nonlinear model. It is designed to allow for three functional forms: a two parameter power, three parameter power, and a three parameter exponential.
The macro section structures macros as a list of lists. The top level list contains one element for each macro token. For each macro token, there is the macro token text, and the conditional replacement text.
Finally, a for loop applies all the macro replacements to the raw script.
See below (scrolling is required):
jags_model <- function (f=c('power2', 'power3', 'exp3')) {
f <- match.arg(f)
# raw script
script <-
"model {
# Model
for (i in 1:length(y)) {
$FUNCTION
y[i] ~ dnorm(mu[i], tau[subject[i]])
}
# Random coefficients
for (i in 1:N) {
theta1[i] ~ dnorm(theta1.mu, theta1.tau)T(0, 1000)
theta2[i] ~ dnorm(theta2.mu, theta2.tau)T(-10, 0)
$THETA3DISTRIBUTION
sigma[i] ~ dnorm(sigma.mu, sigma.tau)T(0, 100);
tau[i] <- 1/(sigma[i]^2)
}
theta1.mu ~ dunif(0, 100)
theta2.mu ~ dunif(-2, 0)
$THETA3PRIOR.MU
sigma.mu ~ dunif(0, 20)
theta1.sigma ~ dunif(0, 100)
theta2.sigma ~ dunif(0, 2)
$THETA3PRIOR.SIGMA
sigma.sigma ~ dunif(0, 10)
# Transformations
theta1.tau <- 1/(theta1.sigma^2)
theta2.tau <- 1/(theta2.sigma^2)
$THETA3.TAU
sigma.tau <- 1/(sigma.sigma^2)
}"
# define macros
macros <- list(list("$FUNCTION",
switch(f,
power2="mu[i] <- theta1[subject[i]] * pow(trial[i], theta2[subject[i]])",
power3="mu[i] <- theta1[subject[i]] * pow(trial[i], theta2[subject[i]]) + theta3[subject[i]];",
exp3="mu[i] <- theta1[subject[i]] * exp(theta2[subject[i]] * (trial[i] - 1)) + theta3[subject[i]];") ),
list("$THETA3DISTRIBUTION",
switch(f,
power3=, exp3= "theta3[i] ~ dnorm(theta3.mu, theta3.tau)T(0, 1000)",
power2="") ),
list("$THETA3PRIOR.MU",
switch(f,
power3=, exp3= "theta3.mu ~ dunif(0, 100)",
power2="") ),
list("$THETA3PRIOR.SIGMA",
switch(f,
power3=, exp3= "theta3.sigma ~ dunif(0, 100)",
power2="") ),
list("$THETA3.TAU",
switch(f,
power3=, exp3= "theta3.tau <- 1/(theta3.sigma^2)",
power2="") )
)
# apply macros
for (m in seq(macros)) {
script <- gsub(macros[[m]][1], macros[[m]][2], script, fixed=TRUE)
}
script
}
Demonstration
Thus, we can produce the processed JAGS model with
x <- jags_model(f='power3')
And if we want to view the resulting model, we can do
cat(x)
which results in
model {
# Model
for (i in 1:length(y)) {
mu[i] <- theta1[subject[i]] * pow(trial[i], theta2[subject[i]]) + theta3[subject[i]];
y[i] ~ dnorm(mu[i], tau[subject[i]])
}
# Random coefficients
for (i in 1:N) {
theta1[i] ~ dnorm(theta1.mu, theta1.tau)T(0, 1000)
theta2[i] ~ dnorm(theta2.mu, theta2.tau)T(-10, 0)
theta3[i] ~ dnorm(theta3.mu, theta3.tau)T(0, 1000)
sigma[i] ~ dnorm(sigma.mu, sigma.tau)T(0, 100);
tau[i] <- 1/(sigma[i]^2)
}
theta1.mu ~ dunif(0, 100)
theta2.mu ~ dunif(-2, 0)
theta3.mu ~ dunif(0, 100)
sigma.mu ~ dunif(0, 20)
theta1.sigma ~ dunif(0, 100)
theta2.sigma ~ dunif(0, 2)
theta3.sigma ~ dunif(0, 100)
sigma.sigma ~ dunif(0, 10)
# Transformations
theta1.tau <- 1/(theta1.sigma^2)
theta2.tau <- 1/(theta2.sigma^2)
theta3.tau <- 1/(theta3.sigma^2)
sigma.tau <- 1/(sigma.sigma^2)
}
|
How to conditionally run element of JAGS script based on user supplied variable?
|
Here is one example of implementing a basic macro substitution system for JAGS scripts.
Explanation of the system
Define a function that takes as arguments any optional elements of the script.
For an
|
How to conditionally run element of JAGS script based on user supplied variable?
Here is one example of implementing a basic macro substitution system for JAGS scripts.
Explanation of the system
Define a function that takes as arguments any optional elements of the script.
For any aspects of the script that vary across argument values, record a macro token. This should be some unique text. Starting and ending with some symbols may assist to make this unambiguous.
For each macro token include code for what the replacement string should be under all possible combinations of the function arguments.
Replace the macro tokens with appropriate placement text based on arguments.
The code below provides one example of how macros could be specified and how to apply the macros to the raw script (suggestions for doing this more elegantly are welcome).
The function returns a replaced model string that could if necessary be passed to a textConnection function for use with rjags.
I like this system for a few reasons:
the raw script is easy to read
the resulting script has proper indentation
you don't have to worry about errors related to commands appearing on the same line
Example
Specifically, this example, aims to allow the user to fit a particular type of multilevel nonlinear model. It is designed to allow for three functional forms: a two parameter power, three parameter power, and a three parameter exponential.
The macro section structures macros as a list of lists. The top level list contains one element for each macro token. For each macro token, there is the macro token text, and the conditional replacement text.
Finally, a for loop applies all the macro replacements to the raw script.
See below (scrolling is required):
jags_model <- function (f=c('power2', 'power3', 'exp3')) {
f <- match.arg(f)
# raw script
script <-
"model {
# Model
for (i in 1:length(y)) {
$FUNCTION
y[i] ~ dnorm(mu[i], tau[subject[i]])
}
# Random coefficients
for (i in 1:N) {
theta1[i] ~ dnorm(theta1.mu, theta1.tau)T(0, 1000)
theta2[i] ~ dnorm(theta2.mu, theta2.tau)T(-10, 0)
$THETA3DISTRIBUTION
sigma[i] ~ dnorm(sigma.mu, sigma.tau)T(0, 100);
tau[i] <- 1/(sigma[i]^2)
}
theta1.mu ~ dunif(0, 100)
theta2.mu ~ dunif(-2, 0)
$THETA3PRIOR.MU
sigma.mu ~ dunif(0, 20)
theta1.sigma ~ dunif(0, 100)
theta2.sigma ~ dunif(0, 2)
$THETA3PRIOR.SIGMA
sigma.sigma ~ dunif(0, 10)
# Transformations
theta1.tau <- 1/(theta1.sigma^2)
theta2.tau <- 1/(theta2.sigma^2)
$THETA3.TAU
sigma.tau <- 1/(sigma.sigma^2)
}"
# define macros
macros <- list(list("$FUNCTION",
switch(f,
power2="mu[i] <- theta1[subject[i]] * pow(trial[i], theta2[subject[i]])",
power3="mu[i] <- theta1[subject[i]] * pow(trial[i], theta2[subject[i]]) + theta3[subject[i]];",
exp3="mu[i] <- theta1[subject[i]] * exp(theta2[subject[i]] * (trial[i] - 1)) + theta3[subject[i]];") ),
list("$THETA3DISTRIBUTION",
switch(f,
power3=, exp3= "theta3[i] ~ dnorm(theta3.mu, theta3.tau)T(0, 1000)",
power2="") ),
list("$THETA3PRIOR.MU",
switch(f,
power3=, exp3= "theta3.mu ~ dunif(0, 100)",
power2="") ),
list("$THETA3PRIOR.SIGMA",
switch(f,
power3=, exp3= "theta3.sigma ~ dunif(0, 100)",
power2="") ),
list("$THETA3.TAU",
switch(f,
power3=, exp3= "theta3.tau <- 1/(theta3.sigma^2)",
power2="") )
)
# apply macros
for (m in seq(macros)) {
script <- gsub(macros[[m]][1], macros[[m]][2], script, fixed=TRUE)
}
script
}
Demonstration
Thus, we can produce the processed JAGS model with
x <- jags_model(f='power3')
And if we want to view the resulting model, we can do
cat(x)
which results in
model {
# Model
for (i in 1:length(y)) {
mu[i] <- theta1[subject[i]] * pow(trial[i], theta2[subject[i]]) + theta3[subject[i]];
y[i] ~ dnorm(mu[i], tau[subject[i]])
}
# Random coefficients
for (i in 1:N) {
theta1[i] ~ dnorm(theta1.mu, theta1.tau)T(0, 1000)
theta2[i] ~ dnorm(theta2.mu, theta2.tau)T(-10, 0)
theta3[i] ~ dnorm(theta3.mu, theta3.tau)T(0, 1000)
sigma[i] ~ dnorm(sigma.mu, sigma.tau)T(0, 100);
tau[i] <- 1/(sigma[i]^2)
}
theta1.mu ~ dunif(0, 100)
theta2.mu ~ dunif(-2, 0)
theta3.mu ~ dunif(0, 100)
sigma.mu ~ dunif(0, 20)
theta1.sigma ~ dunif(0, 100)
theta2.sigma ~ dunif(0, 2)
theta3.sigma ~ dunif(0, 100)
sigma.sigma ~ dunif(0, 10)
# Transformations
theta1.tau <- 1/(theta1.sigma^2)
theta2.tau <- 1/(theta2.sigma^2)
theta3.tau <- 1/(theta3.sigma^2)
sigma.tau <- 1/(sigma.sigma^2)
}
|
How to conditionally run element of JAGS script based on user supplied variable?
Here is one example of implementing a basic macro substitution system for JAGS scripts.
Explanation of the system
Define a function that takes as arguments any optional elements of the script.
For an
|
48,064
|
How to conditionally run element of JAGS script based on user supplied variable?
|
In this specific case you could set the beta2 term to zero
for (i in 1:length(y)) {
mu[i] <- beta1 + indicator[i] * beta2 * time[i]
y[i] ~ dnorm(mu[i], tau)
}
where indicator[] is a vector that is one for those data points that you want to model with beta2 and 0 otherwise. You could also use a scalar to change the model as a whole. However, this approach is probably less efficient because it still samples from an unwanted parameter distribution. I have used the gsub approach before, but I agree it's not pretty.
If the model is written and executed in an R script it can be manipulated as any other string:
modelstring <- paste("
model {
for ( i in 1:N ) {
",ifelse(timevariable,"
mu[i] <- beta1 + beta2 * time[i]
","mu[i] <- beta1"),"
}
y[i] ~ dnorm(mu[i], tau)
}
")
writeLines(modelstring,con=filename)
|
How to conditionally run element of JAGS script based on user supplied variable?
|
In this specific case you could set the beta2 term to zero
for (i in 1:length(y)) {
mu[i] <- beta1 + indicator[i] * beta2 * time[i]
y[i] ~ dnorm(mu[i], tau)
}
where indicator[] is a vector t
|
How to conditionally run element of JAGS script based on user supplied variable?
In this specific case you could set the beta2 term to zero
for (i in 1:length(y)) {
mu[i] <- beta1 + indicator[i] * beta2 * time[i]
y[i] ~ dnorm(mu[i], tau)
}
where indicator[] is a vector that is one for those data points that you want to model with beta2 and 0 otherwise. You could also use a scalar to change the model as a whole. However, this approach is probably less efficient because it still samples from an unwanted parameter distribution. I have used the gsub approach before, but I agree it's not pretty.
If the model is written and executed in an R script it can be manipulated as any other string:
modelstring <- paste("
model {
for ( i in 1:N ) {
",ifelse(timevariable,"
mu[i] <- beta1 + beta2 * time[i]
","mu[i] <- beta1"),"
}
y[i] ~ dnorm(mu[i], tau)
}
")
writeLines(modelstring,con=filename)
|
How to conditionally run element of JAGS script based on user supplied variable?
In this specific case you could set the beta2 term to zero
for (i in 1:length(y)) {
mu[i] <- beta1 + indicator[i] * beta2 * time[i]
y[i] ~ dnorm(mu[i], tau)
}
where indicator[] is a vector t
|
48,065
|
Estimate of variance with the lowest mean square error
|
Define
$$s^2_d = \frac{\sum_{i=1}^n\left(x_i-\bar{x}\,\right)^2}{d}$$
The statistic $(n - 1)s_{n-1}^2 / \sigma^2$ follows a $\chi^2_{n-1}$ distribution. A $\chi^2_{n-1}$ has mean $n-1$ and variance $2(n-1)$. Hence $\text{E}(s_{n-1}^2) = \sigma^2$, and $\text{Var}(s_{n-1}^2) = 2\frac{\sigma^4 }{ n - 1}$.
Now $s_d^2 = \frac{n-1}{d} s_{n-1}^2$
$$\text{Bias}(s_d^2) = E(s_d^2)-\sigma^2 = \frac{n-1}{d}\sigma^2 -\sigma^2=\frac{n-1-d}{d}\sigma^2$$
$$\text {Var}(s_d^2) = 2\sigma^4(n - 1) / d^2$$
$$\text{MSE} = \text{Bias}^2 + \text{Var}$$
Hence
\begin{eqnarray}
\text{MSE}(s_d^2) &=& \left(\frac{n-1-d}{d}\right)^2\sigma^4+ 2\sigma^4(n - 1) / d^2\\
&=&\sigma^4\frac{(n-1-d)^2+2(n-1)}{d^2}\\
&=&\sigma^4\,f(d)\,,\end{eqnarray}
where $f(d)=1+\frac{(n-1)^2 + 2(n-1)-2(n-1)d}{d^2}$
$f(d)$ is at a turning point when $f'(d)=0$
i.e. when $d(-2(n-1))-2((n-1)^2 + 2(n-1)-2(n-1)d) = 0$
which occurs when $d-2=n-1$ ... i.e. when $d=n+1$
Showing that's a minimum rather than a maximum (or indeed a horizontal point of inflexion) is straightforward, but I'll leave it at that for now.
The relevant Wikipedia page does it more generally, getting a formula in terms of the excess kurtosis (which gives the same result in this case). I may incorporate an outline of that derivation at some point.
|
Estimate of variance with the lowest mean square error
|
Define
$$s^2_d = \frac{\sum_{i=1}^n\left(x_i-\bar{x}\,\right)^2}{d}$$
The statistic $(n - 1)s_{n-1}^2 / \sigma^2$ follows a $\chi^2_{n-1}$ distribution. A $\chi^2_{n-1}$ has mean $n-1$ and variance $2
|
Estimate of variance with the lowest mean square error
Define
$$s^2_d = \frac{\sum_{i=1}^n\left(x_i-\bar{x}\,\right)^2}{d}$$
The statistic $(n - 1)s_{n-1}^2 / \sigma^2$ follows a $\chi^2_{n-1}$ distribution. A $\chi^2_{n-1}$ has mean $n-1$ and variance $2(n-1)$. Hence $\text{E}(s_{n-1}^2) = \sigma^2$, and $\text{Var}(s_{n-1}^2) = 2\frac{\sigma^4 }{ n - 1}$.
Now $s_d^2 = \frac{n-1}{d} s_{n-1}^2$
$$\text{Bias}(s_d^2) = E(s_d^2)-\sigma^2 = \frac{n-1}{d}\sigma^2 -\sigma^2=\frac{n-1-d}{d}\sigma^2$$
$$\text {Var}(s_d^2) = 2\sigma^4(n - 1) / d^2$$
$$\text{MSE} = \text{Bias}^2 + \text{Var}$$
Hence
\begin{eqnarray}
\text{MSE}(s_d^2) &=& \left(\frac{n-1-d}{d}\right)^2\sigma^4+ 2\sigma^4(n - 1) / d^2\\
&=&\sigma^4\frac{(n-1-d)^2+2(n-1)}{d^2}\\
&=&\sigma^4\,f(d)\,,\end{eqnarray}
where $f(d)=1+\frac{(n-1)^2 + 2(n-1)-2(n-1)d}{d^2}$
$f(d)$ is at a turning point when $f'(d)=0$
i.e. when $d(-2(n-1))-2((n-1)^2 + 2(n-1)-2(n-1)d) = 0$
which occurs when $d-2=n-1$ ... i.e. when $d=n+1$
Showing that's a minimum rather than a maximum (or indeed a horizontal point of inflexion) is straightforward, but I'll leave it at that for now.
The relevant Wikipedia page does it more generally, getting a formula in terms of the excess kurtosis (which gives the same result in this case). I may incorporate an outline of that derivation at some point.
|
Estimate of variance with the lowest mean square error
Define
$$s^2_d = \frac{\sum_{i=1}^n\left(x_i-\bar{x}\,\right)^2}{d}$$
The statistic $(n - 1)s_{n-1}^2 / \sigma^2$ follows a $\chi^2_{n-1}$ distribution. A $\chi^2_{n-1}$ has mean $n-1$ and variance $2
|
48,066
|
Importance of optimizing the correct loss function
|
Say that I am building a linear regression model p for predicting some values $y_1,…,y_n$.
If the data contains a few extreme outliers in the response - or even just one - the MSE fitted equation can be pulled arbitrarily far away from the MAE one.
Consider the simplest regression model (just an intercept, $\alpha$), and following data:
0.0003 0.0001 0.0002 0.0004 50000 0.0002 0.0004 0.0003 0.0001 0.0003
The MAD solution is $\alpha$ = 0.0003. The MSE solution is 5000.00023.
The MAD of the minimum MAD solution is about 0.0001. The MAD of the minimum MSE solutions is about 5000. You can potentially do very badly, if you use MSE when the criterion is MAD.
|
Importance of optimizing the correct loss function
|
Say that I am building a linear regression model p for predicting some values $y_1,…,y_n$.
If the data contains a few extreme outliers in the response - or even just one - the MSE fitted equation can
|
Importance of optimizing the correct loss function
Say that I am building a linear regression model p for predicting some values $y_1,…,y_n$.
If the data contains a few extreme outliers in the response - or even just one - the MSE fitted equation can be pulled arbitrarily far away from the MAE one.
Consider the simplest regression model (just an intercept, $\alpha$), and following data:
0.0003 0.0001 0.0002 0.0004 50000 0.0002 0.0004 0.0003 0.0001 0.0003
The MAD solution is $\alpha$ = 0.0003. The MSE solution is 5000.00023.
The MAD of the minimum MAD solution is about 0.0001. The MAD of the minimum MSE solutions is about 5000. You can potentially do very badly, if you use MSE when the criterion is MAD.
|
Importance of optimizing the correct loss function
Say that I am building a linear regression model p for predicting some values $y_1,…,y_n$.
If the data contains a few extreme outliers in the response - or even just one - the MSE fitted equation can
|
48,067
|
Importance of optimizing the correct loss function
|
I think this question is hard to answer in general and depends heavily on the data that is analyzed.
Simple example: have your model with only the intercept, e.g. we have no predictors and can just estimate the mean and predict that for all new data. If $y$ is normally distributed the sample mean (i.e. the MSE estimate) is best, even if you test new data with the MAE. That's because to minimize MAE you would always predict the median, and with the normal distribution we have median = mean and the MSE estimate of the mean has lower variance than the median - this means the sample mean is a better estimator for the median than the sample median.
This means we have constructed an situation in which optimizing the "wrong" loss function has helped us. OTH it is also easy to construct a situation where it will give suboptimal results. For example, take a probability distribution with point weights of $\frac{999}{1000}$ on 0 and $\frac{1}{1000}$ on 1. The sample mean will be around $\frac{1}{1000}$ for many sample. Assume we correctly estimate the mean to be 0.001 When we predict this the MAE will be $$
\frac{999}{1000}\frac{1}{1000}+\frac{1}{1000}\frac{999}{1000}=\frac{1998}{1000000}
$$
However, we will almost certainly correctly estimate the median to be 0, the MAE is only
$$
\frac{999}{1000}0+\frac{1}{1000}1=\frac{1}{1000}
$$
That's about half the MAE compared to predicting the mean. So the general answer would be it depends.
|
Importance of optimizing the correct loss function
|
I think this question is hard to answer in general and depends heavily on the data that is analyzed.
Simple example: have your model with only the intercept, e.g. we have no predictors and can just es
|
Importance of optimizing the correct loss function
I think this question is hard to answer in general and depends heavily on the data that is analyzed.
Simple example: have your model with only the intercept, e.g. we have no predictors and can just estimate the mean and predict that for all new data. If $y$ is normally distributed the sample mean (i.e. the MSE estimate) is best, even if you test new data with the MAE. That's because to minimize MAE you would always predict the median, and with the normal distribution we have median = mean and the MSE estimate of the mean has lower variance than the median - this means the sample mean is a better estimator for the median than the sample median.
This means we have constructed an situation in which optimizing the "wrong" loss function has helped us. OTH it is also easy to construct a situation where it will give suboptimal results. For example, take a probability distribution with point weights of $\frac{999}{1000}$ on 0 and $\frac{1}{1000}$ on 1. The sample mean will be around $\frac{1}{1000}$ for many sample. Assume we correctly estimate the mean to be 0.001 When we predict this the MAE will be $$
\frac{999}{1000}\frac{1}{1000}+\frac{1}{1000}\frac{999}{1000}=\frac{1998}{1000000}
$$
However, we will almost certainly correctly estimate the median to be 0, the MAE is only
$$
\frac{999}{1000}0+\frac{1}{1000}1=\frac{1}{1000}
$$
That's about half the MAE compared to predicting the mean. So the general answer would be it depends.
|
Importance of optimizing the correct loss function
I think this question is hard to answer in general and depends heavily on the data that is analyzed.
Simple example: have your model with only the intercept, e.g. we have no predictors and can just es
|
48,068
|
Importance of optimizing the correct loss function
|
Often closed form - solution is reason for preferring certain kinds of loss functions. Or it was since now we have computers for solving numerical problems.
If you have loss function with mean absolute errors, that leads to much more difficult problem than error squared as in least squares method.
And problem is also that it might not be possible to test between non-nested loss functions. That is reason why we have so many estimation methods for the same kind of problem! :)
|
Importance of optimizing the correct loss function
|
Often closed form - solution is reason for preferring certain kinds of loss functions. Or it was since now we have computers for solving numerical problems.
If you have loss function with mean absol
|
Importance of optimizing the correct loss function
Often closed form - solution is reason for preferring certain kinds of loss functions. Or it was since now we have computers for solving numerical problems.
If you have loss function with mean absolute errors, that leads to much more difficult problem than error squared as in least squares method.
And problem is also that it might not be possible to test between non-nested loss functions. That is reason why we have so many estimation methods for the same kind of problem! :)
|
Importance of optimizing the correct loss function
Often closed form - solution is reason for preferring certain kinds of loss functions. Or it was since now we have computers for solving numerical problems.
If you have loss function with mean absol
|
48,069
|
Conditional Expectation of Poisson Random Variables
|
Define $S_n=\sum_{i=1}^n X_i$. By symmetry,
$$
\mathrm{E}\left[ X_1 \mid S_n \right] = \mathrm{E}\left[ X_2 \mid S_n \right] = \dots = \mathrm{E}\left[ X_n \mid S_n \right] \quad \textrm{a.s.} \quad (*)
$$
Hence, using $(*)$ and the linearity of the conditional expectation, we have
$$
\mathrm{E}\left[ X_1 \mid S_n \right] = \frac{1}{n} \mathrm{E}\left[ X_1+\dots+X_n \mid S_n \right] = \frac{1}{n} \mathrm{E}\left[ S_n \mid S_n \right] = \frac{S_n}{n} \quad \textrm{a.s.}
$$
The same reasoning leads to
$$
\mathrm{E}\left[ X_1 +X_2 +3X_3\mid S_n \right] = 5\,\mathrm{E}\left[ X_1 \mid S_n \right] = \frac{5\,S_n}{n} \quad \textrm{a.s.}
$$
Now, remember that $S_n\sim \mathrm{Poisson}(n\theta)$, and find the pmf of $5\,S_n/n$ (consider its support).
|
Conditional Expectation of Poisson Random Variables
|
Define $S_n=\sum_{i=1}^n X_i$. By symmetry,
$$
\mathrm{E}\left[ X_1 \mid S_n \right] = \mathrm{E}\left[ X_2 \mid S_n \right] = \dots = \mathrm{E}\left[ X_n \mid S_n \right] \quad \textrm{a.s.} \quad
|
Conditional Expectation of Poisson Random Variables
Define $S_n=\sum_{i=1}^n X_i$. By symmetry,
$$
\mathrm{E}\left[ X_1 \mid S_n \right] = \mathrm{E}\left[ X_2 \mid S_n \right] = \dots = \mathrm{E}\left[ X_n \mid S_n \right] \quad \textrm{a.s.} \quad (*)
$$
Hence, using $(*)$ and the linearity of the conditional expectation, we have
$$
\mathrm{E}\left[ X_1 \mid S_n \right] = \frac{1}{n} \mathrm{E}\left[ X_1+\dots+X_n \mid S_n \right] = \frac{1}{n} \mathrm{E}\left[ S_n \mid S_n \right] = \frac{S_n}{n} \quad \textrm{a.s.}
$$
The same reasoning leads to
$$
\mathrm{E}\left[ X_1 +X_2 +3X_3\mid S_n \right] = 5\,\mathrm{E}\left[ X_1 \mid S_n \right] = \frac{5\,S_n}{n} \quad \textrm{a.s.}
$$
Now, remember that $S_n\sim \mathrm{Poisson}(n\theta)$, and find the pmf of $5\,S_n/n$ (consider its support).
|
Conditional Expectation of Poisson Random Variables
Define $S_n=\sum_{i=1}^n X_i$. By symmetry,
$$
\mathrm{E}\left[ X_1 \mid S_n \right] = \mathrm{E}\left[ X_2 \mid S_n \right] = \dots = \mathrm{E}\left[ X_n \mid S_n \right] \quad \textrm{a.s.} \quad
|
48,070
|
Conditional Expectation of Poisson Random Variables
|
The OP has apparently found the way, so I am posting an answer.
I will denote $Z \equiv \sum_{i=1}^n X_i$. By linearity of the expected value we have
$$E \left( X_1+X_2+3X_3 |Z \right)= E \left( X_1 |Z \right)+E \left( X_2 |Z \right)+3E \left(X_3 |Z \right)$$
Since the variables are i.i.d. they are also exchangeable,at least with respect to $Z$ (to which they have a symmetric relationship), so the three conditional expected values will be equal:
$$E \left( X_1+X_2+3X_3 |Z \right)= 5E \left( X_1 |Z \right)$$
Moreover, it is a known result that the conditional distribution of $X_1$ conditional on $Z=k$ is a Binomial,
$$X_1 | Z=k \sim Bin\left(k, \frac {E(X_1)}{E(Z)}\right) = Bin\left(k, 1/n\right)$$
and so
$$5E \left( X_1 |Z=k \right) = 5\frac kn$$
Our conditional expectation is viewed as a function of $Z$, is not conditioned just on $Z$ acquiring a specific value. Generalizing the last equation we obtain
$$5E \left( X_1 |Z \right) = \frac 5n Z= 5 \frac 1n \sum_{i=1}^n X_i$$
Note that
$$E \left( X_1 |Z \right) \rightarrow_p E(X_1) \;\;\text {as}\;\; n\rightarrow \infty$$
which should be intuitive.
|
Conditional Expectation of Poisson Random Variables
|
The OP has apparently found the way, so I am posting an answer.
I will denote $Z \equiv \sum_{i=1}^n X_i$. By linearity of the expected value we have
$$E \left( X_1+X_2+3X_3 |Z \right)= E \left( X_1 |
|
Conditional Expectation of Poisson Random Variables
The OP has apparently found the way, so I am posting an answer.
I will denote $Z \equiv \sum_{i=1}^n X_i$. By linearity of the expected value we have
$$E \left( X_1+X_2+3X_3 |Z \right)= E \left( X_1 |Z \right)+E \left( X_2 |Z \right)+3E \left(X_3 |Z \right)$$
Since the variables are i.i.d. they are also exchangeable,at least with respect to $Z$ (to which they have a symmetric relationship), so the three conditional expected values will be equal:
$$E \left( X_1+X_2+3X_3 |Z \right)= 5E \left( X_1 |Z \right)$$
Moreover, it is a known result that the conditional distribution of $X_1$ conditional on $Z=k$ is a Binomial,
$$X_1 | Z=k \sim Bin\left(k, \frac {E(X_1)}{E(Z)}\right) = Bin\left(k, 1/n\right)$$
and so
$$5E \left( X_1 |Z=k \right) = 5\frac kn$$
Our conditional expectation is viewed as a function of $Z$, is not conditioned just on $Z$ acquiring a specific value. Generalizing the last equation we obtain
$$5E \left( X_1 |Z \right) = \frac 5n Z= 5 \frac 1n \sum_{i=1}^n X_i$$
Note that
$$E \left( X_1 |Z \right) \rightarrow_p E(X_1) \;\;\text {as}\;\; n\rightarrow \infty$$
which should be intuitive.
|
Conditional Expectation of Poisson Random Variables
The OP has apparently found the way, so I am posting an answer.
I will denote $Z \equiv \sum_{i=1}^n X_i$. By linearity of the expected value we have
$$E \left( X_1+X_2+3X_3 |Z \right)= E \left( X_1 |
|
48,071
|
Pros and Cons: Methods for Detrending Time Series Data
|
Differenced data
USE: When the series resembles that of a random walk, taking first differences makes it stationary, so that it can be described as linear series representation of autoregressive or moving average terms.
DO NOT USE: When the series appears to randomly fluctuate around its mean.
Log-differenced
USE: Similar to simple differencing but applied when the variance in the series is assumed to depend on the level. Or when the series is an index.
DO NOT USE: When there's no such assumption or where the series is not strictly positive.
Error term
In classical time series decomposition you should proceed as follows:
Decide on whether taking logs of original series is reasonable
Decide on whether regression on time variable is reasonable
Decide on whether to take differences of the residuals
|
Pros and Cons: Methods for Detrending Time Series Data
|
Differenced data
USE: When the series resembles that of a random walk, taking first differences makes it stationary, so that it can be described as linear series representation of autoregressive or mo
|
Pros and Cons: Methods for Detrending Time Series Data
Differenced data
USE: When the series resembles that of a random walk, taking first differences makes it stationary, so that it can be described as linear series representation of autoregressive or moving average terms.
DO NOT USE: When the series appears to randomly fluctuate around its mean.
Log-differenced
USE: Similar to simple differencing but applied when the variance in the series is assumed to depend on the level. Or when the series is an index.
DO NOT USE: When there's no such assumption or where the series is not strictly positive.
Error term
In classical time series decomposition you should proceed as follows:
Decide on whether taking logs of original series is reasonable
Decide on whether regression on time variable is reasonable
Decide on whether to take differences of the residuals
|
Pros and Cons: Methods for Detrending Time Series Data
Differenced data
USE: When the series resembles that of a random walk, taking first differences makes it stationary, so that it can be described as linear series representation of autoregressive or mo
|
48,072
|
How To Write Seasonal ARIMA model mathematically
|
The general $SARIMA(p,d,q)(P,D,Q)_m$ process $X_t$ is the solution of the following equation
$$\Phi(B^m)\phi(B)\nabla_m^D\nabla^d X_t=\Theta(B^m)\theta(B)Z_t,$$
where $Z_t$ is the white noise process. $\nabla_mX_t=X_{t}-X_{t-m}$, $\nabla X_t=X_{t}-X_{t-1}$,
\begin{align}
\Phi(B^m)&=1-\Phi_1B^m -\dots-\Phi_PB^{PM}\\
\phi(B)&=1-\phi_1B-\dots-\phi_p B^{p}\\
\Theta(B^m)&=1-\Theta_1 B^m-\dots-\Theta_Q B^{Qm}\\
\theta(B&)=1-\theta_1B-\dots-\theta_qB^q
\end{align}
and $B^nX_t=X_{t-n}$.
Now take your example of $ARIMA(1,0,3)(1,2,0)_5$. This means that
\begin{align}
\Phi(B^m)&=\Phi(B^5)=1-\Phi_1B^5\\
\phi(B)&=1-\phi_1B\\
\Theta(B^m)&=\Theta(B^5)=1\\
\theta(B&)=1-\theta_1B-\theta_2B^2-\theta_3B^3
\end{align}
So in your case $X_t$ must satisfy the equation:
\begin{align}
(1-\Phi_1B^5)(1-\phi_1B)\nabla_5^2X_t=(1-\theta_1B-\theta_2B^2-\theta_3B^3)Z_t
\end{align}
which we can rewrite as
\begin{align}
(1-\phi_1 B - \Phi_1 B^5 +\phi_1\Phi_1 B^{6})\nabla_5^2X_t=Z_t-\theta_1Z_{t-1}-\theta_2Z_{t-2}-\theta_3Z_{t-3}.
\end{align}
Now $\nabla^2_5X_t=\nabla_5(X_t-X_{t-5})=(X_t-2X_{t-5}+X_{t-10})$ and I leave the last step for the reader to complete.
|
How To Write Seasonal ARIMA model mathematically
|
The general $SARIMA(p,d,q)(P,D,Q)_m$ process $X_t$ is the solution of the following equation
$$\Phi(B^m)\phi(B)\nabla_m^D\nabla^d X_t=\Theta(B^m)\theta(B)Z_t,$$
where $Z_t$ is the white noise process.
|
How To Write Seasonal ARIMA model mathematically
The general $SARIMA(p,d,q)(P,D,Q)_m$ process $X_t$ is the solution of the following equation
$$\Phi(B^m)\phi(B)\nabla_m^D\nabla^d X_t=\Theta(B^m)\theta(B)Z_t,$$
where $Z_t$ is the white noise process. $\nabla_mX_t=X_{t}-X_{t-m}$, $\nabla X_t=X_{t}-X_{t-1}$,
\begin{align}
\Phi(B^m)&=1-\Phi_1B^m -\dots-\Phi_PB^{PM}\\
\phi(B)&=1-\phi_1B-\dots-\phi_p B^{p}\\
\Theta(B^m)&=1-\Theta_1 B^m-\dots-\Theta_Q B^{Qm}\\
\theta(B&)=1-\theta_1B-\dots-\theta_qB^q
\end{align}
and $B^nX_t=X_{t-n}$.
Now take your example of $ARIMA(1,0,3)(1,2,0)_5$. This means that
\begin{align}
\Phi(B^m)&=\Phi(B^5)=1-\Phi_1B^5\\
\phi(B)&=1-\phi_1B\\
\Theta(B^m)&=\Theta(B^5)=1\\
\theta(B&)=1-\theta_1B-\theta_2B^2-\theta_3B^3
\end{align}
So in your case $X_t$ must satisfy the equation:
\begin{align}
(1-\Phi_1B^5)(1-\phi_1B)\nabla_5^2X_t=(1-\theta_1B-\theta_2B^2-\theta_3B^3)Z_t
\end{align}
which we can rewrite as
\begin{align}
(1-\phi_1 B - \Phi_1 B^5 +\phi_1\Phi_1 B^{6})\nabla_5^2X_t=Z_t-\theta_1Z_{t-1}-\theta_2Z_{t-2}-\theta_3Z_{t-3}.
\end{align}
Now $\nabla^2_5X_t=\nabla_5(X_t-X_{t-5})=(X_t-2X_{t-5}+X_{t-10})$ and I leave the last step for the reader to complete.
|
How To Write Seasonal ARIMA model mathematically
The general $SARIMA(p,d,q)(P,D,Q)_m$ process $X_t$ is the solution of the following equation
$$\Phi(B^m)\phi(B)\nabla_m^D\nabla^d X_t=\Theta(B^m)\theta(B)Z_t,$$
where $Z_t$ is the white noise process.
|
48,073
|
Struggling with copula theory
|
It sounds like you are interested in fitting bivariate distributions to data? One way of doing this is to fit a bivariate normal distribution. Unfortunately, many bivariate data sets do not look like a bivariate normal at all. So people have considered more general distributions. One approach is to consider the marginal distributions separately, and then describe the dependence structure using a copula.
Given a choice of marginals, you then have to think about which copula might be appropriate. Unfortunately, we are still living in the copula stone age. Our choice of copulas basically boils down to a list of possibilities which have been written down by people. We choose one of these, and see how well it fits our data, although there is no universally-accepted way of doing so except for grunting and pointing. If it doesn't fit very well, then we can try another, and keep going until we are happy.
Usually, instead of choosing one particular copula, you choose a family of copulas depending on one or more parameters, and then try to find the copula in this family which gives the best fit. One such family is the family of Gaussian copulas, which depend on a parameter $\rho$. By using this family, you are making the assumption that, if $F$ and $G$ are your marginal cdfs, then $\Phi^{-1}F(X)$ and $\Phi^{-1}G(Y)$ follow a bivariate normal distribution with correlation $\rho$. This is perhaps what you mean by linear correlation?
Essentially, this just means that you are transforming $X$ and $Y$ separately (by choosing the marginals) and then fitting a bivariate normal to the result.
If you had the data in @Glen_b's example then you would observe that the $Y$ variable, $u$, looks like it has a uniform distrbution. So you would transform it using $\Phi^{-1}$, the inverse of the normal cdf. On the other hand, the $X$ variable, $x$, looks normal, so you would not transform it. Then you would try to fit a bivariate normal to the transformed data.
It turns out that, for real-life data, this is often inadequate; there is no pair of univariate transformations that will make $X$ and $Y$ look like a bivariate normal distribution and so the Gaussian copula is not a good choice. In particular, this happens when you have tail dependence. Here is a blog post on the Gaussian copula by TGR which goes into more details.
Using the Gaussian copula might work better than just using a bivariate normal, but there might also be better choices available, particularly if you care about the tails of your distribution. For example, there are many popular families of archimedean copulas which have tail dependence.
On the other hand, the Gaussian copula could be a perfectly good choice of copula if you want something flexible and easy to fit and don't mind about the tails. It depends on what it's being used for.
|
Struggling with copula theory
|
It sounds like you are interested in fitting bivariate distributions to data? One way of doing this is to fit a bivariate normal distribution. Unfortunately, many bivariate data sets do not look like
|
Struggling with copula theory
It sounds like you are interested in fitting bivariate distributions to data? One way of doing this is to fit a bivariate normal distribution. Unfortunately, many bivariate data sets do not look like a bivariate normal at all. So people have considered more general distributions. One approach is to consider the marginal distributions separately, and then describe the dependence structure using a copula.
Given a choice of marginals, you then have to think about which copula might be appropriate. Unfortunately, we are still living in the copula stone age. Our choice of copulas basically boils down to a list of possibilities which have been written down by people. We choose one of these, and see how well it fits our data, although there is no universally-accepted way of doing so except for grunting and pointing. If it doesn't fit very well, then we can try another, and keep going until we are happy.
Usually, instead of choosing one particular copula, you choose a family of copulas depending on one or more parameters, and then try to find the copula in this family which gives the best fit. One such family is the family of Gaussian copulas, which depend on a parameter $\rho$. By using this family, you are making the assumption that, if $F$ and $G$ are your marginal cdfs, then $\Phi^{-1}F(X)$ and $\Phi^{-1}G(Y)$ follow a bivariate normal distribution with correlation $\rho$. This is perhaps what you mean by linear correlation?
Essentially, this just means that you are transforming $X$ and $Y$ separately (by choosing the marginals) and then fitting a bivariate normal to the result.
If you had the data in @Glen_b's example then you would observe that the $Y$ variable, $u$, looks like it has a uniform distrbution. So you would transform it using $\Phi^{-1}$, the inverse of the normal cdf. On the other hand, the $X$ variable, $x$, looks normal, so you would not transform it. Then you would try to fit a bivariate normal to the transformed data.
It turns out that, for real-life data, this is often inadequate; there is no pair of univariate transformations that will make $X$ and $Y$ look like a bivariate normal distribution and so the Gaussian copula is not a good choice. In particular, this happens when you have tail dependence. Here is a blog post on the Gaussian copula by TGR which goes into more details.
Using the Gaussian copula might work better than just using a bivariate normal, but there might also be better choices available, particularly if you care about the tails of your distribution. For example, there are many popular families of archimedean copulas which have tail dependence.
On the other hand, the Gaussian copula could be a perfectly good choice of copula if you want something flexible and easy to fit and don't mind about the tails. It depends on what it's being used for.
|
Struggling with copula theory
It sounds like you are interested in fitting bivariate distributions to data? One way of doing this is to fit a bivariate normal distribution. Unfortunately, many bivariate data sets do not look like
|
48,074
|
Struggling with copula theory
|
What convinces you that the Gaussian copula only applies to linear correlation?
This would seem to be a counterexample: a pair of variables with a Gaussian copula, but they're not linearly related:
If that's not what you mean by 'linear correlation', you will need to be more explicit
|
Struggling with copula theory
|
What convinces you that the Gaussian copula only applies to linear correlation?
This would seem to be a counterexample: a pair of variables with a Gaussian copula, but they're not linearly related:
I
|
Struggling with copula theory
What convinces you that the Gaussian copula only applies to linear correlation?
This would seem to be a counterexample: a pair of variables with a Gaussian copula, but they're not linearly related:
If that's not what you mean by 'linear correlation', you will need to be more explicit
|
Struggling with copula theory
What convinces you that the Gaussian copula only applies to linear correlation?
This would seem to be a counterexample: a pair of variables with a Gaussian copula, but they're not linearly related:
I
|
48,075
|
How is the number of particles decided in particle filtering?
|
For this choice I often think about the trade-off between computational cost and the variance of the resulting estimates. As you increase the number of particles or sample size the former increase, while the latter decreases.
Often I do a simple computational experiment:
I create a grid of potential numbers of particle (say $10^2$, $10^3$ and $10^4$).
I do the filtering $N$ times using each sample size.
I plot the sample variance of the quantity I'm interested in (for example the variance of the estimated likelihood) on the Y axis, with the number of particles on the X axis.
You should get a convex curve, that becomes flat as the number of particles increases. Generally I just look at it, and choose a number of particle that seems reasonable in the sense that increasing the number of particles further wouldn't reduce the variance by much.
Obviously this is just a practical approach, maybe there are more rigorous ways of looking at the problem.
|
How is the number of particles decided in particle filtering?
|
For this choice I often think about the trade-off between computational cost and the variance of the resulting estimates. As you increase the number of particles or sample size the former increase, wh
|
How is the number of particles decided in particle filtering?
For this choice I often think about the trade-off between computational cost and the variance of the resulting estimates. As you increase the number of particles or sample size the former increase, while the latter decreases.
Often I do a simple computational experiment:
I create a grid of potential numbers of particle (say $10^2$, $10^3$ and $10^4$).
I do the filtering $N$ times using each sample size.
I plot the sample variance of the quantity I'm interested in (for example the variance of the estimated likelihood) on the Y axis, with the number of particles on the X axis.
You should get a convex curve, that becomes flat as the number of particles increases. Generally I just look at it, and choose a number of particle that seems reasonable in the sense that increasing the number of particles further wouldn't reduce the variance by much.
Obviously this is just a practical approach, maybe there are more rigorous ways of looking at the problem.
|
How is the number of particles decided in particle filtering?
For this choice I often think about the trade-off between computational cost and the variance of the resulting estimates. As you increase the number of particles or sample size the former increase, wh
|
48,076
|
Fitting data to a Poisson distribution, what are the errors?
|
The direct answer to the question - how to deal with small expected counts - is that one might either
(a) combine ranges of cells at the end (a very common approach),
(b) use a different (and perhaps better) goodness of fit test, or
(c) consider dropping the chi-square approximation, and see if one can deal with the discrete distribution of the test statistic more directly, perhaps by simulation.
Approach (a) can be found in many texts. There are many ways you can go about combining cells, but many people simply work from one end or the other, combining cells either to the left, or to the right, until the expected counts are sufficiently high for their purpose.
(However, the most commonly cited rule of thumb for the expected number - that it should be at least 5 for the chi-square approximation to hold - is unnecessarily strict for the sort of approximation most people would require. Many subsequent papers have suggested less stringent rules.)
The other answer by user36381 suggests that with such a large sample size, goodness of fit tests are almost certain to reject; this is true. However, I'm not so sure comparing to other reference distributions will help, since they, too, would almost certainly be rejected by a decent goodness of fit test.
(Why are you testing whether it's Poisson? If you have around a million data points, the sample itself contains a lot of information about distributional shape - do you actually need a name for the distribution?)
|
Fitting data to a Poisson distribution, what are the errors?
|
The direct answer to the question - how to deal with small expected counts - is that one might either
(a) combine ranges of cells at the end (a very common approach),
(b) use a different (and perhap
|
Fitting data to a Poisson distribution, what are the errors?
The direct answer to the question - how to deal with small expected counts - is that one might either
(a) combine ranges of cells at the end (a very common approach),
(b) use a different (and perhaps better) goodness of fit test, or
(c) consider dropping the chi-square approximation, and see if one can deal with the discrete distribution of the test statistic more directly, perhaps by simulation.
Approach (a) can be found in many texts. There are many ways you can go about combining cells, but many people simply work from one end or the other, combining cells either to the left, or to the right, until the expected counts are sufficiently high for their purpose.
(However, the most commonly cited rule of thumb for the expected number - that it should be at least 5 for the chi-square approximation to hold - is unnecessarily strict for the sort of approximation most people would require. Many subsequent papers have suggested less stringent rules.)
The other answer by user36381 suggests that with such a large sample size, goodness of fit tests are almost certain to reject; this is true. However, I'm not so sure comparing to other reference distributions will help, since they, too, would almost certainly be rejected by a decent goodness of fit test.
(Why are you testing whether it's Poisson? If you have around a million data points, the sample itself contains a lot of information about distributional shape - do you actually need a name for the distribution?)
|
Fitting data to a Poisson distribution, what are the errors?
The direct answer to the question - how to deal with small expected counts - is that one might either
(a) combine ranges of cells at the end (a very common approach),
(b) use a different (and perhap
|
48,077
|
Fitting data to a Poisson distribution, what are the errors?
|
This doesn't entirely answer your question regarding how to implement the goodness of fit test. But with a sample size that large, your data will almost certainly fail any test comparing it to a Poisson distribution even if your distribution closely resembles a Poisson distribution (unless, of course, you simulated Poisson data). The power of your test to detect minute deviations from the Poisson distribution would be very high.
It may be better to compare it to other reference distributions to see which distribution it fits best.
|
Fitting data to a Poisson distribution, what are the errors?
|
This doesn't entirely answer your question regarding how to implement the goodness of fit test. But with a sample size that large, your data will almost certainly fail any test comparing it to a Poiss
|
Fitting data to a Poisson distribution, what are the errors?
This doesn't entirely answer your question regarding how to implement the goodness of fit test. But with a sample size that large, your data will almost certainly fail any test comparing it to a Poisson distribution even if your distribution closely resembles a Poisson distribution (unless, of course, you simulated Poisson data). The power of your test to detect minute deviations from the Poisson distribution would be very high.
It may be better to compare it to other reference distributions to see which distribution it fits best.
|
Fitting data to a Poisson distribution, what are the errors?
This doesn't entirely answer your question regarding how to implement the goodness of fit test. But with a sample size that large, your data will almost certainly fail any test comparing it to a Poiss
|
48,078
|
Fitting data to a Poisson distribution, what are the errors?
|
One way to go is by using the "deviance residual" from glms. This is a likelihood ratio for each count. You can easily get these from the glm () function in R. The glm you would fit is one with no intercept, and dummy variables for each year. However with a million observstions this may run into memory problems.
You can calculate the deviance residuals for the poisson model as
$$ d_{ti}^2=2 (\hat{\lambda}_t-n_{ti})+2n_{ti}\log\left (\frac {n_{ti}}{\hat {\lambda}_t}\right) $$
I have use "t" to denote the year ("time"), "i" to denote the observations, $ n_{ti} $ is the "count" variable, and $\hat {\lambda}_t $ is the MLE for year "t". This is approximately equal to the usual "pearson chi-square" residual when lambda is large, but has more "robust" behaviour for small lambda due to the logarithm. The standard pearson residual is $r_{ti}=\frac {(\hat{\lambda}_t-n_{ti})^2}{\hat{\lambda}_t} $ which diverges like $\frac {1}{\hat{\lambda}_t}$ - much faster than logarithm.
Now if your Poisson model is adequate you should roughly have $\sum_{ti} d_{ti}^2\approx df $ where "df" is the number of observed counts minus the number of lambdas you fitted.
Another way you can test the poisson model is to fit a negative binomial model, and see how close the "concentration" parameter is to infinity.
|
Fitting data to a Poisson distribution, what are the errors?
|
One way to go is by using the "deviance residual" from glms. This is a likelihood ratio for each count. You can easily get these from the glm () function in R. The glm you would fit is one with no
|
Fitting data to a Poisson distribution, what are the errors?
One way to go is by using the "deviance residual" from glms. This is a likelihood ratio for each count. You can easily get these from the glm () function in R. The glm you would fit is one with no intercept, and dummy variables for each year. However with a million observstions this may run into memory problems.
You can calculate the deviance residuals for the poisson model as
$$ d_{ti}^2=2 (\hat{\lambda}_t-n_{ti})+2n_{ti}\log\left (\frac {n_{ti}}{\hat {\lambda}_t}\right) $$
I have use "t" to denote the year ("time"), "i" to denote the observations, $ n_{ti} $ is the "count" variable, and $\hat {\lambda}_t $ is the MLE for year "t". This is approximately equal to the usual "pearson chi-square" residual when lambda is large, but has more "robust" behaviour for small lambda due to the logarithm. The standard pearson residual is $r_{ti}=\frac {(\hat{\lambda}_t-n_{ti})^2}{\hat{\lambda}_t} $ which diverges like $\frac {1}{\hat{\lambda}_t}$ - much faster than logarithm.
Now if your Poisson model is adequate you should roughly have $\sum_{ti} d_{ti}^2\approx df $ where "df" is the number of observed counts minus the number of lambdas you fitted.
Another way you can test the poisson model is to fit a negative binomial model, and see how close the "concentration" parameter is to infinity.
|
Fitting data to a Poisson distribution, what are the errors?
One way to go is by using the "deviance residual" from glms. This is a likelihood ratio for each count. You can easily get these from the glm () function in R. The glm you would fit is one with no
|
48,079
|
Fitting data to a Poisson distribution, what are the errors?
|
You could try fitting an exponential distribution to the inter-arrival times (if you have the times of arrivals in your dataset). In this case, you can do a simple KS Test for the exponential fit. If it fits, then the Poisson fits your count data. See the following reference:
ON THE KOLMOGOROV-SMIRNOV TEST FOR THE EXPONENTIAL DISTRIBUTION WITH MEAN UNKNOWN -HUBERT W. LILLIEFORS, AMERICAN STATISTICAL ASSOCIATION JOURNAL, MARCH 1969
|
Fitting data to a Poisson distribution, what are the errors?
|
You could try fitting an exponential distribution to the inter-arrival times (if you have the times of arrivals in your dataset). In this case, you can do a simple KS Test for the exponential fit. If
|
Fitting data to a Poisson distribution, what are the errors?
You could try fitting an exponential distribution to the inter-arrival times (if you have the times of arrivals in your dataset). In this case, you can do a simple KS Test for the exponential fit. If it fits, then the Poisson fits your count data. See the following reference:
ON THE KOLMOGOROV-SMIRNOV TEST FOR THE EXPONENTIAL DISTRIBUTION WITH MEAN UNKNOWN -HUBERT W. LILLIEFORS, AMERICAN STATISTICAL ASSOCIATION JOURNAL, MARCH 1969
|
Fitting data to a Poisson distribution, what are the errors?
You could try fitting an exponential distribution to the inter-arrival times (if you have the times of arrivals in your dataset). In this case, you can do a simple KS Test for the exponential fit. If
|
48,080
|
Checking assumptions LMM: residual plot with diamond shape
|
The diamond pattern in the residuals is due to a combination of the "ceiling effect" you have in the observed female data (i.e., a lot of female data points clustered at the maximum value of 18 or so) and the "floor effect" you have in the observed male data (a lot of male data points clustered at the minimum value of 0).
To see this, imagine taking your second figure (the one with the female and male data plotted side by side in different panels), overlaying the two panels into a single combined plot, and then rotating this plot 45 degrees clockwise so that the identity line is now horizontal. You would get something pretty close to the top graph.
|
Checking assumptions LMM: residual plot with diamond shape
|
The diamond pattern in the residuals is due to a combination of the "ceiling effect" you have in the observed female data (i.e., a lot of female data points clustered at the maximum value of 18 or so)
|
Checking assumptions LMM: residual plot with diamond shape
The diamond pattern in the residuals is due to a combination of the "ceiling effect" you have in the observed female data (i.e., a lot of female data points clustered at the maximum value of 18 or so) and the "floor effect" you have in the observed male data (a lot of male data points clustered at the minimum value of 0).
To see this, imagine taking your second figure (the one with the female and male data plotted side by side in different panels), overlaying the two panels into a single combined plot, and then rotating this plot 45 degrees clockwise so that the identity line is now horizontal. You would get something pretty close to the top graph.
|
Checking assumptions LMM: residual plot with diamond shape
The diamond pattern in the residuals is due to a combination of the "ceiling effect" you have in the observed female data (i.e., a lot of female data points clustered at the maximum value of 18 or so)
|
48,081
|
Checking assumptions LMM: residual plot with diamond shape
|
Diamond (double outward box) distributed residuals are another type of non–monotonic heteroscedasticity that severely violates the homoscedasticity
assumption. For the correction of diamond type of heterocedasticity, the study " Correcting Double Outward Box Distributed Residuals by WCEV"
(http://www.tandfonline.com/doi/full/10.1080/03610926.2016.1213289) can be helpful.
(Update: 2018-01-02)
The test is so simple and powerful. The test based on auxiliary simple regression of absolute or squared residuals on centered external variable. Test independent from numbers of explanatory variables. Usual tests are monotonic. This test also can detect non monotonic patterns such as diamond, butterfly types of heteroskedasticity. The article also contains SAS codes.
|
Checking assumptions LMM: residual plot with diamond shape
|
Diamond (double outward box) distributed residuals are another type of non–monotonic heteroscedasticity that severely violates the homoscedasticity
assumption. For the correction of diamond type of he
|
Checking assumptions LMM: residual plot with diamond shape
Diamond (double outward box) distributed residuals are another type of non–monotonic heteroscedasticity that severely violates the homoscedasticity
assumption. For the correction of diamond type of heterocedasticity, the study " Correcting Double Outward Box Distributed Residuals by WCEV"
(http://www.tandfonline.com/doi/full/10.1080/03610926.2016.1213289) can be helpful.
(Update: 2018-01-02)
The test is so simple and powerful. The test based on auxiliary simple regression of absolute or squared residuals on centered external variable. Test independent from numbers of explanatory variables. Usual tests are monotonic. This test also can detect non monotonic patterns such as diamond, butterfly types of heteroskedasticity. The article also contains SAS codes.
|
Checking assumptions LMM: residual plot with diamond shape
Diamond (double outward box) distributed residuals are another type of non–monotonic heteroscedasticity that severely violates the homoscedasticity
assumption. For the correction of diamond type of he
|
48,082
|
Posterior covariance of Normal-Inverse-Wishart not converging properly
|
The problem was that I was setting the degrees of freedom too low-- it should be at least P+2, where $\Psi$ is a PxP matrix.
|
Posterior covariance of Normal-Inverse-Wishart not converging properly
|
The problem was that I was setting the degrees of freedom too low-- it should be at least P+2, where $\Psi$ is a PxP matrix.
|
Posterior covariance of Normal-Inverse-Wishart not converging properly
The problem was that I was setting the degrees of freedom too low-- it should be at least P+2, where $\Psi$ is a PxP matrix.
|
Posterior covariance of Normal-Inverse-Wishart not converging properly
The problem was that I was setting the degrees of freedom too low-- it should be at least P+2, where $\Psi$ is a PxP matrix.
|
48,083
|
Posterior covariance of Normal-Inverse-Wishart not converging properly
|
Sorry I am slow, but all that changed was setting nu=4?
x = NormalInverseWishartDistribution(np.array([0,0])-3,1,4,np.eye(2)) # nu > 2 + psi.shape[0]
samples = [x.sample() for _ in range(1000)]
data = [np.random.multivariate_normal(mu,cov) for mu,cov in samples]
y = NormalInverseWishartDistribution(np.array([0,0]),1,4,np.eye(2))
z = y.posterior(data)
print 'mu_n: {0}'.format(z.mu)
print 'psi_n: {0}'.format(z.psi)
Gives me:
mu_n: [-3.00472366 -3.02735843]
psi_n: [[ 1785.25130628 -33.05276129]
[ -33.05276129 2425.67075978]]
|
Posterior covariance of Normal-Inverse-Wishart not converging properly
|
Sorry I am slow, but all that changed was setting nu=4?
x = NormalInverseWishartDistribution(np.array([0,0])-3,1,4,np.eye(2)) # nu > 2 + psi.shape[0]
samples = [x.sample() for _ in range(1000)]
data =
|
Posterior covariance of Normal-Inverse-Wishart not converging properly
Sorry I am slow, but all that changed was setting nu=4?
x = NormalInverseWishartDistribution(np.array([0,0])-3,1,4,np.eye(2)) # nu > 2 + psi.shape[0]
samples = [x.sample() for _ in range(1000)]
data = [np.random.multivariate_normal(mu,cov) for mu,cov in samples]
y = NormalInverseWishartDistribution(np.array([0,0]),1,4,np.eye(2))
z = y.posterior(data)
print 'mu_n: {0}'.format(z.mu)
print 'psi_n: {0}'.format(z.psi)
Gives me:
mu_n: [-3.00472366 -3.02735843]
psi_n: [[ 1785.25130628 -33.05276129]
[ -33.05276129 2425.67075978]]
|
Posterior covariance of Normal-Inverse-Wishart not converging properly
Sorry I am slow, but all that changed was setting nu=4?
x = NormalInverseWishartDistribution(np.array([0,0])-3,1,4,np.eye(2)) # nu > 2 + psi.shape[0]
samples = [x.sample() for _ in range(1000)]
data =
|
48,084
|
Classify and regress at the same time
|
Answering the specific question.
Yes, it is possible (but might be undesirable)
Directed graph models (such as ANNs) can cope with that.
You have 5 input variables, and you want to predict gender first, and include this prediction to predict income.
Basically, you need to connect all your inputs to an output, which is gender, then connect all your inputs again to a second output, income (a skip connection, in ANN terminology), plus your first output to the second. Also, don't forget bias terms.
Arrows are weights (coefficients) and circles are nodes.
Then, you want to minimize binomial loss on the prediction of gender, and (perhaps) squared loss on the prediction of income, optimizing the weights in the model. You can write this as your loss function.
$$\mathbb L_\text{total} (\text{input, gender, income})=\mathbb L _\text{binomial}(\text{gender})+\mathbb L _\text{squared}(\text{income})$$
You might want to normalize the loss terms, because, due to variance, one might dominate over the other.
Notice that the prediction of income depends on all weights in the model, so optimizing for the prediction of gender separately first might not be optimal to the predicition of income.
Now,
While this is specifically what you asked for, you have to ask if it's really useful. The separate prediction of gender and subsequently income including the gender predictions might be simpler, and above all, easier to implement.
Also, on imputation,
While studying these mediating relationships might be of interest, I have to warn you about the possibility of imputation.
If your objective is to account for missing gender information in some observations, then consider that the model won't use the actual gender information of the observations containing it. If the independent variables do not predict gender reasonably, you'll be basically forfeiting this information in your model, probably tending to a no informative output in the gender node.
|
Classify and regress at the same time
|
Answering the specific question.
Yes, it is possible (but might be undesirable)
Directed graph models (such as ANNs) can cope with that.
You have 5 input variables, and you want to predict gender firs
|
Classify and regress at the same time
Answering the specific question.
Yes, it is possible (but might be undesirable)
Directed graph models (such as ANNs) can cope with that.
You have 5 input variables, and you want to predict gender first, and include this prediction to predict income.
Basically, you need to connect all your inputs to an output, which is gender, then connect all your inputs again to a second output, income (a skip connection, in ANN terminology), plus your first output to the second. Also, don't forget bias terms.
Arrows are weights (coefficients) and circles are nodes.
Then, you want to minimize binomial loss on the prediction of gender, and (perhaps) squared loss on the prediction of income, optimizing the weights in the model. You can write this as your loss function.
$$\mathbb L_\text{total} (\text{input, gender, income})=\mathbb L _\text{binomial}(\text{gender})+\mathbb L _\text{squared}(\text{income})$$
You might want to normalize the loss terms, because, due to variance, one might dominate over the other.
Notice that the prediction of income depends on all weights in the model, so optimizing for the prediction of gender separately first might not be optimal to the predicition of income.
Now,
While this is specifically what you asked for, you have to ask if it's really useful. The separate prediction of gender and subsequently income including the gender predictions might be simpler, and above all, easier to implement.
Also, on imputation,
While studying these mediating relationships might be of interest, I have to warn you about the possibility of imputation.
If your objective is to account for missing gender information in some observations, then consider that the model won't use the actual gender information of the observations containing it. If the independent variables do not predict gender reasonably, you'll be basically forfeiting this information in your model, probably tending to a no informative output in the gender node.
|
Classify and regress at the same time
Answering the specific question.
Yes, it is possible (but might be undesirable)
Directed graph models (such as ANNs) can cope with that.
You have 5 input variables, and you want to predict gender firs
|
48,085
|
Classify and regress at the same time
|
Why do you want to do this? For your proposal to be possible and meaningful, it must be that you have some missing observations on the binary gender predictor (but not all). If that is the case, the usual approach is to use some (multiple) imputation method. See Multiple imputation for missing values or search this site!
(see also the comments for other ideas). There are some papers about imputation for binary (or categorical) predictors, for instance https://www.statalist.org/forums/forum/general-stata-discussion/general/29284-multiple-imputation-for-missing-categorical-variables, https://statisticalhorizons.com/ml-better-than-mi, https://www.sciencedirect.com/science/article/pii/S0167947310001490
(Sorry if I have misinterpreted the question, then it needs clarification)
|
Classify and regress at the same time
|
Why do you want to do this? For your proposal to be possible and meaningful, it must be that you have some missing observations on the binary gender predictor (but not all). If that is the case, the
|
Classify and regress at the same time
Why do you want to do this? For your proposal to be possible and meaningful, it must be that you have some missing observations on the binary gender predictor (but not all). If that is the case, the usual approach is to use some (multiple) imputation method. See Multiple imputation for missing values or search this site!
(see also the comments for other ideas). There are some papers about imputation for binary (or categorical) predictors, for instance https://www.statalist.org/forums/forum/general-stata-discussion/general/29284-multiple-imputation-for-missing-categorical-variables, https://statisticalhorizons.com/ml-better-than-mi, https://www.sciencedirect.com/science/article/pii/S0167947310001490
(Sorry if I have misinterpreted the question, then it needs clarification)
|
Classify and regress at the same time
Why do you want to do this? For your proposal to be possible and meaningful, it must be that you have some missing observations on the binary gender predictor (but not all). If that is the case, the
|
48,086
|
Classify and regress at the same time
|
As the other answers pointed out, this may not be something you want to do. But in cases where your 2 regression targets are closely related (say in the case of latitude and longitude) it may make sense.
One of the things I really love about neural networks is that they are very flexible, and allow you to define one model that does multiple things. For example, you can have one model that predicts both a classification target and a regression target.
Even if that's not what you should do on this dataset, I still think it's pretty cool, so I'm gonna share some code for a keras neural network in python that does classification and regression at the same time!
First, lets load some data. In this case, we're gonna predict sex (classification) and age (regression) from some census data:
import pandas as pd
adult = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data')
adult.columns = ['age', 'workclass', 'fnlwgt', 'edu', 'edu_num', 'marital_status', 'occupation', 'relationship', 'race', 'sex', 'capital_gain', 'capital_loss','hours_per_week', 'native_country', 'income']
adult["sex"] = adult["sex"].astype('category').cat.codes
adult["workclass"] = adult["workclass"].astype('category').cat.codes
adult["marital_status"] = adult["marital_status"].astype('category').cat.codes
adult["race"] = adult["race"].astype('category').cat.codes
adult["occupation"] = adult["occupation"].astype('category').cat.codes
adult["native_country"] = adult["native_country"].astype('category').cat.codes
target_bin = adult[['sex']].values.astype('float32')
target_num = adult[['age']].values.astype('float32')
X = adult[['workclass', 'edu_num', 'marital_status', 'occupation', 'race', 'capital_gain', 'capital_loss', 'hours_per_week', 'native_country']].values.astype('float32')
X is our predictors, target_bin is the classification target, and target_num is the regression target.
Now lets define a keras model with one input (X) and 2 outputs (target_bin and target_num):
from keras.layers import Input, Dense, BatchNormalization
from keras.models import Model
from keras.optimizers import Adam
from keras.utils.vis_utils import plot_model
input = Input(shape=(X.shape[1],), name='Input')
hidden = Dense(64, name='Shared-Hidden-Layer', activation='relu')(input)
hidden = BatchNormalization()(hidden)
out_bin = Dense(1, name='Output-Bin', activation='sigmoid')(hidden)
out_num = Dense(1, name='Output-Num', activation='linear')(hidden)
model = Model(input, [out_bin, out_num])
model.compile(optimizer=Adam(0.10), loss=['binary_crossentropy', 'mean_squared_error'])
model.summary()
plot_model(model, to_file='model.png')
Now we can fit this model to our data:
model.fit(X, [target_bin, target_num], validation_split=.20, epochs=100, batch_size=2048)
model.predict(X)
We use a 20% validation set, where the model gets a logloss of 0.5649 and a mean squared error of 117.0967, which corresponds to an RMSE of 10.8. A logloss of <.69 means the model learned something useful for classification, and the RMSE of 10.8 is pretty good given that the mean of the numeric target is 38.6.
If you look at this model's predictions, you see it predicts 2 arrays. The first is the probability that the person is female, and the second is the person's predicted age.
You'll notice that I setup this network to use a shared hidden layer from the inputs to predict the outputs. You could also setup the network to e.g. use the sex prediction as a predictor for age, or other creative ways to relate the 2 variables.
So you can make one model to do both classification and regression!
|
Classify and regress at the same time
|
As the other answers pointed out, this may not be something you want to do. But in cases where your 2 regression targets are closely related (say in the case of latitude and longitude) it may make se
|
Classify and regress at the same time
As the other answers pointed out, this may not be something you want to do. But in cases where your 2 regression targets are closely related (say in the case of latitude and longitude) it may make sense.
One of the things I really love about neural networks is that they are very flexible, and allow you to define one model that does multiple things. For example, you can have one model that predicts both a classification target and a regression target.
Even if that's not what you should do on this dataset, I still think it's pretty cool, so I'm gonna share some code for a keras neural network in python that does classification and regression at the same time!
First, lets load some data. In this case, we're gonna predict sex (classification) and age (regression) from some census data:
import pandas as pd
adult = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data')
adult.columns = ['age', 'workclass', 'fnlwgt', 'edu', 'edu_num', 'marital_status', 'occupation', 'relationship', 'race', 'sex', 'capital_gain', 'capital_loss','hours_per_week', 'native_country', 'income']
adult["sex"] = adult["sex"].astype('category').cat.codes
adult["workclass"] = adult["workclass"].astype('category').cat.codes
adult["marital_status"] = adult["marital_status"].astype('category').cat.codes
adult["race"] = adult["race"].astype('category').cat.codes
adult["occupation"] = adult["occupation"].astype('category').cat.codes
adult["native_country"] = adult["native_country"].astype('category').cat.codes
target_bin = adult[['sex']].values.astype('float32')
target_num = adult[['age']].values.astype('float32')
X = adult[['workclass', 'edu_num', 'marital_status', 'occupation', 'race', 'capital_gain', 'capital_loss', 'hours_per_week', 'native_country']].values.astype('float32')
X is our predictors, target_bin is the classification target, and target_num is the regression target.
Now lets define a keras model with one input (X) and 2 outputs (target_bin and target_num):
from keras.layers import Input, Dense, BatchNormalization
from keras.models import Model
from keras.optimizers import Adam
from keras.utils.vis_utils import plot_model
input = Input(shape=(X.shape[1],), name='Input')
hidden = Dense(64, name='Shared-Hidden-Layer', activation='relu')(input)
hidden = BatchNormalization()(hidden)
out_bin = Dense(1, name='Output-Bin', activation='sigmoid')(hidden)
out_num = Dense(1, name='Output-Num', activation='linear')(hidden)
model = Model(input, [out_bin, out_num])
model.compile(optimizer=Adam(0.10), loss=['binary_crossentropy', 'mean_squared_error'])
model.summary()
plot_model(model, to_file='model.png')
Now we can fit this model to our data:
model.fit(X, [target_bin, target_num], validation_split=.20, epochs=100, batch_size=2048)
model.predict(X)
We use a 20% validation set, where the model gets a logloss of 0.5649 and a mean squared error of 117.0967, which corresponds to an RMSE of 10.8. A logloss of <.69 means the model learned something useful for classification, and the RMSE of 10.8 is pretty good given that the mean of the numeric target is 38.6.
If you look at this model's predictions, you see it predicts 2 arrays. The first is the probability that the person is female, and the second is the person's predicted age.
You'll notice that I setup this network to use a shared hidden layer from the inputs to predict the outputs. You could also setup the network to e.g. use the sex prediction as a predictor for age, or other creative ways to relate the 2 variables.
So you can make one model to do both classification and regression!
|
Classify and regress at the same time
As the other answers pointed out, this may not be something you want to do. But in cases where your 2 regression targets are closely related (say in the case of latitude and longitude) it may make se
|
48,087
|
Why do PCA and Factor Analysis return different results in this example?
|
The covariance matrix in this example is given by $$\mathbf C = \left(\begin{array}{c} 1 & \sim 1 & 0 \\ \sim 1 & \sim 1 & 0 \\ 0 & 0 & 100\end{array}\right).$$
To compare PCA and FA, think about how PCA/FA loadings reconstruct the covariance matrix.
The loadings of the first principal component in PCA is a vector $\mathbf v$ that minimizes the reconstruction error $\|\mathbf C - \mathbf v \mathbf v^\top \|$. As is well-known, it is given by the leading eigenvector of $\mathbf C$ scaled by a square root of its eigenvalue, and in this case will be pointing in the $(0,0,1)$ direction (in order to reproduce the covariance of $X_3$ which would otherwise be a major source of reconstruction error).
In contrast, the loadings of the first factor in FA is a vector $\mathbf v$ that minimizes the reconstruction error $\|\mathbf C - \mathbf v \mathbf v^\top - \boldsymbol \Psi \|$, where $\boldsymbol \Psi$ is a diagonal matrix of uniquenesses. This is equivalent to saying that it minimizes the reconstruction error $\|\mathrm{offdiag}\{\mathbf C - \mathbf v \mathbf v^\top\}\|$, i.e. FA does not care about reconstructing the diagonal. Think about $\mathbf C$ with erased diagonal:$$\mathrm{offdiag}\{\mathbf C\}=\left(\begin{array}{c} & \sim 1 & 0 \\ \sim 1 & & 0 \\ 0 & 0 & \end{array}\right).$$ The goal of FA is to reconstruct this part of $\mathbf C$ and so the loadings of the first factor will be pointing in the $(1,1,0)$ direction, in order to reproduce this off-diagonal covariance between $X_1$ and $X_2$.
Note that this analysis is based on the covariance matrix. Conducting an analysis based on the correlation matrix would (in this case) lead both PCA and FA to yield similar outcomes.
My answer to the opposite question might be of interest:
Under which conditions do PCA and FA yield similar results?
For many more details about PCA vs FA issue, see my [very long] answer to this question:
Is there any good reason to use PCA instead of EFA? Also, can PCA be a substitute for factor analysis?
|
Why do PCA and Factor Analysis return different results in this example?
|
The covariance matrix in this example is given by $$\mathbf C = \left(\begin{array}{c} 1 & \sim 1 & 0 \\ \sim 1 & \sim 1 & 0 \\ 0 & 0 & 100\end{array}\right).$$
To compare PCA and FA, think about how
|
Why do PCA and Factor Analysis return different results in this example?
The covariance matrix in this example is given by $$\mathbf C = \left(\begin{array}{c} 1 & \sim 1 & 0 \\ \sim 1 & \sim 1 & 0 \\ 0 & 0 & 100\end{array}\right).$$
To compare PCA and FA, think about how PCA/FA loadings reconstruct the covariance matrix.
The loadings of the first principal component in PCA is a vector $\mathbf v$ that minimizes the reconstruction error $\|\mathbf C - \mathbf v \mathbf v^\top \|$. As is well-known, it is given by the leading eigenvector of $\mathbf C$ scaled by a square root of its eigenvalue, and in this case will be pointing in the $(0,0,1)$ direction (in order to reproduce the covariance of $X_3$ which would otherwise be a major source of reconstruction error).
In contrast, the loadings of the first factor in FA is a vector $\mathbf v$ that minimizes the reconstruction error $\|\mathbf C - \mathbf v \mathbf v^\top - \boldsymbol \Psi \|$, where $\boldsymbol \Psi$ is a diagonal matrix of uniquenesses. This is equivalent to saying that it minimizes the reconstruction error $\|\mathrm{offdiag}\{\mathbf C - \mathbf v \mathbf v^\top\}\|$, i.e. FA does not care about reconstructing the diagonal. Think about $\mathbf C$ with erased diagonal:$$\mathrm{offdiag}\{\mathbf C\}=\left(\begin{array}{c} & \sim 1 & 0 \\ \sim 1 & & 0 \\ 0 & 0 & \end{array}\right).$$ The goal of FA is to reconstruct this part of $\mathbf C$ and so the loadings of the first factor will be pointing in the $(1,1,0)$ direction, in order to reproduce this off-diagonal covariance between $X_1$ and $X_2$.
Note that this analysis is based on the covariance matrix. Conducting an analysis based on the correlation matrix would (in this case) lead both PCA and FA to yield similar outcomes.
My answer to the opposite question might be of interest:
Under which conditions do PCA and FA yield similar results?
For many more details about PCA vs FA issue, see my [very long] answer to this question:
Is there any good reason to use PCA instead of EFA? Also, can PCA be a substitute for factor analysis?
|
Why do PCA and Factor Analysis return different results in this example?
The covariance matrix in this example is given by $$\mathbf C = \left(\begin{array}{c} 1 & \sim 1 & 0 \\ \sim 1 & \sim 1 & 0 \\ 0 & 0 & 100\end{array}\right).$$
To compare PCA and FA, think about how
|
48,088
|
Cumulative Distribution Function Inequality (Discrete Distributions)
|
Try to draw CDF of a Discrete random variable like the (upper) one you have here. Now draw a horizontal line to indicate the level of $a_1$. All you need to do is to find the values of $T$ such that your CDF i.e. $F_T$ satisfies $F_T(T)\leq a_1$. You can move your $a_1$ vertically. Now depending on the level of $a_1$ sometimes you get $P[F_T(T)\leq a_1]<a_1$ and sometimes $P[F_T(T)\leq a_1]= a_1$. The equality happens when your $a_1$ is equal to one of those horizontal (red) lines in the plot of your CDF. OK, see $a_1$ in the graph below.
For what values of $T$ you have $F_T(T)\leq a_1$? Obviously for $t<t_1$. For $t<t_1$, $P_T(t)=P(T< t_1)=0$. And as the plot shows you have $0<a_1$. So the condition you want to prove is correct in this case. Now look at $a_1$ below.
Again for what values of $T$ you have $F_T(T)\leq a_1$? Obviously for all $t< t_2$. Now if $t_1\leq t< t_2$ we have $P_T(t)=P(T\leq t)=a_1$. In this case you will end up with equality i.e. $P[F_T(T)\leq a_1]= a_1$. And if $t<t_1$ then $P_T(t)=P(T\leq t)=0$. Here again as the graph shows the condition holds i.e. $0\leq a_1$. You can do exactly the same argument if you move $a_1$ vertically.
|
Cumulative Distribution Function Inequality (Discrete Distributions)
|
Try to draw CDF of a Discrete random variable like the (upper) one you have here. Now draw a horizontal line to indicate the level of $a_1$. All you need to do is to find the values of $T$ such that y
|
Cumulative Distribution Function Inequality (Discrete Distributions)
Try to draw CDF of a Discrete random variable like the (upper) one you have here. Now draw a horizontal line to indicate the level of $a_1$. All you need to do is to find the values of $T$ such that your CDF i.e. $F_T$ satisfies $F_T(T)\leq a_1$. You can move your $a_1$ vertically. Now depending on the level of $a_1$ sometimes you get $P[F_T(T)\leq a_1]<a_1$ and sometimes $P[F_T(T)\leq a_1]= a_1$. The equality happens when your $a_1$ is equal to one of those horizontal (red) lines in the plot of your CDF. OK, see $a_1$ in the graph below.
For what values of $T$ you have $F_T(T)\leq a_1$? Obviously for $t<t_1$. For $t<t_1$, $P_T(t)=P(T< t_1)=0$. And as the plot shows you have $0<a_1$. So the condition you want to prove is correct in this case. Now look at $a_1$ below.
Again for what values of $T$ you have $F_T(T)\leq a_1$? Obviously for all $t< t_2$. Now if $t_1\leq t< t_2$ we have $P_T(t)=P(T\leq t)=a_1$. In this case you will end up with equality i.e. $P[F_T(T)\leq a_1]= a_1$. And if $t<t_1$ then $P_T(t)=P(T\leq t)=0$. Here again as the graph shows the condition holds i.e. $0\leq a_1$. You can do exactly the same argument if you move $a_1$ vertically.
|
Cumulative Distribution Function Inequality (Discrete Distributions)
Try to draw CDF of a Discrete random variable like the (upper) one you have here. Now draw a horizontal line to indicate the level of $a_1$. All you need to do is to find the values of $T$ such that y
|
48,089
|
Cumulative Distribution Function Inequality (Discrete Distributions)
|
Consider a box $\Omega$ filled with tickets. On each ticket $\omega$ is written a number called $X(\omega)$. For any number $x$, whether or not it appears among the tickets, $F_X(x)$ is (defined to be) the proportion of tickets for which $X \le x.$
Let's add some new information to each ticket $\omega$: next to the value of $X$ written on it, we will also write the value of $F_X(X(\omega))$: it is the proportion of all tickets with values of $X$ less than or equal to this value, $X(\omega).$ (It's the same concept as a percentile or quantile: the tickets with the smallest values of $X$ get the smallest proportions and the tickets with the largest values of $X$ get the largest proportions.) These new values, being proportions, lie between $0$ and $1$ inclusive. But, when $X$ is discrete, they will not include all possible numbers, but only the proportions that actually occur in the box.
Consider drawing a single ticket from this box at random. Fixing a number $a$ in advance, what is the chance that the new value (the "quantile") written on the ticket will not exceed $a$? Of course it's the proportion of tickets with values of $a$ or lower. But all such tickets, by construction, have values of $X$ that lie within the lower $100a\%$ of all the values. Therefore this chance cannot exceed $a$.
The chance might be strictly less than $a$ when $a$ is not one of the actual proportions in the box. Because it cannot be greater than $a$ and now cannot be equal to $a$ it has to be less than $a$!
A simple example is afforded by a box with two tickets: on one of these $X$ equals $0$ and on the other it equals $1$. When we write the proportions on the tickets, then, we will write $1/2$ (or $50\%$) on the first ticket (because half the tickets have values of $0$ or less) and $1$ (or $100\%$) on the second ticket (because all the tickets have values of $1$ or less).
What is the chance that this new value on a randomly drawn ticket will be less than or equal to $a=3/4$ (or $75\%$)? Because the new values are only $50\%$ and $100\%$, and half of them are less than $75\%$, the answer obviously is $1/2$. This is strictly less than $a$ because there are no proportions in the box between $50\%$ and $75\%$. The issue is just that trivial and simple.
The preceding used a tickets in a box metaphor for reasoning about random variables. If we replace $\Omega$ by a probability space, insist that $X$ be a measurable function, and understand "proportion" as the value of the probability measure, then we will have a rigorous proof. And it's still just as trivial.
|
Cumulative Distribution Function Inequality (Discrete Distributions)
|
Consider a box $\Omega$ filled with tickets. On each ticket $\omega$ is written a number called $X(\omega)$. For any number $x$, whether or not it appears among the tickets, $F_X(x)$ is (defined to
|
Cumulative Distribution Function Inequality (Discrete Distributions)
Consider a box $\Omega$ filled with tickets. On each ticket $\omega$ is written a number called $X(\omega)$. For any number $x$, whether or not it appears among the tickets, $F_X(x)$ is (defined to be) the proportion of tickets for which $X \le x.$
Let's add some new information to each ticket $\omega$: next to the value of $X$ written on it, we will also write the value of $F_X(X(\omega))$: it is the proportion of all tickets with values of $X$ less than or equal to this value, $X(\omega).$ (It's the same concept as a percentile or quantile: the tickets with the smallest values of $X$ get the smallest proportions and the tickets with the largest values of $X$ get the largest proportions.) These new values, being proportions, lie between $0$ and $1$ inclusive. But, when $X$ is discrete, they will not include all possible numbers, but only the proportions that actually occur in the box.
Consider drawing a single ticket from this box at random. Fixing a number $a$ in advance, what is the chance that the new value (the "quantile") written on the ticket will not exceed $a$? Of course it's the proportion of tickets with values of $a$ or lower. But all such tickets, by construction, have values of $X$ that lie within the lower $100a\%$ of all the values. Therefore this chance cannot exceed $a$.
The chance might be strictly less than $a$ when $a$ is not one of the actual proportions in the box. Because it cannot be greater than $a$ and now cannot be equal to $a$ it has to be less than $a$!
A simple example is afforded by a box with two tickets: on one of these $X$ equals $0$ and on the other it equals $1$. When we write the proportions on the tickets, then, we will write $1/2$ (or $50\%$) on the first ticket (because half the tickets have values of $0$ or less) and $1$ (or $100\%$) on the second ticket (because all the tickets have values of $1$ or less).
What is the chance that this new value on a randomly drawn ticket will be less than or equal to $a=3/4$ (or $75\%$)? Because the new values are only $50\%$ and $100\%$, and half of them are less than $75\%$, the answer obviously is $1/2$. This is strictly less than $a$ because there are no proportions in the box between $50\%$ and $75\%$. The issue is just that trivial and simple.
The preceding used a tickets in a box metaphor for reasoning about random variables. If we replace $\Omega$ by a probability space, insist that $X$ be a measurable function, and understand "proportion" as the value of the probability measure, then we will have a rigorous proof. And it's still just as trivial.
|
Cumulative Distribution Function Inequality (Discrete Distributions)
Consider a box $\Omega$ filled with tickets. On each ticket $\omega$ is written a number called $X(\omega)$. For any number $x$, whether or not it appears among the tickets, $F_X(x)$ is (defined to
|
48,090
|
Why is Pearson's correlation coefficient defined the way it is?
|
One nice thing you get from dividing by the product of standard deviations is that it guarantees that the correlation coefficient will be between -1 and +1.
If you want to determine if $X$ has a stronger linear relationship with $Y$ or with $Z$ comparing $cov(X,Y)$ with $cov(X,Z)$ directly is not informative, since the scale of each of the covariances depends on the variance of $Y$ an $Z$, which could be very different.
Dividing by $\sigma_X \sigma_Y$ normalizes the covariance, so you can compare $cor(X,Y)$ with $cor(X,Z)$ in meaningful way.
|
Why is Pearson's correlation coefficient defined the way it is?
|
One nice thing you get from dividing by the product of standard deviations is that it guarantees that the correlation coefficient will be between -1 and +1.
If you want to determine if $X$ has a stron
|
Why is Pearson's correlation coefficient defined the way it is?
One nice thing you get from dividing by the product of standard deviations is that it guarantees that the correlation coefficient will be between -1 and +1.
If you want to determine if $X$ has a stronger linear relationship with $Y$ or with $Z$ comparing $cov(X,Y)$ with $cov(X,Z)$ directly is not informative, since the scale of each of the covariances depends on the variance of $Y$ an $Z$, which could be very different.
Dividing by $\sigma_X \sigma_Y$ normalizes the covariance, so you can compare $cor(X,Y)$ with $cor(X,Z)$ in meaningful way.
|
Why is Pearson's correlation coefficient defined the way it is?
One nice thing you get from dividing by the product of standard deviations is that it guarantees that the correlation coefficient will be between -1 and +1.
If you want to determine if $X$ has a stron
|
48,091
|
Is there a way to remove individual trees from a forest in the randomForest package in R?
|
One idea is, instead of creating one forest with N trees, create N "forests" of 1 tree each by calling randomForest() N times. Then you could manipulate them as you wish.
|
Is there a way to remove individual trees from a forest in the randomForest package in R?
|
One idea is, instead of creating one forest with N trees, create N "forests" of 1 tree each by calling randomForest() N times. Then you could manipulate them as you wish.
|
Is there a way to remove individual trees from a forest in the randomForest package in R?
One idea is, instead of creating one forest with N trees, create N "forests" of 1 tree each by calling randomForest() N times. Then you could manipulate them as you wish.
|
Is there a way to remove individual trees from a forest in the randomForest package in R?
One idea is, instead of creating one forest with N trees, create N "forests" of 1 tree each by calling randomForest() N times. Then you could manipulate them as you wish.
|
48,092
|
Is there a way to remove individual trees from a forest in the randomForest package in R?
|
It depends on which language you are more familiar with.
randomForest package implements the original Fortran version of Breiman's random forest. You should try to modify the Fortran code then.
party packages has everything implemented in C. So, you can try to modify the C code.
WEKA RandomForest is implemented in Java and involves the classes Bagging and RandomTree.
Honestly, I am more familiar with Java and I would use WEKA then. I actually implemented some ensemble pruning techniques in WEKA and it was pretty simple.
|
Is there a way to remove individual trees from a forest in the randomForest package in R?
|
It depends on which language you are more familiar with.
randomForest package implements the original Fortran version of Breiman's random forest. You should try to modify the Fortran code then.
part
|
Is there a way to remove individual trees from a forest in the randomForest package in R?
It depends on which language you are more familiar with.
randomForest package implements the original Fortran version of Breiman's random forest. You should try to modify the Fortran code then.
party packages has everything implemented in C. So, you can try to modify the C code.
WEKA RandomForest is implemented in Java and involves the classes Bagging and RandomTree.
Honestly, I am more familiar with Java and I would use WEKA then. I actually implemented some ensemble pruning techniques in WEKA and it was pretty simple.
|
Is there a way to remove individual trees from a forest in the randomForest package in R?
It depends on which language you are more familiar with.
randomForest package implements the original Fortran version of Breiman's random forest. You should try to modify the Fortran code then.
part
|
48,093
|
How to remove seasonality from daily electricity demand
|
Modeling daily electricity demand is a data intensive effort. To simplify this, it's easier to start "zoomed out", estimating monthly loads. Here's an article (with a Youtube video) that describes a monthly model that is simple and easy to understand. The article includes R code:
http://revgr.com/2012/11/06/all-forecasts-are-wrong-but-some-generate-fewer-complaints/
As you "zoom in" to shorter time frames the problem gets more and more complicated. For example, the monthly model includes an integer 12 months/year and starts at the beginning of month 1, while a weekly model includes a non-integer 52.18 weeks/year and might begin at the start of a week, middle of the week, end of the week, etc (i.e. you can't directly compare "week 1" of one year to "week 1" of the next year, they start on different days). It gets more complicated when you drop down to daily or hourly time frames.
The hierarchy in time frames, starting with the longest time frame, is typically:
1) Population growth and economic activity.
2) Long term seasonal temperature terms (summer, winter, etc).
3) Day of the week (Tuesday, Wednesday and Thursday are typically similar workdays; the remaining days have their own individual "day-of-the-week" values).
4) Holidays, the day before and the day after a holiday (many holidays have a similar value as a typical Sunday "day-of-the-week" value).
5) Temperature due to time of day, cooler nights, warmer days, is the sun shining, is it raining, etc. (this is a refinement of item 2 above).
6) Work load during the day. People are typically at home during the night and at work during the day, so lot of electricity consuming workplaces shut down at night.
7) Other terms such as humidity, daylight savings time, etc.
The bottom line is, at the daily and hourly time frames, a lot of data (and complexity) is required.
You can Google "daily electrical load models" (or hourly models) and various papers will show up. Some are based on neural nets, support vector machines, etc. Here's a link to a paper by Rob Hyndman that explains another technique.
http://www.tandfonline.com/doi/abs/10.1198/jasa.2011.tm09771#.UrNTUtJDuyw
The methods used in that paper are in the "forecast" package:
http://robjhyndman.com/software/forecast/
|
How to remove seasonality from daily electricity demand
|
Modeling daily electricity demand is a data intensive effort. To simplify this, it's easier to start "zoomed out", estimating monthly loads. Here's an article (with a Youtube video) that describes
|
How to remove seasonality from daily electricity demand
Modeling daily electricity demand is a data intensive effort. To simplify this, it's easier to start "zoomed out", estimating monthly loads. Here's an article (with a Youtube video) that describes a monthly model that is simple and easy to understand. The article includes R code:
http://revgr.com/2012/11/06/all-forecasts-are-wrong-but-some-generate-fewer-complaints/
As you "zoom in" to shorter time frames the problem gets more and more complicated. For example, the monthly model includes an integer 12 months/year and starts at the beginning of month 1, while a weekly model includes a non-integer 52.18 weeks/year and might begin at the start of a week, middle of the week, end of the week, etc (i.e. you can't directly compare "week 1" of one year to "week 1" of the next year, they start on different days). It gets more complicated when you drop down to daily or hourly time frames.
The hierarchy in time frames, starting with the longest time frame, is typically:
1) Population growth and economic activity.
2) Long term seasonal temperature terms (summer, winter, etc).
3) Day of the week (Tuesday, Wednesday and Thursday are typically similar workdays; the remaining days have their own individual "day-of-the-week" values).
4) Holidays, the day before and the day after a holiday (many holidays have a similar value as a typical Sunday "day-of-the-week" value).
5) Temperature due to time of day, cooler nights, warmer days, is the sun shining, is it raining, etc. (this is a refinement of item 2 above).
6) Work load during the day. People are typically at home during the night and at work during the day, so lot of electricity consuming workplaces shut down at night.
7) Other terms such as humidity, daylight savings time, etc.
The bottom line is, at the daily and hourly time frames, a lot of data (and complexity) is required.
You can Google "daily electrical load models" (or hourly models) and various papers will show up. Some are based on neural nets, support vector machines, etc. Here's a link to a paper by Rob Hyndman that explains another technique.
http://www.tandfonline.com/doi/abs/10.1198/jasa.2011.tm09771#.UrNTUtJDuyw
The methods used in that paper are in the "forecast" package:
http://robjhyndman.com/software/forecast/
|
How to remove seasonality from daily electricity demand
Modeling daily electricity demand is a data intensive effort. To simplify this, it's easier to start "zoomed out", estimating monthly loads. Here's an article (with a Youtube video) that describes
|
48,094
|
How to remove seasonality from daily electricity demand
|
i'm having a fabulous run with ucm. You could model this as daily seasonality & with an annual cycle. You also have a very evident trend.
Post back here if you succeeded with ucm (proc ucm)
|
How to remove seasonality from daily electricity demand
|
i'm having a fabulous run with ucm. You could model this as daily seasonality & with an annual cycle. You also have a very evident trend.
Post back here if you succeeded with ucm (proc ucm)
|
How to remove seasonality from daily electricity demand
i'm having a fabulous run with ucm. You could model this as daily seasonality & with an annual cycle. You also have a very evident trend.
Post back here if you succeeded with ucm (proc ucm)
|
How to remove seasonality from daily electricity demand
i'm having a fabulous run with ucm. You could model this as daily seasonality & with an annual cycle. You also have a very evident trend.
Post back here if you succeeded with ucm (proc ucm)
|
48,095
|
Probability of always more heads than tails
|
For a fixed value of $n$, I'm not sure that a simpler formula exists. However, for $n=\infty$, the probability that there will be more heads than tails permanently is simply equal to $2p-1$. We can show this as follows.
Let $x_k$ denote the probability of success conditional on the current state being $k$ heads. We have the simple recurrence $x_k=p x_{k+1}+(1-p)x_{k-1}$, which we can rewrite as
$$x_k=\frac{1}{p}x_{k-1} - \frac{1-p}{p}x_{k-2}.$$
Solutions to this recurrence have the form
$x_k = a_1\lambda_1^k+a_2\lambda_2^k$, where the $\lambda_i$ are roots of the characteristic polynomial $z^2-\frac{1}{p}z+\frac{1-p}{p}$:
\begin{align}
\lambda_1=1, ~~~~~~\lambda_2=\frac{1-p}{p},
\end{align}
We also have the constraints that $x_0=0$ and for $p>1/2$, $\lim_{k\rightarrow \infty}x_k=1$ (see below). It follows that the only possible solution is
$$x_k=1-\left(\frac{1-p}{p}\right)^k.$$
Since we start with $0$ heads, then in order to survive forever, we must toss a head in the first toss, and then survive from the state of one head. The probability is therefore
$$px_1=p\left(1-\frac{1-p}{p}\right)=p-(1-p)=2p-1.$$
Now the answer to the question "how do we know that $\lim_{k\rightarrow \infty}x_k=1$?" There are two ways to go about this. The first is to start from the Borel-Cantelli lemma as in this answer. But there is also a direct proof.
Let $x_{k,n}$ denote the probability that, starting from a state of $k$ heads, we survive at least $n$ more rounds. Note that $x_{k,0}=1$ for $k>0$, and $x_{0,0}=0$. Note also that the $x_{k,n}$ must satisfy
$$x_{k,n}=p x_{k+1,n-1}+(1-p)x_{k-1,n-1}.$$
Since our values of $x_k$ computed above satisfy this same recurrence, then by monotinicity we may deduce that
$$\left(x_{k,n-1}\geq x_k \forall k\right)\implies \left(x_{k,n}\geq x_k \forall k\right),$$
and since this inequality holds for $n=0$, then by induction it must hold for all $n$. From this it follows that $\lim_{n\rightarrow\infty}x_{k,n}\geq x_k$ for all $k$, which in turn implies that $\lim_{k\rightarrow \infty}\lim_{n\rightarrow\infty}x_{k,n}=1$. This in turn implies that $\lim_{n\rightarrow\infty}x_{k,n}=x_k$ for all $k$, as deduced above.
|
Probability of always more heads than tails
|
For a fixed value of $n$, I'm not sure that a simpler formula exists. However, for $n=\infty$, the probability that there will be more heads than tails permanently is simply equal to $2p-1$. We can
|
Probability of always more heads than tails
For a fixed value of $n$, I'm not sure that a simpler formula exists. However, for $n=\infty$, the probability that there will be more heads than tails permanently is simply equal to $2p-1$. We can show this as follows.
Let $x_k$ denote the probability of success conditional on the current state being $k$ heads. We have the simple recurrence $x_k=p x_{k+1}+(1-p)x_{k-1}$, which we can rewrite as
$$x_k=\frac{1}{p}x_{k-1} - \frac{1-p}{p}x_{k-2}.$$
Solutions to this recurrence have the form
$x_k = a_1\lambda_1^k+a_2\lambda_2^k$, where the $\lambda_i$ are roots of the characteristic polynomial $z^2-\frac{1}{p}z+\frac{1-p}{p}$:
\begin{align}
\lambda_1=1, ~~~~~~\lambda_2=\frac{1-p}{p},
\end{align}
We also have the constraints that $x_0=0$ and for $p>1/2$, $\lim_{k\rightarrow \infty}x_k=1$ (see below). It follows that the only possible solution is
$$x_k=1-\left(\frac{1-p}{p}\right)^k.$$
Since we start with $0$ heads, then in order to survive forever, we must toss a head in the first toss, and then survive from the state of one head. The probability is therefore
$$px_1=p\left(1-\frac{1-p}{p}\right)=p-(1-p)=2p-1.$$
Now the answer to the question "how do we know that $\lim_{k\rightarrow \infty}x_k=1$?" There are two ways to go about this. The first is to start from the Borel-Cantelli lemma as in this answer. But there is also a direct proof.
Let $x_{k,n}$ denote the probability that, starting from a state of $k$ heads, we survive at least $n$ more rounds. Note that $x_{k,0}=1$ for $k>0$, and $x_{0,0}=0$. Note also that the $x_{k,n}$ must satisfy
$$x_{k,n}=p x_{k+1,n-1}+(1-p)x_{k-1,n-1}.$$
Since our values of $x_k$ computed above satisfy this same recurrence, then by monotinicity we may deduce that
$$\left(x_{k,n-1}\geq x_k \forall k\right)\implies \left(x_{k,n}\geq x_k \forall k\right),$$
and since this inequality holds for $n=0$, then by induction it must hold for all $n$. From this it follows that $\lim_{n\rightarrow\infty}x_{k,n}\geq x_k$ for all $k$, which in turn implies that $\lim_{k\rightarrow \infty}\lim_{n\rightarrow\infty}x_{k,n}=1$. This in turn implies that $\lim_{n\rightarrow\infty}x_{k,n}=x_k$ for all $k$, as deduced above.
|
Probability of always more heads than tails
For a fixed value of $n$, I'm not sure that a simpler formula exists. However, for $n=\infty$, the probability that there will be more heads than tails permanently is simply equal to $2p-1$. We can
|
48,096
|
Why does fixed effect p-value in a mixed model act unintuitively?
|
Your model corresponds to
$$Y_{ijk}=\beta_0+\beta_i+u_{ij}+e_{ijk}$$
Using the properties of the errors, $e_{ijk}$, The corresponding model for the means is given as:
$$\overline{Y}_{ij}=\beta_0+\beta_i+u_{ij}+\overline{e}_{ij}$$
where the variance of $\overline{e}_{ij}$ is now $\frac{\sigma^2_e}{n_{ij}}$, where $n_{ij}=4$ in your data set (ie "balanced"). Now this shows that the individual means are sufficient for the betas, given the variance parameters. This is why they dont matter. It happens with any divisible distribution that has non unique predictors.
Note that the variance components are $0.55=\sqrt{\sigma^2_u+\frac{\sigma^2_e}{4}}$, which is the variance of $u_{ij}+\overline{e}_{ij}$.
|
Why does fixed effect p-value in a mixed model act unintuitively?
|
Your model corresponds to
$$Y_{ijk}=\beta_0+\beta_i+u_{ij}+e_{ijk}$$
Using the properties of the errors, $e_{ijk}$, The corresponding model for the means is given as:
$$\overline{Y}_{ij}=\beta_0+\beta
|
Why does fixed effect p-value in a mixed model act unintuitively?
Your model corresponds to
$$Y_{ijk}=\beta_0+\beta_i+u_{ij}+e_{ijk}$$
Using the properties of the errors, $e_{ijk}$, The corresponding model for the means is given as:
$$\overline{Y}_{ij}=\beta_0+\beta_i+u_{ij}+\overline{e}_{ij}$$
where the variance of $\overline{e}_{ij}$ is now $\frac{\sigma^2_e}{n_{ij}}$, where $n_{ij}=4$ in your data set (ie "balanced"). Now this shows that the individual means are sufficient for the betas, given the variance parameters. This is why they dont matter. It happens with any divisible distribution that has non unique predictors.
Note that the variance components are $0.55=\sqrt{\sigma^2_u+\frac{\sigma^2_e}{4}}$, which is the variance of $u_{ij}+\overline{e}_{ij}$.
|
Why does fixed effect p-value in a mixed model act unintuitively?
Your model corresponds to
$$Y_{ijk}=\beta_0+\beta_i+u_{ij}+e_{ijk}$$
Using the properties of the errors, $e_{ijk}$, The corresponding model for the means is given as:
$$\overline{Y}_{ij}=\beta_0+\beta
|
48,097
|
How to calculate estimated proportions and their confidence intervals from a mixed model?
|
First a note: you can't calculate a decent standard error on the probabilities, you have to do so on a logit scale and use those to construct your confidence intervals. Intervals around probabilities are hardly symmetrical, and definitely not when using a mixed model.
You can easily plot the effects using the package effects:
With the function Effect() you can specify the effects you want to plot and plot immediately, or extract the information you want.
Some random fake data:
ndata <- data.frame(
DV = sample(0:1,200,TRUE),
Treatment1 = rep(rep(c('A1','B1'),25),4),
Treatment2 = rep(rep(c('A2','B2'),each=25),4),
Block = rep(c("Block1","Block2"),each=100)
)
m <- glmer (DV ~ Treatment1 * Treatment2 + (1|Block/Treatment1),
data=ndata, family = binomial)
To get a plot of the effects, you can simply do:
plot(allEffects(m))
To get:
The same you get with plot(Effect(c("Treatment1","Treatment2"),m)
If you want to get the actual data out, you can save the result of a call to Effect() in an object, and extract the necessary data:
est <- Effect(c("Treatment1","Treatment2"),m)
cbind(est$x,est$fit,est$se,est$lower,est$upper)
to get:
Treatment1 Treatment2 est$fit est$se est$lower est$upper
1 A1 A2 -7.696104e-02 0.2775554 -0.6209597 0.4670376
2 B1 A2 -1.670541e-01 0.2896820 -0.7348204 0.4007122
3 A1 B2 -3.364722e-01 0.2927591 -0.9102694 0.2373250
4 B1 B2 1.110223e-16 0.2773501 -0.5435962 0.5435962
Note that these are on the original (logit) scale. Calculating a confidence interval would involve transforming this to the original scale, using eg. plogis() :
> cbind(est$x,plogis(est$fit),plogis(est$lower),plogis(est$upper))
Treatment1 Treatment2 plogis(est$fit) plogis(est$lower) plogis(est$upper)
1 A1 A2 0.4807692 0.3495632 0.6146824
2 B1 A2 0.4583333 0.3241378 0.5988588
3 A1 B2 0.4166667 0.2869447 0.5590543
4 B1 B2 0.5000000 0.3673514 0.6326486
PS : this is not the cleanest code, it's just for illustrative purposes.
|
How to calculate estimated proportions and their confidence intervals from a mixed model?
|
First a note: you can't calculate a decent standard error on the probabilities, you have to do so on a logit scale and use those to construct your confidence intervals. Intervals around probabilities
|
How to calculate estimated proportions and their confidence intervals from a mixed model?
First a note: you can't calculate a decent standard error on the probabilities, you have to do so on a logit scale and use those to construct your confidence intervals. Intervals around probabilities are hardly symmetrical, and definitely not when using a mixed model.
You can easily plot the effects using the package effects:
With the function Effect() you can specify the effects you want to plot and plot immediately, or extract the information you want.
Some random fake data:
ndata <- data.frame(
DV = sample(0:1,200,TRUE),
Treatment1 = rep(rep(c('A1','B1'),25),4),
Treatment2 = rep(rep(c('A2','B2'),each=25),4),
Block = rep(c("Block1","Block2"),each=100)
)
m <- glmer (DV ~ Treatment1 * Treatment2 + (1|Block/Treatment1),
data=ndata, family = binomial)
To get a plot of the effects, you can simply do:
plot(allEffects(m))
To get:
The same you get with plot(Effect(c("Treatment1","Treatment2"),m)
If you want to get the actual data out, you can save the result of a call to Effect() in an object, and extract the necessary data:
est <- Effect(c("Treatment1","Treatment2"),m)
cbind(est$x,est$fit,est$se,est$lower,est$upper)
to get:
Treatment1 Treatment2 est$fit est$se est$lower est$upper
1 A1 A2 -7.696104e-02 0.2775554 -0.6209597 0.4670376
2 B1 A2 -1.670541e-01 0.2896820 -0.7348204 0.4007122
3 A1 B2 -3.364722e-01 0.2927591 -0.9102694 0.2373250
4 B1 B2 1.110223e-16 0.2773501 -0.5435962 0.5435962
Note that these are on the original (logit) scale. Calculating a confidence interval would involve transforming this to the original scale, using eg. plogis() :
> cbind(est$x,plogis(est$fit),plogis(est$lower),plogis(est$upper))
Treatment1 Treatment2 plogis(est$fit) plogis(est$lower) plogis(est$upper)
1 A1 A2 0.4807692 0.3495632 0.6146824
2 B1 A2 0.4583333 0.3241378 0.5988588
3 A1 B2 0.4166667 0.2869447 0.5590543
4 B1 B2 0.5000000 0.3673514 0.6326486
PS : this is not the cleanest code, it's just for illustrative purposes.
|
How to calculate estimated proportions and their confidence intervals from a mixed model?
First a note: you can't calculate a decent standard error on the probabilities, you have to do so on a logit scale and use those to construct your confidence intervals. Intervals around probabilities
|
48,098
|
Why Bayesian logistic (probit) regression instead of standard logistic (probit) regression?
|
Arguably, Bayesian logistic/probit regression would be better if you had informative prior, or if there was perfect or quasi-perfect separation or if you wanted to fit a hierarchical model.
If you have an informative prior, then use it. And nothing better than use it in a Bayesian approach. If there is perfect separation, a good prior (even if only weakly informative) may help you to deal with this problem. Last, but not least, I think Bayes excels with hierarchical models.
And yet, I'd still favor a Bayesian approach even if none of the above is true. And for one simple reason: It's easier to interpret Bayesian results than frequentist ones.
As it is known, it's hard to correctly compute standard errors for interaction terms in logistic/probit regression. However, it's quite easy to compute the uncertainty of interaction terms with a Bayesian approach. See the chosen answer to this question of mine about interaction terms in logistic regression. Also, with Bayes you can use posterior predictive checks to check the fit of your model, a great bonus!
|
Why Bayesian logistic (probit) regression instead of standard logistic (probit) regression?
|
Arguably, Bayesian logistic/probit regression would be better if you had informative prior, or if there was perfect or quasi-perfect separation or if you wanted to fit a hierarchical model.
If you ha
|
Why Bayesian logistic (probit) regression instead of standard logistic (probit) regression?
Arguably, Bayesian logistic/probit regression would be better if you had informative prior, or if there was perfect or quasi-perfect separation or if you wanted to fit a hierarchical model.
If you have an informative prior, then use it. And nothing better than use it in a Bayesian approach. If there is perfect separation, a good prior (even if only weakly informative) may help you to deal with this problem. Last, but not least, I think Bayes excels with hierarchical models.
And yet, I'd still favor a Bayesian approach even if none of the above is true. And for one simple reason: It's easier to interpret Bayesian results than frequentist ones.
As it is known, it's hard to correctly compute standard errors for interaction terms in logistic/probit regression. However, it's quite easy to compute the uncertainty of interaction terms with a Bayesian approach. See the chosen answer to this question of mine about interaction terms in logistic regression. Also, with Bayes you can use posterior predictive checks to check the fit of your model, a great bonus!
|
Why Bayesian logistic (probit) regression instead of standard logistic (probit) regression?
Arguably, Bayesian logistic/probit regression would be better if you had informative prior, or if there was perfect or quasi-perfect separation or if you wanted to fit a hierarchical model.
If you ha
|
48,099
|
About Trivariate Normal Distribution
|
If $X \sim N_k(\mu,\Sigma)$, then $Q=(X-\mu)'\Sigma^{-1}(X-\mu) \sim \chi^2_k$. Further, the level sets of $Q$ are the ellipsoids you refer to. So the 72% you mention comes from a chi-square distribution (these calcs in R):
> pchisq(1.96^2,df=3)
[1] 0.7209157
As do the other numbers:
> pchisq(1.96^2,df=10)
[1] 0.04579014
> sqrt(qchisq(0.95,df=10))
[1] 4.278672
See http://en.wikipedia.org/wiki/Multivariate_normal_distribution#Prediction_Interval
|
About Trivariate Normal Distribution
|
If $X \sim N_k(\mu,\Sigma)$, then $Q=(X-\mu)'\Sigma^{-1}(X-\mu) \sim \chi^2_k$. Further, the level sets of $Q$ are the ellipsoids you refer to. So the 72% you mention comes from a chi-square distribut
|
About Trivariate Normal Distribution
If $X \sim N_k(\mu,\Sigma)$, then $Q=(X-\mu)'\Sigma^{-1}(X-\mu) \sim \chi^2_k$. Further, the level sets of $Q$ are the ellipsoids you refer to. So the 72% you mention comes from a chi-square distribution (these calcs in R):
> pchisq(1.96^2,df=3)
[1] 0.7209157
As do the other numbers:
> pchisq(1.96^2,df=10)
[1] 0.04579014
> sqrt(qchisq(0.95,df=10))
[1] 4.278672
See http://en.wikipedia.org/wiki/Multivariate_normal_distribution#Prediction_Interval
|
About Trivariate Normal Distribution
If $X \sim N_k(\mu,\Sigma)$, then $Q=(X-\mu)'\Sigma^{-1}(X-\mu) \sim \chi^2_k$. Further, the level sets of $Q$ are the ellipsoids you refer to. So the 72% you mention comes from a chi-square distribut
|
48,100
|
Relation of slopes of predictors when they are correlated in linear regression
|
When you omitt $X_2$ from your first regression, your estimate of the coefficient $\beta_{10}$ will be subject to the usual omitted variable bias:
$$plim\: \widehat{\beta}_{10} = \beta_{11} + \beta_{21}\frac{Cov(X_1,X_2)}{Var(X_1)} $$
and the only way that this bias vanishes is if $X_2$ is not useful in predicting $Y$, i.e. $\beta_{21} = 0$ in regression 3, or $Cov(X_1,X_2)=0$. The same reasoning holds for the bias in the second regression.
The derivation of the omitted variable bias formula is as follows. For ease of notation let me write the full model and the model with $X_2$ missing as
$$\begin{align}
Y &= \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \epsilon \\
Y &= \beta_0 + \beta_1 + u
\end{align}$$
In your regression with $X_2$ missing, you estimate
$$
\widehat{\beta}_{1} = \frac{Cov(X_1,Y)}{Var(X_1)} = \frac{\sum^N_{i=1}(X_{1i}-\overline{X}_1)(Y_i-\overline{Y})}{\sum^N_{i=1}(X_{1i}-\overline{X}_1)^2} $$
where we now substitute $Y_i$ and $\overline{Y}_i$ with
$$\begin{align}Y_i &= \beta_{0}+\beta_{1}X_{1i} + u_i \\
\overline{Y}_i &= \beta_{0}+\beta_{1}\overline{X}_{1i}+\overline{u}_i
\end{align}$$
and $u_i = \beta_2 X_{2i} + \epsilon_i$, which gives us
$$ \widehat{\beta}_{1} = \frac{\sum^N_{i=1}(X_{1i}-\overline{X}_1)([\beta_{0}+\beta_{1}X_{1i} + \beta_2 X_{2i} + \epsilon_i]-[\beta_{0}+\beta_{1}\overline{X}_{1}+\beta_2 \overline{X}_2 + \overline{\epsilon}])}{\sum^N_{i=1}(X_{1i}-\overline{X}_1)^2}.
$$
Now multiply out and collect terms
$$ \begin{align}
\widehat{\beta}_{1} &= \frac{\beta_1 \sum^N_{i=1}(X_{1i}-\overline{X}_1)^2 + \beta_2 \sum^N_{i=1}(X_{1i}-\overline{X}_1)(X_{2i}-\overline{X}_2) + \sum^N_{i=1}(X_{1i}-\overline{X}_1)(\epsilon_{i}-\overline{\epsilon})}{\sum^N_{i=1}(X_{1i}-\overline{X}_1)^2} \\
&= \beta_1 + \beta_2 \frac{\sum^N_{i=1}(X_{1i}-\overline{X}_1)(X_{2i}-\overline{X}_2)}{\sum^N_{i=1}(X_{1i}-\overline{X}_1)^2} + \frac{\sum^N_{i=1}(X_{1i}-\overline{X}_1)(\epsilon_{i}-\overline{\epsilon})}{\sum^N_{i=1}(X_{1i}-\overline{X}_1)^2} \\
&= \beta_1 + \beta_2 \frac{Cov(X_1,X_2)}{Var(X_1)} + \frac{Cov(X_1,\epsilon)}{Var(X_1)}.
\end{align}$$
Given that $Cov(X_1,\epsilon) = 0$ by assumption, this leaves you with the omitted variable bias formula from above.
As concerns your p-values, in your third regression the estimated variance for, say $X_1$, is
$$Var\widehat{\beta}_{X_{1}} = \frac{\sigma^2_3}{NVar(X_1)[1-Corr(X_1,X_2)^2]}$$
When you omit $X_2$ in your first regression the estimated variance is
$$Var\widehat{\beta}_{X_{1}} = \frac{\sigma^2_1}{NVar(X_1)}$$
Given that the correlation term with $X_2$ is now missing, the estimate of your standard error is likely to be much lower - this should happen in your case because the correlation between the independent variables is high. The standard errors are then used to construct your t statistic and p-values, so in regressions 1 and 2 you should observe higher significance. In some instances the standard error can be higher though: this happens if $Corr(X_1,X_2)$ is low and $X_2$ is a strong predictor for $Y$ such that the regression error in 3 ($\sigma^2_3$) is much smaller than $\sigma^2_1$.
With regards to your observation that the p-values in regression 1 and 2 are similar, this should just be due to chance. If you compare the variance estimates of the two regressions
$$Var\widehat{\beta}_{X_{1}} = \frac{\sigma^2_1}{NVar(X_1)},\quad Var\widehat{\beta}_{X_{2}} = \frac{\sigma^2_2}{NVar(X_2)}$$
you can see that the relationship depends on the variability of the two variables and their predictive power on the dependent variable (given by $\sigma^2_1$ and $\sigma^2_2$). If the variances are similar and $Corr(Y,X_1)$ is similar to $Corr(Y,X_2)$, then you will get similar p-values as well.
|
Relation of slopes of predictors when they are correlated in linear regression
|
When you omitt $X_2$ from your first regression, your estimate of the coefficient $\beta_{10}$ will be subject to the usual omitted variable bias:
$$plim\: \widehat{\beta}_{10} = \beta_{11} + \beta_{2
|
Relation of slopes of predictors when they are correlated in linear regression
When you omitt $X_2$ from your first regression, your estimate of the coefficient $\beta_{10}$ will be subject to the usual omitted variable bias:
$$plim\: \widehat{\beta}_{10} = \beta_{11} + \beta_{21}\frac{Cov(X_1,X_2)}{Var(X_1)} $$
and the only way that this bias vanishes is if $X_2$ is not useful in predicting $Y$, i.e. $\beta_{21} = 0$ in regression 3, or $Cov(X_1,X_2)=0$. The same reasoning holds for the bias in the second regression.
The derivation of the omitted variable bias formula is as follows. For ease of notation let me write the full model and the model with $X_2$ missing as
$$\begin{align}
Y &= \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \epsilon \\
Y &= \beta_0 + \beta_1 + u
\end{align}$$
In your regression with $X_2$ missing, you estimate
$$
\widehat{\beta}_{1} = \frac{Cov(X_1,Y)}{Var(X_1)} = \frac{\sum^N_{i=1}(X_{1i}-\overline{X}_1)(Y_i-\overline{Y})}{\sum^N_{i=1}(X_{1i}-\overline{X}_1)^2} $$
where we now substitute $Y_i$ and $\overline{Y}_i$ with
$$\begin{align}Y_i &= \beta_{0}+\beta_{1}X_{1i} + u_i \\
\overline{Y}_i &= \beta_{0}+\beta_{1}\overline{X}_{1i}+\overline{u}_i
\end{align}$$
and $u_i = \beta_2 X_{2i} + \epsilon_i$, which gives us
$$ \widehat{\beta}_{1} = \frac{\sum^N_{i=1}(X_{1i}-\overline{X}_1)([\beta_{0}+\beta_{1}X_{1i} + \beta_2 X_{2i} + \epsilon_i]-[\beta_{0}+\beta_{1}\overline{X}_{1}+\beta_2 \overline{X}_2 + \overline{\epsilon}])}{\sum^N_{i=1}(X_{1i}-\overline{X}_1)^2}.
$$
Now multiply out and collect terms
$$ \begin{align}
\widehat{\beta}_{1} &= \frac{\beta_1 \sum^N_{i=1}(X_{1i}-\overline{X}_1)^2 + \beta_2 \sum^N_{i=1}(X_{1i}-\overline{X}_1)(X_{2i}-\overline{X}_2) + \sum^N_{i=1}(X_{1i}-\overline{X}_1)(\epsilon_{i}-\overline{\epsilon})}{\sum^N_{i=1}(X_{1i}-\overline{X}_1)^2} \\
&= \beta_1 + \beta_2 \frac{\sum^N_{i=1}(X_{1i}-\overline{X}_1)(X_{2i}-\overline{X}_2)}{\sum^N_{i=1}(X_{1i}-\overline{X}_1)^2} + \frac{\sum^N_{i=1}(X_{1i}-\overline{X}_1)(\epsilon_{i}-\overline{\epsilon})}{\sum^N_{i=1}(X_{1i}-\overline{X}_1)^2} \\
&= \beta_1 + \beta_2 \frac{Cov(X_1,X_2)}{Var(X_1)} + \frac{Cov(X_1,\epsilon)}{Var(X_1)}.
\end{align}$$
Given that $Cov(X_1,\epsilon) = 0$ by assumption, this leaves you with the omitted variable bias formula from above.
As concerns your p-values, in your third regression the estimated variance for, say $X_1$, is
$$Var\widehat{\beta}_{X_{1}} = \frac{\sigma^2_3}{NVar(X_1)[1-Corr(X_1,X_2)^2]}$$
When you omit $X_2$ in your first regression the estimated variance is
$$Var\widehat{\beta}_{X_{1}} = \frac{\sigma^2_1}{NVar(X_1)}$$
Given that the correlation term with $X_2$ is now missing, the estimate of your standard error is likely to be much lower - this should happen in your case because the correlation between the independent variables is high. The standard errors are then used to construct your t statistic and p-values, so in regressions 1 and 2 you should observe higher significance. In some instances the standard error can be higher though: this happens if $Corr(X_1,X_2)$ is low and $X_2$ is a strong predictor for $Y$ such that the regression error in 3 ($\sigma^2_3$) is much smaller than $\sigma^2_1$.
With regards to your observation that the p-values in regression 1 and 2 are similar, this should just be due to chance. If you compare the variance estimates of the two regressions
$$Var\widehat{\beta}_{X_{1}} = \frac{\sigma^2_1}{NVar(X_1)},\quad Var\widehat{\beta}_{X_{2}} = \frac{\sigma^2_2}{NVar(X_2)}$$
you can see that the relationship depends on the variability of the two variables and their predictive power on the dependent variable (given by $\sigma^2_1$ and $\sigma^2_2$). If the variances are similar and $Corr(Y,X_1)$ is similar to $Corr(Y,X_2)$, then you will get similar p-values as well.
|
Relation of slopes of predictors when they are correlated in linear regression
When you omitt $X_2$ from your first regression, your estimate of the coefficient $\beta_{10}$ will be subject to the usual omitted variable bias:
$$plim\: \widehat{\beta}_{10} = \beta_{11} + \beta_{2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.