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 |
|---|---|---|---|---|---|---|
19,101 | What is the cost function in cv.glm in R's boot package? | r is a vector that contains the actual outcome, pi is a vector that contains the fitted values.
cost <- function(r, pi = 0) mean(abs(r-pi) > 0.5)
This is saying $cost = \sum|r_i - pi_i|$. You can define your own cost functions. In your case for binary classification you can do something like this
mycost <- function(r, pi){
weight1 = 1 #cost for getting 1 wrong
weight0 = 1 #cost for getting 0 wrong
c1 = (r==1)&(pi<0.5) #logical vector - true if actual 1 but predict 0
c0 = (r==0)&(pi>=0.5) #logical vector - true if actual 0 but predict 1
return(mean(weight1*c1+weight0*c0))
}
and put mycost as an argument in the cv.glm function. | What is the cost function in cv.glm in R's boot package? | r is a vector that contains the actual outcome, pi is a vector that contains the fitted values.
cost <- function(r, pi = 0) mean(abs(r-pi) > 0.5)
This is saying $cost = \sum|r_i - pi_i|$. You can def | What is the cost function in cv.glm in R's boot package?
r is a vector that contains the actual outcome, pi is a vector that contains the fitted values.
cost <- function(r, pi = 0) mean(abs(r-pi) > 0.5)
This is saying $cost = \sum|r_i - pi_i|$. You can define your own cost functions. In your case for binary classification you can do something like this
mycost <- function(r, pi){
weight1 = 1 #cost for getting 1 wrong
weight0 = 1 #cost for getting 0 wrong
c1 = (r==1)&(pi<0.5) #logical vector - true if actual 1 but predict 0
c0 = (r==0)&(pi>=0.5) #logical vector - true if actual 0 but predict 1
return(mean(weight1*c1+weight0*c0))
}
and put mycost as an argument in the cv.glm function. | What is the cost function in cv.glm in R's boot package?
r is a vector that contains the actual outcome, pi is a vector that contains the fitted values.
cost <- function(r, pi = 0) mean(abs(r-pi) > 0.5)
This is saying $cost = \sum|r_i - pi_i|$. You can def |
19,102 | What is the cost function in cv.glm in R's boot package? | cost <- function(r, pi = 0) mean(abs(r-pi) > 0.5)
First, you have set a cut-off as 0.5. Your r is 0/1, but pi is probability. So individual cost is 1 if absolute error is greater than 0.5, otherwise 0.
Then, this function calculates the average error rate.
But remember, the cut-off has been set before you define your cost function.
Actually, I think it makes more sense if the choice of cut-off is determined by cost function. | What is the cost function in cv.glm in R's boot package? | cost <- function(r, pi = 0) mean(abs(r-pi) > 0.5)
First, you have set a cut-off as 0.5. Your r is 0/1, but pi is probability. So individual cost is 1 if absolute error is greater than 0.5, otherwise | What is the cost function in cv.glm in R's boot package?
cost <- function(r, pi = 0) mean(abs(r-pi) > 0.5)
First, you have set a cut-off as 0.5. Your r is 0/1, but pi is probability. So individual cost is 1 if absolute error is greater than 0.5, otherwise 0.
Then, this function calculates the average error rate.
But remember, the cut-off has been set before you define your cost function.
Actually, I think it makes more sense if the choice of cut-off is determined by cost function. | What is the cost function in cv.glm in R's boot package?
cost <- function(r, pi = 0) mean(abs(r-pi) > 0.5)
First, you have set a cut-off as 0.5. Your r is 0/1, but pi is probability. So individual cost is 1 if absolute error is greater than 0.5, otherwise |
19,103 | What is the cost function in cv.glm in R's boot package? | The answer by @SLi already explains very well what the cost function you have defined does. However, I thought I would add that the cost function is used to calculate the delta value from cv.glm, which is a measurement of the cross validation error. However, critically delta is the weighted average of the error of each fold given by the cost. We see this by inspecting the relevant bit of the code:
for (i in seq_len(ms)) {
j.out <- seq_len(n)[(s == i)]
j.in <- seq_len(n)[(s != i)]
Call$data <- data[j.in, , drop = FALSE]
d.glm <- eval.parent(Call)
p.alpha <- n.s[i]/n # create weighting for averaging later
cost.i <- cost(glm.y[j.out], predict(d.glm, data[j.out,
, drop = FALSE], type = "response"))
CV <- CV + p.alpha * cost.i # add previous error to running total
cost.0 <- cost.0 - p.alpha * cost(glm.y, predict(d.glm,
data, type = "response"))
}
and the value returned by the function is:
list(call = call, K = K, delta = as.numeric(c(CV, CV + cost.0)),
seed = seed) | What is the cost function in cv.glm in R's boot package? | The answer by @SLi already explains very well what the cost function you have defined does. However, I thought I would add that the cost function is used to calculate the delta value from cv.glm, whic | What is the cost function in cv.glm in R's boot package?
The answer by @SLi already explains very well what the cost function you have defined does. However, I thought I would add that the cost function is used to calculate the delta value from cv.glm, which is a measurement of the cross validation error. However, critically delta is the weighted average of the error of each fold given by the cost. We see this by inspecting the relevant bit of the code:
for (i in seq_len(ms)) {
j.out <- seq_len(n)[(s == i)]
j.in <- seq_len(n)[(s != i)]
Call$data <- data[j.in, , drop = FALSE]
d.glm <- eval.parent(Call)
p.alpha <- n.s[i]/n # create weighting for averaging later
cost.i <- cost(glm.y[j.out], predict(d.glm, data[j.out,
, drop = FALSE], type = "response"))
CV <- CV + p.alpha * cost.i # add previous error to running total
cost.0 <- cost.0 - p.alpha * cost(glm.y, predict(d.glm,
data, type = "response"))
}
and the value returned by the function is:
list(call = call, K = K, delta = as.numeric(c(CV, CV + cost.0)),
seed = seed) | What is the cost function in cv.glm in R's boot package?
The answer by @SLi already explains very well what the cost function you have defined does. However, I thought I would add that the cost function is used to calculate the delta value from cv.glm, whic |
19,104 | RandomForest - MDS plot interpretation | The function MDSplot plots the (PCA of) the proximity matrix. From the documentation for randomForest, the proximity matrix is:
A matrix of proximity measures among the input (based on the frequency that pairs of data points are in the same terminal nodes).
Based on this description, we can guess at what the different plots mean. You seem to have specified k=4, which means a decomposition of the proximity matrix in 4 components. For each entry (i,j) in this matrix of plots, what is plotted is the PCA decomposition along dimension i versus the PCA decomposition along dimension j.
I did a PCA on the same data and got a nice seperation between all the classes in PC1 and PC2 already, but here Dim1 and Dim2 seem to just seperate 3 behaviours. Does this mean that these three behaviours are the more dissimilar than all other behaviours (so MDS tries to find the greatest dissimilarity between variables, but not necessarily all variables in the first step)?
MDS can only base its analysis on the output of your randomForest. If you're expecting a better separation, then you might want to check the classification performance of your randomForest. Another thing to keep in mind is that your PCA is mapping from 9-dimensional data to 2 dimensions, but the MDS is mapping from an NxN-dimensional proximity matrix to 2 dimensions, where N is the number of datapoints.
What does the positioning of the three clusters (as e.g in Dim1 and Dim2) indicate?
It just tells you how far apart (relatively) these clusters are from each other. It's a visualisation aid, so I wouldn't over-interpret it.
Since I'm rather new to R I also have problems plotting a legend to this plot (however I have an idea what the different colours mean), but maybe somebody could help?
The way R works, there's no way to plot legend after-the-fact (unlike in say Matlab, where this information is stored inside the figure object). However, looking at the code for MDSplot, we see that relevant code block is:
palette <- if (require(RColorBrewer) && nlevs < 12) brewer.pal(nlevs, "Set1")
...
plot(rf.mds$points, col = palette[as.numeric(fac)], pch = pch, ...)
So the colours will be taken from that palette, and mapped to the levels (behaviours) in whichever order you've given them. So if you want to plot a legend:
legend(x,y,levels(fac),col=brewer.pal(nlevs, 'Set1'), pch=pch)
would probably work. | RandomForest - MDS plot interpretation | The function MDSplot plots the (PCA of) the proximity matrix. From the documentation for randomForest, the proximity matrix is:
A matrix of proximity measures among the input (based on the frequency | RandomForest - MDS plot interpretation
The function MDSplot plots the (PCA of) the proximity matrix. From the documentation for randomForest, the proximity matrix is:
A matrix of proximity measures among the input (based on the frequency that pairs of data points are in the same terminal nodes).
Based on this description, we can guess at what the different plots mean. You seem to have specified k=4, which means a decomposition of the proximity matrix in 4 components. For each entry (i,j) in this matrix of plots, what is plotted is the PCA decomposition along dimension i versus the PCA decomposition along dimension j.
I did a PCA on the same data and got a nice seperation between all the classes in PC1 and PC2 already, but here Dim1 and Dim2 seem to just seperate 3 behaviours. Does this mean that these three behaviours are the more dissimilar than all other behaviours (so MDS tries to find the greatest dissimilarity between variables, but not necessarily all variables in the first step)?
MDS can only base its analysis on the output of your randomForest. If you're expecting a better separation, then you might want to check the classification performance of your randomForest. Another thing to keep in mind is that your PCA is mapping from 9-dimensional data to 2 dimensions, but the MDS is mapping from an NxN-dimensional proximity matrix to 2 dimensions, where N is the number of datapoints.
What does the positioning of the three clusters (as e.g in Dim1 and Dim2) indicate?
It just tells you how far apart (relatively) these clusters are from each other. It's a visualisation aid, so I wouldn't over-interpret it.
Since I'm rather new to R I also have problems plotting a legend to this plot (however I have an idea what the different colours mean), but maybe somebody could help?
The way R works, there's no way to plot legend after-the-fact (unlike in say Matlab, where this information is stored inside the figure object). However, looking at the code for MDSplot, we see that relevant code block is:
palette <- if (require(RColorBrewer) && nlevs < 12) brewer.pal(nlevs, "Set1")
...
plot(rf.mds$points, col = palette[as.numeric(fac)], pch = pch, ...)
So the colours will be taken from that palette, and mapped to the levels (behaviours) in whichever order you've given them. So if you want to plot a legend:
legend(x,y,levels(fac),col=brewer.pal(nlevs, 'Set1'), pch=pch)
would probably work. | RandomForest - MDS plot interpretation
The function MDSplot plots the (PCA of) the proximity matrix. From the documentation for randomForest, the proximity matrix is:
A matrix of proximity measures among the input (based on the frequency |
19,105 | Errors-in-variables regression: is it valid to pool data from three sites? | This is a mutual calibration problem: that is, of quantitatively comparing two independent measurement devices.
There appear to be two principal issues. The first (which is only implicit in the question) is in framing the problem: how should one determine whether a new method is "equivalent" to an approved one? The second concerns how to analyze data in which some samples may have been measured more than once.
Framing the question
The best (and perhaps obvious) solution to the stated problem is to evaluate the new method using samples with accurately known values obtained from comparable media (such as human plasma). (This is usually done by spiking actual samples with standard materials of known concentration.) Because this has not been done, let's assume it is either not possible or would not be acceptable to the regulators (for whatever reason). Thus, we are reduced to comparing two measurement methods, one of which is being used as a reference because it is believed to be accurate and reproducible (but without perfect precision).
In effect, the client will be requesting that the FDA allow the new method as a proxy or surrogate for the approved method. As such, their burden is to demonstrate that results from the new method will predict, with sufficient accuracy, what the approved method would have determined had it been applied. The subtle aspect of this is that we are not attempting to predict the true values themselves--we don't even know them. Thus, errors-in-variables regression might not be the most appropriate way to analyze these data.
The usual solution in such cases is "inverse regression" (as described, for instance, in Draper & Smith, Applied Regression Analysis (Second Edition), section 1.7). Briefly, this technique regresses the new method's results $Y$ against the approved method's results $X$, erects a suitable prediction interval, and then functionally inverts that interval to obtain ranges of $X$ for any given values of $Y$. If, for the intended range of $Y$ values, these ranges of $X$ are "sufficiently small," then $Y$ is an effective proxy for $X$. (In my experience this approach tends to be conservatively stringent: these intervals can be surprisingly large unless both measurements are highly accurate, precise, and linearly related.)
Addressing duplicate samples
The relevant concepts here are of sample support and components of variance. "Sample support" refers to the physical portion of a subject (a human being here) that is actually measured. After some portion of the subject is taken, it usually needs to be divided into subsamples suitable for the measurement process. We might be concerned about the possibility of variation between subsamples. In a liquid sample which is well-mixed, there is essentially no variation in the underlying quantity (such as a concentration of a chemical) throughout the sample, but in samples of solids or semisolids (which might include blood), such variation can be substantial. Considering that laboratories often need only microliters of a solution to perform a measurement, we have to be concerned about variation almost on a microscopic scale. This could be important.
The possibility of such variation within a physical sample indicates that the variation in measurement results should be partitioned into separate "components of variance." One component is the variance from within-sample variation, and others are contributions to variance from each independent step of the subsequent measurement process. (These steps may include the physical act of subsampling, further chemical and physical processing of the sample--such as adding stabilizers or centrifugation--, injection of the sample into the measuring instrument, variations within the instrument, variations between instruments, and other variations due to changes in who operates the instrument, possible ambient contamination in the laboratories, and more. I hope this makes it clear that in order to do a really good job of answering this question, the statistician needs a thorough understanding of the entire sampling and analytical process. All I can do is provide some general guidance.)
These considerations apply to the question at hand because one "sample" that is measured at two different "sites" really is two physical samples obtained from the same person and then split among laboratories. The measurement by the approved method will use one piece of a split sample and the simultaneous measurement by the new method will use another piece of the split sample. By considering the components of variance these splits imply, we can settle the main issue of the question. It should now be clear that differences between these paired measurements should be attributed to two things: first, actual differences between the measurement procedures--this is what we are trying to assess--and second, differences due to any variation within the sample as well as variation caused by the physical processes of extracting the two subsamples to be measured. If physical reasoning about the sample homogeneity and the subsampling process can establish that the second form of variance is negligible, then indeed there is no "interference" as claimed by the reviewer. Otherwise, these components of variance may need explicitly to be modeled and estimated in the inverse regression analysis. | Errors-in-variables regression: is it valid to pool data from three sites? | This is a mutual calibration problem: that is, of quantitatively comparing two independent measurement devices.
There appear to be two principal issues. The first (which is only implicit in the quest | Errors-in-variables regression: is it valid to pool data from three sites?
This is a mutual calibration problem: that is, of quantitatively comparing two independent measurement devices.
There appear to be two principal issues. The first (which is only implicit in the question) is in framing the problem: how should one determine whether a new method is "equivalent" to an approved one? The second concerns how to analyze data in which some samples may have been measured more than once.
Framing the question
The best (and perhaps obvious) solution to the stated problem is to evaluate the new method using samples with accurately known values obtained from comparable media (such as human plasma). (This is usually done by spiking actual samples with standard materials of known concentration.) Because this has not been done, let's assume it is either not possible or would not be acceptable to the regulators (for whatever reason). Thus, we are reduced to comparing two measurement methods, one of which is being used as a reference because it is believed to be accurate and reproducible (but without perfect precision).
In effect, the client will be requesting that the FDA allow the new method as a proxy or surrogate for the approved method. As such, their burden is to demonstrate that results from the new method will predict, with sufficient accuracy, what the approved method would have determined had it been applied. The subtle aspect of this is that we are not attempting to predict the true values themselves--we don't even know them. Thus, errors-in-variables regression might not be the most appropriate way to analyze these data.
The usual solution in such cases is "inverse regression" (as described, for instance, in Draper & Smith, Applied Regression Analysis (Second Edition), section 1.7). Briefly, this technique regresses the new method's results $Y$ against the approved method's results $X$, erects a suitable prediction interval, and then functionally inverts that interval to obtain ranges of $X$ for any given values of $Y$. If, for the intended range of $Y$ values, these ranges of $X$ are "sufficiently small," then $Y$ is an effective proxy for $X$. (In my experience this approach tends to be conservatively stringent: these intervals can be surprisingly large unless both measurements are highly accurate, precise, and linearly related.)
Addressing duplicate samples
The relevant concepts here are of sample support and components of variance. "Sample support" refers to the physical portion of a subject (a human being here) that is actually measured. After some portion of the subject is taken, it usually needs to be divided into subsamples suitable for the measurement process. We might be concerned about the possibility of variation between subsamples. In a liquid sample which is well-mixed, there is essentially no variation in the underlying quantity (such as a concentration of a chemical) throughout the sample, but in samples of solids or semisolids (which might include blood), such variation can be substantial. Considering that laboratories often need only microliters of a solution to perform a measurement, we have to be concerned about variation almost on a microscopic scale. This could be important.
The possibility of such variation within a physical sample indicates that the variation in measurement results should be partitioned into separate "components of variance." One component is the variance from within-sample variation, and others are contributions to variance from each independent step of the subsequent measurement process. (These steps may include the physical act of subsampling, further chemical and physical processing of the sample--such as adding stabilizers or centrifugation--, injection of the sample into the measuring instrument, variations within the instrument, variations between instruments, and other variations due to changes in who operates the instrument, possible ambient contamination in the laboratories, and more. I hope this makes it clear that in order to do a really good job of answering this question, the statistician needs a thorough understanding of the entire sampling and analytical process. All I can do is provide some general guidance.)
These considerations apply to the question at hand because one "sample" that is measured at two different "sites" really is two physical samples obtained from the same person and then split among laboratories. The measurement by the approved method will use one piece of a split sample and the simultaneous measurement by the new method will use another piece of the split sample. By considering the components of variance these splits imply, we can settle the main issue of the question. It should now be clear that differences between these paired measurements should be attributed to two things: first, actual differences between the measurement procedures--this is what we are trying to assess--and second, differences due to any variation within the sample as well as variation caused by the physical processes of extracting the two subsamples to be measured. If physical reasoning about the sample homogeneity and the subsampling process can establish that the second form of variance is negligible, then indeed there is no "interference" as claimed by the reviewer. Otherwise, these components of variance may need explicitly to be modeled and estimated in the inverse regression analysis. | Errors-in-variables regression: is it valid to pool data from three sites?
This is a mutual calibration problem: that is, of quantitatively comparing two independent measurement devices.
There appear to be two principal issues. The first (which is only implicit in the quest |
19,106 | When does the law of large numbers fail? | There are two theorems (of Kolmogorov) and both require that the expected value be finite. The first holds when variables are IID, the second, when sampling is independent and the variance of the $X_n$ satisfies
$$\sum_{n=1}^\infty \frac{V(X_n)}{n^2} < \infty$$
Say that all $X_n$ have expected value 0, but their variance is $n^2$ so that the condition obviously fails. What happens then? You can still compute an estimated mean, but that mean will not tend to 0 as you sample deeper and deeper. It will tend to deviate more and more as you keep sampling.
Let's give an example. Say that $X_n$ is uniform $U(-n2^n , n2^n)$ so that the condition above fails epically.
$$\sum_{n=1}^\infty \frac{V(X_n)}{n^2} = \sum_{n=1}^\infty \frac{n^2 2^{2n+2}}{12}\frac{1}{n^2} = \frac{1}{3} \sum_{n=1}^\infty 4^n = \infty.$$
By noting that
$$\bar{X}_n = \frac{X_n}{n} + \frac{n-1}{n}\bar{X}_{n-1},$$
we see by induction that the computed average $\bar{X}_n$ is always within the interval $(-2^n, 2^n)$. By using the same formula for $n+1$, we also see that there is always a chance greater than $1/8$ that $\bar{X}_{n+1}$ lies outside $(-2^n, 2^n)$. Indeed, $\frac{X_{n+1}}{n+1}$ is uniform $U(-2^{n+1},2^{n+1})$ and lies outside $(-2^n, 2^n)$ with probability $1/4$. On the other hand, $\frac{n}{n+1}\bar{X}_n$ is in $(-2^n, 2^n)$ by induction, and by symmetry it is positive with probability $1/2$. From these observations it follows immediately that $\bar{X}_{n+1}$ is greater than $2^n$ or smaller than $-2^n$,
each with a probability larger than $1/16$. Since the probability that $|\bar{X}_{n+1}| > 2^n$ is greater than $1/8$, there cannot be convergence to 0 as $n$ goes to infinity.
Now, to specifically answer your question, consider an event $A$. If I understood well, you ask "in what conditions is the following statement false?"
$$ \lim_{n \rightarrow \infty} \frac{1}{n}\sum_{k = 1}^{n} 1_A(X_k) = P(X \in A), \; [P]\;a.s.$$
where $1_A$ is the indicator function of the event $A$, i.e. $1_A(X_k) = 1$ if $X_k \in A$ and $0$ otherwise and the $X_k$ are identically distributed (and distributed like $X$).
We see that the condition above will hold, because the variance of an indicator function is bounded above by 1/4, which is the maximum variance of a Bernouilli 0-1 variable. Still, what can go wrong is the second assumption of the strong law of large numbers, namely independent sampling. If the random variables $X_k$ are not sampled independently then convergence is not ensured.
For example, if $X_k$ = $X_1$ for all $k$ then the ratio will be either 1 or 0, whatever the value of $n$, so convergence does not occur (unless $A$ has probability 0 or 1 of course). This is a fake and extreme example. I am not aware of practical cases where convergence to the theoretical probability will not occur. Still, the potentiality exists if sampling is not independent. | When does the law of large numbers fail? | There are two theorems (of Kolmogorov) and both require that the expected value be finite. The first holds when variables are IID, the second, when sampling is independent and the variance of the $X_n | When does the law of large numbers fail?
There are two theorems (of Kolmogorov) and both require that the expected value be finite. The first holds when variables are IID, the second, when sampling is independent and the variance of the $X_n$ satisfies
$$\sum_{n=1}^\infty \frac{V(X_n)}{n^2} < \infty$$
Say that all $X_n$ have expected value 0, but their variance is $n^2$ so that the condition obviously fails. What happens then? You can still compute an estimated mean, but that mean will not tend to 0 as you sample deeper and deeper. It will tend to deviate more and more as you keep sampling.
Let's give an example. Say that $X_n$ is uniform $U(-n2^n , n2^n)$ so that the condition above fails epically.
$$\sum_{n=1}^\infty \frac{V(X_n)}{n^2} = \sum_{n=1}^\infty \frac{n^2 2^{2n+2}}{12}\frac{1}{n^2} = \frac{1}{3} \sum_{n=1}^\infty 4^n = \infty.$$
By noting that
$$\bar{X}_n = \frac{X_n}{n} + \frac{n-1}{n}\bar{X}_{n-1},$$
we see by induction that the computed average $\bar{X}_n$ is always within the interval $(-2^n, 2^n)$. By using the same formula for $n+1$, we also see that there is always a chance greater than $1/8$ that $\bar{X}_{n+1}$ lies outside $(-2^n, 2^n)$. Indeed, $\frac{X_{n+1}}{n+1}$ is uniform $U(-2^{n+1},2^{n+1})$ and lies outside $(-2^n, 2^n)$ with probability $1/4$. On the other hand, $\frac{n}{n+1}\bar{X}_n$ is in $(-2^n, 2^n)$ by induction, and by symmetry it is positive with probability $1/2$. From these observations it follows immediately that $\bar{X}_{n+1}$ is greater than $2^n$ or smaller than $-2^n$,
each with a probability larger than $1/16$. Since the probability that $|\bar{X}_{n+1}| > 2^n$ is greater than $1/8$, there cannot be convergence to 0 as $n$ goes to infinity.
Now, to specifically answer your question, consider an event $A$. If I understood well, you ask "in what conditions is the following statement false?"
$$ \lim_{n \rightarrow \infty} \frac{1}{n}\sum_{k = 1}^{n} 1_A(X_k) = P(X \in A), \; [P]\;a.s.$$
where $1_A$ is the indicator function of the event $A$, i.e. $1_A(X_k) = 1$ if $X_k \in A$ and $0$ otherwise and the $X_k$ are identically distributed (and distributed like $X$).
We see that the condition above will hold, because the variance of an indicator function is bounded above by 1/4, which is the maximum variance of a Bernouilli 0-1 variable. Still, what can go wrong is the second assumption of the strong law of large numbers, namely independent sampling. If the random variables $X_k$ are not sampled independently then convergence is not ensured.
For example, if $X_k$ = $X_1$ for all $k$ then the ratio will be either 1 or 0, whatever the value of $n$, so convergence does not occur (unless $A$ has probability 0 or 1 of course). This is a fake and extreme example. I am not aware of practical cases where convergence to the theoretical probability will not occur. Still, the potentiality exists if sampling is not independent. | When does the law of large numbers fail?
There are two theorems (of Kolmogorov) and both require that the expected value be finite. The first holds when variables are IID, the second, when sampling is independent and the variance of the $X_n |
19,107 | Computing correlation (and the significance of said correlation) between a pair of time series | You can use the ccf function to get the cross-correlation, but this will only give you a plot. If the estimated cross correlations fall outside the dash red line, then you can conclude that there is a statistically significant cross-correlation. But I do not know of a package with a formally encapsulated test. Example from ccf doc:
require(graphics)
## Example from Venables & Ripley (Provided in CCF help file)
ccf(mdeaths, fdeaths, ylab = "cross-correlation")
Note, that the question of significance test is also discussed here. | Computing correlation (and the significance of said correlation) between a pair of time series | You can use the ccf function to get the cross-correlation, but this will only give you a plot. If the estimated cross correlations fall outside the dash red line, then you can conclude that there is | Computing correlation (and the significance of said correlation) between a pair of time series
You can use the ccf function to get the cross-correlation, but this will only give you a plot. If the estimated cross correlations fall outside the dash red line, then you can conclude that there is a statistically significant cross-correlation. But I do not know of a package with a formally encapsulated test. Example from ccf doc:
require(graphics)
## Example from Venables & Ripley (Provided in CCF help file)
ccf(mdeaths, fdeaths, ylab = "cross-correlation")
Note, that the question of significance test is also discussed here. | Computing correlation (and the significance of said correlation) between a pair of time series
You can use the ccf function to get the cross-correlation, but this will only give you a plot. If the estimated cross correlations fall outside the dash red line, then you can conclude that there is |
19,108 | Computing correlation (and the significance of said correlation) between a pair of time series | How do you define correlation for non stationary time series? Do you plan to take the correlation of the diff or these time series?
If not, I suggest you look for cointegration rather than correlation (cf Granger etc...) | Computing correlation (and the significance of said correlation) between a pair of time series | How do you define correlation for non stationary time series? Do you plan to take the correlation of the diff or these time series?
If not, I suggest you look for cointegration rather than correlation | Computing correlation (and the significance of said correlation) between a pair of time series
How do you define correlation for non stationary time series? Do you plan to take the correlation of the diff or these time series?
If not, I suggest you look for cointegration rather than correlation (cf Granger etc...) | Computing correlation (and the significance of said correlation) between a pair of time series
How do you define correlation for non stationary time series? Do you plan to take the correlation of the diff or these time series?
If not, I suggest you look for cointegration rather than correlation |
19,109 | Difference between Multivariate Time Series data and Panel Data | In short, there is no such thing as Multivariate Time Series data. The only classic data types out there are: Cross Sections, Time Series, Pooled Cross Sections, and Panel data.
Panel data is multidimensional. Time series is one-dimensional. Time Series data is a type of panel data. Daily closing prices for last one year for 1 company is a Time Series dataset because the time variable alone uniquely identifies each observation. I will work with only 8 days worth of prices instead of a year, but the idea is the same.
Daily closing prices for last one year for 10 companies can be both a Panel dataset and a Time Series dataset, depending on whether it is in wide or long format.
If the data is organized so that Time still uniquely identifies each observation (i.e. wide format) then it is still a time series dataset, and you will have different columns for the daily closing price for each of the 10 companies. See example below:
If, on the other hand, it is organized so that Time alone no longer uniquely identifies each observation (i.e. long format) then it is a panel dataset. With 10 companies, you need to use Time and Company ID together to uniquely identify each observation. See example below:
In any statistical software it is straightforward to reshape a dataset from wide to long and from long to wide.
The term Multivariate Time Series is heard around, but it refers not to a type of dataset but to a type of analysis. To be more exact, it refers to the type of time series regression analysis in which there is more than one response variable. (Make sure to distinguish it from Multiple Time Series regression, which refers to a regression with one response variable and several predictor variables). One example of Multivariate Time Series Analysis is VAR (Vector AutoRegression).
More on VAR here:
https://en.wikipedia.org/wiki/Vector_autoregression
I hope this helps. | Difference between Multivariate Time Series data and Panel Data | In short, there is no such thing as Multivariate Time Series data. The only classic data types out there are: Cross Sections, Time Series, Pooled Cross Sections, and Panel data.
Panel data is multidi | Difference between Multivariate Time Series data and Panel Data
In short, there is no such thing as Multivariate Time Series data. The only classic data types out there are: Cross Sections, Time Series, Pooled Cross Sections, and Panel data.
Panel data is multidimensional. Time series is one-dimensional. Time Series data is a type of panel data. Daily closing prices for last one year for 1 company is a Time Series dataset because the time variable alone uniquely identifies each observation. I will work with only 8 days worth of prices instead of a year, but the idea is the same.
Daily closing prices for last one year for 10 companies can be both a Panel dataset and a Time Series dataset, depending on whether it is in wide or long format.
If the data is organized so that Time still uniquely identifies each observation (i.e. wide format) then it is still a time series dataset, and you will have different columns for the daily closing price for each of the 10 companies. See example below:
If, on the other hand, it is organized so that Time alone no longer uniquely identifies each observation (i.e. long format) then it is a panel dataset. With 10 companies, you need to use Time and Company ID together to uniquely identify each observation. See example below:
In any statistical software it is straightforward to reshape a dataset from wide to long and from long to wide.
The term Multivariate Time Series is heard around, but it refers not to a type of dataset but to a type of analysis. To be more exact, it refers to the type of time series regression analysis in which there is more than one response variable. (Make sure to distinguish it from Multiple Time Series regression, which refers to a regression with one response variable and several predictor variables). One example of Multivariate Time Series Analysis is VAR (Vector AutoRegression).
More on VAR here:
https://en.wikipedia.org/wiki/Vector_autoregression
I hope this helps. | Difference between Multivariate Time Series data and Panel Data
In short, there is no such thing as Multivariate Time Series data. The only classic data types out there are: Cross Sections, Time Series, Pooled Cross Sections, and Panel data.
Panel data is multidi |
19,110 | Identifiability of neural network models | Linear, single-layer FFNs are non-identified
The question as since been edited to exclude this case; I retain it here because understanding the linear case is a simple example of the phenomenon of interest.
Consider a feedforward neural network with 1 hidden layer and all linear activations. The task is a simple OLS regression task.
So we have the model $\hat{y}=X A B$ and the objective is
$$
\min_{A,B} \frac{1}{2}|| y - X A B ||_2^2
$$
for some choice of $A, B$ of appropriate shape. $A$ is the input-to-hidden weights, and $B$ is the hidden-to-output weights.
Clearly the elements of the weight matrices are not identifiable in general, since there are any number of possible configurations for which two pairs of matrices $A,B$ have the same product.
Nonlinear, single-layer FFNs are still non-identified
Building up from the linear, single-layer FFN, we can also observe non-identifiability in the nonlinear, single-layer FFN.
As an example, adding a $\tanh$ nonlinearity to any of the linear activations creates a nonlinear network. This network is still non-identified, because for any loss value, a permutation of the weights of two (or more) neurons at one layer, and their corresponding neurons at the next layer, will likewise result in the same loss value.
In general, neural networks are non-identified
We can use the same reasoning to show that neural networks are non-identified in all but very particular parameterizations.
For example, there is no particular reason that convolutional filters must occur in any particular order. Nor is it required that convolutional filters have any particular sign, since subsequent weights could have the opposite sign to "reverse" that choice.
Likewise, the units in an RNN can be permuted to obtain the same loss.
See also: Can we use MLE to estimate Neural Network weights? | Identifiability of neural network models | Linear, single-layer FFNs are non-identified
The question as since been edited to exclude this case; I retain it here because understanding the linear case is a simple example of the phenomenon of int | Identifiability of neural network models
Linear, single-layer FFNs are non-identified
The question as since been edited to exclude this case; I retain it here because understanding the linear case is a simple example of the phenomenon of interest.
Consider a feedforward neural network with 1 hidden layer and all linear activations. The task is a simple OLS regression task.
So we have the model $\hat{y}=X A B$ and the objective is
$$
\min_{A,B} \frac{1}{2}|| y - X A B ||_2^2
$$
for some choice of $A, B$ of appropriate shape. $A$ is the input-to-hidden weights, and $B$ is the hidden-to-output weights.
Clearly the elements of the weight matrices are not identifiable in general, since there are any number of possible configurations for which two pairs of matrices $A,B$ have the same product.
Nonlinear, single-layer FFNs are still non-identified
Building up from the linear, single-layer FFN, we can also observe non-identifiability in the nonlinear, single-layer FFN.
As an example, adding a $\tanh$ nonlinearity to any of the linear activations creates a nonlinear network. This network is still non-identified, because for any loss value, a permutation of the weights of two (or more) neurons at one layer, and their corresponding neurons at the next layer, will likewise result in the same loss value.
In general, neural networks are non-identified
We can use the same reasoning to show that neural networks are non-identified in all but very particular parameterizations.
For example, there is no particular reason that convolutional filters must occur in any particular order. Nor is it required that convolutional filters have any particular sign, since subsequent weights could have the opposite sign to "reverse" that choice.
Likewise, the units in an RNN can be permuted to obtain the same loss.
See also: Can we use MLE to estimate Neural Network weights? | Identifiability of neural network models
Linear, single-layer FFNs are non-identified
The question as since been edited to exclude this case; I retain it here because understanding the linear case is a simple example of the phenomenon of int |
19,111 | Identifiability of neural network models | There at at least $n!$ global optima when fitting a 1-layer neural network, constituted of $n$ neurons. This comes from the fact that, if you exchange two neurons on a specific level, and then you exchange the weights attributed to these neurons on the next level, you will obtain exactly the same fit. | Identifiability of neural network models | There at at least $n!$ global optima when fitting a 1-layer neural network, constituted of $n$ neurons. This comes from the fact that, if you exchange two neurons on a specific level, and then you ex | Identifiability of neural network models
There at at least $n!$ global optima when fitting a 1-layer neural network, constituted of $n$ neurons. This comes from the fact that, if you exchange two neurons on a specific level, and then you exchange the weights attributed to these neurons on the next level, you will obtain exactly the same fit. | Identifiability of neural network models
There at at least $n!$ global optima when fitting a 1-layer neural network, constituted of $n$ neurons. This comes from the fact that, if you exchange two neurons on a specific level, and then you ex |
19,112 | Panel Data: Pooled OLS vs. RE vs. FE Effects | First, you are right, Pooled OLS estimation is simply an OLS technique run on Panel data.
Second, know that to check how much your data are poolable, you can use the Breusch-Pagan Lagrange multiplier test -- whose null hypothesis $H_0$ is that the variance of the unobserved fixed effects is zero $\iff$ pooled OLS might be the appropriate model. Thus, if you keep $H_0$ and suspect endogeneity issues, you may want to leave the panel-data world, and use other estimation technics to deal with those, e.g. IV (multiple-SLS), GMM.
Third, in a FE specification, individual specific parameters do not vanish and can be added back in (with identical coefficients but standard errors that need to be adjusted). This is actually all what LSDV model is about (with added-back grand-average and within averages).
Fourth, to deal with autocorrelation (of errors), GLS-like transformations may help you theoretically, but in practice, it only deals with heteroscedasticity (WLS, FGLS). However, note that depending on the space (temporal, geographical, sociological, etc...) in which you assume the autocorrelation works through, you can proxy its structure and finally perform a GLS-like transformation, e.g. spatial panel. | Panel Data: Pooled OLS vs. RE vs. FE Effects | First, you are right, Pooled OLS estimation is simply an OLS technique run on Panel data.
Second, know that to check how much your data are poolable, you can use the Breusch-Pagan Lagrange multiplier | Panel Data: Pooled OLS vs. RE vs. FE Effects
First, you are right, Pooled OLS estimation is simply an OLS technique run on Panel data.
Second, know that to check how much your data are poolable, you can use the Breusch-Pagan Lagrange multiplier test -- whose null hypothesis $H_0$ is that the variance of the unobserved fixed effects is zero $\iff$ pooled OLS might be the appropriate model. Thus, if you keep $H_0$ and suspect endogeneity issues, you may want to leave the panel-data world, and use other estimation technics to deal with those, e.g. IV (multiple-SLS), GMM.
Third, in a FE specification, individual specific parameters do not vanish and can be added back in (with identical coefficients but standard errors that need to be adjusted). This is actually all what LSDV model is about (with added-back grand-average and within averages).
Fourth, to deal with autocorrelation (of errors), GLS-like transformations may help you theoretically, but in practice, it only deals with heteroscedasticity (WLS, FGLS). However, note that depending on the space (temporal, geographical, sociological, etc...) in which you assume the autocorrelation works through, you can proxy its structure and finally perform a GLS-like transformation, e.g. spatial panel. | Panel Data: Pooled OLS vs. RE vs. FE Effects
First, you are right, Pooled OLS estimation is simply an OLS technique run on Panel data.
Second, know that to check how much your data are poolable, you can use the Breusch-Pagan Lagrange multiplier |
19,113 | detect number of peaks in audio recording | I don't think what follows is the best solution, but @eipi10 had a good suggestion to check out this answer on CrossValidated. So I did.
A general approach is to smooth the data and then find peaks by comparing a local maximum filter to the smooth.
The first step is to create the argmax function:
argmax <- function(x, y, w=1, ...) {
require(zoo)
n <- length(y)
y.smooth <- loess(y ~ x, ...)$fitted
y.max <- rollapply(zoo(y.smooth), 2*w+1, max, align="center")
delta <- y.max - y.smooth[-c(1:w, n+1-1:w)]
i.max <- which(delta <= 0) + w
list(x=x[i.max], i=i.max, y.hat=y.smooth)
}
Its return value includes the arguments of the local maxima (x)--which answers the question--and the indexes into the x- and y-arrays where those local maxima occur (i).
I made minor modifications to the test plotting function: (a) to explicitly define x and y and (b) to show the number of peaks:
test <- function(x, y, w, span) {
peaks <- argmax(x, y, w=w, span=span)
plot(x, y, cex=0.75, col="Gray", main=paste("w = ", w, ", span = ",
span, ", peaks = ",
length(peaks$x), sep=""))
lines(x, peaks$y.hat, lwd=2) #$
y.min <- min(y)
sapply(peaks$i, function(i) lines(c(x[i],x[i]), c(y.min, peaks$y.hat[i]),
col="Red", lty=2))
points(x[peaks$i], peaks$y.hat[peaks$i], col="Red", pch=19, cex=1.25)
}
Like the fpeaks approach I mentioned in my original question, this approach also requires a good deal of tuning. I won't know the "right" answer (i.e., the number of syllables/peaks) going into this, so I'm not sure how to define a decision rule.
par(mfrow=c(3,1))
test(ms[,1], ms[,2], 2, 0.01)
test(ms[,1], ms[,2], 2, 0.045)
test(ms[,1], ms[,2], 2, 0.05)
At this point fpeaks seems a little less complicated to me, but still not satisfying. | detect number of peaks in audio recording | I don't think what follows is the best solution, but @eipi10 had a good suggestion to check out this answer on CrossValidated. So I did.
A general approach is to smooth the data and then find peaks b | detect number of peaks in audio recording
I don't think what follows is the best solution, but @eipi10 had a good suggestion to check out this answer on CrossValidated. So I did.
A general approach is to smooth the data and then find peaks by comparing a local maximum filter to the smooth.
The first step is to create the argmax function:
argmax <- function(x, y, w=1, ...) {
require(zoo)
n <- length(y)
y.smooth <- loess(y ~ x, ...)$fitted
y.max <- rollapply(zoo(y.smooth), 2*w+1, max, align="center")
delta <- y.max - y.smooth[-c(1:w, n+1-1:w)]
i.max <- which(delta <= 0) + w
list(x=x[i.max], i=i.max, y.hat=y.smooth)
}
Its return value includes the arguments of the local maxima (x)--which answers the question--and the indexes into the x- and y-arrays where those local maxima occur (i).
I made minor modifications to the test plotting function: (a) to explicitly define x and y and (b) to show the number of peaks:
test <- function(x, y, w, span) {
peaks <- argmax(x, y, w=w, span=span)
plot(x, y, cex=0.75, col="Gray", main=paste("w = ", w, ", span = ",
span, ", peaks = ",
length(peaks$x), sep=""))
lines(x, peaks$y.hat, lwd=2) #$
y.min <- min(y)
sapply(peaks$i, function(i) lines(c(x[i],x[i]), c(y.min, peaks$y.hat[i]),
col="Red", lty=2))
points(x[peaks$i], peaks$y.hat[peaks$i], col="Red", pch=19, cex=1.25)
}
Like the fpeaks approach I mentioned in my original question, this approach also requires a good deal of tuning. I won't know the "right" answer (i.e., the number of syllables/peaks) going into this, so I'm not sure how to define a decision rule.
par(mfrow=c(3,1))
test(ms[,1], ms[,2], 2, 0.01)
test(ms[,1], ms[,2], 2, 0.045)
test(ms[,1], ms[,2], 2, 0.05)
At this point fpeaks seems a little less complicated to me, but still not satisfying. | detect number of peaks in audio recording
I don't think what follows is the best solution, but @eipi10 had a good suggestion to check out this answer on CrossValidated. So I did.
A general approach is to smooth the data and then find peaks b |
19,114 | detect number of peaks in audio recording | I had similar problems to analyse protein electrophoresis profiles.
I solved them by applying some of the functions of the msprocess R package on the second derivates of the profiles (see https://fr.wikipedia.org/wiki/D%C3%A9pouillement_d'une_courbe#Position_et_hauteur_du_pic). This has been published here:
http://onlinelibrary.wiley.com/doi/10.1111/1755-0998.12389/abstract;jsessionid=8EE0B64238728C0979FF71C576884771.f02t03
I have no idea whether similar solution can work for you.
Good luck | detect number of peaks in audio recording | I had similar problems to analyse protein electrophoresis profiles.
I solved them by applying some of the functions of the msprocess R package on the second derivates of the profiles (see https://fr.w | detect number of peaks in audio recording
I had similar problems to analyse protein electrophoresis profiles.
I solved them by applying some of the functions of the msprocess R package on the second derivates of the profiles (see https://fr.wikipedia.org/wiki/D%C3%A9pouillement_d'une_courbe#Position_et_hauteur_du_pic). This has been published here:
http://onlinelibrary.wiley.com/doi/10.1111/1755-0998.12389/abstract;jsessionid=8EE0B64238728C0979FF71C576884771.f02t03
I have no idea whether similar solution can work for you.
Good luck | detect number of peaks in audio recording
I had similar problems to analyse protein electrophoresis profiles.
I solved them by applying some of the functions of the msprocess R package on the second derivates of the profiles (see https://fr.w |
19,115 | detect number of peaks in audio recording | I would like to suggest a solution utilising the changepoint package. The simplistic example below attempts to identify peaks, defined here as change points by looking at one channel from the available data.
Example
Data sourcing
# Libs
library(seewave)
library(tuneR)
# Download
tmpWav <- tempfile(fileext = ".wav")
download.file(url = "https://www.dropbox.com/s/koqyfeaqge8t9iw/test.wav?dl=0",
destfile = tmpWav)
# Read
w <- readWave(filename = tmpWav)
Data preparation
# Libs
require(changepoint)
# Create time series data for one channel as an example
leftTS <- ts(data = w@left)
## Preview
plot.ts(leftTS)
Chart generated via the plot.ts call:
Change-point analysis
The changepoint package provides a number of option for identifying changes/peaks in the data. The code below provides only a simple example of finding 3 peaks using BinSeg method:
# BinSeg method (example)
leftTSpelt <- cpt.var(data = leftTS, method = "BinSeg", penalty = "BIC", Q = 3)
## Preview
plot(leftTSpelt, cpt.width = 3)
Obtained chart:
It is also possible to get values:
cpts(leftTSpelt)
[1] 89582 165572 181053
Side notes
The provided example is mostly concerned with illustrating how the change point analysis can be applied to the provided data; caution should be exercised with respect to parameters passed to the cp.var function. A detailed explanation of the package and the available functionalities is given in the following paper:
Killick, Rebecca and Eckley, Idris (2014) changepoint:an R package for changepoint analysis. Journal of Statistical Software, 58 (3). pp. 1-19.
ecp
ecp, is another worth mentioning R package. The ecp facilitates undertaking non-parametric multivariate change point analysis, which may be useful if the one would like to identify change points occurring across multiple channels. | detect number of peaks in audio recording | I would like to suggest a solution utilising the changepoint package. The simplistic example below attempts to identify peaks, defined here as change points by looking at one channel from the availabl | detect number of peaks in audio recording
I would like to suggest a solution utilising the changepoint package. The simplistic example below attempts to identify peaks, defined here as change points by looking at one channel from the available data.
Example
Data sourcing
# Libs
library(seewave)
library(tuneR)
# Download
tmpWav <- tempfile(fileext = ".wav")
download.file(url = "https://www.dropbox.com/s/koqyfeaqge8t9iw/test.wav?dl=0",
destfile = tmpWav)
# Read
w <- readWave(filename = tmpWav)
Data preparation
# Libs
require(changepoint)
# Create time series data for one channel as an example
leftTS <- ts(data = w@left)
## Preview
plot.ts(leftTS)
Chart generated via the plot.ts call:
Change-point analysis
The changepoint package provides a number of option for identifying changes/peaks in the data. The code below provides only a simple example of finding 3 peaks using BinSeg method:
# BinSeg method (example)
leftTSpelt <- cpt.var(data = leftTS, method = "BinSeg", penalty = "BIC", Q = 3)
## Preview
plot(leftTSpelt, cpt.width = 3)
Obtained chart:
It is also possible to get values:
cpts(leftTSpelt)
[1] 89582 165572 181053
Side notes
The provided example is mostly concerned with illustrating how the change point analysis can be applied to the provided data; caution should be exercised with respect to parameters passed to the cp.var function. A detailed explanation of the package and the available functionalities is given in the following paper:
Killick, Rebecca and Eckley, Idris (2014) changepoint:an R package for changepoint analysis. Journal of Statistical Software, 58 (3). pp. 1-19.
ecp
ecp, is another worth mentioning R package. The ecp facilitates undertaking non-parametric multivariate change point analysis, which may be useful if the one would like to identify change points occurring across multiple channels. | detect number of peaks in audio recording
I would like to suggest a solution utilising the changepoint package. The simplistic example below attempts to identify peaks, defined here as change points by looking at one channel from the availabl |
19,116 | detect number of peaks in audio recording | Here is a library in Python I used earlier while trying to estimate periodicity by finding peaks in the autocorrelation function.
It uses first-order differences/discrete derivatives for peak detection and supports tuning by threshold and minimum distance (between consecutive peaks) parameters. One can also enhance the peak resolution using Gaussian density estimation and interpolation (see link).
It worked quite well out of the box for me without much tweaking, even for noisy data. Give it a try. | detect number of peaks in audio recording | Here is a library in Python I used earlier while trying to estimate periodicity by finding peaks in the autocorrelation function.
It uses first-order differences/discrete derivatives for peak detecti | detect number of peaks in audio recording
Here is a library in Python I used earlier while trying to estimate periodicity by finding peaks in the autocorrelation function.
It uses first-order differences/discrete derivatives for peak detection and supports tuning by threshold and minimum distance (between consecutive peaks) parameters. One can also enhance the peak resolution using Gaussian density estimation and interpolation (see link).
It worked quite well out of the box for me without much tweaking, even for noisy data. Give it a try. | detect number of peaks in audio recording
Here is a library in Python I used earlier while trying to estimate periodicity by finding peaks in the autocorrelation function.
It uses first-order differences/discrete derivatives for peak detecti |
19,117 | When is it OK to write "we assumed a normal distribution" of an empirical measurement? | I find your question really interesting. Let's have some things into account:
To say that an observed variable is continuous in real life is going to be always kind of wrong, because it's very difficult to measure really continuously.
Now add the properties of a normal random variable $N(\mu, \sigma^2)$: range $(-\infty; +\infty)$, symmetrical distribution (mean = mode = median), the probability density function $f_X(x)$ has inflection points at $x = \mu - \sigma$ and $x = \mu + \sigma$.
To say that a random variable $X$ follows a Log-Normal distribution implies that the variable $Y=log(X) $ follows a normal distribution.
With that said, to say that any observed variable follows a normal or a Log-Normal distribution sounds kind of crazy. In practice, what's done is that you measure deviations of the observed frequencies from the expected frequencies, if that variable came from a normal (or any other distribution) population. If you can say that those deviations are just random, because you are sampling, then you can say something like there's not enough evidence to reject the null hypothesis that this variable comes from a normal population, which is translated into we will work as if (assuming that) the variable follows a normal distribution.
Answering to your first question, I don't think that there's someone as bold to say that a variable is assumed to be normally distributed without further evidence. To say something like that, you need at least a qq-plot, an histogram, a goodness-of-fit test or a combination of those.
To answer the second question, the particular interest in the normal distribution is that many of the classical tests are based on an assumption of normality of the variable, like the t-test, or the $\chi^2$-test for the variance. So, normality simplifies work, that's all. | When is it OK to write "we assumed a normal distribution" of an empirical measurement? | I find your question really interesting. Let's have some things into account:
To say that an observed variable is continuous in real life is going to be always kind of wrong, because it's very diffic | When is it OK to write "we assumed a normal distribution" of an empirical measurement?
I find your question really interesting. Let's have some things into account:
To say that an observed variable is continuous in real life is going to be always kind of wrong, because it's very difficult to measure really continuously.
Now add the properties of a normal random variable $N(\mu, \sigma^2)$: range $(-\infty; +\infty)$, symmetrical distribution (mean = mode = median), the probability density function $f_X(x)$ has inflection points at $x = \mu - \sigma$ and $x = \mu + \sigma$.
To say that a random variable $X$ follows a Log-Normal distribution implies that the variable $Y=log(X) $ follows a normal distribution.
With that said, to say that any observed variable follows a normal or a Log-Normal distribution sounds kind of crazy. In practice, what's done is that you measure deviations of the observed frequencies from the expected frequencies, if that variable came from a normal (or any other distribution) population. If you can say that those deviations are just random, because you are sampling, then you can say something like there's not enough evidence to reject the null hypothesis that this variable comes from a normal population, which is translated into we will work as if (assuming that) the variable follows a normal distribution.
Answering to your first question, I don't think that there's someone as bold to say that a variable is assumed to be normally distributed without further evidence. To say something like that, you need at least a qq-plot, an histogram, a goodness-of-fit test or a combination of those.
To answer the second question, the particular interest in the normal distribution is that many of the classical tests are based on an assumption of normality of the variable, like the t-test, or the $\chi^2$-test for the variance. So, normality simplifies work, that's all. | When is it OK to write "we assumed a normal distribution" of an empirical measurement?
I find your question really interesting. Let's have some things into account:
To say that an observed variable is continuous in real life is going to be always kind of wrong, because it's very diffic |
19,118 | When is it OK to write "we assumed a normal distribution" of an empirical measurement? | This largely depends on the robustness of your inferences to errors in the distribution
When you are dealing with quantities that are either directly observable, or for which there is some close estimator (e.g., residuals for error terms), you can use the data to make non-parametric estimates of the distribution. Assuming you have sufficient data to do this, it is generally best to avoid making a distributional assumption about those quantities, unless you are subjecting these assumptions to empirical tests/diagnostics to confirm the plausibility of the assumed form. The reason for this is obvious --- if the values are observable (or closely estimable) then with a reasonable amount of data you can estimate the distribution, so there is no need to blindly assume its form.
Now, it is of course that case that parametric statistical models assume a parametric distributional form of some kind. In most statistical analysis in a regression context, we specify a model form that has an assumed form for the "error terms". For example, in a standard Gaussian regression we assume that the error terms are normally distributed. Once we have fit our model to the data we can then construct diagnostic plots of residuals and use these to determine whether there are any obvious departures from the assumed distributional form. If the assumed distribution is dubious we have two options: (1) we can either change our model assumptions and rinse-and-repeat; or (2) we can keep our existing model and use it only for inferences, etc., that are known to be robust to errors in the assumed error distribution in the model. In many cases the latter approach is fine (so long as other assumptions in the model are okay), since many of the conclusions from a regression model are robust to the distribution of the error term.$^\dagger$
More generally, the importance of the distributional form is going to depend on what kind of inferences you are making and how robust these inferences are to errors in the assumed form. This is contextual; in some projects you will want inferences about model coefficients, whereas in others you will want predictions of observable variables, and in others you may want something else. Generally speaking, the following advice applies:
If you are using a parametric model (which assumes a parametric distribution of a particular kind), always make an effort to choose a form that is as close to the data as is reasonable. This will usually involve conducting diagnostic tests on observable quantities in the model (e.g., residuals in a regression) and then varying the model with transformations, changes in form, etc., until you feel that you have a good representation of the data. It is generally bad practice to make "bald assumptions" that are not scrutinised against diagnostic plots, etc.
Always consider the kinds of inferences/predictions you actually want to make in your analysis, and consider how sensitive/robust each of these are to errors in the assumed parametric distributional form. If you need to make inferences/predictions that are highly sensitive to the assumed distributional form then you need to ensure that you apply diagnostic tests and you are satisfied that the assumed distribution is a reasonable representation of the data.
For some proposed transformations, like taking the logarithms of quantities under analysis, there are natural theoretical considerations that apply. For example, variables are generally transformed onto a log-scale (i.e., taking logarithms) if they are positive quantities that tend to change by a percentage that has a roughly fixed distribution over time. This is true of many quantities studied in economics and physics. Transformation of variables should be informed by theoretical considerations and empirical analysis.
In some cases you will be limited by the available knowledge on model forms (i.e., the extent of the statistical literature on the forms of interest to you). You might want to vary your model in some way but find that there is little or no research on the properties of the ideal model. In such cases, you may need to fall back on suboptimal models, and include appropriate caveats in your analysis.
$^\dagger$ Specifically, assuming you have a reasonable amount of data, the estimated coefficients are highly robust to the assumed error distribution, but predicted values of the response variable are not. | When is it OK to write "we assumed a normal distribution" of an empirical measurement? | This largely depends on the robustness of your inferences to errors in the distribution
When you are dealing with quantities that are either directly observable, or for which there is some close estim | When is it OK to write "we assumed a normal distribution" of an empirical measurement?
This largely depends on the robustness of your inferences to errors in the distribution
When you are dealing with quantities that are either directly observable, or for which there is some close estimator (e.g., residuals for error terms), you can use the data to make non-parametric estimates of the distribution. Assuming you have sufficient data to do this, it is generally best to avoid making a distributional assumption about those quantities, unless you are subjecting these assumptions to empirical tests/diagnostics to confirm the plausibility of the assumed form. The reason for this is obvious --- if the values are observable (or closely estimable) then with a reasonable amount of data you can estimate the distribution, so there is no need to blindly assume its form.
Now, it is of course that case that parametric statistical models assume a parametric distributional form of some kind. In most statistical analysis in a regression context, we specify a model form that has an assumed form for the "error terms". For example, in a standard Gaussian regression we assume that the error terms are normally distributed. Once we have fit our model to the data we can then construct diagnostic plots of residuals and use these to determine whether there are any obvious departures from the assumed distributional form. If the assumed distribution is dubious we have two options: (1) we can either change our model assumptions and rinse-and-repeat; or (2) we can keep our existing model and use it only for inferences, etc., that are known to be robust to errors in the assumed error distribution in the model. In many cases the latter approach is fine (so long as other assumptions in the model are okay), since many of the conclusions from a regression model are robust to the distribution of the error term.$^\dagger$
More generally, the importance of the distributional form is going to depend on what kind of inferences you are making and how robust these inferences are to errors in the assumed form. This is contextual; in some projects you will want inferences about model coefficients, whereas in others you will want predictions of observable variables, and in others you may want something else. Generally speaking, the following advice applies:
If you are using a parametric model (which assumes a parametric distribution of a particular kind), always make an effort to choose a form that is as close to the data as is reasonable. This will usually involve conducting diagnostic tests on observable quantities in the model (e.g., residuals in a regression) and then varying the model with transformations, changes in form, etc., until you feel that you have a good representation of the data. It is generally bad practice to make "bald assumptions" that are not scrutinised against diagnostic plots, etc.
Always consider the kinds of inferences/predictions you actually want to make in your analysis, and consider how sensitive/robust each of these are to errors in the assumed parametric distributional form. If you need to make inferences/predictions that are highly sensitive to the assumed distributional form then you need to ensure that you apply diagnostic tests and you are satisfied that the assumed distribution is a reasonable representation of the data.
For some proposed transformations, like taking the logarithms of quantities under analysis, there are natural theoretical considerations that apply. For example, variables are generally transformed onto a log-scale (i.e., taking logarithms) if they are positive quantities that tend to change by a percentage that has a roughly fixed distribution over time. This is true of many quantities studied in economics and physics. Transformation of variables should be informed by theoretical considerations and empirical analysis.
In some cases you will be limited by the available knowledge on model forms (i.e., the extent of the statistical literature on the forms of interest to you). You might want to vary your model in some way but find that there is little or no research on the properties of the ideal model. In such cases, you may need to fall back on suboptimal models, and include appropriate caveats in your analysis.
$^\dagger$ Specifically, assuming you have a reasonable amount of data, the estimated coefficients are highly robust to the assumed error distribution, but predicted values of the response variable are not. | When is it OK to write "we assumed a normal distribution" of an empirical measurement?
This largely depends on the robustness of your inferences to errors in the distribution
When you are dealing with quantities that are either directly observable, or for which there is some close estim |
19,119 | When is it OK to write "we assumed a normal distribution" of an empirical measurement? | Gnedenko and Hinchin in their textbook "Elementary introduction in the theory of probability" claim that there is a tedious theoretical proof of the following claim. If the value of a variable is influenced by numerous statistically independent factors, then it is appropriate to assume that the values of the variable is normally distributed. For instance, if one shuts bullets from the gun into the target, then the final position of the bullet is influenced by numerous independent factors (wind, shaking of the hands, the mass of a bullet, the friction between the hand and the gun, etc). | When is it OK to write "we assumed a normal distribution" of an empirical measurement? | Gnedenko and Hinchin in their textbook "Elementary introduction in the theory of probability" claim that there is a tedious theoretical proof of the following claim. If the value of a variable is infl | When is it OK to write "we assumed a normal distribution" of an empirical measurement?
Gnedenko and Hinchin in their textbook "Elementary introduction in the theory of probability" claim that there is a tedious theoretical proof of the following claim. If the value of a variable is influenced by numerous statistically independent factors, then it is appropriate to assume that the values of the variable is normally distributed. For instance, if one shuts bullets from the gun into the target, then the final position of the bullet is influenced by numerous independent factors (wind, shaking of the hands, the mass of a bullet, the friction between the hand and the gun, etc). | When is it OK to write "we assumed a normal distribution" of an empirical measurement?
Gnedenko and Hinchin in their textbook "Elementary introduction in the theory of probability" claim that there is a tedious theoretical proof of the following claim. If the value of a variable is infl |
19,120 | Prove the relation between Mahalanobis distance and Leverage? | My description of the Mahalanobis distance at Bottom to top explanation of the Mahalanobis distance? includes two key results:
By definition, it does not change when the regressors are uniformly shifted.
The squared Mahalanobis distance between vectors $x$ and $y$ is given by $$D^2(x,y) = (x-y)^\prime \Sigma^{-1}(x-y)$$ where $\Sigma$ is the covariance of the data.
(1) allows us to assume the means of the regressors are all zero. It remains to compute $h_i$. However, for the claim to be true, we need to add one more assumption:
The model must include an intercept.
Allowing for this, let there be $k \ge 0$ regressors and $n$ data, writing the value of regressor $j$ for observation $i$ as $x_{ij}$. Let the column vector of these $n$ values for regressor $j$ be written $\mathbf{x}_{,j}$ and the row vector of these $k$ values for observation $i$ be written $\mathbf{x}_i$. Then the model matrix is
$$X = \pmatrix{ 1 &x_{11} &\cdots &x_{1k} \\ 1 &x_{21} &\cdots &x_{2k} \\
\vdots &\vdots &\vdots &\vdots \\ 1 &x_{n1} &\cdots &x_{nk}}$$
and, by definition, the hat matrix is
$$H = X(X^\prime X)^{-1} X^\prime,$$
whence entry $i$ along the diagonal is
$$h_i = h_{ii} = (1; \mathbf{x}_i) (X^\prime X)^{-1} (1; \mathbf{x}_i)^\prime.\tag{1}$$
There's nothing for it but to work out that central matrix inverse--but by virtue of the first key result, it's easy, especially when we write it in block-matrix form:
$$X^\prime X = n\pmatrix{1 & \mathbf{0}^\prime \\ \mathbf{0} & C}$$
where $\mathbf{0} = (0,0,\ldots,0)^\prime$ and
$$C_{jk} = \frac{1}{n} \sum_{i=1}^n x_{ij} x_{ik} = \frac{n-1}{n}\operatorname{Cov}(\mathbf{x}_j, \mathbf{x}_k) = \frac{n-1}{n}\Sigma_{jk}.$$
(I have written $\Sigma$ for the sample covariance matrix of the regressors.)
Because this is block diagonal, its inverse can be found simply by inverting the blocks:
$$(X^\prime X)^{-1} = \frac{1}{n}\pmatrix{1 & \mathbf{0}^\prime \\ \mathbf{0} & C^{-1}} = \pmatrix{\frac{1}{n} & \mathbf{0}^\prime \\ \mathbf{0} & \frac{1}{n-1}\Sigma^{-1}}.$$
From the definition $(1)$ we obtain
$$\eqalign{
h_i &= (1; \mathbf{x}_i) \pmatrix{\frac{1}{n} & \mathbf{0}^\prime \\ \mathbf{0} & \frac{1}{n-1}\Sigma^{-1}}(1; \mathbf{x}_i)^\prime \\
&=\frac{1}{n} + \frac{1}{n-1}\mathbf{x}_i \Sigma^{-1}\mathbf{x}_i^\prime \\
&=\frac{1}{n} + \frac{1}{n-1} D^2(\mathbf{x}_i, \mathbf{0}).
}$$
Solving for the squared Mahalanobis length $D_i^2 = D^2(\mathbf{x}_i, \mathbf{0})$ yields
$$D_i^2 = (n-1)\left(h_i - \frac{1}{n}\right),$$
QED.
Looking back, we may trace the additive term $1/n$ to the presence of an intercept, which introduced the column of ones into the model matrix $X$. The multiplicative term $n-1$ appeared after assuming the Mahalanobis distance would be computed using the sample covariance estimate (which divides the sums of squares and products by $n-1$) rather than the covariance matrix of the data (which divides the sum of squares and products by $n$).
The chief value of this analysis is to impart a geometric interpretation to the leverage, which measures how much a unit change in the response at observation $i$ will change the fitted value at that observation: high-leverage observations are at large Mahalanobis distances from the centroid of the regressors, exactly as a mechanically efficient lever operates at a large distance from its fulcrum.
R code to show that the relation indeed holds:
x <- mtcars
# Compute Mahalanobis distances
h <- hat(x, intercept = TRUE); names(h) <- rownames(mtcars)
M <- mahalanobis(x, colMeans(x), cov(x))
# Compute D^2 of the question
n <- nrow(x); D2 <- (n-1)*(h - 1/n)
# Compare.
all.equal(M, D2) # TRUE
print(signif(cbind(M, D2), 3)) | Prove the relation between Mahalanobis distance and Leverage? | My description of the Mahalanobis distance at Bottom to top explanation of the Mahalanobis distance? includes two key results:
By definition, it does not change when the regressors are uniformly shif | Prove the relation between Mahalanobis distance and Leverage?
My description of the Mahalanobis distance at Bottom to top explanation of the Mahalanobis distance? includes two key results:
By definition, it does not change when the regressors are uniformly shifted.
The squared Mahalanobis distance between vectors $x$ and $y$ is given by $$D^2(x,y) = (x-y)^\prime \Sigma^{-1}(x-y)$$ where $\Sigma$ is the covariance of the data.
(1) allows us to assume the means of the regressors are all zero. It remains to compute $h_i$. However, for the claim to be true, we need to add one more assumption:
The model must include an intercept.
Allowing for this, let there be $k \ge 0$ regressors and $n$ data, writing the value of regressor $j$ for observation $i$ as $x_{ij}$. Let the column vector of these $n$ values for regressor $j$ be written $\mathbf{x}_{,j}$ and the row vector of these $k$ values for observation $i$ be written $\mathbf{x}_i$. Then the model matrix is
$$X = \pmatrix{ 1 &x_{11} &\cdots &x_{1k} \\ 1 &x_{21} &\cdots &x_{2k} \\
\vdots &\vdots &\vdots &\vdots \\ 1 &x_{n1} &\cdots &x_{nk}}$$
and, by definition, the hat matrix is
$$H = X(X^\prime X)^{-1} X^\prime,$$
whence entry $i$ along the diagonal is
$$h_i = h_{ii} = (1; \mathbf{x}_i) (X^\prime X)^{-1} (1; \mathbf{x}_i)^\prime.\tag{1}$$
There's nothing for it but to work out that central matrix inverse--but by virtue of the first key result, it's easy, especially when we write it in block-matrix form:
$$X^\prime X = n\pmatrix{1 & \mathbf{0}^\prime \\ \mathbf{0} & C}$$
where $\mathbf{0} = (0,0,\ldots,0)^\prime$ and
$$C_{jk} = \frac{1}{n} \sum_{i=1}^n x_{ij} x_{ik} = \frac{n-1}{n}\operatorname{Cov}(\mathbf{x}_j, \mathbf{x}_k) = \frac{n-1}{n}\Sigma_{jk}.$$
(I have written $\Sigma$ for the sample covariance matrix of the regressors.)
Because this is block diagonal, its inverse can be found simply by inverting the blocks:
$$(X^\prime X)^{-1} = \frac{1}{n}\pmatrix{1 & \mathbf{0}^\prime \\ \mathbf{0} & C^{-1}} = \pmatrix{\frac{1}{n} & \mathbf{0}^\prime \\ \mathbf{0} & \frac{1}{n-1}\Sigma^{-1}}.$$
From the definition $(1)$ we obtain
$$\eqalign{
h_i &= (1; \mathbf{x}_i) \pmatrix{\frac{1}{n} & \mathbf{0}^\prime \\ \mathbf{0} & \frac{1}{n-1}\Sigma^{-1}}(1; \mathbf{x}_i)^\prime \\
&=\frac{1}{n} + \frac{1}{n-1}\mathbf{x}_i \Sigma^{-1}\mathbf{x}_i^\prime \\
&=\frac{1}{n} + \frac{1}{n-1} D^2(\mathbf{x}_i, \mathbf{0}).
}$$
Solving for the squared Mahalanobis length $D_i^2 = D^2(\mathbf{x}_i, \mathbf{0})$ yields
$$D_i^2 = (n-1)\left(h_i - \frac{1}{n}\right),$$
QED.
Looking back, we may trace the additive term $1/n$ to the presence of an intercept, which introduced the column of ones into the model matrix $X$. The multiplicative term $n-1$ appeared after assuming the Mahalanobis distance would be computed using the sample covariance estimate (which divides the sums of squares and products by $n-1$) rather than the covariance matrix of the data (which divides the sum of squares and products by $n$).
The chief value of this analysis is to impart a geometric interpretation to the leverage, which measures how much a unit change in the response at observation $i$ will change the fitted value at that observation: high-leverage observations are at large Mahalanobis distances from the centroid of the regressors, exactly as a mechanically efficient lever operates at a large distance from its fulcrum.
R code to show that the relation indeed holds:
x <- mtcars
# Compute Mahalanobis distances
h <- hat(x, intercept = TRUE); names(h) <- rownames(mtcars)
M <- mahalanobis(x, colMeans(x), cov(x))
# Compute D^2 of the question
n <- nrow(x); D2 <- (n-1)*(h - 1/n)
# Compare.
all.equal(M, D2) # TRUE
print(signif(cbind(M, D2), 3)) | Prove the relation between Mahalanobis distance and Leverage?
My description of the Mahalanobis distance at Bottom to top explanation of the Mahalanobis distance? includes two key results:
By definition, it does not change when the regressors are uniformly shif |
19,121 | Prove the relation between Mahalanobis distance and Leverage? | I fear @whuber's answer assumes a key step that is not assumable. I don't know how to fix it, but I want to explain the mistake. The problem is the statement "(1) allows us to assume the means of the regressors are all zero." While that is true for the Mahalanobis distance, @whuber assumes the raw data to be mean zero before any Malanobis distance enters the picture. I don't know how this is justifiable.
To see this, let's redo the calculation without assuming that $X$ is centered. As above, we have:
$$[H]_{ii} = \begin{bmatrix} 1 \\ x_i \end{bmatrix}^T (X^T X)^{-1} \begin{bmatrix} 1 \\ x_i \end{bmatrix}$$
One can see that $X^T X = \sum_{i} x_i x_i^T$. @whuber assumes that the data is centered and thus writes:
$$X^T X = n \begin{bmatrix} 1 & 0^T \\ 0 & C \end{bmatrix}$$
But how is this justified? No Mahalanobis distance has (yet) entered the picture. Nothing tells us that the data is centered. In actuality, the correct expression is:
$$X^T X = n \begin{bmatrix} 1 & \mu^T \\ \mu & \Sigma + \mu \mu^T \end{bmatrix}$$
An easy block inversion is no longer possible and I don't know how to complete the derivation. | Prove the relation between Mahalanobis distance and Leverage? | I fear @whuber's answer assumes a key step that is not assumable. I don't know how to fix it, but I want to explain the mistake. The problem is the statement "(1) allows us to assume the means of the | Prove the relation between Mahalanobis distance and Leverage?
I fear @whuber's answer assumes a key step that is not assumable. I don't know how to fix it, but I want to explain the mistake. The problem is the statement "(1) allows us to assume the means of the regressors are all zero." While that is true for the Mahalanobis distance, @whuber assumes the raw data to be mean zero before any Malanobis distance enters the picture. I don't know how this is justifiable.
To see this, let's redo the calculation without assuming that $X$ is centered. As above, we have:
$$[H]_{ii} = \begin{bmatrix} 1 \\ x_i \end{bmatrix}^T (X^T X)^{-1} \begin{bmatrix} 1 \\ x_i \end{bmatrix}$$
One can see that $X^T X = \sum_{i} x_i x_i^T$. @whuber assumes that the data is centered and thus writes:
$$X^T X = n \begin{bmatrix} 1 & 0^T \\ 0 & C \end{bmatrix}$$
But how is this justified? No Mahalanobis distance has (yet) entered the picture. Nothing tells us that the data is centered. In actuality, the correct expression is:
$$X^T X = n \begin{bmatrix} 1 & \mu^T \\ \mu & \Sigma + \mu \mu^T \end{bmatrix}$$
An easy block inversion is no longer possible and I don't know how to complete the derivation. | Prove the relation between Mahalanobis distance and Leverage?
I fear @whuber's answer assumes a key step that is not assumable. I don't know how to fix it, but I want to explain the mistake. The problem is the statement "(1) allows us to assume the means of the |
19,122 | Merging observations in Gaussian Process | Great question and what you are suggesting sounds reasonable. However personally I would proceed differently in order to be efficient. As you said two points that are close provide little additional information and hence the effective degrees of freedom of the model is less than the number of data points observed. In such a case it may be worth using Nystroms method which is described well in GPML (chapter on sparse approximations can be seen http://www.gaussianprocess.org/gpml/). The method is very easy to implement and recently been proved to be highly accurate by Rudi et al. (http://arxiv.org/abs/1507.04717) | Merging observations in Gaussian Process | Great question and what you are suggesting sounds reasonable. However personally I would proceed differently in order to be efficient. As you said two points that are close provide little additional i | Merging observations in Gaussian Process
Great question and what you are suggesting sounds reasonable. However personally I would proceed differently in order to be efficient. As you said two points that are close provide little additional information and hence the effective degrees of freedom of the model is less than the number of data points observed. In such a case it may be worth using Nystroms method which is described well in GPML (chapter on sparse approximations can be seen http://www.gaussianprocess.org/gpml/). The method is very easy to implement and recently been proved to be highly accurate by Rudi et al. (http://arxiv.org/abs/1507.04717) | Merging observations in Gaussian Process
Great question and what you are suggesting sounds reasonable. However personally I would proceed differently in order to be efficient. As you said two points that are close provide little additional i |
19,123 | Merging observations in Gaussian Process | I have also been investigating merging observations when performing Gaussian Process regression. In my problem I have only one covariate.
I'm not sure I necessarily agree that the Nystrom approximation is preferable. In particular, if a sufficient approximation can be found based on a merged dataset, calculations could be quicker than when one uses the Nystrom approximation.
Below are some graphs showing 1000 data points and the posterior GP mean, the posterior GP mean with merged records, and the posterior GP mean using the Nystrom approximation. Records were grouped based on equal sized buckets of the ordered covariate. The approximation order relates to the number of groups when merging records and the order of the Nystrom approximation. The merging approach and the Nystrom approximation both produce results that are identical to standard GP regression when when the approximation order is equal to the number of points.
In this case, when the order of the approximation is 10 the merging approach seems preferable. When the order is 20, the mean from the Nystrom approximation is visually indistinguishable from the exact GP posterior mean, although the mean based on merging observations is probably good enough. When the order is 5, both are pretty poor. | Merging observations in Gaussian Process | I have also been investigating merging observations when performing Gaussian Process regression. In my problem I have only one covariate.
I'm not sure I necessarily agree that the Nystrom approximati | Merging observations in Gaussian Process
I have also been investigating merging observations when performing Gaussian Process regression. In my problem I have only one covariate.
I'm not sure I necessarily agree that the Nystrom approximation is preferable. In particular, if a sufficient approximation can be found based on a merged dataset, calculations could be quicker than when one uses the Nystrom approximation.
Below are some graphs showing 1000 data points and the posterior GP mean, the posterior GP mean with merged records, and the posterior GP mean using the Nystrom approximation. Records were grouped based on equal sized buckets of the ordered covariate. The approximation order relates to the number of groups when merging records and the order of the Nystrom approximation. The merging approach and the Nystrom approximation both produce results that are identical to standard GP regression when when the approximation order is equal to the number of points.
In this case, when the order of the approximation is 10 the merging approach seems preferable. When the order is 20, the mean from the Nystrom approximation is visually indistinguishable from the exact GP posterior mean, although the mean based on merging observations is probably good enough. When the order is 5, both are pretty poor. | Merging observations in Gaussian Process
I have also been investigating merging observations when performing Gaussian Process regression. In my problem I have only one covariate.
I'm not sure I necessarily agree that the Nystrom approximati |
19,124 | What does it mean if the median or average of sums is greater than sum of those of addends? | Medians are not linear, so there are a variety of circumstances under which something like that (i.e. $\text{median}(X_1)+\text{median}(X_2)<\text{median}(X_1+X_2)$) might happen.
It's very easy to construct discrete examples where that sort of thing occurs, but it's also common in continuous situations.
For example it can happen with skewed continuous distributions - with a heavy right tail, the medians might both be small but the median of the sum is "pulled up" because there's a good chance that one of the two is large, and a value above the median is typically going to be far above it, making the median of the sum larger than the sum of the medians.
Here's an explicit example: Take $X_1,X_2 \, \stackrel{\text{i.i.d.}}{ \sim} \operatorname{Exp}(1)$. Then $X_1$ and $X_2$ have median $\log(2) \approx 0.693$ so the sum of the medians is less than $1.4$, but $X_1+X_2\sim \operatorname{Gamma}(2,1)$ which has median $\approx 1.678$ (actually $ -W_{-1}(-\frac{1}{2 e}) - 1$ according to Wolfram Alpha) | What does it mean if the median or average of sums is greater than sum of those of addends? | Medians are not linear, so there are a variety of circumstances under which something like that (i.e. $\text{median}(X_1)+\text{median}(X_2)<\text{median}(X_1+X_2)$) might happen.
It's very easy to co | What does it mean if the median or average of sums is greater than sum of those of addends?
Medians are not linear, so there are a variety of circumstances under which something like that (i.e. $\text{median}(X_1)+\text{median}(X_2)<\text{median}(X_1+X_2)$) might happen.
It's very easy to construct discrete examples where that sort of thing occurs, but it's also common in continuous situations.
For example it can happen with skewed continuous distributions - with a heavy right tail, the medians might both be small but the median of the sum is "pulled up" because there's a good chance that one of the two is large, and a value above the median is typically going to be far above it, making the median of the sum larger than the sum of the medians.
Here's an explicit example: Take $X_1,X_2 \, \stackrel{\text{i.i.d.}}{ \sim} \operatorname{Exp}(1)$. Then $X_1$ and $X_2$ have median $\log(2) \approx 0.693$ so the sum of the medians is less than $1.4$, but $X_1+X_2\sim \operatorname{Gamma}(2,1)$ which has median $\approx 1.678$ (actually $ -W_{-1}(-\frac{1}{2 e}) - 1$ according to Wolfram Alpha) | What does it mean if the median or average of sums is greater than sum of those of addends?
Medians are not linear, so there are a variety of circumstances under which something like that (i.e. $\text{median}(X_1)+\text{median}(X_2)<\text{median}(X_1+X_2)$) might happen.
It's very easy to co |
19,125 | Importance of McNemar test in caret::confusionMatrix | Interpret the McNemar’s Test for Classifiers
McNemar’s Test captures the errors made by both models. Specifically, the No/Yes and Yes/No (A/B and B/A in your case) cells in the confusion matrix. The test checks if there is a significant difference between the counts in these two cells. That is all.
If these cells have counts that are similar, it shows us that both models make errors in much the same proportion, just on different instances of the test set. In this case, the result of the test would not be significant and the null hypothesis would not be rejected.
Fail to Reject Null Hypothesis: Classifiers have a similar proportion
of errors on the test set.
Reject Null Hypothesis: Classifiers have a different proportion of
errors on the test set.
More information can be found out here:
https://machinelearningmastery.com/mcnemars-test-for-machine-learning/ | Importance of McNemar test in caret::confusionMatrix | Interpret the McNemar’s Test for Classifiers
McNemar’s Test captures the errors made by both models. Specifically, the No/Yes and Yes/No (A/B and B/A in your case) cells in the confusion matrix. The t | Importance of McNemar test in caret::confusionMatrix
Interpret the McNemar’s Test for Classifiers
McNemar’s Test captures the errors made by both models. Specifically, the No/Yes and Yes/No (A/B and B/A in your case) cells in the confusion matrix. The test checks if there is a significant difference between the counts in these two cells. That is all.
If these cells have counts that are similar, it shows us that both models make errors in much the same proportion, just on different instances of the test set. In this case, the result of the test would not be significant and the null hypothesis would not be rejected.
Fail to Reject Null Hypothesis: Classifiers have a similar proportion
of errors on the test set.
Reject Null Hypothesis: Classifiers have a different proportion of
errors on the test set.
More information can be found out here:
https://machinelearningmastery.com/mcnemars-test-for-machine-learning/ | Importance of McNemar test in caret::confusionMatrix
Interpret the McNemar’s Test for Classifiers
McNemar’s Test captures the errors made by both models. Specifically, the No/Yes and Yes/No (A/B and B/A in your case) cells in the confusion matrix. The t |
19,126 | Importance of McNemar test in caret::confusionMatrix | This is an interesting question that has different answers according to the context. I agree with what
have answered you before, so here I will focus more on the context.
It is normal that you have been confused when looking for McNemar's test interpretation on the Internet. The main reason is that both the historical origin of the test (Genetics), as well as its common use in the medical and social science fields, make its interpretation difficult in the context of machine learning. Here I explain what I have learned so far.
First of all, it is important to know that there are two different scenarios in the context of machine learning. The first one is that you are evaluating the quality of your model vs. the reference data (test data or possibly training data). The second scenario is when you are comparing two classification models (algorithms).
In the first scenario you would normally look for the p-value of the test to be greater than 0.05. That is, do not reject the null hypothesis that assumes homogeneity of the proportion of misclassified cases for the two class labels. In your confusion matrix above, these proportions are calculated from cells AB and BA. A significant value here would indicate that your algorithm misclassifies one label more than another.
In the second scenario you would probably look for the opposite. That is, that the p-value of the test is less than 0.05. This would indicate that the classifiers have different error rates. This is evidence that you can use in conjunction with other indicators such as individual model accuracy to conclude that one is better than another.
On your second question, you may have already seen that the accuracy provided by the caret package has nothing to do with McNemar's test. This is because the accuracy measures other information from the confusion matrix (cells AA and BB).
Finally, on the third question I agree with what Alexis suggested.
In summary: what McNemar's theoretically calls marginal homogeneity is, in the first scenario, the homogeneity of the rate of misclassifying the two class labels. In the second scenario, it refers to the homogeneity of the error rates of the classifiers.
I hope that these ideas will give you a better understanding of the results that caret provides. | Importance of McNemar test in caret::confusionMatrix | This is an interesting question that has different answers according to the context. I agree with what
have answered you before, so here I will focus more on the context.
It is normal that you have be | Importance of McNemar test in caret::confusionMatrix
This is an interesting question that has different answers according to the context. I agree with what
have answered you before, so here I will focus more on the context.
It is normal that you have been confused when looking for McNemar's test interpretation on the Internet. The main reason is that both the historical origin of the test (Genetics), as well as its common use in the medical and social science fields, make its interpretation difficult in the context of machine learning. Here I explain what I have learned so far.
First of all, it is important to know that there are two different scenarios in the context of machine learning. The first one is that you are evaluating the quality of your model vs. the reference data (test data or possibly training data). The second scenario is when you are comparing two classification models (algorithms).
In the first scenario you would normally look for the p-value of the test to be greater than 0.05. That is, do not reject the null hypothesis that assumes homogeneity of the proportion of misclassified cases for the two class labels. In your confusion matrix above, these proportions are calculated from cells AB and BA. A significant value here would indicate that your algorithm misclassifies one label more than another.
In the second scenario you would probably look for the opposite. That is, that the p-value of the test is less than 0.05. This would indicate that the classifiers have different error rates. This is evidence that you can use in conjunction with other indicators such as individual model accuracy to conclude that one is better than another.
On your second question, you may have already seen that the accuracy provided by the caret package has nothing to do with McNemar's test. This is because the accuracy measures other information from the confusion matrix (cells AA and BB).
Finally, on the third question I agree with what Alexis suggested.
In summary: what McNemar's theoretically calls marginal homogeneity is, in the first scenario, the homogeneity of the rate of misclassifying the two class labels. In the second scenario, it refers to the homogeneity of the error rates of the classifiers.
I hope that these ideas will give you a better understanding of the results that caret provides. | Importance of McNemar test in caret::confusionMatrix
This is an interesting question that has different answers according to the context. I agree with what
have answered you before, so here I will focus more on the context.
It is normal that you have be |
19,127 | Importance of McNemar test in caret::confusionMatrix | McNemar's test is specifically a test of paired proportions. Pre-post is one structure defining pairing, but cross-sectional measurement of two separate dichotomous variables is also an allowable pairing structure in the data, the quasi-longitudinal nature of case-control data is yet another pairing structure appropriate to this test.
The null hypothesis is more or less that the proportions of one variable are equal across both values of the other other variable. A significant test result means that you have rejected this null hypothesis, and decided that your two variables are associated (i.e. that knowing something about one, gives you information about the other), and therefore that the proportion of one variable changes depending on the values of the other variable.
Blunt accuracy does not account for the accuracy due to chance, which is dependent on the size of the proportions in each group.
McNemar's test can only be applied to a 2x2 table, so no 3x3. However, there is Cochran's Q test which is like a generalization of McNemar's test to the repeated measures scenario for binary data—that is, it is analogous to a repeated measures ANOVA for binary measures—(Cochran's Q for a 2x2 gives the same results as for McNemar's test... caveat: take care regarding continuity corrections). | Importance of McNemar test in caret::confusionMatrix | McNemar's test is specifically a test of paired proportions. Pre-post is one structure defining pairing, but cross-sectional measurement of two separate dichotomous variables is also an allowable pair | Importance of McNemar test in caret::confusionMatrix
McNemar's test is specifically a test of paired proportions. Pre-post is one structure defining pairing, but cross-sectional measurement of two separate dichotomous variables is also an allowable pairing structure in the data, the quasi-longitudinal nature of case-control data is yet another pairing structure appropriate to this test.
The null hypothesis is more or less that the proportions of one variable are equal across both values of the other other variable. A significant test result means that you have rejected this null hypothesis, and decided that your two variables are associated (i.e. that knowing something about one, gives you information about the other), and therefore that the proportion of one variable changes depending on the values of the other variable.
Blunt accuracy does not account for the accuracy due to chance, which is dependent on the size of the proportions in each group.
McNemar's test can only be applied to a 2x2 table, so no 3x3. However, there is Cochran's Q test which is like a generalization of McNemar's test to the repeated measures scenario for binary data—that is, it is analogous to a repeated measures ANOVA for binary measures—(Cochran's Q for a 2x2 gives the same results as for McNemar's test... caveat: take care regarding continuity corrections). | Importance of McNemar test in caret::confusionMatrix
McNemar's test is specifically a test of paired proportions. Pre-post is one structure defining pairing, but cross-sectional measurement of two separate dichotomous variables is also an allowable pair |
19,128 | How to correctly apply the Nemenyi post-hoc test after the Friedman test | I also just started to look at this question.
As mentioned before, when we use the normal distribution to calculate p-values for each test, then these p-values do not take multiple testing into account. To correct for it and control the family-wise error rate, we need some adjustments. Bonferonni, i.e. dividing the significance level or multiplying the raw p-values by the number of tests, is only one possible correction. There are a large number of other multiple testing p-value corrections that are in many cases less conservative.
These p-value corrections do not take the specific structure of the hypothesis tests into account.
I am more familiar with the pairwise comparison of the original data instead of the rank transformed data as in Kruskal-Wallis or Friedman tests. In that case, which is the Tukey HSD test, the test statistic for the multiple comparison is distributed according to the studentized range distribution, which is the distribution for all pairwise comparisons under the assumption of independent samples. It is based on probabilities of multivariate normal distribution which could be calculated by numerical integration but are usually used from tables.
My guess, since I don't know the theory, is that the studentized range distribution can be applied to the case of rank tests in a similar way as in the Tukey HSD pairwise comparisons.
So, using (2) normal distribution plus multiple testing p-value corrections and using (1) studentized range distributions are two different ways of getting an approximate distribution of the test statistics. However, if the assumptions for the use of the studentized range distribution are satisfied, then it should provide a better approximation since it is designed for the specific problem of all pairwise comparisons. | How to correctly apply the Nemenyi post-hoc test after the Friedman test | I also just started to look at this question.
As mentioned before, when we use the normal distribution to calculate p-values for each test, then these p-values do not take multiple testing into accou | How to correctly apply the Nemenyi post-hoc test after the Friedman test
I also just started to look at this question.
As mentioned before, when we use the normal distribution to calculate p-values for each test, then these p-values do not take multiple testing into account. To correct for it and control the family-wise error rate, we need some adjustments. Bonferonni, i.e. dividing the significance level or multiplying the raw p-values by the number of tests, is only one possible correction. There are a large number of other multiple testing p-value corrections that are in many cases less conservative.
These p-value corrections do not take the specific structure of the hypothesis tests into account.
I am more familiar with the pairwise comparison of the original data instead of the rank transformed data as in Kruskal-Wallis or Friedman tests. In that case, which is the Tukey HSD test, the test statistic for the multiple comparison is distributed according to the studentized range distribution, which is the distribution for all pairwise comparisons under the assumption of independent samples. It is based on probabilities of multivariate normal distribution which could be calculated by numerical integration but are usually used from tables.
My guess, since I don't know the theory, is that the studentized range distribution can be applied to the case of rank tests in a similar way as in the Tukey HSD pairwise comparisons.
So, using (2) normal distribution plus multiple testing p-value corrections and using (1) studentized range distributions are two different ways of getting an approximate distribution of the test statistics. However, if the assumptions for the use of the studentized range distribution are satisfied, then it should provide a better approximation since it is designed for the specific problem of all pairwise comparisons. | How to correctly apply the Nemenyi post-hoc test after the Friedman test
I also just started to look at this question.
As mentioned before, when we use the normal distribution to calculate p-values for each test, then these p-values do not take multiple testing into accou |
19,129 | How to correctly apply the Nemenyi post-hoc test after the Friedman test | As far as I know, when comparing only 2 algorithms, Demšar suggests the Wilcoxon signed rank test rather than Friedman + posthoc. I am, sadly, just as confuzed as you when it comes to decyphering what demšar's dividing by k-1 is supposed to mean. | How to correctly apply the Nemenyi post-hoc test after the Friedman test | As far as I know, when comparing only 2 algorithms, Demšar suggests the Wilcoxon signed rank test rather than Friedman + posthoc. I am, sadly, just as confuzed as you when it comes to decyphering what | How to correctly apply the Nemenyi post-hoc test after the Friedman test
As far as I know, when comparing only 2 algorithms, Demšar suggests the Wilcoxon signed rank test rather than Friedman + posthoc. I am, sadly, just as confuzed as you when it comes to decyphering what demšar's dividing by k-1 is supposed to mean. | How to correctly apply the Nemenyi post-hoc test after the Friedman test
As far as I know, when comparing only 2 algorithms, Demšar suggests the Wilcoxon signed rank test rather than Friedman + posthoc. I am, sadly, just as confuzed as you when it comes to decyphering what |
19,130 | How to correctly apply the Nemenyi post-hoc test after the Friedman test | I think the first approach is more correct, likewise, the Nemenyi test (also known as the Wilcoxon–Nemenyi–McDonald–Thompson test) suggested in the book "Nonparametric statistical methods" (Hollander, Wolfe, & Chicken, 2014) and implemented in the R NSM3 package (i.e., pWNMTfunction). For each $ij$ pair of ranks sum, $b$ blocks, $k$ groups/treatments:
$Q=\frac{|R_i-R_j|}{\sqrt{\frac{bk(k+1)}{12}}} \sim q_{(k, df)}$
Thus, reject $H_0$ if:
$|R_i-R_j| \geq q_{crit}\times{\sqrt{\frac{bk(k+1)}{12}}}$
The function calculates the p-value and difference between the sums of ranks. Example using the Monte Carlo (with 10000 Iterations):
ds <- data.frame(block = factor(rep(1:8, rep(3 ,8))),
group = factor(rep( c( "A" , "B" , "C" ), 8 )),
score = c(98,109,105,
65,69,80,
90,66,105,
90,92,97,
72,93,81,
94,126,101,
96,90,103,
100,116,105))
NSM3::pWNMT(x = ds$score,
b = ds$block,
trt = ds$group |> as.numeric(), n.mc=10000)
#> Number of blocks: n=8
#> Number of treatments: k=3
#> Using the Monte Carlo (with 10000 Iterations) method:
#>
#> For treatments 1 - 2, the Wilcoxon, Nemenyi, McDonald-Thompson R Statistic is 8.
#> The smallest experimentwise error rate leading to rejection is 0.1476.
#>
#> For treatments 1 - 3, the Wilcoxon, Nemenyi, McDonald-Thompson R Statistic is 10.
#> The smallest experimentwise error rate leading to rejection is 0.0403.
#>
#> For treatments 2 - 3, the Wilcoxon, Nemenyi, McDonald-Thompson R Statistic is 2.
#> The smallest experimentwise error rate leading to rejection is 0.9663.
#>
The $q_{crt}$ can be obtained via the function cRangeNor(α, k) (see note), which will provide critical values almost equal to the ones on qtukey function from the stats package. Example:
k <- 3
alpha <- .05
df <- Inf
NSM3::cRangeNor(alpha = alpha, k = k)
#> [1] 3.315
stats::qtukey(p = alpha, nmeans = k, df = df, lower.tail = F)
#> [1] 3.314493
The test statistic presented above is equivalent to the one provided by Pohlert (2014):
$Q=\frac{|\bar R_i - \bar R_j|}{\sqrt{\frac{k(k+1)}{6b}}} \times \sqrt{2}$
Thus, reject $H_0$ if:
$|\bar R_i - \bar R_j| \geq \frac{q_{crit}}{\sqrt{2}} \times {\sqrt{\frac{k(k+1)}{6b}}}$
(be aware that you did not use the mean of the ranks (i.e, $\bar R_i$) in your question, you just used ($R_i$).
The function posthoc.friedman.nemenyi.test from this PMCMR package (currently frdAllPairsNemenyiTest function in the PMCMRpluspacakge) will provide (default) Asymptotic p-values. While the function pWNMT from the NSM3 package will provide p-values using the Monte Carlo (default). In this function, you can set method = "Exact" to obtain exact p-values if permutations are $10000$ or less. The exact method can take ages to present results...
Note: that $df = Inf$ is assumed, some sources assume $df = b-k$. | How to correctly apply the Nemenyi post-hoc test after the Friedman test | I think the first approach is more correct, likewise, the Nemenyi test (also known as the Wilcoxon–Nemenyi–McDonald–Thompson test) suggested in the book "Nonparametric statistical methods" (Hollander, | How to correctly apply the Nemenyi post-hoc test after the Friedman test
I think the first approach is more correct, likewise, the Nemenyi test (also known as the Wilcoxon–Nemenyi–McDonald–Thompson test) suggested in the book "Nonparametric statistical methods" (Hollander, Wolfe, & Chicken, 2014) and implemented in the R NSM3 package (i.e., pWNMTfunction). For each $ij$ pair of ranks sum, $b$ blocks, $k$ groups/treatments:
$Q=\frac{|R_i-R_j|}{\sqrt{\frac{bk(k+1)}{12}}} \sim q_{(k, df)}$
Thus, reject $H_0$ if:
$|R_i-R_j| \geq q_{crit}\times{\sqrt{\frac{bk(k+1)}{12}}}$
The function calculates the p-value and difference between the sums of ranks. Example using the Monte Carlo (with 10000 Iterations):
ds <- data.frame(block = factor(rep(1:8, rep(3 ,8))),
group = factor(rep( c( "A" , "B" , "C" ), 8 )),
score = c(98,109,105,
65,69,80,
90,66,105,
90,92,97,
72,93,81,
94,126,101,
96,90,103,
100,116,105))
NSM3::pWNMT(x = ds$score,
b = ds$block,
trt = ds$group |> as.numeric(), n.mc=10000)
#> Number of blocks: n=8
#> Number of treatments: k=3
#> Using the Monte Carlo (with 10000 Iterations) method:
#>
#> For treatments 1 - 2, the Wilcoxon, Nemenyi, McDonald-Thompson R Statistic is 8.
#> The smallest experimentwise error rate leading to rejection is 0.1476.
#>
#> For treatments 1 - 3, the Wilcoxon, Nemenyi, McDonald-Thompson R Statistic is 10.
#> The smallest experimentwise error rate leading to rejection is 0.0403.
#>
#> For treatments 2 - 3, the Wilcoxon, Nemenyi, McDonald-Thompson R Statistic is 2.
#> The smallest experimentwise error rate leading to rejection is 0.9663.
#>
The $q_{crt}$ can be obtained via the function cRangeNor(α, k) (see note), which will provide critical values almost equal to the ones on qtukey function from the stats package. Example:
k <- 3
alpha <- .05
df <- Inf
NSM3::cRangeNor(alpha = alpha, k = k)
#> [1] 3.315
stats::qtukey(p = alpha, nmeans = k, df = df, lower.tail = F)
#> [1] 3.314493
The test statistic presented above is equivalent to the one provided by Pohlert (2014):
$Q=\frac{|\bar R_i - \bar R_j|}{\sqrt{\frac{k(k+1)}{6b}}} \times \sqrt{2}$
Thus, reject $H_0$ if:
$|\bar R_i - \bar R_j| \geq \frac{q_{crit}}{\sqrt{2}} \times {\sqrt{\frac{k(k+1)}{6b}}}$
(be aware that you did not use the mean of the ranks (i.e, $\bar R_i$) in your question, you just used ($R_i$).
The function posthoc.friedman.nemenyi.test from this PMCMR package (currently frdAllPairsNemenyiTest function in the PMCMRpluspacakge) will provide (default) Asymptotic p-values. While the function pWNMT from the NSM3 package will provide p-values using the Monte Carlo (default). In this function, you can set method = "Exact" to obtain exact p-values if permutations are $10000$ or less. The exact method can take ages to present results...
Note: that $df = Inf$ is assumed, some sources assume $df = b-k$. | How to correctly apply the Nemenyi post-hoc test after the Friedman test
I think the first approach is more correct, likewise, the Nemenyi test (also known as the Wilcoxon–Nemenyi–McDonald–Thompson test) suggested in the book "Nonparametric statistical methods" (Hollander, |
19,131 | How to correctly apply the Nemenyi post-hoc test after the Friedman test | I also stumbled across the questio whether to compute the p-value from a normal or studentized t-distribution. Unfortunately, I still can't answer it, because different papers communicate different methods.
Nevertheless, for calculating adjusted p-values, you have to multiply the uncorrected p-value with the adjustment factor, e.g. p*(k-1) in case of comparisons against one control method or p*((k*(k-1))/2) for n x n comparisons.
What you should divide by the adjustment factor is the alpha value, if compared with unadjusted p's. | How to correctly apply the Nemenyi post-hoc test after the Friedman test | I also stumbled across the questio whether to compute the p-value from a normal or studentized t-distribution. Unfortunately, I still can't answer it, because different papers communicate different me | How to correctly apply the Nemenyi post-hoc test after the Friedman test
I also stumbled across the questio whether to compute the p-value from a normal or studentized t-distribution. Unfortunately, I still can't answer it, because different papers communicate different methods.
Nevertheless, for calculating adjusted p-values, you have to multiply the uncorrected p-value with the adjustment factor, e.g. p*(k-1) in case of comparisons against one control method or p*((k*(k-1))/2) for n x n comparisons.
What you should divide by the adjustment factor is the alpha value, if compared with unadjusted p's. | How to correctly apply the Nemenyi post-hoc test after the Friedman test
I also stumbled across the questio whether to compute the p-value from a normal or studentized t-distribution. Unfortunately, I still can't answer it, because different papers communicate different me |
19,132 | Time Series Forecasting with Daily Data: ARIMA with regressor | You should be evaluating models and forecasts from different origins across different horizons and not one one number in order to gauge an approach.
I assume that your data is from the US. I prefer 3+ years of daily data as you can have two holidays landing on a weekend and get no weekday read. It looks like your Thanksgiving impact is a day off in the 2012 or there was a recording error of some kind and caused the model to miss the Thanksgiving day effect.
Januarys are typically low in the dataset if you look as a % of the year. Weekends are high. The dummies reflect this behavior....MONTH_EFF01, FIXED_EFF_N10507,FIXED_EFF_N10607
I have found that using an AR component with daily data assumes that the last two weeks day of the week pattern is how the pattern is in general which is a big assumption. We started with 11 monthly dummies and 6 daily dummies. Some dropped out of the model. B**1 means that there is a lag impact the day after a holiday. There were 6 special days of the month (days 2,3,5,21,29,30----21 might be spurious?) and 3 time trends, 2 seasonal pulses (where a day of the week started deviating from the typical, a 0 before this data and a 1 every 7th day after) and 2 outliers (note the thanksgiving!) This took just under 7 minutes to run. Download all results here www.autobox.com/se/dd/daily.zip
It includes a quick and dirty XLS sheet to check to see if the model makes sense. Of course, the XLS % are in fact bad as they are crude benchmarks.
Try estimating this model:
Y(T) = .53169E+06
+[X1(T)][(+ .13482E+06B** 1)] M_HALLOWEEN
+[X2(T)][(+ .17378E+06B**-3)] M_JULY4TH
+[X3(T)][(- .11556E+06)] M_MEMORIALDAY
+[X4(T)][(- .16706E+06B**-4+ .13960E+06B**-3- .15636E+06B**-2
- .19886E+06B**-1)] M_NEWYEARS
+[X5(T)][(+ .17023E+06B**-2- .26854E+06B**-1- .14257E+06B** 1)] M_THANKSGIVI
+[X6(T)][(- 71726. )] MONTH_EFF01
+[X7(T)][(+ 55617. )] MONTH_EFF02
+[X8(T)][(+ 27827. )] MONTH_EFF03
+[X9(T)][(- 37945. )] MONTH_EFF09
+[X10(T)[(- 23652. )] MONTH_EFF10
+[X11(T)[(- 33488. )] MONTH_EFF11
+[X12(T)[(+ 39389. )] FIXED_EFF_N10107
+[X13(T)[(+ 63399. )] FIXED_EFF_N10207
+[X14(T)[(+ .13727E+06)] FIXED_EFF_N10307
+[X15(T)[(+ .25144E+06)] FIXED_EFF_N10407
+[X16(T)[(+ .32004E+06)] FIXED_EFF_N10507
+[X17(T)[(+ .29156E+06)] FIXED_EFF_N10607
+[X18(T)[(+ 74960. )] FIXED_DAY02
+[X19(T)[(+ 39299. )] FIXED_DAY03
+[X20(T)[(+ 27660. )] FIXED_DAY05
+[X21(T)[(- 33451. )] FIXED_DAY21
+[X22(T)[(+ 43602. )] FIXED_DAY29
+[X23(T)[(+ 68016. )] FIXED_DAY30
+[X24(T)[(+ 226.98 )] :TIME TREND 1 1/ 1 1/ 3/2011 I~T00001__010311stack
+[X25(T)[(- 133.25 )] :TIME TREND 423 61/ 3 2/29/2012 I~T00423__010311stack
+[X26(T)[(+ 164.56 )] :TIME TREND 631 91/ 1 9/24/2012 I~T00631__010311stack
+[X27(T)[(- .42528E+06)] :SEASONAL PULSE 733 105/ 5 1/ 4/2013 I~S00733__010311stack
+[X28(T)[(- .33108E+06)] :SEASONAL PULSE 370 53/ 6 1/ 7/2012 I~S00370__010311stack
+[X29(T)[(- .82083E+06)] :PULSE 326 47/ 4 11/24/2011 I~P00326__010311stack
+[X30(T)[(+ .17502E+06)] :PULSE 394 57/ 2 1/31/2012 I~P00394__010311stack
+ + [A(T)] | Time Series Forecasting with Daily Data: ARIMA with regressor | You should be evaluating models and forecasts from different origins across different horizons and not one one number in order to gauge an approach.
I assume that your data is from the US. I prefer 3 | Time Series Forecasting with Daily Data: ARIMA with regressor
You should be evaluating models and forecasts from different origins across different horizons and not one one number in order to gauge an approach.
I assume that your data is from the US. I prefer 3+ years of daily data as you can have two holidays landing on a weekend and get no weekday read. It looks like your Thanksgiving impact is a day off in the 2012 or there was a recording error of some kind and caused the model to miss the Thanksgiving day effect.
Januarys are typically low in the dataset if you look as a % of the year. Weekends are high. The dummies reflect this behavior....MONTH_EFF01, FIXED_EFF_N10507,FIXED_EFF_N10607
I have found that using an AR component with daily data assumes that the last two weeks day of the week pattern is how the pattern is in general which is a big assumption. We started with 11 monthly dummies and 6 daily dummies. Some dropped out of the model. B**1 means that there is a lag impact the day after a holiday. There were 6 special days of the month (days 2,3,5,21,29,30----21 might be spurious?) and 3 time trends, 2 seasonal pulses (where a day of the week started deviating from the typical, a 0 before this data and a 1 every 7th day after) and 2 outliers (note the thanksgiving!) This took just under 7 minutes to run. Download all results here www.autobox.com/se/dd/daily.zip
It includes a quick and dirty XLS sheet to check to see if the model makes sense. Of course, the XLS % are in fact bad as they are crude benchmarks.
Try estimating this model:
Y(T) = .53169E+06
+[X1(T)][(+ .13482E+06B** 1)] M_HALLOWEEN
+[X2(T)][(+ .17378E+06B**-3)] M_JULY4TH
+[X3(T)][(- .11556E+06)] M_MEMORIALDAY
+[X4(T)][(- .16706E+06B**-4+ .13960E+06B**-3- .15636E+06B**-2
- .19886E+06B**-1)] M_NEWYEARS
+[X5(T)][(+ .17023E+06B**-2- .26854E+06B**-1- .14257E+06B** 1)] M_THANKSGIVI
+[X6(T)][(- 71726. )] MONTH_EFF01
+[X7(T)][(+ 55617. )] MONTH_EFF02
+[X8(T)][(+ 27827. )] MONTH_EFF03
+[X9(T)][(- 37945. )] MONTH_EFF09
+[X10(T)[(- 23652. )] MONTH_EFF10
+[X11(T)[(- 33488. )] MONTH_EFF11
+[X12(T)[(+ 39389. )] FIXED_EFF_N10107
+[X13(T)[(+ 63399. )] FIXED_EFF_N10207
+[X14(T)[(+ .13727E+06)] FIXED_EFF_N10307
+[X15(T)[(+ .25144E+06)] FIXED_EFF_N10407
+[X16(T)[(+ .32004E+06)] FIXED_EFF_N10507
+[X17(T)[(+ .29156E+06)] FIXED_EFF_N10607
+[X18(T)[(+ 74960. )] FIXED_DAY02
+[X19(T)[(+ 39299. )] FIXED_DAY03
+[X20(T)[(+ 27660. )] FIXED_DAY05
+[X21(T)[(- 33451. )] FIXED_DAY21
+[X22(T)[(+ 43602. )] FIXED_DAY29
+[X23(T)[(+ 68016. )] FIXED_DAY30
+[X24(T)[(+ 226.98 )] :TIME TREND 1 1/ 1 1/ 3/2011 I~T00001__010311stack
+[X25(T)[(- 133.25 )] :TIME TREND 423 61/ 3 2/29/2012 I~T00423__010311stack
+[X26(T)[(+ 164.56 )] :TIME TREND 631 91/ 1 9/24/2012 I~T00631__010311stack
+[X27(T)[(- .42528E+06)] :SEASONAL PULSE 733 105/ 5 1/ 4/2013 I~S00733__010311stack
+[X28(T)[(- .33108E+06)] :SEASONAL PULSE 370 53/ 6 1/ 7/2012 I~S00370__010311stack
+[X29(T)[(- .82083E+06)] :PULSE 326 47/ 4 11/24/2011 I~P00326__010311stack
+[X30(T)[(+ .17502E+06)] :PULSE 394 57/ 2 1/31/2012 I~P00394__010311stack
+ + [A(T)] | Time Series Forecasting with Daily Data: ARIMA with regressor
You should be evaluating models and forecasts from different origins across different horizons and not one one number in order to gauge an approach.
I assume that your data is from the US. I prefer 3 |
19,133 | Does the principle of indifference apply to the Borel-Kolmogorov paradox? | One one hand, we have a pre-theoretic, intuitive understanding of probability. On the other, we have Kolomogorov's formal axiomatization of probability.
The principle of indifference belongs to our intuitive understanding of probability. We feel that any formalization of probability should respect it. However, as you note, our formal theory of probability does not always do this, and the the Borel-Komogorov paradox is one of the cases where it doesn't.
So, here's what I think you're really asking: How do we resolve the conflict between this attractive intuitive principle and our modern measure-theoretic theory of probability?
One could side with our formal theory, as the other answer and the commenters do. They claim that, if you choose the limit to the equator in the Borel-Kolmogorov paradox in a certain way, the principle of indifference does not hold, and our intuitions are incorrect.
I find this unsatisfactory. I believe that if our formal theory does not capture this basic and obviously true intuition, then it is deficient. We should seek to modify the theory, not reject this basic principle.
Alan Hájek, a philosopher of probability, has taken this position, and he argues convincingly for it in this article. A longer article by him on conditional probability can be found here, where he also discusses some classic problems like the two envelopes paradox. | Does the principle of indifference apply to the Borel-Kolmogorov paradox? | One one hand, we have a pre-theoretic, intuitive understanding of probability. On the other, we have Kolomogorov's formal axiomatization of probability.
The principle of indifference belongs to our i | Does the principle of indifference apply to the Borel-Kolmogorov paradox?
One one hand, we have a pre-theoretic, intuitive understanding of probability. On the other, we have Kolomogorov's formal axiomatization of probability.
The principle of indifference belongs to our intuitive understanding of probability. We feel that any formalization of probability should respect it. However, as you note, our formal theory of probability does not always do this, and the the Borel-Komogorov paradox is one of the cases where it doesn't.
So, here's what I think you're really asking: How do we resolve the conflict between this attractive intuitive principle and our modern measure-theoretic theory of probability?
One could side with our formal theory, as the other answer and the commenters do. They claim that, if you choose the limit to the equator in the Borel-Kolmogorov paradox in a certain way, the principle of indifference does not hold, and our intuitions are incorrect.
I find this unsatisfactory. I believe that if our formal theory does not capture this basic and obviously true intuition, then it is deficient. We should seek to modify the theory, not reject this basic principle.
Alan Hájek, a philosopher of probability, has taken this position, and he argues convincingly for it in this article. A longer article by him on conditional probability can be found here, where he also discusses some classic problems like the two envelopes paradox. | Does the principle of indifference apply to the Borel-Kolmogorov paradox?
One one hand, we have a pre-theoretic, intuitive understanding of probability. On the other, we have Kolomogorov's formal axiomatization of probability.
The principle of indifference belongs to our i |
19,134 | Does the principle of indifference apply to the Borel-Kolmogorov paradox? | I don't see the point of the "principle of indifference". The Wikipedia article's answer is better: "Probabilities may not be well defined if the mechanism or method that produces the random variable is not clearly defined." In other words, without even restricting ourselves to questions of probability, "An ambiguously-posed question does not have a single unambiguous answer." | Does the principle of indifference apply to the Borel-Kolmogorov paradox? | I don't see the point of the "principle of indifference". The Wikipedia article's answer is better: "Probabilities may not be well defined if the mechanism or method that produces the random variabl | Does the principle of indifference apply to the Borel-Kolmogorov paradox?
I don't see the point of the "principle of indifference". The Wikipedia article's answer is better: "Probabilities may not be well defined if the mechanism or method that produces the random variable is not clearly defined." In other words, without even restricting ourselves to questions of probability, "An ambiguously-posed question does not have a single unambiguous answer." | Does the principle of indifference apply to the Borel-Kolmogorov paradox?
I don't see the point of the "principle of indifference". The Wikipedia article's answer is better: "Probabilities may not be well defined if the mechanism or method that produces the random variabl |
19,135 | How to test the effect of a grouping variable with a non-linear model? | You could stratify by the values of the categorical predictor and compare fits. For example suppose you have continuous predictors $X_{1}, ..., X_{p}$ and dependent variable $Y$. I believe nls() gives the maximum likelihood estimate of $f$ such that
$$ Y = f(X_1, ..., X_p) + \varepsilon $$
where $\varepsilon \sim N(0,\sigma^2)$ and $f$ is parameterized in some non-linear way (see the nls helpfile). Suppose you have a categorical predictor $B$ with $m$ levels and stratify the data based on the values of $B$ and fit the model within each strata. Since these are disjoint subsets of the data, the log-likelihood for the stratified model, $L_1$ is the sum of the likelihood within each strata, which can be extracted from an nls model using the logLik function (you can also get the log-likelihood from the unstratified model, $L_0$, using logLik).
The unstratified model is clearly a submodel of the stratified model, so the likelihood ratio test is appropriate to see whether the larger model is worth the added complexity - the test statistic is
$$ \lambda = 2(L_1-L_0)$$
If the categorical predictor truly has no effect, $\lambda$ has a $\chi^2$ distribution with degrees of freedom equal to $mp - p = p(m-1)$, where $p$ is the number of parameters underlying your non-linear regression function. You can use pchisq() to calculate $\chi^2$ p-values. | How to test the effect of a grouping variable with a non-linear model? | You could stratify by the values of the categorical predictor and compare fits. For example suppose you have continuous predictors $X_{1}, ..., X_{p}$ and dependent variable $Y$. I believe nls() gives | How to test the effect of a grouping variable with a non-linear model?
You could stratify by the values of the categorical predictor and compare fits. For example suppose you have continuous predictors $X_{1}, ..., X_{p}$ and dependent variable $Y$. I believe nls() gives the maximum likelihood estimate of $f$ such that
$$ Y = f(X_1, ..., X_p) + \varepsilon $$
where $\varepsilon \sim N(0,\sigma^2)$ and $f$ is parameterized in some non-linear way (see the nls helpfile). Suppose you have a categorical predictor $B$ with $m$ levels and stratify the data based on the values of $B$ and fit the model within each strata. Since these are disjoint subsets of the data, the log-likelihood for the stratified model, $L_1$ is the sum of the likelihood within each strata, which can be extracted from an nls model using the logLik function (you can also get the log-likelihood from the unstratified model, $L_0$, using logLik).
The unstratified model is clearly a submodel of the stratified model, so the likelihood ratio test is appropriate to see whether the larger model is worth the added complexity - the test statistic is
$$ \lambda = 2(L_1-L_0)$$
If the categorical predictor truly has no effect, $\lambda$ has a $\chi^2$ distribution with degrees of freedom equal to $mp - p = p(m-1)$, where $p$ is the number of parameters underlying your non-linear regression function. You can use pchisq() to calculate $\chi^2$ p-values. | How to test the effect of a grouping variable with a non-linear model?
You could stratify by the values of the categorical predictor and compare fits. For example suppose you have continuous predictors $X_{1}, ..., X_{p}$ and dependent variable $Y$. I believe nls() gives |
19,136 | How to test the effect of a grouping variable with a non-linear model? | I found that it is possible to code categorical variables with nls(), simply by multiplying true/false vectors into your equation. Example:
# null model (no difference between groups; all have the same coefficients)
nls.null <- nls(formula = percent_on_cells ~ vmax*(Time/(Time+km)),
data = mehg,
start = list(vmax = 0.6, km = 10))
# alternative model (each group has different coefficients)
nls.alt <- nls(formula = percent_on_cells ~
as.numeric(DOC==0)*(vmax1)*(Time/(Time+(km1)))
+ as.numeric(DOC==1)*(vmax2)*(Time/(Time+(km2)))
+ as.numeric(DOC==10)*(vmax3)*(Time/(Time+(km3)))
+ as.numeric(DOC==100)*(vmax4)*(Time/(Time+(km4))),
data = mehg,
start = list(vmax1=0.63, km1=3.6,
vmax2=0.64, km2=3.6,
vmax3=0.50, km3=3.2,
vmax4= 0.40, km4=9.7)) | How to test the effect of a grouping variable with a non-linear model? | I found that it is possible to code categorical variables with nls(), simply by multiplying true/false vectors into your equation. Example:
# null model (no difference between groups; all have the sam | How to test the effect of a grouping variable with a non-linear model?
I found that it is possible to code categorical variables with nls(), simply by multiplying true/false vectors into your equation. Example:
# null model (no difference between groups; all have the same coefficients)
nls.null <- nls(formula = percent_on_cells ~ vmax*(Time/(Time+km)),
data = mehg,
start = list(vmax = 0.6, km = 10))
# alternative model (each group has different coefficients)
nls.alt <- nls(formula = percent_on_cells ~
as.numeric(DOC==0)*(vmax1)*(Time/(Time+(km1)))
+ as.numeric(DOC==1)*(vmax2)*(Time/(Time+(km2)))
+ as.numeric(DOC==10)*(vmax3)*(Time/(Time+(km3)))
+ as.numeric(DOC==100)*(vmax4)*(Time/(Time+(km4))),
data = mehg,
start = list(vmax1=0.63, km1=3.6,
vmax2=0.64, km2=3.6,
vmax3=0.50, km3=3.2,
vmax4= 0.40, km4=9.7)) | How to test the effect of a grouping variable with a non-linear model?
I found that it is possible to code categorical variables with nls(), simply by multiplying true/false vectors into your equation. Example:
# null model (no difference between groups; all have the sam |
19,137 | How to do cross-validation with a Cox proportional hazards model? | An ROC curve is not useful in this setting, although the generalized ROC area (c-index, which does not require any dichotomization at all) is. The R rms package will compute the c-index and cross-validated or bootstrap overfitting-corrected versions of it. You can do this without holding back any data if you fully pre-specify the model or repeat a backwards stepdown algorithm at each resample. If you truly want to do external validation, i.e., if your validation sample is enormous, you can use the following rms functions: rcorr.cens, val.surv. | How to do cross-validation with a Cox proportional hazards model? | An ROC curve is not useful in this setting, although the generalized ROC area (c-index, which does not require any dichotomization at all) is. The R rms package will compute the c-index and cross-val | How to do cross-validation with a Cox proportional hazards model?
An ROC curve is not useful in this setting, although the generalized ROC area (c-index, which does not require any dichotomization at all) is. The R rms package will compute the c-index and cross-validated or bootstrap overfitting-corrected versions of it. You can do this without holding back any data if you fully pre-specify the model or repeat a backwards stepdown algorithm at each resample. If you truly want to do external validation, i.e., if your validation sample is enormous, you can use the following rms functions: rcorr.cens, val.surv. | How to do cross-validation with a Cox proportional hazards model?
An ROC curve is not useful in this setting, although the generalized ROC area (c-index, which does not require any dichotomization at all) is. The R rms package will compute the c-index and cross-val |
19,138 | How to do cross-validation with a Cox proportional hazards model? | I know that this question is pretty old but what I have done when I encountered the same problem was to use the predict function to get a "score" for each subject in the validation set. This was followed by splitting the subjects according to whether the score was higher or lower than than median and plotting the Kaplan-Meier curve. This should show a separation of the subjects if your model is predictive. I also tested the correlation of score (actually of its ln [for normal distribution]) with survival using the coxph function from the survival package in R. | How to do cross-validation with a Cox proportional hazards model? | I know that this question is pretty old but what I have done when I encountered the same problem was to use the predict function to get a "score" for each subject in the validation set. This was follo | How to do cross-validation with a Cox proportional hazards model?
I know that this question is pretty old but what I have done when I encountered the same problem was to use the predict function to get a "score" for each subject in the validation set. This was followed by splitting the subjects according to whether the score was higher or lower than than median and plotting the Kaplan-Meier curve. This should show a separation of the subjects if your model is predictive. I also tested the correlation of score (actually of its ln [for normal distribution]) with survival using the coxph function from the survival package in R. | How to do cross-validation with a Cox proportional hazards model?
I know that this question is pretty old but what I have done when I encountered the same problem was to use the predict function to get a "score" for each subject in the validation set. This was follo |
19,139 | Optimal penalty selection for lasso | Checkout Theorem 5.1 of this Bickel et al.. A statistically optimal choice in terms of the error $\|y-\hat{y}(\lambda)\|_2^2$ is $\lambda = A \sigma_{\text{noise}} \sqrt{\dfrac{\log p}{n}}$ (with high probability), for a constant $A > 2\sqrt{2}$. | Optimal penalty selection for lasso | Checkout Theorem 5.1 of this Bickel et al.. A statistically optimal choice in terms of the error $\|y-\hat{y}(\lambda)\|_2^2$ is $\lambda = A \sigma_{\text{noise}} \sqrt{\dfrac{\log p}{n}}$ (with high | Optimal penalty selection for lasso
Checkout Theorem 5.1 of this Bickel et al.. A statistically optimal choice in terms of the error $\|y-\hat{y}(\lambda)\|_2^2$ is $\lambda = A \sigma_{\text{noise}} \sqrt{\dfrac{\log p}{n}}$ (with high probability), for a constant $A > 2\sqrt{2}$. | Optimal penalty selection for lasso
Checkout Theorem 5.1 of this Bickel et al.. A statistically optimal choice in terms of the error $\|y-\hat{y}(\lambda)\|_2^2$ is $\lambda = A \sigma_{\text{noise}} \sqrt{\dfrac{\log p}{n}}$ (with high |
19,140 | Optimal penalty selection for lasso | I take it that you are mostly interested in regression, as in the cited paper, and not other applications of the $\ell_1$-penalty (graphical lasso, say).
I then believe that some answers can be found in the paper On the “degrees of freedom” of the lasso by Zou et al. Briefly, it gives an analytic formula for the effective degrees of freedom, which for the squared error loss allows you to replace CV by an analytic $C_p$-type statistic, say.
Another place to look is in The Dantzig selector: Statistical estimation when p is much larger than n and the discussion papers in the same issue of Annals of Statistics. My understanding is that they solve a problem closely related to lasso regression but with a fixed choice of penalty coefficient. But please take a look at the discussion papers too.
If you are not interested in prediction, but in model selection, I am not aware of similar results. Prediction optimal models often result in too many selected variables in regression models. In the paper Stability selection Meinshausen and Bühlmann presents a subsampling technique more useful for model selection, but it may be too computationally demanding for your needs. | Optimal penalty selection for lasso | I take it that you are mostly interested in regression, as in the cited paper, and not other applications of the $\ell_1$-penalty (graphical lasso, say).
I then believe that some answers can be found | Optimal penalty selection for lasso
I take it that you are mostly interested in regression, as in the cited paper, and not other applications of the $\ell_1$-penalty (graphical lasso, say).
I then believe that some answers can be found in the paper On the “degrees of freedom” of the lasso by Zou et al. Briefly, it gives an analytic formula for the effective degrees of freedom, which for the squared error loss allows you to replace CV by an analytic $C_p$-type statistic, say.
Another place to look is in The Dantzig selector: Statistical estimation when p is much larger than n and the discussion papers in the same issue of Annals of Statistics. My understanding is that they solve a problem closely related to lasso regression but with a fixed choice of penalty coefficient. But please take a look at the discussion papers too.
If you are not interested in prediction, but in model selection, I am not aware of similar results. Prediction optimal models often result in too many selected variables in regression models. In the paper Stability selection Meinshausen and Bühlmann presents a subsampling technique more useful for model selection, but it may be too computationally demanding for your needs. | Optimal penalty selection for lasso
I take it that you are mostly interested in regression, as in the cited paper, and not other applications of the $\ell_1$-penalty (graphical lasso, say).
I then believe that some answers can be found |
19,141 | Optimal penalty selection for lasso | Since this question has been asked, interesting progress has been made. For instance, consider this paper
Chichignoud, M., Lederer, J., & Wainwright, M. (2016). A Practical Scheme and Fast Algorithm to Tune the Lasso With Optimality Guarantees. Journal of Machine Learning Research, 17, 1–17.
They propose a method to select the LASSO tuning parameter with provable finite sample guarantees for model selection. As they say in the paper, "For standard calibration schemes, among them Cross-Validation, no comparable guarantees are available in the literature. In fact, we are not aware of any finite sample guarantees for standard calibration schemes". | Optimal penalty selection for lasso | Since this question has been asked, interesting progress has been made. For instance, consider this paper
Chichignoud, M., Lederer, J., & Wainwright, M. (2016). A Practical Scheme and Fast Algorithm | Optimal penalty selection for lasso
Since this question has been asked, interesting progress has been made. For instance, consider this paper
Chichignoud, M., Lederer, J., & Wainwright, M. (2016). A Practical Scheme and Fast Algorithm to Tune the Lasso With Optimality Guarantees. Journal of Machine Learning Research, 17, 1–17.
They propose a method to select the LASSO tuning parameter with provable finite sample guarantees for model selection. As they say in the paper, "For standard calibration schemes, among them Cross-Validation, no comparable guarantees are available in the literature. In fact, we are not aware of any finite sample guarantees for standard calibration schemes". | Optimal penalty selection for lasso
Since this question has been asked, interesting progress has been made. For instance, consider this paper
Chichignoud, M., Lederer, J., & Wainwright, M. (2016). A Practical Scheme and Fast Algorithm |
19,142 | Optimal penalty selection for lasso | This does not answer your question, but: in a large data setting, it may be fine to tune the regularizer using a single train/test split, instead of doing it 10 or so times in cross-validation (or more for bootstrap). The size and representativeness of the sample chosen for the devset determines the accuracy of the estimation of the optimal regularizer.
In my experience the held-out loss is relatively flat over a substantial regularizer range. I'm sure this fact may not hold for other problems. | Optimal penalty selection for lasso | This does not answer your question, but: in a large data setting, it may be fine to tune the regularizer using a single train/test split, instead of doing it 10 or so times in cross-validation (or mor | Optimal penalty selection for lasso
This does not answer your question, but: in a large data setting, it may be fine to tune the regularizer using a single train/test split, instead of doing it 10 or so times in cross-validation (or more for bootstrap). The size and representativeness of the sample chosen for the devset determines the accuracy of the estimation of the optimal regularizer.
In my experience the held-out loss is relatively flat over a substantial regularizer range. I'm sure this fact may not hold for other problems. | Optimal penalty selection for lasso
This does not answer your question, but: in a large data setting, it may be fine to tune the regularizer using a single train/test split, instead of doing it 10 or so times in cross-validation (or mor |
19,143 | If we shouldn't do post hoc power calculations, are post hoc effect size calculations also invalid? | The problem is in the use of the "post-hoc effect size," not that its calculation is invalid. A "post-hoc effect size" is fundamentally an estimate of population parameters (e.g., mean difference between two groups and a standard deviation, not a standard error!) whose precisions might be affected by study design but aren't otherwise determined by study design. After all, using a "post-hoc effect-size" estimate from a pilot study to design a definitive study is good practice.
One problem, addressed in many threads here as you note, is that a post-hoc power calculation based on the "post-hoc effect size" is meaningless. As Russ Lenth puts it so simply:
You’ve got the data, did the analysis, and did not achieve “significance.” So you compute power retrospectively to see if the test was powerful enough or not. This is an empty question. Of course it wasn’t powerful enough – that’s why the result isn’t significant. Power calculations are useful for design, not analysis.
In your example, there is similarly no error in calculating the "post-hoc effect size." The error is in your clients' trying to use that "post-hoc effect size" to reverse-engineer an "insignificant" null-hypothesis test into a post-hoc equivalence test. Null-hypothesis tests and equivalence tests are fundamentally different. Attempts at post-hoc equivalence tests aren't just meaningless; they are misleading. This page provides more details and a literature reference. In particular, Walker and Nowacki emphasize:
The determination of the equivalence margin, $\delta$, is the most critical step in equivalence/noninferiority testing... the value of the equivalence margin should be determined before the data is recorded. This is essential to maintain the type I error at the desired level...
Using a traditional comparative test to establish equivalence/noninferiority leads frequently to incorrect conclusions. The reason is two-fold. First, the burden of the proof is on the wrong hypothesis, i.e., that of a difference... the risk of incorrectly concluding equivalence can be very high. The other reason is that the margin of equivalence is not considered, and thus the concept of equivalence is not well defined.
As always, proper specification of the question should precede the study design and data analysis. Changing the hypothesis after the results are obtained is the problem. | If we shouldn't do post hoc power calculations, are post hoc effect size calculations also invalid? | The problem is in the use of the "post-hoc effect size," not that its calculation is invalid. A "post-hoc effect size" is fundamentally an estimate of population parameters (e.g., mean difference betw | If we shouldn't do post hoc power calculations, are post hoc effect size calculations also invalid?
The problem is in the use of the "post-hoc effect size," not that its calculation is invalid. A "post-hoc effect size" is fundamentally an estimate of population parameters (e.g., mean difference between two groups and a standard deviation, not a standard error!) whose precisions might be affected by study design but aren't otherwise determined by study design. After all, using a "post-hoc effect-size" estimate from a pilot study to design a definitive study is good practice.
One problem, addressed in many threads here as you note, is that a post-hoc power calculation based on the "post-hoc effect size" is meaningless. As Russ Lenth puts it so simply:
You’ve got the data, did the analysis, and did not achieve “significance.” So you compute power retrospectively to see if the test was powerful enough or not. This is an empty question. Of course it wasn’t powerful enough – that’s why the result isn’t significant. Power calculations are useful for design, not analysis.
In your example, there is similarly no error in calculating the "post-hoc effect size." The error is in your clients' trying to use that "post-hoc effect size" to reverse-engineer an "insignificant" null-hypothesis test into a post-hoc equivalence test. Null-hypothesis tests and equivalence tests are fundamentally different. Attempts at post-hoc equivalence tests aren't just meaningless; they are misleading. This page provides more details and a literature reference. In particular, Walker and Nowacki emphasize:
The determination of the equivalence margin, $\delta$, is the most critical step in equivalence/noninferiority testing... the value of the equivalence margin should be determined before the data is recorded. This is essential to maintain the type I error at the desired level...
Using a traditional comparative test to establish equivalence/noninferiority leads frequently to incorrect conclusions. The reason is two-fold. First, the burden of the proof is on the wrong hypothesis, i.e., that of a difference... the risk of incorrectly concluding equivalence can be very high. The other reason is that the margin of equivalence is not considered, and thus the concept of equivalence is not well defined.
As always, proper specification of the question should precede the study design and data analysis. Changing the hypothesis after the results are obtained is the problem. | If we shouldn't do post hoc power calculations, are post hoc effect size calculations also invalid?
The problem is in the use of the "post-hoc effect size," not that its calculation is invalid. A "post-hoc effect size" is fundamentally an estimate of population parameters (e.g., mean difference betw |
19,144 | L2 Regularization Constant | You are absolutely right in your observation that the number of parameters will affect the regularization cost.
I don't think there are any rule-of-thumb values for $\lambda$ (but $\lambda=1$ would be considered large). If cross-validation is too time-consuming, you could hold-out a part of the training data and tune $\lambda$ using early stopping. You would still need to try several values for $\lambda$ common practice is to try something like $0.01, 0.02,\ldots,0.4$.
For really large networks, it might be more convenient to use other regularization methods, like dropout, instead of $\ell_2$ regularization. | L2 Regularization Constant | You are absolutely right in your observation that the number of parameters will affect the regularization cost.
I don't think there are any rule-of-thumb values for $\lambda$ (but $\lambda=1$ would b | L2 Regularization Constant
You are absolutely right in your observation that the number of parameters will affect the regularization cost.
I don't think there are any rule-of-thumb values for $\lambda$ (but $\lambda=1$ would be considered large). If cross-validation is too time-consuming, you could hold-out a part of the training data and tune $\lambda$ using early stopping. You would still need to try several values for $\lambda$ common practice is to try something like $0.01, 0.02,\ldots,0.4$.
For really large networks, it might be more convenient to use other regularization methods, like dropout, instead of $\ell_2$ regularization. | L2 Regularization Constant
You are absolutely right in your observation that the number of parameters will affect the regularization cost.
I don't think there are any rule-of-thumb values for $\lambda$ (but $\lambda=1$ would b |
19,145 | L2 Regularization Constant | You should not care for the final loss but rather about its derivative. Each parameter's derivative with regards to the loss will see its derivative corrected by the regularisation but this term won't affect the backprop.
So overall the loss will be huge but only the error part (that does not really scale up with the number of parameters) will affect the backprop. | L2 Regularization Constant | You should not care for the final loss but rather about its derivative. Each parameter's derivative with regards to the loss will see its derivative corrected by the regularisation but this term won't | L2 Regularization Constant
You should not care for the final loss but rather about its derivative. Each parameter's derivative with regards to the loss will see its derivative corrected by the regularisation but this term won't affect the backprop.
So overall the loss will be huge but only the error part (that does not really scale up with the number of parameters) will affect the backprop. | L2 Regularization Constant
You should not care for the final loss but rather about its derivative. Each parameter's derivative with regards to the loss will see its derivative corrected by the regularisation but this term won't |
19,146 | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that? | You asked "What more can I do to induce stationarity?" If a series exhibits a level shift (symptom) then this is an example of non-stationarity. The correct remedy is to "de-mean" the data not to difference it. Additionally a series may exhibit a change in deterministic trend or a seasonal pulse which can be rectified by Intervention Detection schemes. If the series has a change in parameters over time (symptom) the correct remedy is to find the break points via a Chow Test and to use the most recent set or some form of threshold model (TAR). If a series has a change in error variance over time (symptom) the correct remedy might be WLS a form of GLS or some form of power transform or failing those relatively simple remedies some form of GARCH model.
If you post your original data I might be able to help more. | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that? | You asked "What more can I do to induce stationarity?" If a series exhibits a level shift (symptom) then this is an example of non-stationarity. The correct remedy is to "de-mean" the data not to diff | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that?
You asked "What more can I do to induce stationarity?" If a series exhibits a level shift (symptom) then this is an example of non-stationarity. The correct remedy is to "de-mean" the data not to difference it. Additionally a series may exhibit a change in deterministic trend or a seasonal pulse which can be rectified by Intervention Detection schemes. If the series has a change in parameters over time (symptom) the correct remedy is to find the break points via a Chow Test and to use the most recent set or some form of threshold model (TAR). If a series has a change in error variance over time (symptom) the correct remedy might be WLS a form of GLS or some form of power transform or failing those relatively simple remedies some form of GARCH model.
If you post your original data I might be able to help more. | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that?
You asked "What more can I do to induce stationarity?" If a series exhibits a level shift (symptom) then this is an example of non-stationarity. The correct remedy is to "de-mean" the data not to diff |
19,147 | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that? | Read carefully: it doesn't say that the time series is not stationary. It says that the initial coefficients are not stationary (which I presume means they don't describe a stationary process).
You could try putting in your own guess for starting values, as it suggests. But I suspect that it's choosing bad starting values in the first place because the model is mis-specified. If you already differenced the time series, you probably don't also want to specify integration order 1. You probably mean order=(2, 0, 2), not order=(2, 1, 2). | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that? | Read carefully: it doesn't say that the time series is not stationary. It says that the initial coefficients are not stationary (which I presume means they don't describe a stationary process).
You co | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that?
Read carefully: it doesn't say that the time series is not stationary. It says that the initial coefficients are not stationary (which I presume means they don't describe a stationary process).
You could try putting in your own guess for starting values, as it suggests. But I suspect that it's choosing bad starting values in the first place because the model is mis-specified. If you already differenced the time series, you probably don't also want to specify integration order 1. You probably mean order=(2, 0, 2), not order=(2, 1, 2). | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that?
Read carefully: it doesn't say that the time series is not stationary. It says that the initial coefficients are not stationary (which I presume means they don't describe a stationary process).
You co |
19,148 | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that? | In a time series signal, stationarity can be introduced by using windowing. You can break your single time series signal into smaller signals using good window technique with overlap. Windowing is required to avoid spurious peaks in the frequency domain and overlap is required to conserve signal energy.
Typically a speech signal (8KHz sampling frequency) has 30 msec frames giving 240 samples per frame. This is convoluted using a hamming window with 50% overlap. | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that? | In a time series signal, stationarity can be introduced by using windowing. You can break your single time series signal into smaller signals using good window technique with overlap. Windowing is req | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that?
In a time series signal, stationarity can be introduced by using windowing. You can break your single time series signal into smaller signals using good window technique with overlap. Windowing is required to avoid spurious peaks in the frequency domain and overlap is required to conserve signal energy.
Typically a speech signal (8KHz sampling frequency) has 30 msec frames giving 240 samples per frame. This is convoluted using a hamming window with 50% overlap. | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that?
In a time series signal, stationarity can be introduced by using windowing. You can break your single time series signal into smaller signals using good window technique with overlap. Windowing is req |
19,149 | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that? | The differenced time series is not stationary since it does not have a constant variance.
You could try a logarithmic differentiation. | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that? | The differenced time series is not stationary since it does not have a constant variance.
You could try a logarithmic differentiation. | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that?
The differenced time series is not stationary since it does not have a constant variance.
You could try a logarithmic differentiation. | Statsmodels says ARIMA is not appropriate because series is not stationary, how is it testing that?
The differenced time series is not stationary since it does not have a constant variance.
You could try a logarithmic differentiation. |
19,150 | Model assumptions of partial least squares (PLS) regression | When we say that the standard OLS regression has some assumptions, we mean that these assumptions are needed to derive some desirable properties of the OLS estimator such as e.g. that it is the best linear unbiased estimator -- see Gauss-Markov theorem and an excellent answer by @mpiktas in What is a complete list of the usual assumptions for linear regression? No assumptions are needed in order to simply regress $y$ on $X$. Assumptions only appear in the context of optimality statements.
More generally, "assumptions" is something that only a theoretical result (theorem) can have.
Similarly for PLS regression. It is always possible to use PLS regression to regress $y$ on $X$. So when you ask what are the assumptions of PLS regression, what are the optimality statements that you think about? In fact, I am not aware of any. PLS regression is one form of shrinkage regularization, see my answer in Theory behind partial least squares regression for some context and overview. Regularized estimators are biased, so no amount of assumptions will e.g. prove the unbiasedness.
Moreover, the actual outcome of PLS regression depends on how many PLS components are included in the model, which acts as a regularization parameter. Talking about any assumptions only makes sense if the procedure for selecting this parameter is completely specified (and it usually isn't). So I don't think there are any optimality results for PLS at all, which means that PLS regression has no assumptions. I think the same is true for any other penalized regression methods such as principal component regression or ridge regression.
Update: I have expanded this argument in my answer to What are the assumptions of ridge regression and how to test them?
Of course, there can still be rules of thumb that say when PLS regression is likely to be useful and when not. Please see my answer linked above for some discussion; experienced practitioners of PLSR (I am not one of them) could certainly say more to that. | Model assumptions of partial least squares (PLS) regression | When we say that the standard OLS regression has some assumptions, we mean that these assumptions are needed to derive some desirable properties of the OLS estimator such as e.g. that it is the best l | Model assumptions of partial least squares (PLS) regression
When we say that the standard OLS regression has some assumptions, we mean that these assumptions are needed to derive some desirable properties of the OLS estimator such as e.g. that it is the best linear unbiased estimator -- see Gauss-Markov theorem and an excellent answer by @mpiktas in What is a complete list of the usual assumptions for linear regression? No assumptions are needed in order to simply regress $y$ on $X$. Assumptions only appear in the context of optimality statements.
More generally, "assumptions" is something that only a theoretical result (theorem) can have.
Similarly for PLS regression. It is always possible to use PLS regression to regress $y$ on $X$. So when you ask what are the assumptions of PLS regression, what are the optimality statements that you think about? In fact, I am not aware of any. PLS regression is one form of shrinkage regularization, see my answer in Theory behind partial least squares regression for some context and overview. Regularized estimators are biased, so no amount of assumptions will e.g. prove the unbiasedness.
Moreover, the actual outcome of PLS regression depends on how many PLS components are included in the model, which acts as a regularization parameter. Talking about any assumptions only makes sense if the procedure for selecting this parameter is completely specified (and it usually isn't). So I don't think there are any optimality results for PLS at all, which means that PLS regression has no assumptions. I think the same is true for any other penalized regression methods such as principal component regression or ridge regression.
Update: I have expanded this argument in my answer to What are the assumptions of ridge regression and how to test them?
Of course, there can still be rules of thumb that say when PLS regression is likely to be useful and when not. Please see my answer linked above for some discussion; experienced practitioners of PLSR (I am not one of them) could certainly say more to that. | Model assumptions of partial least squares (PLS) regression
When we say that the standard OLS regression has some assumptions, we mean that these assumptions are needed to derive some desirable properties of the OLS estimator such as e.g. that it is the best l |
19,151 | Model assumptions of partial least squares (PLS) regression | Apparently, PLS does not make "hard" assumptions about the joint distribution of your variables. This means you have to be careful to choose appropriate test statistics (I assume this lack of dependence on variable distributions classifies PLS as a non-parametric technique). Suggestions I found for appropriate statistics are 1) using r-squared for dependent latent variables and 2) resampling methods for assessing stability of estimates.
The main difference between OLS/MLS and PLS is the former typically uses maximum likelihood estimation of population parameters to predict relationships between variables, while PLS estimates values of variables for the true population to predict relationships between groups of variables (by associating groups of predictor/response variables with latent variables).
I'm also interested in handling replicated/repeated experiments, specifically multifactorial ones, however I'm not sure how to approach this using PLS.
Handbook of Partial Least Squares: Concepts, Methods and Applications (page 659, section 28.4)
Wold, H. 2006. Predictor Specification. Encyclopedia of Statistical Sciences. 9.
http://www.rug.nl/staff/t.k.dijkstra/latentvariablesandindices.pdf (pages 4 & 5) | Model assumptions of partial least squares (PLS) regression | Apparently, PLS does not make "hard" assumptions about the joint distribution of your variables. This means you have to be careful to choose appropriate test statistics (I assume this lack of dependen | Model assumptions of partial least squares (PLS) regression
Apparently, PLS does not make "hard" assumptions about the joint distribution of your variables. This means you have to be careful to choose appropriate test statistics (I assume this lack of dependence on variable distributions classifies PLS as a non-parametric technique). Suggestions I found for appropriate statistics are 1) using r-squared for dependent latent variables and 2) resampling methods for assessing stability of estimates.
The main difference between OLS/MLS and PLS is the former typically uses maximum likelihood estimation of population parameters to predict relationships between variables, while PLS estimates values of variables for the true population to predict relationships between groups of variables (by associating groups of predictor/response variables with latent variables).
I'm also interested in handling replicated/repeated experiments, specifically multifactorial ones, however I'm not sure how to approach this using PLS.
Handbook of Partial Least Squares: Concepts, Methods and Applications (page 659, section 28.4)
Wold, H. 2006. Predictor Specification. Encyclopedia of Statistical Sciences. 9.
http://www.rug.nl/staff/t.k.dijkstra/latentvariablesandindices.pdf (pages 4 & 5) | Model assumptions of partial least squares (PLS) regression
Apparently, PLS does not make "hard" assumptions about the joint distribution of your variables. This means you have to be careful to choose appropriate test statistics (I assume this lack of dependen |
19,152 | Model assumptions of partial least squares (PLS) regression | I found a simulation study concerning the influence of non-normality and small sample size in PLS; the authors conclude: "All three techniques [PLS included] were remarkably robust against moderate departures from normality, and equally so."
However, for qualification: "It appears that all three techniques are fairly robust to small to moderate skew or kurtosis (up to skew = 1.1 and kurtosis = 1.6). However, with more extremely skewed data (skew = 1.8 and kurtosis = 3.8), all three techniques suffer a substantial and statistically significant loss of power for both n = 40 and n = 90 (the two sample sizes we tested). For example with n = 90 and medium effect size, regression's power is 76% with normal data, but drops to 53% for extremely skewed data. Under the same conditions PLS's power drops from 75% to 48%, while LISREL drops from 79% to 50%."
(Personally, I would consider those quite modest departures from normality with pretty steep decrements in power.)
Citation: Dale L. Goodhue, William Lewis, and Ron Thompson. Does PLS Have Advantages for Small Sample Size or Non-Normal Data? MIS Quarterly 2012; 36 (3): 891-1001. | Model assumptions of partial least squares (PLS) regression | I found a simulation study concerning the influence of non-normality and small sample size in PLS; the authors conclude: "All three techniques [PLS included] were remarkably robust against moderate de | Model assumptions of partial least squares (PLS) regression
I found a simulation study concerning the influence of non-normality and small sample size in PLS; the authors conclude: "All three techniques [PLS included] were remarkably robust against moderate departures from normality, and equally so."
However, for qualification: "It appears that all three techniques are fairly robust to small to moderate skew or kurtosis (up to skew = 1.1 and kurtosis = 1.6). However, with more extremely skewed data (skew = 1.8 and kurtosis = 3.8), all three techniques suffer a substantial and statistically significant loss of power for both n = 40 and n = 90 (the two sample sizes we tested). For example with n = 90 and medium effect size, regression's power is 76% with normal data, but drops to 53% for extremely skewed data. Under the same conditions PLS's power drops from 75% to 48%, while LISREL drops from 79% to 50%."
(Personally, I would consider those quite modest departures from normality with pretty steep decrements in power.)
Citation: Dale L. Goodhue, William Lewis, and Ron Thompson. Does PLS Have Advantages for Small Sample Size or Non-Normal Data? MIS Quarterly 2012; 36 (3): 891-1001. | Model assumptions of partial least squares (PLS) regression
I found a simulation study concerning the influence of non-normality and small sample size in PLS; the authors conclude: "All three techniques [PLS included] were remarkably robust against moderate de |
19,153 | Is there an intuitive characterization of distance correlation? | This my answer doesn't answer the question correctly. Please read the comments.
Let us compare usual covariance and distance covariance. The effective part of both are their numerators. (Denominators are simply averaging.) The numerator of covariance is the summed cross-product (= scalar product) of deviations from one point, the mean: $\Sigma (x_i-\mu^x)(y_i-\mu^y)$ (with superscripted $\mu$ as that centroid). To rewrite the expression in this style: $\Sigma d_{i\mu}^x d_{i\mu}^y$, with $d$ standing for the deviation of point $i$ from the centroid, i.e. its (signed) distance to the centroid. The covariance is defined by the sum of the products of the two distances over all points.
How things are with distance covariance? The numerator is, as you know, $\Sigma d_{ij}^x d_{ij}^y$. Isn't it very much like what we've written above? And what is the difference? Here, distance $d$ is between varying data points, not between a data point and the mean as above. The distance covariance is defined by the sum of the products of the two distances over all pairs of points.
Scalar product (between two entities - in our case, variables $x$ and $y$) based on co-distance from one fixed point is maximized when the data are arranged along one straight line. Scalar product based on co-distance from a var*i*able point is maximized when the data are arranged along a straight line locally, piecewisely; in other words, when the data overall represent chain of any shape, dependency of any shape.
And indeed, usual covariance is bigger when the relationship is closer to be perfect linear and variances are bigger. If you standardize the variances to a fixed unit, the covariance depends only on the strength of linear association, and it is then called Pearson correlation. And, as we know - and just have got some intuition why - distance covariance is bigger when the relationship is closer to be perfect curve and data spreads are bigger. If you standardize the spreads to a fixed unit, the covariance depends only on the strength of some curvilinear association, and it is then called Brownian (distance) correlation. | Is there an intuitive characterization of distance correlation? | This my answer doesn't answer the question correctly. Please read the comments.
Let us compare usual covariance and distance covariance. The effective part of both are their numerators. (Denominators | Is there an intuitive characterization of distance correlation?
This my answer doesn't answer the question correctly. Please read the comments.
Let us compare usual covariance and distance covariance. The effective part of both are their numerators. (Denominators are simply averaging.) The numerator of covariance is the summed cross-product (= scalar product) of deviations from one point, the mean: $\Sigma (x_i-\mu^x)(y_i-\mu^y)$ (with superscripted $\mu$ as that centroid). To rewrite the expression in this style: $\Sigma d_{i\mu}^x d_{i\mu}^y$, with $d$ standing for the deviation of point $i$ from the centroid, i.e. its (signed) distance to the centroid. The covariance is defined by the sum of the products of the two distances over all points.
How things are with distance covariance? The numerator is, as you know, $\Sigma d_{ij}^x d_{ij}^y$. Isn't it very much like what we've written above? And what is the difference? Here, distance $d$ is between varying data points, not between a data point and the mean as above. The distance covariance is defined by the sum of the products of the two distances over all pairs of points.
Scalar product (between two entities - in our case, variables $x$ and $y$) based on co-distance from one fixed point is maximized when the data are arranged along one straight line. Scalar product based on co-distance from a var*i*able point is maximized when the data are arranged along a straight line locally, piecewisely; in other words, when the data overall represent chain of any shape, dependency of any shape.
And indeed, usual covariance is bigger when the relationship is closer to be perfect linear and variances are bigger. If you standardize the variances to a fixed unit, the covariance depends only on the strength of linear association, and it is then called Pearson correlation. And, as we know - and just have got some intuition why - distance covariance is bigger when the relationship is closer to be perfect curve and data spreads are bigger. If you standardize the spreads to a fixed unit, the covariance depends only on the strength of some curvilinear association, and it is then called Brownian (distance) correlation. | Is there an intuitive characterization of distance correlation?
This my answer doesn't answer the question correctly. Please read the comments.
Let us compare usual covariance and distance covariance. The effective part of both are their numerators. (Denominators |
19,154 | Likelihood ratio test - lmer R - Non-nested models | This is not correct in two ways:
(Ordinary) likelihood ratio test can only be used to compare nested models;
We cannot compare mean models under REML. (This is not the case here, see @KarlOveHufthammer's comments below.)
In the case of using ML, I am aware of using AIC or BIC to compare the non-nested models. | Likelihood ratio test - lmer R - Non-nested models | This is not correct in two ways:
(Ordinary) likelihood ratio test can only be used to compare nested models;
We cannot compare mean models under REML. (This is not the case here, see @KarlOveHufthamm | Likelihood ratio test - lmer R - Non-nested models
This is not correct in two ways:
(Ordinary) likelihood ratio test can only be used to compare nested models;
We cannot compare mean models under REML. (This is not the case here, see @KarlOveHufthammer's comments below.)
In the case of using ML, I am aware of using AIC or BIC to compare the non-nested models. | Likelihood ratio test - lmer R - Non-nested models
This is not correct in two ways:
(Ordinary) likelihood ratio test can only be used to compare nested models;
We cannot compare mean models under REML. (This is not the case here, see @KarlOveHufthamm |
19,155 | Large sample asymptotic/theory - Why to care about? | Better late than never. Let me first list three (I think important) reasons why we focus on asymptotic unbiasedness (consistency) of estimators.
a) Consistency is a minimum criterion. If an estimator doesn't correctly estimate even with lots of data, then what good is it? This is the justification given in Wooldridge: Introductory Econometrics.
b) Finite sample properties are much harder to prove (or rather, asymptotic statements are easier). I am currently doing some research myself, and whenever you can rely on large sample tools, things get much easier. Laws of large numbers, martingale convergence theorems etc. are nice tools for getting asymptotic results, but don't help with finite samples. I believe something along these lines is mentioned in Hayashi (2000): Econometrics.
c) If estimators are biased for small samples, one can potentially correct or at least improve with so called small sample corrections. These are often complicated theoretically (to prove they improve on the estimator without the correction). Plus, most people are fine with relying on large samples, so small sample corrections are often not implemented in standard statistics software, because only few people require them (those that can't get more data AND care about unbiasedness). Thus, there are certain barriers to using those uncommon corrections.
On your questions. What do we mean by "large sample"? This depends heavily on the context, and for specific tools it can be answered via simulation. That is, you artificially generate data, and see how, say, the rejection rate behaves as a function of sample size, or the bias behaves as a function of sample size. A specific example is here, where the authors see how many clusters it takes for OLS clustered standard errors, block bootstraped standard errors etc. to perform well. Some theorists also have statements on the rate of convergence, but for practical purposes the simulations appear to be more informative.
Does it really take $n\to \infty$? If that's what the theory says, yes, but in application we can accept small, negligible bias, which we have with sufficiently large sample sizes with high probability. What sufficiently means depends on the context, see above.
On question 3: usually, the question of unbiasedness (for all sample sizes) and consistency (unbiasedness for large samples) is considered separately. An estimator can be biased, but consistent, in which case indeed only the large sample estimates are unbiased. But there are also estimators that are unbiased and consistent, which are theoretically applicable for any sample size. (An estimator can also be unbiased but inconsistent for technical reasons.) | Large sample asymptotic/theory - Why to care about? | Better late than never. Let me first list three (I think important) reasons why we focus on asymptotic unbiasedness (consistency) of estimators.
a) Consistency is a minimum criterion. If an estimator | Large sample asymptotic/theory - Why to care about?
Better late than never. Let me first list three (I think important) reasons why we focus on asymptotic unbiasedness (consistency) of estimators.
a) Consistency is a minimum criterion. If an estimator doesn't correctly estimate even with lots of data, then what good is it? This is the justification given in Wooldridge: Introductory Econometrics.
b) Finite sample properties are much harder to prove (or rather, asymptotic statements are easier). I am currently doing some research myself, and whenever you can rely on large sample tools, things get much easier. Laws of large numbers, martingale convergence theorems etc. are nice tools for getting asymptotic results, but don't help with finite samples. I believe something along these lines is mentioned in Hayashi (2000): Econometrics.
c) If estimators are biased for small samples, one can potentially correct or at least improve with so called small sample corrections. These are often complicated theoretically (to prove they improve on the estimator without the correction). Plus, most people are fine with relying on large samples, so small sample corrections are often not implemented in standard statistics software, because only few people require them (those that can't get more data AND care about unbiasedness). Thus, there are certain barriers to using those uncommon corrections.
On your questions. What do we mean by "large sample"? This depends heavily on the context, and for specific tools it can be answered via simulation. That is, you artificially generate data, and see how, say, the rejection rate behaves as a function of sample size, or the bias behaves as a function of sample size. A specific example is here, where the authors see how many clusters it takes for OLS clustered standard errors, block bootstraped standard errors etc. to perform well. Some theorists also have statements on the rate of convergence, but for practical purposes the simulations appear to be more informative.
Does it really take $n\to \infty$? If that's what the theory says, yes, but in application we can accept small, negligible bias, which we have with sufficiently large sample sizes with high probability. What sufficiently means depends on the context, see above.
On question 3: usually, the question of unbiasedness (for all sample sizes) and consistency (unbiasedness for large samples) is considered separately. An estimator can be biased, but consistent, in which case indeed only the large sample estimates are unbiased. But there are also estimators that are unbiased and consistent, which are theoretically applicable for any sample size. (An estimator can also be unbiased but inconsistent for technical reasons.) | Large sample asymptotic/theory - Why to care about?
Better late than never. Let me first list three (I think important) reasons why we focus on asymptotic unbiasedness (consistency) of estimators.
a) Consistency is a minimum criterion. If an estimator |
19,156 | Numeric solvers for stochastic differential equations in R: are there any? | CRAN is your friend: http://cran.r-project.org/web/views/DifferentialEquations.html
Stochastic Differential Equations (SDEs)
In a stochastic differential equation, the unknown quantity is a stochastic process.
The package sde provides functions for simulation and inference for stochastic differential equations. It is the accompanying package to the book by Iacus (2008).
The package pomp contains functions for statistical inference for partially observed Markov processes.
The Sim.DiffProc package simulates diffusion processes and has functions for numerical solution of stochastic differential equations.
Package GillespieSSA implements Gillespie's exact stochastic simulation algorithm (Direct method) and several approximate methods. | Numeric solvers for stochastic differential equations in R: are there any? | CRAN is your friend: http://cran.r-project.org/web/views/DifferentialEquations.html
Stochastic Differential Equations (SDEs)
In a stochastic differential equation, the unknown quantity is a stochastic | Numeric solvers for stochastic differential equations in R: are there any?
CRAN is your friend: http://cran.r-project.org/web/views/DifferentialEquations.html
Stochastic Differential Equations (SDEs)
In a stochastic differential equation, the unknown quantity is a stochastic process.
The package sde provides functions for simulation and inference for stochastic differential equations. It is the accompanying package to the book by Iacus (2008).
The package pomp contains functions for statistical inference for partially observed Markov processes.
The Sim.DiffProc package simulates diffusion processes and has functions for numerical solution of stochastic differential equations.
Package GillespieSSA implements Gillespie's exact stochastic simulation algorithm (Direct method) and several approximate methods. | Numeric solvers for stochastic differential equations in R: are there any?
CRAN is your friend: http://cran.r-project.org/web/views/DifferentialEquations.html
Stochastic Differential Equations (SDEs)
In a stochastic differential equation, the unknown quantity is a stochastic |
19,157 | Numeric solvers for stochastic differential equations in R: are there any? | There is a R package for SDE: http://cran.r-project.org/web/packages/sde/sde.pdf
But I am not sure if it works for non-homogeneous SDE | Numeric solvers for stochastic differential equations in R: are there any? | There is a R package for SDE: http://cran.r-project.org/web/packages/sde/sde.pdf
But I am not sure if it works for non-homogeneous SDE | Numeric solvers for stochastic differential equations in R: are there any?
There is a R package for SDE: http://cran.r-project.org/web/packages/sde/sde.pdf
But I am not sure if it works for non-homogeneous SDE | Numeric solvers for stochastic differential equations in R: are there any?
There is a R package for SDE: http://cran.r-project.org/web/packages/sde/sde.pdf
But I am not sure if it works for non-homogeneous SDE |
19,158 | SVD of a matrix with missing values | Yes, in practice those values are skipped. In your description in terms of a Frobenius norm, this corresponds to minimising the components of the norm which can be measured, i.e. those which have known ratings. The regularisation term can be seen as a Bayesian prior on the components of the feature vectors, with the SVD calculating the maximum likelihood estimator, subject to this prior and the known values.
It's probably best to think of the SVD as a method for inferring the missing values. If you've already got a better way of doing this, why do you need the SVD? If you don't, then the SVD will happily fill in the gaps for you. | SVD of a matrix with missing values | Yes, in practice those values are skipped. In your description in terms of a Frobenius norm, this corresponds to minimising the components of the norm which can be measured, i.e. those which have know | SVD of a matrix with missing values
Yes, in practice those values are skipped. In your description in terms of a Frobenius norm, this corresponds to minimising the components of the norm which can be measured, i.e. those which have known ratings. The regularisation term can be seen as a Bayesian prior on the components of the feature vectors, with the SVD calculating the maximum likelihood estimator, subject to this prior and the known values.
It's probably best to think of the SVD as a method for inferring the missing values. If you've already got a better way of doing this, why do you need the SVD? If you don't, then the SVD will happily fill in the gaps for you. | SVD of a matrix with missing values
Yes, in practice those values are skipped. In your description in terms of a Frobenius norm, this corresponds to minimising the components of the norm which can be measured, i.e. those which have know |
19,159 | SVD of a matrix with missing values | There is a thesis which reviews many recommendation systems and compares them, but does not talk about long term tracking of the missing items, for example, to test the predictions. That's part of your question? Using the time component in that way? Among the many papers and methods the thesis reviews are time aware/sensitive systems, such as the research in the Rendle papers.
If your question is also about handling sparsity of data, that is also discussed in detail throughout the thesis and there are many methods.
sparse matrices and imputation with zeroes or matrix factorization that adds a linking matrix of clustering of users (users who rate items similarly) or a linking matrix of clustering of items.
The thesis title is "Low Rank Models for Recommender Systems with Limited Preference Information" by Evgeny Frolov
https://www.skoltech.ru/app/data/uploads/2018/09/Frolov_Dissertation_Final1.pdf | SVD of a matrix with missing values | There is a thesis which reviews many recommendation systems and compares them, but does not talk about long term tracking of the missing items, for example, to test the predictions. That's part of yo | SVD of a matrix with missing values
There is a thesis which reviews many recommendation systems and compares them, but does not talk about long term tracking of the missing items, for example, to test the predictions. That's part of your question? Using the time component in that way? Among the many papers and methods the thesis reviews are time aware/sensitive systems, such as the research in the Rendle papers.
If your question is also about handling sparsity of data, that is also discussed in detail throughout the thesis and there are many methods.
sparse matrices and imputation with zeroes or matrix factorization that adds a linking matrix of clustering of users (users who rate items similarly) or a linking matrix of clustering of items.
The thesis title is "Low Rank Models for Recommender Systems with Limited Preference Information" by Evgeny Frolov
https://www.skoltech.ru/app/data/uploads/2018/09/Frolov_Dissertation_Final1.pdf | SVD of a matrix with missing values
There is a thesis which reviews many recommendation systems and compares them, but does not talk about long term tracking of the missing items, for example, to test the predictions. That's part of yo |
19,160 | SVD of a matrix with missing values | In practice, what do people do with the missing values from the recommendation matrix, which is the whole point of doing the calculation? My guess from reading Simon's blog post is that he ONLY uses the non-missing terms to build a model.
That's right -- that's the point of his and your model, to predict the missing terms, right? It's a crucial point that many actually forget. They think they can just "assume" to pre-assign a constant to missing data without a care in the world, and things will magically work out well enough from an SVD. Garbage in, garbage out: It's real, and you had better watch it. You'd better not feed junk data to a model if you want something useful to result.
It is certainly NOT "best to infer any missing values" on majority sparse dataset and then run SVD on that with some hope to impute values for you (which you already imputed before you ran SVD, right?). What do you think, a model is magic? THere is no magic nor technology to overcome majority garbage data. You cannot lie to a model that data is real data when it's not real at all, but really just some junk you just plain made up from thin air.
SVD does other useful things so I'm certainly not saying SVD is worthless in the least. Go ahead and use SVD only on complete datasets, perhaps which you've intelligently imputed missing values on already using a machine learning model with all due attention to bias error and variance error during its development.
Machine learning is the way. So if you still want to know how to impute values using a matrix factorization design, there are certainly good ways to do exactly this using machine learning, and importantly they don't feed any junk data to a model to pointlessly attempt to learn from.
Exactly such a machine learning matrix factorization model is presented quite well by the instructors of the Stanford online course Mining Massive Data Sets, in module 5. They show you the math and explain the model. They don't code it up for you though.
It's OK because you can code it up yourself, if you understand basic machine learning. Do you know what a loss function and a cost function are? Regularization? Gradient descent? ARe you OK with matrix multiplication and addition? Bias error and variance error? If so then you are good. If not then you should consider to take Andrew Ng's online course Machine Learning at Coursera, which is one of the many good starting places. Then also go take the online course Mining Massive Data Sets which talks exactly about matrix factorization and machine learning for making recommender models.
Suffice it to say, you can completely design as well as code up your own factorization model which handles missing data very well, just like Simon Funk did, and you can do it from scratch but it's not hard at all any more like it was back in his day, because now you can use a tool like TensorFlow or Microsoft CNTK which does a lot for you. Define a loss function and a cost function, choose an optimizer, partition your dataset into training, dev, test from the data that's actually available (labeled data) and let it run. Seriously, it works. It's not easy debugging TF and its graph building errors, but it can work great in the end and takes less than one page of code.
Specifically, one way to not feed fake data to a matrix factorization machine learning model, is to skip over the missing data's matrix elements in your loss and cost functions. | SVD of a matrix with missing values | In practice, what do people do with the missing values from the recommendation matrix, which is the whole point of doing the calculation? My guess from reading Simon's blog post is that he ONLY uses t | SVD of a matrix with missing values
In practice, what do people do with the missing values from the recommendation matrix, which is the whole point of doing the calculation? My guess from reading Simon's blog post is that he ONLY uses the non-missing terms to build a model.
That's right -- that's the point of his and your model, to predict the missing terms, right? It's a crucial point that many actually forget. They think they can just "assume" to pre-assign a constant to missing data without a care in the world, and things will magically work out well enough from an SVD. Garbage in, garbage out: It's real, and you had better watch it. You'd better not feed junk data to a model if you want something useful to result.
It is certainly NOT "best to infer any missing values" on majority sparse dataset and then run SVD on that with some hope to impute values for you (which you already imputed before you ran SVD, right?). What do you think, a model is magic? THere is no magic nor technology to overcome majority garbage data. You cannot lie to a model that data is real data when it's not real at all, but really just some junk you just plain made up from thin air.
SVD does other useful things so I'm certainly not saying SVD is worthless in the least. Go ahead and use SVD only on complete datasets, perhaps which you've intelligently imputed missing values on already using a machine learning model with all due attention to bias error and variance error during its development.
Machine learning is the way. So if you still want to know how to impute values using a matrix factorization design, there are certainly good ways to do exactly this using machine learning, and importantly they don't feed any junk data to a model to pointlessly attempt to learn from.
Exactly such a machine learning matrix factorization model is presented quite well by the instructors of the Stanford online course Mining Massive Data Sets, in module 5. They show you the math and explain the model. They don't code it up for you though.
It's OK because you can code it up yourself, if you understand basic machine learning. Do you know what a loss function and a cost function are? Regularization? Gradient descent? ARe you OK with matrix multiplication and addition? Bias error and variance error? If so then you are good. If not then you should consider to take Andrew Ng's online course Machine Learning at Coursera, which is one of the many good starting places. Then also go take the online course Mining Massive Data Sets which talks exactly about matrix factorization and machine learning for making recommender models.
Suffice it to say, you can completely design as well as code up your own factorization model which handles missing data very well, just like Simon Funk did, and you can do it from scratch but it's not hard at all any more like it was back in his day, because now you can use a tool like TensorFlow or Microsoft CNTK which does a lot for you. Define a loss function and a cost function, choose an optimizer, partition your dataset into training, dev, test from the data that's actually available (labeled data) and let it run. Seriously, it works. It's not easy debugging TF and its graph building errors, but it can work great in the end and takes less than one page of code.
Specifically, one way to not feed fake data to a matrix factorization machine learning model, is to skip over the missing data's matrix elements in your loss and cost functions. | SVD of a matrix with missing values
In practice, what do people do with the missing values from the recommendation matrix, which is the whole point of doing the calculation? My guess from reading Simon's blog post is that he ONLY uses t |
19,161 | How to deal with a mix of binary and continuous inputs in neural networks? [duplicate] | One way to handle this situation is to rescale the inputs so that their variances are on roughly the same scale. This advice is generally given for regression modeling, but it really applies to all modeling situations that involve variables measured on different scales. This is because the variance of a binary variable is often quite different from the variance of a continuous variable. Gelman and Hill (2006) recommend rescaling continuous inputs by two standard deviations to obtain parity with (un-scaled) binary inputs. This recommendation is also reflected in a paper and blog post.
A more specific recommendation for neural networks is to use "effect coding" for binary inputs (that is, -1 and 1) instead of "dummy coding" (0 and 1), and to take the additional step of centering continuous variables. These recommendations come from an extensive FAQ by Warren Sarle, in particular the sections "Why not code binary inputs as 0 and 1?" and "Should I standardize the input variables?" The gist, though, is the same:
The contribution of an input will depend heavily on its variability relative to other inputs.
As for unordered categorical variables -- you must break them out into binary indicators. They simply are not meaningful otherwise. | How to deal with a mix of binary and continuous inputs in neural networks? [duplicate] | One way to handle this situation is to rescale the inputs so that their variances are on roughly the same scale. This advice is generally given for regression modeling, but it really applies to all mo | How to deal with a mix of binary and continuous inputs in neural networks? [duplicate]
One way to handle this situation is to rescale the inputs so that their variances are on roughly the same scale. This advice is generally given for regression modeling, but it really applies to all modeling situations that involve variables measured on different scales. This is because the variance of a binary variable is often quite different from the variance of a continuous variable. Gelman and Hill (2006) recommend rescaling continuous inputs by two standard deviations to obtain parity with (un-scaled) binary inputs. This recommendation is also reflected in a paper and blog post.
A more specific recommendation for neural networks is to use "effect coding" for binary inputs (that is, -1 and 1) instead of "dummy coding" (0 and 1), and to take the additional step of centering continuous variables. These recommendations come from an extensive FAQ by Warren Sarle, in particular the sections "Why not code binary inputs as 0 and 1?" and "Should I standardize the input variables?" The gist, though, is the same:
The contribution of an input will depend heavily on its variability relative to other inputs.
As for unordered categorical variables -- you must break them out into binary indicators. They simply are not meaningful otherwise. | How to deal with a mix of binary and continuous inputs in neural networks? [duplicate]
One way to handle this situation is to rescale the inputs so that their variances are on roughly the same scale. This advice is generally given for regression modeling, but it really applies to all mo |
19,162 | Using generalized method of moments (GMM) to calculate logistic regression parameter | Assuming $A\leq 1$, this model has Bernoulli response variable $Y_i$ with
$$
Pr(Y_i = 1) = \frac{A}{1+e^{-X_i'b}},
$$
where $b$ (and possibly $A$, depending on whether it is treated as a constant or a parameter) are the fitted coefficients and $X_i$ is the data for observation $i$. I assume the intercept term is handled by adding a variable with constant value 1 to the data matrix.
The moment conditions are:
\begin{align*}
\mathbb{E}\bigg[\bigg(Y_i-\frac{A}{1+e^{-X_i'b}}\bigg)X_i\bigg] &= 0.
\end{align*}
We replace this with the sample counterpart of the condition, assuming $N$ observations:
$$
m = \frac{1}{N}\sum_{i=1}^N \bigg[\bigg(Y_i-\frac{A}{1+e^{-X_i'b}}\bigg)X_i\bigg] = 0
$$
This is practically solved by minimizing $m'm$ across all possible coefficient values $b$ (below we will use the Nelder-Mead simplex to perform this optimization).
Borrowing from an excellent R-bloggers tutorial on the topic, it is pretty straightforward to implement this in R with the gmm package. As an example, let's work with the iris dataset, predicting if an iris is versicolor based on its sepal length and width and petal length and width. I'll assume $A$ is constant and equal to 1 in this case:
dat <- as.matrix(cbind(data.frame(IsVersicolor = as.numeric(iris$Species == "versicolor"), Intercept=1), iris[,1:4]))
head(dat)
# IsVersicolor Intercept Sepal.Length Sepal.Width Petal.Length Petal.Width
# [1,] 0 1 5.1 3.5 1.4 0.2
# [2,] 0 1 4.9 3.0 1.4 0.2
# [3,] 0 1 4.7 3.2 1.3 0.2
# [4,] 0 1 4.6 3.1 1.5 0.2
# [5,] 0 1 5.0 3.6 1.4 0.2
# [6,] 0 1 5.4 3.9 1.7 0.4
Here are the coefficients fitted using logistic regression:
summary(glm(IsVersicolor~., data=as.data.frame(dat[,-2]), family="binomial"))
# Coefficients:
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) 7.3785 2.4993 2.952 0.003155 **
# Sepal.Length -0.2454 0.6496 -0.378 0.705634
# Sepal.Width -2.7966 0.7835 -3.569 0.000358 ***
# Petal.Length 1.3136 0.6838 1.921 0.054713 .
# Petal.Width -2.7783 1.1731 -2.368 0.017868 *
The main piece we need to use gmm is a function that returns the moment conditions, namely rows $(Y_i-\frac{A}{1+e^{-X_i'b}})X_i$ for each observation $i$:
moments <- function(b, X) {
A <- 1
as.vector(X[,1] - A / (1 + exp(-(X[,-1] %*% cbind(b))))) * X[,-1]
}
We can now numerically fit coefficients $b$, using the linear regression coefficients as a convenient initial point (as suggested in the tutorial linked above):
init.coef <- lm(IsVersicolor~., data=as.data.frame(dat[,-2]))$coefficients
library(gmm)
fitted <- gmm(moments, x = dat, t0 = init.coef, type = "iterative", crit = 1e-19,
wmatrix = "optimal", method = "Nelder-Mead",
control = list(reltol = 1e-19, maxit = 20000))
fitted
# (Intercept) Sepal.Length Sepal.Width Petal.Length Petal.Width
# 7.37849 -0.24536 -2.79657 1.31364 -2.77834
#
# Convergence code = 0
The convergence code of 0 indicates the procedure converged, and the parameters are identical to those returned by logistic regression.
A quick look at the gmm package source (functions momentEstim.baseGmm.iterative and gmm:::.obj1 for the parameters provided) shows that the gmm package is minimizing $m'm$ as indicated above. The following equivalent code calls the R optim function directly, performing the same optimization we achieved above with the call to gmm:
gmm.objective <- function(theta, x, momentFun) {
avg.moment <- colMeans(momentFun(theta, x))
sum(avg.moment^2)
}
optim(init.coef, gmm.objective, x=dat, momentFun=moments,
control = list(reltol = 1e-19, maxit = 20000))$par
# (Intercept) Sepal.Length Sepal.Width Petal.Length Petal.Width
# 7.3784866 -0.2453567 -2.7965681 1.3136433 -2.7783439 | Using generalized method of moments (GMM) to calculate logistic regression parameter | Assuming $A\leq 1$, this model has Bernoulli response variable $Y_i$ with
$$
Pr(Y_i = 1) = \frac{A}{1+e^{-X_i'b}},
$$
where $b$ (and possibly $A$, depending on whether it is treated as a constant or a | Using generalized method of moments (GMM) to calculate logistic regression parameter
Assuming $A\leq 1$, this model has Bernoulli response variable $Y_i$ with
$$
Pr(Y_i = 1) = \frac{A}{1+e^{-X_i'b}},
$$
where $b$ (and possibly $A$, depending on whether it is treated as a constant or a parameter) are the fitted coefficients and $X_i$ is the data for observation $i$. I assume the intercept term is handled by adding a variable with constant value 1 to the data matrix.
The moment conditions are:
\begin{align*}
\mathbb{E}\bigg[\bigg(Y_i-\frac{A}{1+e^{-X_i'b}}\bigg)X_i\bigg] &= 0.
\end{align*}
We replace this with the sample counterpart of the condition, assuming $N$ observations:
$$
m = \frac{1}{N}\sum_{i=1}^N \bigg[\bigg(Y_i-\frac{A}{1+e^{-X_i'b}}\bigg)X_i\bigg] = 0
$$
This is practically solved by minimizing $m'm$ across all possible coefficient values $b$ (below we will use the Nelder-Mead simplex to perform this optimization).
Borrowing from an excellent R-bloggers tutorial on the topic, it is pretty straightforward to implement this in R with the gmm package. As an example, let's work with the iris dataset, predicting if an iris is versicolor based on its sepal length and width and petal length and width. I'll assume $A$ is constant and equal to 1 in this case:
dat <- as.matrix(cbind(data.frame(IsVersicolor = as.numeric(iris$Species == "versicolor"), Intercept=1), iris[,1:4]))
head(dat)
# IsVersicolor Intercept Sepal.Length Sepal.Width Petal.Length Petal.Width
# [1,] 0 1 5.1 3.5 1.4 0.2
# [2,] 0 1 4.9 3.0 1.4 0.2
# [3,] 0 1 4.7 3.2 1.3 0.2
# [4,] 0 1 4.6 3.1 1.5 0.2
# [5,] 0 1 5.0 3.6 1.4 0.2
# [6,] 0 1 5.4 3.9 1.7 0.4
Here are the coefficients fitted using logistic regression:
summary(glm(IsVersicolor~., data=as.data.frame(dat[,-2]), family="binomial"))
# Coefficients:
# Estimate Std. Error z value Pr(>|z|)
# (Intercept) 7.3785 2.4993 2.952 0.003155 **
# Sepal.Length -0.2454 0.6496 -0.378 0.705634
# Sepal.Width -2.7966 0.7835 -3.569 0.000358 ***
# Petal.Length 1.3136 0.6838 1.921 0.054713 .
# Petal.Width -2.7783 1.1731 -2.368 0.017868 *
The main piece we need to use gmm is a function that returns the moment conditions, namely rows $(Y_i-\frac{A}{1+e^{-X_i'b}})X_i$ for each observation $i$:
moments <- function(b, X) {
A <- 1
as.vector(X[,1] - A / (1 + exp(-(X[,-1] %*% cbind(b))))) * X[,-1]
}
We can now numerically fit coefficients $b$, using the linear regression coefficients as a convenient initial point (as suggested in the tutorial linked above):
init.coef <- lm(IsVersicolor~., data=as.data.frame(dat[,-2]))$coefficients
library(gmm)
fitted <- gmm(moments, x = dat, t0 = init.coef, type = "iterative", crit = 1e-19,
wmatrix = "optimal", method = "Nelder-Mead",
control = list(reltol = 1e-19, maxit = 20000))
fitted
# (Intercept) Sepal.Length Sepal.Width Petal.Length Petal.Width
# 7.37849 -0.24536 -2.79657 1.31364 -2.77834
#
# Convergence code = 0
The convergence code of 0 indicates the procedure converged, and the parameters are identical to those returned by logistic regression.
A quick look at the gmm package source (functions momentEstim.baseGmm.iterative and gmm:::.obj1 for the parameters provided) shows that the gmm package is minimizing $m'm$ as indicated above. The following equivalent code calls the R optim function directly, performing the same optimization we achieved above with the call to gmm:
gmm.objective <- function(theta, x, momentFun) {
avg.moment <- colMeans(momentFun(theta, x))
sum(avg.moment^2)
}
optim(init.coef, gmm.objective, x=dat, momentFun=moments,
control = list(reltol = 1e-19, maxit = 20000))$par
# (Intercept) Sepal.Length Sepal.Width Petal.Length Petal.Width
# 7.3784866 -0.2453567 -2.7965681 1.3136433 -2.7783439 | Using generalized method of moments (GMM) to calculate logistic regression parameter
Assuming $A\leq 1$, this model has Bernoulli response variable $Y_i$ with
$$
Pr(Y_i = 1) = \frac{A}{1+e^{-X_i'b}},
$$
where $b$ (and possibly $A$, depending on whether it is treated as a constant or a |
19,163 | Using generalized method of moments (GMM) to calculate logistic regression parameter | One intuition for the moment conditions:
$E\left[ \left(Y_i - \frac{1}{1+e^{-X_i' \beta} }\right)X_i \right]$
Is that you want your prediction errors to be mean zero and uncorrelated with the independent variables.
Once you think of $\epsilon_i = Y_i- \frac{1} {1+e^{-X_i'\beta}}$ as an error term, then the canonical moment conditions are analogous to the moments you'd use in OLS. | Using generalized method of moments (GMM) to calculate logistic regression parameter | One intuition for the moment conditions:
$E\left[ \left(Y_i - \frac{1}{1+e^{-X_i' \beta} }\right)X_i \right]$
Is that you want your prediction errors to be mean zero and uncorrelated with the independ | Using generalized method of moments (GMM) to calculate logistic regression parameter
One intuition for the moment conditions:
$E\left[ \left(Y_i - \frac{1}{1+e^{-X_i' \beta} }\right)X_i \right]$
Is that you want your prediction errors to be mean zero and uncorrelated with the independent variables.
Once you think of $\epsilon_i = Y_i- \frac{1} {1+e^{-X_i'\beta}}$ as an error term, then the canonical moment conditions are analogous to the moments you'd use in OLS. | Using generalized method of moments (GMM) to calculate logistic regression parameter
One intuition for the moment conditions:
$E\left[ \left(Y_i - \frac{1}{1+e^{-X_i' \beta} }\right)X_i \right]$
Is that you want your prediction errors to be mean zero and uncorrelated with the independ |
19,164 | Best way to visualize attrition using R? | I agree with @gung. The Sankey diagram you posted is, I think, a pretty good example of where the technique can help. While it is complicated, the context (energy input and output) is complex too and it is hard to think of a nicer way of visualizing the paths of inputs-to-outputs-acting-as-new-inputs across multiple categories of usage.
Now then, for the attrition example you posted, as others have noted it is not helpful to use a Sankey diagram. I think you need to post your full set of variables if you want a good recommendation on alternative visualizations though. If you simply want to show differences in attrition sources between sites and clinicians, a small-multiples series of dot plots may be the easiest for your audience to understand and for you to implement (see this example, where in your case the groups could be the sites, the elements within the groups would be the causes of attrition, and the horizontal axis would be 0-100%).
If the Sankey diagram is something you want to use, and you are willing to dabble in another high level language, there is a nice example (with code) on the gallery for the Python plotting package, matplotlib. | Best way to visualize attrition using R? | I agree with @gung. The Sankey diagram you posted is, I think, a pretty good example of where the technique can help. While it is complicated, the context (energy input and output) is complex too and | Best way to visualize attrition using R?
I agree with @gung. The Sankey diagram you posted is, I think, a pretty good example of where the technique can help. While it is complicated, the context (energy input and output) is complex too and it is hard to think of a nicer way of visualizing the paths of inputs-to-outputs-acting-as-new-inputs across multiple categories of usage.
Now then, for the attrition example you posted, as others have noted it is not helpful to use a Sankey diagram. I think you need to post your full set of variables if you want a good recommendation on alternative visualizations though. If you simply want to show differences in attrition sources between sites and clinicians, a small-multiples series of dot plots may be the easiest for your audience to understand and for you to implement (see this example, where in your case the groups could be the sites, the elements within the groups would be the causes of attrition, and the horizontal axis would be 0-100%).
If the Sankey diagram is something you want to use, and you are willing to dabble in another high level language, there is a nice example (with code) on the gallery for the Python plotting package, matplotlib. | Best way to visualize attrition using R?
I agree with @gung. The Sankey diagram you posted is, I think, a pretty good example of where the technique can help. While it is complicated, the context (energy input and output) is complex too and |
19,165 | Best way to visualize attrition using R? | I wouldn't necessarily assume the lack of a method implies that method is unimportant or not useful. After all, for all the methods that currently exist in R, there was a time (quite possibly recent--R is only ~10 years old) when there was no package for it.
However, I should think there are any number of ways to visualize data such as attrition. My first thought looking at your chart, is that it could be represented with a dot plot. Other possibilities exist as well. The extra functionality of the Sankey Diagram is going to come into play when you have some attrition due to a particular cause at one point, and then more due to the same cause later with other inputs and outputs in between. That would be more complicated to represent by standard plots (it's also harder to follow even with a Sankey diagram--for example, the one at the top of the page takes quite a bit of work to read). Since you don't seem to have that, the Sankey diagram seems to be pretty, but overkill. | Best way to visualize attrition using R? | I wouldn't necessarily assume the lack of a method implies that method is unimportant or not useful. After all, for all the methods that currently exist in R, there was a time (quite possibly recent- | Best way to visualize attrition using R?
I wouldn't necessarily assume the lack of a method implies that method is unimportant or not useful. After all, for all the methods that currently exist in R, there was a time (quite possibly recent--R is only ~10 years old) when there was no package for it.
However, I should think there are any number of ways to visualize data such as attrition. My first thought looking at your chart, is that it could be represented with a dot plot. Other possibilities exist as well. The extra functionality of the Sankey Diagram is going to come into play when you have some attrition due to a particular cause at one point, and then more due to the same cause later with other inputs and outputs in between. That would be more complicated to represent by standard plots (it's also harder to follow even with a Sankey diagram--for example, the one at the top of the page takes quite a bit of work to read). Since you don't seem to have that, the Sankey diagram seems to be pretty, but overkill. | Best way to visualize attrition using R?
I wouldn't necessarily assume the lack of a method implies that method is unimportant or not useful. After all, for all the methods that currently exist in R, there was a time (quite possibly recent- |
19,166 | Best way to visualize attrition using R? | How about using R code to write an SVG file with the arrow widths set according to your data, and a simple layout. Then load into Inkscape and bend the arrows around, add labels etc etc to your heart's content to make something pretty.
Obvious problem: you need to redo all your prettification in Inkscape if your data changes (although you might be able to use your pretty SVG from Inkscape as a template and just substitute new arrow widths in).
But honestly, if that multi-coloured mess of straggling squiggles at the top is a good Sankey diagram, I'd hate to see a bad one on a full stomach [although staring at it for a few more minutes has given me a clue about what it's about, a good graphic shouldn't need that]. | Best way to visualize attrition using R? | How about using R code to write an SVG file with the arrow widths set according to your data, and a simple layout. Then load into Inkscape and bend the arrows around, add labels etc etc to your heart' | Best way to visualize attrition using R?
How about using R code to write an SVG file with the arrow widths set according to your data, and a simple layout. Then load into Inkscape and bend the arrows around, add labels etc etc to your heart's content to make something pretty.
Obvious problem: you need to redo all your prettification in Inkscape if your data changes (although you might be able to use your pretty SVG from Inkscape as a template and just substitute new arrow widths in).
But honestly, if that multi-coloured mess of straggling squiggles at the top is a good Sankey diagram, I'd hate to see a bad one on a full stomach [although staring at it for a few more minutes has given me a clue about what it's about, a good graphic shouldn't need that]. | Best way to visualize attrition using R?
How about using R code to write an SVG file with the arrow widths set according to your data, and a simple layout. Then load into Inkscape and bend the arrows around, add labels etc etc to your heart' |
19,167 | How to calculate forecast error (confidence intervals) for ongoing periods? | There are so many narrow aspects calculating prediction intervals: data generating process and the model used to described this process (time series model, regression model), is your data stationary (for this type your conclusion is wrong as stationary data is not tending to run far from its mean value) or explosive (for an integrated process you will see something that you described). I think that an excellent review by Chris Chatfield regarding Prediction Intervals will answer most of your questions.
Regarding unit sales:
since you have a short forecasting interval you may try to forecast by exponential smoothing (in R it is the ets() function from forecast)
another option would be to model it like ARIMA process (the same library has auto.arima())
in micro-econometrics, however, regression models are preferable to a-theoretic ones, but in the short run they not necessarily beat the first two
Both cases has formulas to calculate the prediction intervals and are discussed in above-mentioned review (commonly the normality of the residuals is assumed, but this is not a crucial assumption). | How to calculate forecast error (confidence intervals) for ongoing periods? | There are so many narrow aspects calculating prediction intervals: data generating process and the model used to described this process (time series model, regression model), is your data stationary ( | How to calculate forecast error (confidence intervals) for ongoing periods?
There are so many narrow aspects calculating prediction intervals: data generating process and the model used to described this process (time series model, regression model), is your data stationary (for this type your conclusion is wrong as stationary data is not tending to run far from its mean value) or explosive (for an integrated process you will see something that you described). I think that an excellent review by Chris Chatfield regarding Prediction Intervals will answer most of your questions.
Regarding unit sales:
since you have a short forecasting interval you may try to forecast by exponential smoothing (in R it is the ets() function from forecast)
another option would be to model it like ARIMA process (the same library has auto.arima())
in micro-econometrics, however, regression models are preferable to a-theoretic ones, but in the short run they not necessarily beat the first two
Both cases has formulas to calculate the prediction intervals and are discussed in above-mentioned review (commonly the normality of the residuals is assumed, but this is not a crucial assumption). | How to calculate forecast error (confidence intervals) for ongoing periods?
There are so many narrow aspects calculating prediction intervals: data generating process and the model used to described this process (time series model, regression model), is your data stationary ( |
19,168 | Ordering of time series for machine learning | The answer to this question is that this will work fine as long as your model order is correctly specified, as then the errors from your model will be independent.
This paper here shows that if a model has poor cross-validation will underestimate how poor it actually is. In all other cases the cross-validation will do a good job, in particular, a better job than the out-of-sample evaluation usually used in the time series context. | Ordering of time series for machine learning | The answer to this question is that this will work fine as long as your model order is correctly specified, as then the errors from your model will be independent.
This paper here shows that if a mode | Ordering of time series for machine learning
The answer to this question is that this will work fine as long as your model order is correctly specified, as then the errors from your model will be independent.
This paper here shows that if a model has poor cross-validation will underestimate how poor it actually is. In all other cases the cross-validation will do a good job, in particular, a better job than the out-of-sample evaluation usually used in the time series context. | Ordering of time series for machine learning
The answer to this question is that this will work fine as long as your model order is correctly specified, as then the errors from your model will be independent.
This paper here shows that if a mode |
19,169 | Ordering of time series for machine learning | Interesting question!
The approach you describe is certainly very widely used by people using standard ML methods that require fixed-length feature vectors of attributes, to analyse time series data.
In the post that you link to, Hyndman points out that there are correlations between the reshaped data vectors (samples). This could be problematic, as k-CV (or other evaluation methods that divide data at random into training and testing sets) assumes that all samples are independent. However, I don't think this concern is relevant for the case of a standard ML methods, that treat attributes separately.
For explanation, let me simplify your notation by assuming $n=3$, so the the first few data vectors (labelled alphabetically) will be:
\begin{align}
A&: (y_1, y_2, y_3; y_4) \\
B&: (y_2, y_3, y_4; y_5) \\
C&: (y_3, y_4, y_5; y_6) \\
\end{align}
Clearly, A and B have terms such as $y_2$ in common. But, for A, this is the value of its second attribute whereas for B this is the value of its first attribute. | Ordering of time series for machine learning | Interesting question!
The approach you describe is certainly very widely used by people using standard ML methods that require fixed-length feature vectors of attributes, to analyse time series data. | Ordering of time series for machine learning
Interesting question!
The approach you describe is certainly very widely used by people using standard ML methods that require fixed-length feature vectors of attributes, to analyse time series data.
In the post that you link to, Hyndman points out that there are correlations between the reshaped data vectors (samples). This could be problematic, as k-CV (or other evaluation methods that divide data at random into training and testing sets) assumes that all samples are independent. However, I don't think this concern is relevant for the case of a standard ML methods, that treat attributes separately.
For explanation, let me simplify your notation by assuming $n=3$, so the the first few data vectors (labelled alphabetically) will be:
\begin{align}
A&: (y_1, y_2, y_3; y_4) \\
B&: (y_2, y_3, y_4; y_5) \\
C&: (y_3, y_4, y_5; y_6) \\
\end{align}
Clearly, A and B have terms such as $y_2$ in common. But, for A, this is the value of its second attribute whereas for B this is the value of its first attribute. | Ordering of time series for machine learning
Interesting question!
The approach you describe is certainly very widely used by people using standard ML methods that require fixed-length feature vectors of attributes, to analyse time series data. |
19,170 | Two-sample T-test with weighted data | Use regression methods. A simple linear regression with group coded as 0-1 (or 1-2, etc) is equivalent to a t-test, but regression software usually has the capability to incorporate weigths correctly. | Two-sample T-test with weighted data | Use regression methods. A simple linear regression with group coded as 0-1 (or 1-2, etc) is equivalent to a t-test, but regression software usually has the capability to incorporate weigths correctly. | Two-sample T-test with weighted data
Use regression methods. A simple linear regression with group coded as 0-1 (or 1-2, etc) is equivalent to a t-test, but regression software usually has the capability to incorporate weigths correctly. | Two-sample T-test with weighted data
Use regression methods. A simple linear regression with group coded as 0-1 (or 1-2, etc) is equivalent to a t-test, but regression software usually has the capability to incorporate weigths correctly. |
19,171 | Hamiltonian Monte Carlo for dummies | As mentioned in the comments by cwl, bjw and Sycorax, the following resources are useful (I can recommend them from my own experience as well):
Statistical rethinking by R. McElreath has a short but very approachable introduction (and is a great book overall).
Conceptual Introduction to Hamiltonian Monte Carlo by M. Betancourt goes into depth.
Stan documentation also has a solid section on HMC | Hamiltonian Monte Carlo for dummies | As mentioned in the comments by cwl, bjw and Sycorax, the following resources are useful (I can recommend them from my own experience as well):
Statistical rethinking by R. McElreath has a short but | Hamiltonian Monte Carlo for dummies
As mentioned in the comments by cwl, bjw and Sycorax, the following resources are useful (I can recommend them from my own experience as well):
Statistical rethinking by R. McElreath has a short but very approachable introduction (and is a great book overall).
Conceptual Introduction to Hamiltonian Monte Carlo by M. Betancourt goes into depth.
Stan documentation also has a solid section on HMC | Hamiltonian Monte Carlo for dummies
As mentioned in the comments by cwl, bjw and Sycorax, the following resources are useful (I can recommend them from my own experience as well):
Statistical rethinking by R. McElreath has a short but |
19,172 | Why Test Statistic for the Pearson Correlation Coefficient is $\frac {r\sqrt{n-2}}{\sqrt{1-r^2}}$ | (providing an answer to the question)
When the residuals in a linear regression are normally distributed, the least squares parameter $\hat{\beta}$ is normally distributed. Of course, when the variance of the residuals must be estimated from the sample, the exact distribution of $\hat{\beta}$ under the null hypothesis is $t$ with $n-p$ degrees of freedom ($p$ the dimension of the model, usually two for a slope and intercept).
Per @Dason's link, the $t$ for the Pearson Correlation Coefficient can be shown to be mathematically equivalent to the $t$ test statistic for the least squares regression parameter by:
$$t = \frac{\hat{\beta}}{\sqrt{\frac{\text{MSE}}{\sum (X_i - \bar{X})^2}}}= \frac{r (S_y / S_x)}{\sqrt{\frac{(n-1)(1-r^2)S_y^2}{(n-2)(n-1)S_x^2}}}=\frac{r\sqrt{n-2}}{\sqrt{1-r^2}}$$ | Why Test Statistic for the Pearson Correlation Coefficient is $\frac {r\sqrt{n-2}}{\sqrt{1-r^2}}$ | (providing an answer to the question)
When the residuals in a linear regression are normally distributed, the least squares parameter $\hat{\beta}$ is normally distributed. Of course, when the varianc | Why Test Statistic for the Pearson Correlation Coefficient is $\frac {r\sqrt{n-2}}{\sqrt{1-r^2}}$
(providing an answer to the question)
When the residuals in a linear regression are normally distributed, the least squares parameter $\hat{\beta}$ is normally distributed. Of course, when the variance of the residuals must be estimated from the sample, the exact distribution of $\hat{\beta}$ under the null hypothesis is $t$ with $n-p$ degrees of freedom ($p$ the dimension of the model, usually two for a slope and intercept).
Per @Dason's link, the $t$ for the Pearson Correlation Coefficient can be shown to be mathematically equivalent to the $t$ test statistic for the least squares regression parameter by:
$$t = \frac{\hat{\beta}}{\sqrt{\frac{\text{MSE}}{\sum (X_i - \bar{X})^2}}}= \frac{r (S_y / S_x)}{\sqrt{\frac{(n-1)(1-r^2)S_y^2}{(n-2)(n-1)S_x^2}}}=\frac{r\sqrt{n-2}}{\sqrt{1-r^2}}$$ | Why Test Statistic for the Pearson Correlation Coefficient is $\frac {r\sqrt{n-2}}{\sqrt{1-r^2}}$
(providing an answer to the question)
When the residuals in a linear regression are normally distributed, the least squares parameter $\hat{\beta}$ is normally distributed. Of course, when the varianc |
19,173 | For what models does the bias of MLE fall faster than the variance? | In general, you need models where the MLE is not asymptotically normal but converges to some other distribution (and it does so at a faster rate). This usually happens when the parameter under estimation is at the boundary of the parameter space. Intuitively, this means that the MLE will approach the parameter "only from the one side", so it "improves on convergence speed" since it is not "distracted" by going "back and forth" around the parameter.
A standard example, is the MLE for $\theta$ in an i.i.d. sample of $U(0,\theta)$ uniform r.v.'s The MLE here is the maximum order statistic,
$$\hat \theta_n = u_{(n)}$$
Its finite sample distribution is
$$F_{\hat \theta_n} = \frac {(\hat \theta_n)^n}{\theta ^n},\;\;\; f_{\hat \theta}=n\frac {(\hat \theta_n)^{n-1}}{\theta ^n}$$
$$\mathbb E(\hat \theta_n) = \frac {n}{n+1}\theta \implies B(\hat \theta) = -\frac {1}{n+1}\theta$$
So $B(\hat \theta_n) = O(1/n)$. But the same increased rate will hold also for the variance.
One can also verify that to obtain a limiting distribution, we need to look at the variable $n(\theta - \hat \theta_n)$,(i.e we need to scale by $n$) since
$$P[n(\theta - \hat \theta_n)\leq z] = 1-P[\hat \theta_n\leq \theta - (z/n)]$$
$$=1-\frac 1 {\theta^n}\cdot \left(\theta + \frac{-z}{n}\right)^n = 1-\frac {\theta^n} {\theta^n}\cdot \left(1 + \frac{-z/\theta}{n}\right)^n$$
$$\to 1- e^{-z/\theta}$$
which is the CDF of the Exponential distribution.
I hope this provides some direction. | For what models does the bias of MLE fall faster than the variance? | In general, you need models where the MLE is not asymptotically normal but converges to some other distribution (and it does so at a faster rate). This usually happens when the parameter under estimat | For what models does the bias of MLE fall faster than the variance?
In general, you need models where the MLE is not asymptotically normal but converges to some other distribution (and it does so at a faster rate). This usually happens when the parameter under estimation is at the boundary of the parameter space. Intuitively, this means that the MLE will approach the parameter "only from the one side", so it "improves on convergence speed" since it is not "distracted" by going "back and forth" around the parameter.
A standard example, is the MLE for $\theta$ in an i.i.d. sample of $U(0,\theta)$ uniform r.v.'s The MLE here is the maximum order statistic,
$$\hat \theta_n = u_{(n)}$$
Its finite sample distribution is
$$F_{\hat \theta_n} = \frac {(\hat \theta_n)^n}{\theta ^n},\;\;\; f_{\hat \theta}=n\frac {(\hat \theta_n)^{n-1}}{\theta ^n}$$
$$\mathbb E(\hat \theta_n) = \frac {n}{n+1}\theta \implies B(\hat \theta) = -\frac {1}{n+1}\theta$$
So $B(\hat \theta_n) = O(1/n)$. But the same increased rate will hold also for the variance.
One can also verify that to obtain a limiting distribution, we need to look at the variable $n(\theta - \hat \theta_n)$,(i.e we need to scale by $n$) since
$$P[n(\theta - \hat \theta_n)\leq z] = 1-P[\hat \theta_n\leq \theta - (z/n)]$$
$$=1-\frac 1 {\theta^n}\cdot \left(\theta + \frac{-z}{n}\right)^n = 1-\frac {\theta^n} {\theta^n}\cdot \left(1 + \frac{-z/\theta}{n}\right)^n$$
$$\to 1- e^{-z/\theta}$$
which is the CDF of the Exponential distribution.
I hope this provides some direction. | For what models does the bias of MLE fall faster than the variance?
In general, you need models where the MLE is not asymptotically normal but converges to some other distribution (and it does so at a faster rate). This usually happens when the parameter under estimat |
19,174 | For what models does the bias of MLE fall faster than the variance? | Following comments in my other answer (and looking again at the title of the OP's question!), here is an not very rigorous theoretical exploration of the issue.
We want to determine whether Bias $B(\hat \theta_n) = E(\hat \theta_n) - \theta$ may have different convergence rate than the square root of the Variance,
$$B(\hat \theta_n) = O(1/n^{\delta}),\;\;\; \sqrt {\text{Var}(\hat \theta_n)} = O(1/n^{\gamma}), \;\;\gamma \neq \delta \;???$$
We have
$$B(\hat \theta_n) = O(1/n^{\delta}) \implies \lim n^{\delta}\mathbb E(\hat \theta_n) < K \implies \lim n^{2\delta}[\mathbb E(\hat \theta_n)]^2 < K'$$
$$\implies [\mathbb E(\hat \theta_n)]^2 = O(1/n^{2\delta}) \tag{1}$$
while
$$ \sqrt {\text{Var}(\hat \theta_n)} = O(1/n^{\gamma}) \implies \lim n^{\gamma}\sqrt{\mathbb E (\hat \theta_n^2) - [\mathbb E(\hat \theta_n)]^2 }<M$$
$$\implies \lim \sqrt{n^{2\gamma}\mathbb E (\hat \theta_n^2) - n^{2\gamma}[\mathbb E(\hat \theta_n)]^2 }<M $$
$$\implies \lim n^{2\gamma}\mathbb E (\hat \theta_n^2) - \lim n^{2\gamma}[\mathbb E(\hat \theta_n)]^2 < M' \tag{2}$$
We see that $(2)$ may hold happen if
A) both components are $O(1/n^{2\gamma})$, in which case we can only have $\gamma = \delta$.
B) But it may also hold if
$$\lim n^{2\gamma}[\mathbb E(\hat \theta_n)]^2 \to 0 \implies [\mathbb E(\hat \theta_n)]^2 = o(1/n^{2\gamma}) \tag{3}$$
For $(3)$ to be compatible with $(1)$, we must have
$$n^{2\gamma} < n^{2\delta} \implies \delta > \gamma\tag {4} $$
So it appears that in principle it is possible to have the Bias converging at a faster rate than the square root of the variance. But we cannot have the square root of the variance converging at a faster rate than the Bias. | For what models does the bias of MLE fall faster than the variance? | Following comments in my other answer (and looking again at the title of the OP's question!), here is an not very rigorous theoretical exploration of the issue.
We want to determine whether Bias $B(\h | For what models does the bias of MLE fall faster than the variance?
Following comments in my other answer (and looking again at the title of the OP's question!), here is an not very rigorous theoretical exploration of the issue.
We want to determine whether Bias $B(\hat \theta_n) = E(\hat \theta_n) - \theta$ may have different convergence rate than the square root of the Variance,
$$B(\hat \theta_n) = O(1/n^{\delta}),\;\;\; \sqrt {\text{Var}(\hat \theta_n)} = O(1/n^{\gamma}), \;\;\gamma \neq \delta \;???$$
We have
$$B(\hat \theta_n) = O(1/n^{\delta}) \implies \lim n^{\delta}\mathbb E(\hat \theta_n) < K \implies \lim n^{2\delta}[\mathbb E(\hat \theta_n)]^2 < K'$$
$$\implies [\mathbb E(\hat \theta_n)]^2 = O(1/n^{2\delta}) \tag{1}$$
while
$$ \sqrt {\text{Var}(\hat \theta_n)} = O(1/n^{\gamma}) \implies \lim n^{\gamma}\sqrt{\mathbb E (\hat \theta_n^2) - [\mathbb E(\hat \theta_n)]^2 }<M$$
$$\implies \lim \sqrt{n^{2\gamma}\mathbb E (\hat \theta_n^2) - n^{2\gamma}[\mathbb E(\hat \theta_n)]^2 }<M $$
$$\implies \lim n^{2\gamma}\mathbb E (\hat \theta_n^2) - \lim n^{2\gamma}[\mathbb E(\hat \theta_n)]^2 < M' \tag{2}$$
We see that $(2)$ may hold happen if
A) both components are $O(1/n^{2\gamma})$, in which case we can only have $\gamma = \delta$.
B) But it may also hold if
$$\lim n^{2\gamma}[\mathbb E(\hat \theta_n)]^2 \to 0 \implies [\mathbb E(\hat \theta_n)]^2 = o(1/n^{2\gamma}) \tag{3}$$
For $(3)$ to be compatible with $(1)$, we must have
$$n^{2\gamma} < n^{2\delta} \implies \delta > \gamma\tag {4} $$
So it appears that in principle it is possible to have the Bias converging at a faster rate than the square root of the variance. But we cannot have the square root of the variance converging at a faster rate than the Bias. | For what models does the bias of MLE fall faster than the variance?
Following comments in my other answer (and looking again at the title of the OP's question!), here is an not very rigorous theoretical exploration of the issue.
We want to determine whether Bias $B(\h |
19,175 | Does it makes sense to use feature selection before Random Forest? | Yes it does and it is quite common. If you expect more than ~50% of your features not even are redundant but utterly useless. E.g. the randomForest package has the wrapper function rfcv() which will pretrain a randomForest and omit the least important variables. rfcv function refer to this chapter.
Remember to embed feature selection + modeling in a outer cross-validation loop to avoid over optimistic results.
[edit below]
I could moderate "utterly useless". A single random forest will most often not as e.g. regression with lasso regularization completely ignore features, even if these (in simulated hindsight) were random features. Decision tree splits by features are chosen by local criteria in any of the thousands or millions of nodes and cannot later be undone.
I do not advocate cutting features down to one superior selection, but it is for some data sets possible to achieve substantial increase in prediction performance (estimated by a repeated outer cross-validation) using this variable selection. A typical finding would be that keeping 100% of features or only few percent work less well, and then there can be a broad middle range with similar estimated prediction performance.
Perhaps a reasonable thumb rule: When one expect that lasso-like regularization would serve better than a ridge-like regularization for a given problem, then one could try pre-training a random forest and rank the features by the inner out-of-bag cross-validated variable importance and try drop some of the least important features. Variable importance quantifies how much the cross-validated model prediction decreases, when a given feature is permuted(values shuffled) after training, before prediction. One will never be certain if one specific feature should be included or not, but it likely much easier to predict by the top 5% features, than the bottom 5%.
From a practical point of view, computational run time could be lowered, and maybe some resources could be saved, if there is a fixed acquisition cost per feature. | Does it makes sense to use feature selection before Random Forest? | Yes it does and it is quite common. If you expect more than ~50% of your features not even are redundant but utterly useless. E.g. the randomForest package has the wrapper function rfcv() which will p | Does it makes sense to use feature selection before Random Forest?
Yes it does and it is quite common. If you expect more than ~50% of your features not even are redundant but utterly useless. E.g. the randomForest package has the wrapper function rfcv() which will pretrain a randomForest and omit the least important variables. rfcv function refer to this chapter.
Remember to embed feature selection + modeling in a outer cross-validation loop to avoid over optimistic results.
[edit below]
I could moderate "utterly useless". A single random forest will most often not as e.g. regression with lasso regularization completely ignore features, even if these (in simulated hindsight) were random features. Decision tree splits by features are chosen by local criteria in any of the thousands or millions of nodes and cannot later be undone.
I do not advocate cutting features down to one superior selection, but it is for some data sets possible to achieve substantial increase in prediction performance (estimated by a repeated outer cross-validation) using this variable selection. A typical finding would be that keeping 100% of features or only few percent work less well, and then there can be a broad middle range with similar estimated prediction performance.
Perhaps a reasonable thumb rule: When one expect that lasso-like regularization would serve better than a ridge-like regularization for a given problem, then one could try pre-training a random forest and rank the features by the inner out-of-bag cross-validated variable importance and try drop some of the least important features. Variable importance quantifies how much the cross-validated model prediction decreases, when a given feature is permuted(values shuffled) after training, before prediction. One will never be certain if one specific feature should be included or not, but it likely much easier to predict by the top 5% features, than the bottom 5%.
From a practical point of view, computational run time could be lowered, and maybe some resources could be saved, if there is a fixed acquisition cost per feature. | Does it makes sense to use feature selection before Random Forest?
Yes it does and it is quite common. If you expect more than ~50% of your features not even are redundant but utterly useless. E.g. the randomForest package has the wrapper function rfcv() which will p |
19,176 | Resources for Interrupted time series analysis in R | This is known as change-point analysis. The R package changepoint can do this for you: see the documentation here (including references to the literature): http://www.lancs.ac.uk/~killick/Pub/KillickEckley2011.pdf | Resources for Interrupted time series analysis in R | This is known as change-point analysis. The R package changepoint can do this for you: see the documentation here (including references to the literature): http://www.lancs.ac.uk/~killick/Pub/KillickE | Resources for Interrupted time series analysis in R
This is known as change-point analysis. The R package changepoint can do this for you: see the documentation here (including references to the literature): http://www.lancs.ac.uk/~killick/Pub/KillickEckley2011.pdf | Resources for Interrupted time series analysis in R
This is known as change-point analysis. The R package changepoint can do this for you: see the documentation here (including references to the literature): http://www.lancs.ac.uk/~killick/Pub/KillickE |
19,177 | Resources for Interrupted time series analysis in R | I would suggest a repeated measures hierarchical model. This method should provide robust results since each individual will act as his/her own control.
Try checking out this link from UCLA. | Resources for Interrupted time series analysis in R | I would suggest a repeated measures hierarchical model. This method should provide robust results since each individual will act as his/her own control.
Try checking out this link from UCLA. | Resources for Interrupted time series analysis in R
I would suggest a repeated measures hierarchical model. This method should provide robust results since each individual will act as his/her own control.
Try checking out this link from UCLA. | Resources for Interrupted time series analysis in R
I would suggest a repeated measures hierarchical model. This method should provide robust results since each individual will act as his/her own control.
Try checking out this link from UCLA. |
19,178 | Resources for Interrupted time series analysis in R | A couple professors from ASU have a nice resource for interrupted time series in R that I found helpful. They provide reproducible examples for modeling the effect of a policy intervention.
The book is called Foundations of Program Evaluation: Regression Tools for Impact Analysis, and it is available for free on github. | Resources for Interrupted time series analysis in R | A couple professors from ASU have a nice resource for interrupted time series in R that I found helpful. They provide reproducible examples for modeling the effect of a policy intervention.
The book i | Resources for Interrupted time series analysis in R
A couple professors from ASU have a nice resource for interrupted time series in R that I found helpful. They provide reproducible examples for modeling the effect of a policy intervention.
The book is called Foundations of Program Evaluation: Regression Tools for Impact Analysis, and it is available for free on github. | Resources for Interrupted time series analysis in R
A couple professors from ASU have a nice resource for interrupted time series in R that I found helpful. They provide reproducible examples for modeling the effect of a policy intervention.
The book i |
19,179 | Resources for Interrupted time series analysis in R | For a Bayesian approach, you can use mcp to fit a Poisson or Binomial model (because you have counts from fixed-interval periods) with autoregression applied to the residuals (in the log space). Then compare a two-segment model to a one-segment model using cross-validation.
Before we start, note that for this dataset, this model does not fit well and cross-validation looks unstable. So I would refrain from using the following in high-stakes scenarios, but it illustrates a general approach:
# Fit the change point model
library(mcp)
model_full = list(
count ~ 1 + ar(1), # intercept and AR(1)
~ 1 # New intercept
)
fit_full = mcp(model_full, data = df, family = poisson(), par_x = "year")
# Fit the null model
model_null = list(
count ~ 1 + ar(1) # just a stable AR(1)
)
fit_null = mcp(model_null, data = df, family = poisson(), par_x = "year")
# Compare predictive performance using LOO cross-validation
fit_full$loo = loo(fit_full)
fit_null$loo = loo(fit_null)
loo::loo_compare(fit_full$loo, fit_null$loo)
For the present dataset, this results in
elpd_diff se_diff
model2 0.0 0.0
model1 -459.1 64.3
I.e., an elpd_diff/se_diff ratio of around 7 in favor of the null model (no change). Possible improvements include:
modeling the periodical trend using sin() or cos().
adding prior information about the likely location of the change, e.g., prior = list(cp_1 = dnorm(1999.8, 0.5).
Read more about modeling autoregression, doing model comparison, and setting priors the mcp website. Disclosure: I am the developer of mcp. | Resources for Interrupted time series analysis in R | For a Bayesian approach, you can use mcp to fit a Poisson or Binomial model (because you have counts from fixed-interval periods) with autoregression applied to the residuals (in the log space). Then | Resources for Interrupted time series analysis in R
For a Bayesian approach, you can use mcp to fit a Poisson or Binomial model (because you have counts from fixed-interval periods) with autoregression applied to the residuals (in the log space). Then compare a two-segment model to a one-segment model using cross-validation.
Before we start, note that for this dataset, this model does not fit well and cross-validation looks unstable. So I would refrain from using the following in high-stakes scenarios, but it illustrates a general approach:
# Fit the change point model
library(mcp)
model_full = list(
count ~ 1 + ar(1), # intercept and AR(1)
~ 1 # New intercept
)
fit_full = mcp(model_full, data = df, family = poisson(), par_x = "year")
# Fit the null model
model_null = list(
count ~ 1 + ar(1) # just a stable AR(1)
)
fit_null = mcp(model_null, data = df, family = poisson(), par_x = "year")
# Compare predictive performance using LOO cross-validation
fit_full$loo = loo(fit_full)
fit_null$loo = loo(fit_null)
loo::loo_compare(fit_full$loo, fit_null$loo)
For the present dataset, this results in
elpd_diff se_diff
model2 0.0 0.0
model1 -459.1 64.3
I.e., an elpd_diff/se_diff ratio of around 7 in favor of the null model (no change). Possible improvements include:
modeling the periodical trend using sin() or cos().
adding prior information about the likely location of the change, e.g., prior = list(cp_1 = dnorm(1999.8, 0.5).
Read more about modeling autoregression, doing model comparison, and setting priors the mcp website. Disclosure: I am the developer of mcp. | Resources for Interrupted time series analysis in R
For a Bayesian approach, you can use mcp to fit a Poisson or Binomial model (because you have counts from fixed-interval periods) with autoregression applied to the residuals (in the log space). Then |
19,180 | How to decide which interaction terms to include in a multiple regression model? | I think you can deal with some of these issues based on your domain knowledge. 21 predictors aren't a lot with 11,000 records, if your outcome variable is some continuous measure, so the issues you face are what predictors and interactions to include and how to deal with collinearity.
For building the model, you might not want to omit any of your 21 original predictors. When you omit 1 of 2 highly correlated predictors, you are throwing out information provided by the one you omit and run the risk of your results being too closely tied to the peculiarities of those correlated variables in the particular sample that you are analyzing. Also, don't depend on correlation of independent variables with your dependent variable for choosing predictors to include. Keeping some predictors poorly correlated with the dependent variable might help improve the performance of other predictors, even in the absence of interactions.
For interactions, consider adding interactions that you think might be important based on your domain knowledge. That presumably will be a lot fewer than the 420 possible 2-way interactions among 21 predictors so that you will still have a reasonably small number of independent variables. You might even consider not including any interactions at all and seeing if the 21 predictors on their own work well enough for your purposes. Sometimes it's best to start simple, and add complexity only as needed.
One way to deal with collinearity would be based on domain knowledge: combine correlated predictors into a single predictor that captures the essential underlying phenomenon that those correlated predictors represent. That would seem to be consistent with your goal to use your model for inference. If you can combine correlated predictors in a way that's defensible based on domain knowledge, you might reduce the number of predictors in the model in a way that makes inference easier.
Alternatively, to deal with collinearity you could use an approach like ridge regression that tends to treat collinear predictors together. My impression is that ridge regression is more often used for predictive rather than for inferential models, but it does have the advantage of handling collinearity in a reasonable way. It returns coefficients for all predictors, which is either an advantage or a disadvantage depending on your perspective. Some might prefer LASSO for inference as it retains only a subset of predictors, but its particular choice among collinear predictors might be sample dependent and you would have to consider that in interpreting the results.
My guess is that a bigger problem than dealing with 21 predictor variables will be finding appropriate scaling transformations for your variables so that they work reasonably well in the approximation of a linear model. | How to decide which interaction terms to include in a multiple regression model? | I think you can deal with some of these issues based on your domain knowledge. 21 predictors aren't a lot with 11,000 records, if your outcome variable is some continuous measure, so the issues you fa | How to decide which interaction terms to include in a multiple regression model?
I think you can deal with some of these issues based on your domain knowledge. 21 predictors aren't a lot with 11,000 records, if your outcome variable is some continuous measure, so the issues you face are what predictors and interactions to include and how to deal with collinearity.
For building the model, you might not want to omit any of your 21 original predictors. When you omit 1 of 2 highly correlated predictors, you are throwing out information provided by the one you omit and run the risk of your results being too closely tied to the peculiarities of those correlated variables in the particular sample that you are analyzing. Also, don't depend on correlation of independent variables with your dependent variable for choosing predictors to include. Keeping some predictors poorly correlated with the dependent variable might help improve the performance of other predictors, even in the absence of interactions.
For interactions, consider adding interactions that you think might be important based on your domain knowledge. That presumably will be a lot fewer than the 420 possible 2-way interactions among 21 predictors so that you will still have a reasonably small number of independent variables. You might even consider not including any interactions at all and seeing if the 21 predictors on their own work well enough for your purposes. Sometimes it's best to start simple, and add complexity only as needed.
One way to deal with collinearity would be based on domain knowledge: combine correlated predictors into a single predictor that captures the essential underlying phenomenon that those correlated predictors represent. That would seem to be consistent with your goal to use your model for inference. If you can combine correlated predictors in a way that's defensible based on domain knowledge, you might reduce the number of predictors in the model in a way that makes inference easier.
Alternatively, to deal with collinearity you could use an approach like ridge regression that tends to treat collinear predictors together. My impression is that ridge regression is more often used for predictive rather than for inferential models, but it does have the advantage of handling collinearity in a reasonable way. It returns coefficients for all predictors, which is either an advantage or a disadvantage depending on your perspective. Some might prefer LASSO for inference as it retains only a subset of predictors, but its particular choice among collinear predictors might be sample dependent and you would have to consider that in interpreting the results.
My guess is that a bigger problem than dealing with 21 predictor variables will be finding appropriate scaling transformations for your variables so that they work reasonably well in the approximation of a linear model. | How to decide which interaction terms to include in a multiple regression model?
I think you can deal with some of these issues based on your domain knowledge. 21 predictors aren't a lot with 11,000 records, if your outcome variable is some continuous measure, so the issues you fa |
19,181 | How can I programmatically detect segments of a data series to fit with different curves? | My interpretation of the question is that the OP is looking for methodologies that would fit the shape(s) of the examples provided, not the HAC residuals. In addition, automated routines that don't require significant human or analyst intervention are desired. Box-Jenkins may not be appropriate, despite their emphasis in this thread, since they do require substantial analyst involvement.
R modules exist for this type of non-moment based, pattern matching. Permutation distribution clustering is such a pattern matching technique developed by a Max Planck Institute scientist that meets the criteria you've outlined. Its application is to time series data, but it's not limited to that. Here's a citation for the R module that's been developed:
pdc: An R Package for Complexity-Based Clustering of Time Series by Andreas Brandmaier
In addition to PDC, there's the machine learning, iSax routine developed by Eamon Keogh at UC Irvine that's also worth comparison.
Finally, there's this paper on Data Smashing: Uncovering Lurking Order in Data by Chattopadhyay and Lipson. Beyond the clever title, there is a serious purpose at work. Here's the abstract:
"From automatic speech recognition to discovering unusual stars, underlying
almost all automated discovery tasks is the ability to compare and contrast
data streams with each other, to identify connections and spot outliers. Despite the prevalence of data, however, automated methods are not keeping pace. A key bottleneck is that most data comparison algorithms today rely on a human expert to specify what ‘features’ of the data are relevant for comparison. Here, we propose a new principle for estimating the similarity between the sources of arbitrary data streams, using neither domain knowledge nor learning. We demonstrate the application of this principle to the analysis of data from a number of real-world challenging problems, including the disambiguation of electro-encephalograph patterns pertaining to epileptic seizures, detection of anomalous cardiac activity fromheart sound recordings and classification of astronomical objects from raw photometry. In all these cases and without access to any domain knowledge, we demonstrate performance on a par with the accuracy achieved by specialized algorithms and heuristics
devised by domain experts. We suggest that data smashing principles may open the door to understanding increasingly complex observations, especially when experts do not know what to look for."
This approach goes way beyond curvilinear fit. It's worth checking out. | How can I programmatically detect segments of a data series to fit with different curves? | My interpretation of the question is that the OP is looking for methodologies that would fit the shape(s) of the examples provided, not the HAC residuals. In addition, automated routines that don't re | How can I programmatically detect segments of a data series to fit with different curves?
My interpretation of the question is that the OP is looking for methodologies that would fit the shape(s) of the examples provided, not the HAC residuals. In addition, automated routines that don't require significant human or analyst intervention are desired. Box-Jenkins may not be appropriate, despite their emphasis in this thread, since they do require substantial analyst involvement.
R modules exist for this type of non-moment based, pattern matching. Permutation distribution clustering is such a pattern matching technique developed by a Max Planck Institute scientist that meets the criteria you've outlined. Its application is to time series data, but it's not limited to that. Here's a citation for the R module that's been developed:
pdc: An R Package for Complexity-Based Clustering of Time Series by Andreas Brandmaier
In addition to PDC, there's the machine learning, iSax routine developed by Eamon Keogh at UC Irvine that's also worth comparison.
Finally, there's this paper on Data Smashing: Uncovering Lurking Order in Data by Chattopadhyay and Lipson. Beyond the clever title, there is a serious purpose at work. Here's the abstract:
"From automatic speech recognition to discovering unusual stars, underlying
almost all automated discovery tasks is the ability to compare and contrast
data streams with each other, to identify connections and spot outliers. Despite the prevalence of data, however, automated methods are not keeping pace. A key bottleneck is that most data comparison algorithms today rely on a human expert to specify what ‘features’ of the data are relevant for comparison. Here, we propose a new principle for estimating the similarity between the sources of arbitrary data streams, using neither domain knowledge nor learning. We demonstrate the application of this principle to the analysis of data from a number of real-world challenging problems, including the disambiguation of electro-encephalograph patterns pertaining to epileptic seizures, detection of anomalous cardiac activity fromheart sound recordings and classification of astronomical objects from raw photometry. In all these cases and without access to any domain knowledge, we demonstrate performance on a par with the accuracy achieved by specialized algorithms and heuristics
devised by domain experts. We suggest that data smashing principles may open the door to understanding increasingly complex observations, especially when experts do not know what to look for."
This approach goes way beyond curvilinear fit. It's worth checking out. | How can I programmatically detect segments of a data series to fit with different curves?
My interpretation of the question is that the OP is looking for methodologies that would fit the shape(s) of the examples provided, not the HAC residuals. In addition, automated routines that don't re |
19,182 | How can I programmatically detect segments of a data series to fit with different curves? | Detecting change points in a time series requires the construction of a robust global ARIMA model (certainly flawed by model changes and parameter changes over time in your case ) and then identifying the most significant change point in the parameters of that model. Using your 509 values the most significant change point was around period 353. I used some proprietary algorithms available in AUTOBOX (which I have helped develop) that could possibly be licensed for your customized application. The basic idea is to separate the data into two parts and upon finding the most important change point re-analyze each of the two time ranges separately (1-352 ; 353-509 ) to determine further change points within each of the two sets. This is repeated until you have k subsets. I have attached the first step using this approach. Visually it appears to me that the most important point change point has been identified. | How can I programmatically detect segments of a data series to fit with different curves? | Detecting change points in a time series requires the construction of a robust global ARIMA model (certainly flawed by model changes and parameter changes over time in your case ) and then identifying | How can I programmatically detect segments of a data series to fit with different curves?
Detecting change points in a time series requires the construction of a robust global ARIMA model (certainly flawed by model changes and parameter changes over time in your case ) and then identifying the most significant change point in the parameters of that model. Using your 509 values the most significant change point was around period 353. I used some proprietary algorithms available in AUTOBOX (which I have helped develop) that could possibly be licensed for your customized application. The basic idea is to separate the data into two parts and upon finding the most important change point re-analyze each of the two time ranges separately (1-352 ; 353-509 ) to determine further change points within each of the two sets. This is repeated until you have k subsets. I have attached the first step using this approach. Visually it appears to me that the most important point change point has been identified. | How can I programmatically detect segments of a data series to fit with different curves?
Detecting change points in a time series requires the construction of a robust global ARIMA model (certainly flawed by model changes and parameter changes over time in your case ) and then identifying |
19,183 | How can I programmatically detect segments of a data series to fit with different curves? | I think that the title of the thread is misleading: You are not looking to compare density functions but you are actually looking for structural breaks in a time series. However, you do not specify whether these structural breaks are supposed to be found in a rolling time window or in hindsight by looking at the total history of the time series. In this sense your question is actually a duplicate to this: What method to detect structural breaks on time series?
As mentioned by Rob Hyndman in this link, R offers the strucchange package for this purpose. I played around with your data but I must say that the results are dissappointing [is the first data point really 4 or supposed to be 54?]:
raw = c(54,53,53,53,53,58,56,52,49,52,56,51,44,39,39,39,37,33,27,21,18,12,19,30,45,66,92,118,135,148,153,160,168,174,181,187,191,190,191,192,194,194,194,193,193,201,200,199,199,199,197,193,190,187,176,162,157,154,144,126,110,87,74,57,46,44,51,60,65,66,90,106,99,87,84,85,83,91,95,99,101,102,102,103,105,110,107,108,135,171,171,141,120,78,42,44,52,54,103,128,82,103,46,27,73,123,125,77,24,30,27,36,42,49,32,55,20,16,21,31,78,140,116,99,58,139,70,22,44,7,48,32,18,16,25,16,17,35,29,11,13,8,8,18,14,0,10,18,2,1,4,0,61,87,91,2,0,2,9,40,21,2,14,5,9,49,116,100,114,115,62,41,119,191,190,164,156,109,37,15,0,5,1,0,0,2,4,2,0,48,129,168,112,98,95,119,125,191,241,209,229,230,231,246,249,240,99,32,0,0,2,13,28,39,15,15,19,31,47,61,92,91,99,108,114,118,121,125,129,129,125,125,131,135,138,142,147,141,149,153,152,153,159,161,158,158,162,167,171,173,174,176,178,184,190,190,185,190,200,199,189,196,197,197,196,199,200,195,187,191,192,190,186,184,184,179,173,171,170,164,156,155,156,151,141,141,139,143,143,140,146,145,130,126,127,127,125,122,122,127,131,134,140,150,160,166,175,192,208,243,251,255,255,255,249,221,190,181,181,181,181,179,173,165,159,153,162,169,165,154,144,142,145,136,134,131,130,128,124,119,115,103,78,54,40,25,8,2,7,12,25,13,22,15,33,34,57,71,48,16,1,2,0,2,21,112,174,191,190,152,153,161,159,153,71,16,28,3,4,0,14,26,30,26,15,12,19,21,18,53,89,125,139,140,142,141,135,136,140,159,170,173,176,184,180,170,167,168,170,167,161,163,170,164,161,160,163,163,160,160,163,169,166,161,156,155,156,158,160,150,149,149,151,154,156,156,156,151,149,150,153,154,151,146,144,149,150,151,152,151,150,148,147,144,141,137,133,130,128,128,128,136,143,159,180,196,205,212,218,222,225,227,227,225,223,222,222,221,220,220,220,220,221,222,223,221,223,225,226,227,228,232,235,234,236,238,240,241,240,239,237,238,240,240,237,236,239,238,235)
raw = log(raw+1)
d = as.ts(raw,frequency = 12)
dd = ts.intersect(d = d, d1 = lag(d, -1),d2 = lag(d, -2),d3 = lag(d, -3),d4 = lag(d, -4),d5 = lag(d, -5),d6 = lag(d, -6),d7 = lag(d, -7),d8 = lag(d, -8),d9 = lag(d, -9),d10 = lag(d, -10),d11 = lag(d, -11),d12 = lag(d, -12))
(breakpoints(d ~d1 + d2+ d3+ d4+ d5+ d6+ d7+ d8+ d9+ d10+ d11+ d12, data = dd))
>Breakpoints at observation number:
>151
>Corresponding to breakdates:
>163
(breakpoints(d ~d1 + d2, data = dd))
>Breakpoints at observation number:
>95 178
>Corresponding to breakdates:
>107 190
I am not a regular user of the package. As you can see it depends on the model you fit on the data. You can experiment with
library(forecast)
auto.arima(raw)
which gives you the best fitting ARIMA model. | How can I programmatically detect segments of a data series to fit with different curves? | I think that the title of the thread is misleading: You are not looking to compare density functions but you are actually looking for structural breaks in a time series. However, you do not specify wh | How can I programmatically detect segments of a data series to fit with different curves?
I think that the title of the thread is misleading: You are not looking to compare density functions but you are actually looking for structural breaks in a time series. However, you do not specify whether these structural breaks are supposed to be found in a rolling time window or in hindsight by looking at the total history of the time series. In this sense your question is actually a duplicate to this: What method to detect structural breaks on time series?
As mentioned by Rob Hyndman in this link, R offers the strucchange package for this purpose. I played around with your data but I must say that the results are dissappointing [is the first data point really 4 or supposed to be 54?]:
raw = c(54,53,53,53,53,58,56,52,49,52,56,51,44,39,39,39,37,33,27,21,18,12,19,30,45,66,92,118,135,148,153,160,168,174,181,187,191,190,191,192,194,194,194,193,193,201,200,199,199,199,197,193,190,187,176,162,157,154,144,126,110,87,74,57,46,44,51,60,65,66,90,106,99,87,84,85,83,91,95,99,101,102,102,103,105,110,107,108,135,171,171,141,120,78,42,44,52,54,103,128,82,103,46,27,73,123,125,77,24,30,27,36,42,49,32,55,20,16,21,31,78,140,116,99,58,139,70,22,44,7,48,32,18,16,25,16,17,35,29,11,13,8,8,18,14,0,10,18,2,1,4,0,61,87,91,2,0,2,9,40,21,2,14,5,9,49,116,100,114,115,62,41,119,191,190,164,156,109,37,15,0,5,1,0,0,2,4,2,0,48,129,168,112,98,95,119,125,191,241,209,229,230,231,246,249,240,99,32,0,0,2,13,28,39,15,15,19,31,47,61,92,91,99,108,114,118,121,125,129,129,125,125,131,135,138,142,147,141,149,153,152,153,159,161,158,158,162,167,171,173,174,176,178,184,190,190,185,190,200,199,189,196,197,197,196,199,200,195,187,191,192,190,186,184,184,179,173,171,170,164,156,155,156,151,141,141,139,143,143,140,146,145,130,126,127,127,125,122,122,127,131,134,140,150,160,166,175,192,208,243,251,255,255,255,249,221,190,181,181,181,181,179,173,165,159,153,162,169,165,154,144,142,145,136,134,131,130,128,124,119,115,103,78,54,40,25,8,2,7,12,25,13,22,15,33,34,57,71,48,16,1,2,0,2,21,112,174,191,190,152,153,161,159,153,71,16,28,3,4,0,14,26,30,26,15,12,19,21,18,53,89,125,139,140,142,141,135,136,140,159,170,173,176,184,180,170,167,168,170,167,161,163,170,164,161,160,163,163,160,160,163,169,166,161,156,155,156,158,160,150,149,149,151,154,156,156,156,151,149,150,153,154,151,146,144,149,150,151,152,151,150,148,147,144,141,137,133,130,128,128,128,136,143,159,180,196,205,212,218,222,225,227,227,225,223,222,222,221,220,220,220,220,221,222,223,221,223,225,226,227,228,232,235,234,236,238,240,241,240,239,237,238,240,240,237,236,239,238,235)
raw = log(raw+1)
d = as.ts(raw,frequency = 12)
dd = ts.intersect(d = d, d1 = lag(d, -1),d2 = lag(d, -2),d3 = lag(d, -3),d4 = lag(d, -4),d5 = lag(d, -5),d6 = lag(d, -6),d7 = lag(d, -7),d8 = lag(d, -8),d9 = lag(d, -9),d10 = lag(d, -10),d11 = lag(d, -11),d12 = lag(d, -12))
(breakpoints(d ~d1 + d2+ d3+ d4+ d5+ d6+ d7+ d8+ d9+ d10+ d11+ d12, data = dd))
>Breakpoints at observation number:
>151
>Corresponding to breakdates:
>163
(breakpoints(d ~d1 + d2, data = dd))
>Breakpoints at observation number:
>95 178
>Corresponding to breakdates:
>107 190
I am not a regular user of the package. As you can see it depends on the model you fit on the data. You can experiment with
library(forecast)
auto.arima(raw)
which gives you the best fitting ARIMA model. | How can I programmatically detect segments of a data series to fit with different curves?
I think that the title of the thread is misleading: You are not looking to compare density functions but you are actually looking for structural breaks in a time series. However, you do not specify wh |
19,184 | The variance-covariance matrix of the least squares parameter estimation | The other answer here and the answers on a later version of this question here [Covariance matrix of least squares estimator $\hat{\beta}$ are not correct
In the book you are referencing, the data $x_1,\dots,x_N$ ($x_i^{\top}$ is the ith row of $\mathbf{X}$) are not random. The authors say that the $y_i$ are uncorrelated with constant variance. And we have the formula
$$
\hat{\beta} = (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbf{y}.
$$
That's really all they say. There is no assumption that the real distribution of $Y$ is a linear function of $X$ plus a noise. And there is no explicit assumption that $\mathbb{E}(Y|X) = 0$. So, if you try to work with the information you are actually given in the book, you'll do something like this:
First we compute the expectation:
$$
\mathbb{E}(\hat{\beta}) = (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y}) = (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y})
$$
So
\begin{align}
\mathbb{E}(\hat{\beta})\mathbb{E}(\hat{\beta})^T &= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y}) \Bigl((\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y})\Bigr)^{\top} \\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y}) \mathbb{E}(\mathbf{y})^{\top} \mathbf{X}(\mathbf{X}^{\top}\mathbf{X})^{-1} \\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y}) \mathbb{E}(\mathbf{y})^{\top} \mathbf{X}\bigl((\mathbf{X}^{\top}\mathbf{X})^{-1}\bigr)^{\top} \\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y}) \mathbb{E}(\mathbf{y})^{\top} \mathbf{X}(\mathbf{X}^{\top}\mathbf{X})^{-1}
\end{align}
And
\begin{align}
\mathbb{E}(\hat{\beta}\hat{\beta}^T) &= \mathbb{E}\biggl((\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbf{y}\Bigl( (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbf{y}\Bigr)^{\top} \biggr)\\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y} \mathbf{y}^{\top}) \mathbf{X} (\mathbf{X}^{\top}\mathbf{X})^{-1}
\end{align}
The variance-covariance matrix is the difference as usual, which comes out as
\begin{align}
&(\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\bigl(\mathbb{E}(\mathbf{y} \mathbf{y}^{\top}) - \mathbb{E}(\mathbf{y}) \mathbb{E}(\mathbf{y})^{\top} \bigr) \mathbf{X} (\mathbf{X}^{\top}\mathbf{X})^{-1} \\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\bigl(\sigma^2 I_{N\times N} \bigr) \mathbf{X} (\mathbf{X}^{\top}\mathbf{X})^{-1} \\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\sigma^2
\end{align}
So the only assumption that we had, I use explicitly at the end: We know the variance-covariance matrix of $\mathbf{y}$ is just $\sigma^2$ multiplied by the identity matrix. | The variance-covariance matrix of the least squares parameter estimation | The other answer here and the answers on a later version of this question here [Covariance matrix of least squares estimator $\hat{\beta}$ are not correct
In the book you are referencing, the data $x | The variance-covariance matrix of the least squares parameter estimation
The other answer here and the answers on a later version of this question here [Covariance matrix of least squares estimator $\hat{\beta}$ are not correct
In the book you are referencing, the data $x_1,\dots,x_N$ ($x_i^{\top}$ is the ith row of $\mathbf{X}$) are not random. The authors say that the $y_i$ are uncorrelated with constant variance. And we have the formula
$$
\hat{\beta} = (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbf{y}.
$$
That's really all they say. There is no assumption that the real distribution of $Y$ is a linear function of $X$ plus a noise. And there is no explicit assumption that $\mathbb{E}(Y|X) = 0$. So, if you try to work with the information you are actually given in the book, you'll do something like this:
First we compute the expectation:
$$
\mathbb{E}(\hat{\beta}) = (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y}) = (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y})
$$
So
\begin{align}
\mathbb{E}(\hat{\beta})\mathbb{E}(\hat{\beta})^T &= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y}) \Bigl((\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y})\Bigr)^{\top} \\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y}) \mathbb{E}(\mathbf{y})^{\top} \mathbf{X}(\mathbf{X}^{\top}\mathbf{X})^{-1} \\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y}) \mathbb{E}(\mathbf{y})^{\top} \mathbf{X}\bigl((\mathbf{X}^{\top}\mathbf{X})^{-1}\bigr)^{\top} \\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y}) \mathbb{E}(\mathbf{y})^{\top} \mathbf{X}(\mathbf{X}^{\top}\mathbf{X})^{-1}
\end{align}
And
\begin{align}
\mathbb{E}(\hat{\beta}\hat{\beta}^T) &= \mathbb{E}\biggl((\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbf{y}\Bigl( (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbf{y}\Bigr)^{\top} \biggr)\\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\mathbb{E}(\mathbf{y} \mathbf{y}^{\top}) \mathbf{X} (\mathbf{X}^{\top}\mathbf{X})^{-1}
\end{align}
The variance-covariance matrix is the difference as usual, which comes out as
\begin{align}
&(\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\bigl(\mathbb{E}(\mathbf{y} \mathbf{y}^{\top}) - \mathbb{E}(\mathbf{y}) \mathbb{E}(\mathbf{y})^{\top} \bigr) \mathbf{X} (\mathbf{X}^{\top}\mathbf{X})^{-1} \\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\mathbf{X}^{\top}\bigl(\sigma^2 I_{N\times N} \bigr) \mathbf{X} (\mathbf{X}^{\top}\mathbf{X})^{-1} \\
&= (\mathbf{X}^{\top}\mathbf{X})^{-1}\sigma^2
\end{align}
So the only assumption that we had, I use explicitly at the end: We know the variance-covariance matrix of $\mathbf{y}$ is just $\sigma^2$ multiplied by the identity matrix. | The variance-covariance matrix of the least squares parameter estimation
The other answer here and the answers on a later version of this question here [Covariance matrix of least squares estimator $\hat{\beta}$ are not correct
In the book you are referencing, the data $x |
19,185 | The variance-covariance matrix of the least squares parameter estimation | Because $x_i$ are fixed, so
$$\mathrm{Var}[\hat{\beta}] = (\mathbf{X}^T\mathbf{X})^{-1}\mathrm{Var}[\mathbf{y}] $$
And
$$\mathrm{Var}[\mathbf{y}] = \mathrm{Cov}[\mathbf{y}]=
\left[\begin{array}{ccc}
\sigma_{11} & \cdots & \sigma_{1 n} \\
\vdots & \ddots & \vdots \\
\sigma_{p1} & \cdots & \sigma_{n n}
\end{array}\right]
=\sigma^2 \mathbf{I}
$$
Because $y_i$ are uncorrelated and have constant variance $\sigma^2$,
$$\sigma_{ij}=\mathrm{Cov}[y_i, y_j]=E[y_iy_j]-E[y_i]E[y_j]=\sigma^2\delta_{ij}$$
Therefore,
$$\mathrm{Var}[\hat{\beta}] = (\mathbf{X}^T\mathbf{X})^{-1} \sigma^2$$ | The variance-covariance matrix of the least squares parameter estimation | Because $x_i$ are fixed, so
$$\mathrm{Var}[\hat{\beta}] = (\mathbf{X}^T\mathbf{X})^{-1}\mathrm{Var}[\mathbf{y}] $$
And
$$\mathrm{Var}[\mathbf{y}] = \mathrm{Cov}[\mathbf{y}]=
\left[\begin{array}{ccc}
\ | The variance-covariance matrix of the least squares parameter estimation
Because $x_i$ are fixed, so
$$\mathrm{Var}[\hat{\beta}] = (\mathbf{X}^T\mathbf{X})^{-1}\mathrm{Var}[\mathbf{y}] $$
And
$$\mathrm{Var}[\mathbf{y}] = \mathrm{Cov}[\mathbf{y}]=
\left[\begin{array}{ccc}
\sigma_{11} & \cdots & \sigma_{1 n} \\
\vdots & \ddots & \vdots \\
\sigma_{p1} & \cdots & \sigma_{n n}
\end{array}\right]
=\sigma^2 \mathbf{I}
$$
Because $y_i$ are uncorrelated and have constant variance $\sigma^2$,
$$\sigma_{ij}=\mathrm{Cov}[y_i, y_j]=E[y_iy_j]-E[y_i]E[y_j]=\sigma^2\delta_{ij}$$
Therefore,
$$\mathrm{Var}[\hat{\beta}] = (\mathbf{X}^T\mathbf{X})^{-1} \sigma^2$$ | The variance-covariance matrix of the least squares parameter estimation
Because $x_i$ are fixed, so
$$\mathrm{Var}[\hat{\beta}] = (\mathbf{X}^T\mathbf{X})^{-1}\mathrm{Var}[\mathbf{y}] $$
And
$$\mathrm{Var}[\mathbf{y}] = \mathrm{Cov}[\mathbf{y}]=
\left[\begin{array}{ccc}
\ |
19,186 | The variance-covariance matrix of the least squares parameter estimation | T_M's answer addresses the first part of the question, namely, how (3.6) implies (3.8). I will address the second part, why use
$ \hat{\sigma}^2 = \frac{1}{N-p-1}\sum_{i=1}^N(y_i-\hat{y}_i)^2. $
(This was probably answered many times elsewhere, but it's easier to repeat it in the convenient notation than to translate other answers.)
If we make additional modelling assumptions (see below), then $ \hat{\sigma}^2 = \frac{1}{N-p-1}\sum_{i=1}^N(y_i-\hat{y}_i)^2$ is an unbiased estimator of the true variance. This justifies using this expression even when no such assumptions are made, because it is better than nothing. The sharp statement is as follows.
Claim. Let the data be generated by the true model $Y = \sum_{j=0}^m \beta_j X_j + \mathcal{E}$ with $E[\mathcal{E}]=0$, $\mathrm{var}[\mathcal{E}]=\sigma^2$, and uncorrelated errors (meaning that $\mathrm{var}[\mathbf{y}] = \sigma^2\mathbf{I}$). Then the least-squares estimate $\hat{\mathbf{y}}:=\mathbf{X}\hat{\boldsymbol{\beta}}$ satisfies $E[\sum_{i=1}^N(Y_i-\hat{Y}_i)^2]=(N-p-1)\sigma^2$, where $p+1$ is the number of linearly independent columns in $\mathbf{X}$.
For simplicity, let all $m+1$ columns of $\mathbf{X}$ be linearly independent, so $m=p$. Each row of $N\times(p+1)$ matrix $\mathbf{X}$ has the form $[1, X_1, \dots, X_p]$. I will use $\mathbf{X}^+$ to denote the (Moore-Penrose) pseudo-inverse of $\mathbf{X}$. If you are not comfortable with it, just remember that for a matrix with independent columns we write $\mathbf{X}^+ = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T$.
Proof. The least-squares solution for parameters is given by $\hat{\boldsymbol{\beta}}=\mathbf{X}^+\mathbf{y}$, so $\hat{\mathbf{y}}=\mathbf{X}\mathbf{X}^+\mathbf{y}$. We can write
$$ \begin{align}
\sum_{i=1}^N(Y_i-\hat{Y}_i)^2 & = (\mathbf{y} - \hat{\mathbf{y}})^T (\mathbf{y} - \hat{\mathbf{y}}) = \mathbf{y}^T (\mathbf{I} - \mathbf{X}\mathbf{X}^+)^T (\mathbf{I} - \mathbf{X}\mathbf{X}^+)\mathbf{y} \\
& = \mathrm{tr}\, \mathbf{y}^T (\mathbf{I} - \mathbf{X}\mathbf{X}^+)^T (\mathbf{I} - \mathbf{X}\mathbf{X}^+)\mathbf{y} = \mathrm{tr}\, (\mathbf{I} - \mathbf{X}\mathbf{X}^+)\mathbf{y} \mathbf{y}^T.
\end{align} $$
In the last transition we used the property of trace $\mathrm{tr}\,AB = \mathrm{tr}\,BA$ and that $P:=\mathbf{I} - \mathbf{X}\mathbf{X}^+$ is an orthogonal projection: orthogonal projections satisfy $P = P^T = P^2$. We will also require another property: that $P$ is an orthogonal projection onto the orthogonal complement of the column-space (range) of $\mathbf{X}$. That is, for any linear combination of columns, $\mathbf{X}\mathbf{w} = \sum_{j=0}^{p} \mathbf{x}_p w_p$, we have $P \mathbf{X}\mathbf{w} = \mathbf{0}$. Also, $\mathrm{tr}\,P = N-p-1$. All these properties can be demonstrated without a reference to the pseudo-inverse and orthogonal projections, but they are best understood at this level of abstraction.
The observed data is $\mathbf{y} = \mathbf{f}(\mathbf{X}) + \mathbf{e}$, where $\mathbf{f}(\mathbf{X})\equiv \mathbf{f} := E[\mathbf{y}]$. From the assumptions about the errors and $X$'s being "fixed", we have $E[\mathbf{y}\mathbf{y}^T] = \mathbf{f}\mathbf{f}^T + \sigma^2\mathbf{I}$. We use this in the expectation of the sum of squared residuals:
$$ \begin{align}
E[\sum_{i=1}^N(Y_i-\hat{Y}_i)^2] & = E[ \mathrm{tr}\, (\mathbf{I} - \mathbf{X}\mathbf{X}^+)\mathbf{y} \mathbf{y}^T] = \mathrm{tr}\, (\mathbf{I} - \mathbf{X}\mathbf{X}^+) E[ \mathbf{y} \mathbf{y}^T] \\
& = \mathrm{tr}\, \{ (\mathbf{I} - \mathbf{X}\mathbf{X}^+) \mathbf{f}\mathbf{f}^T \} + \sigma^2 \mathrm{tr}\, \{ (\mathbf{I} - \mathbf{X}\mathbf{X}^+)\} \\
& = \mathrm{tr}\, \{ \underbrace{(\mathbf{I} - \mathbf{X}\mathbf{X}^+) \mathbf{f}}_{=\mathbf{0}}\mathbf{f}^T \} + (N-p-1) \sigma^2.
\end{align},$$
where we again used the properties of the projection. $\blacksquare$.
Note that:
the assumption of uncorrelated homoskedastic errors ($\mathrm{var}\,\mathbf{y} = \sigma^2 \mathbf{I}$) is weaker than then assumption of i.i.d. errors;
there is no assumption of anything being Gaussian or normally distributed. | The variance-covariance matrix of the least squares parameter estimation | T_M's answer addresses the first part of the question, namely, how (3.6) implies (3.8). I will address the second part, why use
$ \hat{\sigma}^2 = \frac{1}{N-p-1}\sum_{i=1}^N(y_i-\hat{y}_i)^2. $
(Th | The variance-covariance matrix of the least squares parameter estimation
T_M's answer addresses the first part of the question, namely, how (3.6) implies (3.8). I will address the second part, why use
$ \hat{\sigma}^2 = \frac{1}{N-p-1}\sum_{i=1}^N(y_i-\hat{y}_i)^2. $
(This was probably answered many times elsewhere, but it's easier to repeat it in the convenient notation than to translate other answers.)
If we make additional modelling assumptions (see below), then $ \hat{\sigma}^2 = \frac{1}{N-p-1}\sum_{i=1}^N(y_i-\hat{y}_i)^2$ is an unbiased estimator of the true variance. This justifies using this expression even when no such assumptions are made, because it is better than nothing. The sharp statement is as follows.
Claim. Let the data be generated by the true model $Y = \sum_{j=0}^m \beta_j X_j + \mathcal{E}$ with $E[\mathcal{E}]=0$, $\mathrm{var}[\mathcal{E}]=\sigma^2$, and uncorrelated errors (meaning that $\mathrm{var}[\mathbf{y}] = \sigma^2\mathbf{I}$). Then the least-squares estimate $\hat{\mathbf{y}}:=\mathbf{X}\hat{\boldsymbol{\beta}}$ satisfies $E[\sum_{i=1}^N(Y_i-\hat{Y}_i)^2]=(N-p-1)\sigma^2$, where $p+1$ is the number of linearly independent columns in $\mathbf{X}$.
For simplicity, let all $m+1$ columns of $\mathbf{X}$ be linearly independent, so $m=p$. Each row of $N\times(p+1)$ matrix $\mathbf{X}$ has the form $[1, X_1, \dots, X_p]$. I will use $\mathbf{X}^+$ to denote the (Moore-Penrose) pseudo-inverse of $\mathbf{X}$. If you are not comfortable with it, just remember that for a matrix with independent columns we write $\mathbf{X}^+ = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T$.
Proof. The least-squares solution for parameters is given by $\hat{\boldsymbol{\beta}}=\mathbf{X}^+\mathbf{y}$, so $\hat{\mathbf{y}}=\mathbf{X}\mathbf{X}^+\mathbf{y}$. We can write
$$ \begin{align}
\sum_{i=1}^N(Y_i-\hat{Y}_i)^2 & = (\mathbf{y} - \hat{\mathbf{y}})^T (\mathbf{y} - \hat{\mathbf{y}}) = \mathbf{y}^T (\mathbf{I} - \mathbf{X}\mathbf{X}^+)^T (\mathbf{I} - \mathbf{X}\mathbf{X}^+)\mathbf{y} \\
& = \mathrm{tr}\, \mathbf{y}^T (\mathbf{I} - \mathbf{X}\mathbf{X}^+)^T (\mathbf{I} - \mathbf{X}\mathbf{X}^+)\mathbf{y} = \mathrm{tr}\, (\mathbf{I} - \mathbf{X}\mathbf{X}^+)\mathbf{y} \mathbf{y}^T.
\end{align} $$
In the last transition we used the property of trace $\mathrm{tr}\,AB = \mathrm{tr}\,BA$ and that $P:=\mathbf{I} - \mathbf{X}\mathbf{X}^+$ is an orthogonal projection: orthogonal projections satisfy $P = P^T = P^2$. We will also require another property: that $P$ is an orthogonal projection onto the orthogonal complement of the column-space (range) of $\mathbf{X}$. That is, for any linear combination of columns, $\mathbf{X}\mathbf{w} = \sum_{j=0}^{p} \mathbf{x}_p w_p$, we have $P \mathbf{X}\mathbf{w} = \mathbf{0}$. Also, $\mathrm{tr}\,P = N-p-1$. All these properties can be demonstrated without a reference to the pseudo-inverse and orthogonal projections, but they are best understood at this level of abstraction.
The observed data is $\mathbf{y} = \mathbf{f}(\mathbf{X}) + \mathbf{e}$, where $\mathbf{f}(\mathbf{X})\equiv \mathbf{f} := E[\mathbf{y}]$. From the assumptions about the errors and $X$'s being "fixed", we have $E[\mathbf{y}\mathbf{y}^T] = \mathbf{f}\mathbf{f}^T + \sigma^2\mathbf{I}$. We use this in the expectation of the sum of squared residuals:
$$ \begin{align}
E[\sum_{i=1}^N(Y_i-\hat{Y}_i)^2] & = E[ \mathrm{tr}\, (\mathbf{I} - \mathbf{X}\mathbf{X}^+)\mathbf{y} \mathbf{y}^T] = \mathrm{tr}\, (\mathbf{I} - \mathbf{X}\mathbf{X}^+) E[ \mathbf{y} \mathbf{y}^T] \\
& = \mathrm{tr}\, \{ (\mathbf{I} - \mathbf{X}\mathbf{X}^+) \mathbf{f}\mathbf{f}^T \} + \sigma^2 \mathrm{tr}\, \{ (\mathbf{I} - \mathbf{X}\mathbf{X}^+)\} \\
& = \mathrm{tr}\, \{ \underbrace{(\mathbf{I} - \mathbf{X}\mathbf{X}^+) \mathbf{f}}_{=\mathbf{0}}\mathbf{f}^T \} + (N-p-1) \sigma^2.
\end{align},$$
where we again used the properties of the projection. $\blacksquare$.
Note that:
the assumption of uncorrelated homoskedastic errors ($\mathrm{var}\,\mathbf{y} = \sigma^2 \mathbf{I}$) is weaker than then assumption of i.i.d. errors;
there is no assumption of anything being Gaussian or normally distributed. | The variance-covariance matrix of the least squares parameter estimation
T_M's answer addresses the first part of the question, namely, how (3.6) implies (3.8). I will address the second part, why use
$ \hat{\sigma}^2 = \frac{1}{N-p-1}\sum_{i=1}^N(y_i-\hat{y}_i)^2. $
(Th |
19,187 | Checking for a statistically significant peak | I was thinking of the smoothing idea also. But there is a whole area called response surface methodology that searches for peaks in noisy data (it does primarily involve using local quadratic fits to the data) and there was a famous paper I recall with "Bump hunting" in the title. Here are some links to books on response surface methodology. Ray Myer's books are particularly well-written. I will try to find the bump hunting paper.
Response Surface Methodology: Process and Product Optimization Using Designed Experiments
Response Surface Methodology And Related Topics
Response surface methodology
Empirical Model-Building and Response Surfaces
Although not the article I was looking for, here is a very relevant article by Jerry Friedman and Nick Fisher that deals with these ideas applied to high-dimensional data.
Here is an article with some online comments.
So I hope you at least appreciate my response. I think your ideas are good and on the right track but yes I do think you might be reinventing the wheel and I hope you and others will look at these excellent references. | Checking for a statistically significant peak | I was thinking of the smoothing idea also. But there is a whole area called response surface methodology that searches for peaks in noisy data (it does primarily involve using local quadratic fits to | Checking for a statistically significant peak
I was thinking of the smoothing idea also. But there is a whole area called response surface methodology that searches for peaks in noisy data (it does primarily involve using local quadratic fits to the data) and there was a famous paper I recall with "Bump hunting" in the title. Here are some links to books on response surface methodology. Ray Myer's books are particularly well-written. I will try to find the bump hunting paper.
Response Surface Methodology: Process and Product Optimization Using Designed Experiments
Response Surface Methodology And Related Topics
Response surface methodology
Empirical Model-Building and Response Surfaces
Although not the article I was looking for, here is a very relevant article by Jerry Friedman and Nick Fisher that deals with these ideas applied to high-dimensional data.
Here is an article with some online comments.
So I hope you at least appreciate my response. I think your ideas are good and on the right track but yes I do think you might be reinventing the wheel and I hope you and others will look at these excellent references. | Checking for a statistically significant peak
I was thinking of the smoothing idea also. But there is a whole area called response surface methodology that searches for peaks in noisy data (it does primarily involve using local quadratic fits to |
19,188 | Checking for a statistically significant peak | Even though you have not answered my question, if my guess is right you are looking for a test of white noise which amounts in the frequency domain to show that spectrum is flat. So Fisher's periodogram test which in this reference is called Fisher's kappa could be used. See the link.
http://www4.stat.ncsu.edu/~dickey/Spain/pdf_Notes/Spectral2.pdf
Bartlett's test is also mentioned in the reference.
Now rejecting the null hypothesis amounts to finding a significant peak in the periodogram. This would mean that a periodic component exists in the time series.
Because the test is in the frequency domain and involves periodogram ordinates the ordinate have a chi square 2 distribution under the null hypothesis and are independent. This special distribution comes about only because of the transformation to the frequency domain. If x were time this would not work in the time domain or in general the distribution for the ys would not be independent chi square.
But take the model y=constant independent of x. Use the y$_m$, the mean of the ys as the estimate for the constant. Then testing for the existence of a peak would amount to rejecting that the residuals form a white noise sequence. | Checking for a statistically significant peak | Even though you have not answered my question, if my guess is right you are looking for a test of white noise which amounts in the frequency domain to show that spectrum is flat. So Fisher's periodog | Checking for a statistically significant peak
Even though you have not answered my question, if my guess is right you are looking for a test of white noise which amounts in the frequency domain to show that spectrum is flat. So Fisher's periodogram test which in this reference is called Fisher's kappa could be used. See the link.
http://www4.stat.ncsu.edu/~dickey/Spain/pdf_Notes/Spectral2.pdf
Bartlett's test is also mentioned in the reference.
Now rejecting the null hypothesis amounts to finding a significant peak in the periodogram. This would mean that a periodic component exists in the time series.
Because the test is in the frequency domain and involves periodogram ordinates the ordinate have a chi square 2 distribution under the null hypothesis and are independent. This special distribution comes about only because of the transformation to the frequency domain. If x were time this would not work in the time domain or in general the distribution for the ys would not be independent chi square.
But take the model y=constant independent of x. Use the y$_m$, the mean of the ys as the estimate for the constant. Then testing for the existence of a peak would amount to rejecting that the residuals form a white noise sequence. | Checking for a statistically significant peak
Even though you have not answered my question, if my guess is right you are looking for a test of white noise which amounts in the frequency domain to show that spectrum is flat. So Fisher's periodog |
19,189 | $L_1$ or $L_.5$ metrics for clustering? | The key here is understanding the "curse of dimensionality" the paper references. From wikipedia: when the number of dimensions is very large,
nearly all of the high-dimensional space is "far away" from the centre, or, to put it another way, the high-dimensional unit space can be said to consist almost entirely of the "corners" of the hypercube, with almost no "middle"
As a result, it starts to get tricky to think about which points are close to which other points, because they're all more or less equally far apart. This is the problem in the first paper you linked to.
The problem with high p is that it emphasizes the larger values--five squared and four squared are nine units apart, but one squared and two squared are only three units apart. So the larger dimensions (things in the corners) dominate everything and you lose contrast. So this inflation of large distances is what you want to avoid. With a fractional p, the emphasis is on differences in the smaller dimensions--dimensions that actually have intermediate values--which gives you more contrast. | $L_1$ or $L_.5$ metrics for clustering? | The key here is understanding the "curse of dimensionality" the paper references. From wikipedia: when the number of dimensions is very large,
nearly all of the high-dimensional space is "far away" f | $L_1$ or $L_.5$ metrics for clustering?
The key here is understanding the "curse of dimensionality" the paper references. From wikipedia: when the number of dimensions is very large,
nearly all of the high-dimensional space is "far away" from the centre, or, to put it another way, the high-dimensional unit space can be said to consist almost entirely of the "corners" of the hypercube, with almost no "middle"
As a result, it starts to get tricky to think about which points are close to which other points, because they're all more or less equally far apart. This is the problem in the first paper you linked to.
The problem with high p is that it emphasizes the larger values--five squared and four squared are nine units apart, but one squared and two squared are only three units apart. So the larger dimensions (things in the corners) dominate everything and you lose contrast. So this inflation of large distances is what you want to avoid. With a fractional p, the emphasis is on differences in the smaller dimensions--dimensions that actually have intermediate values--which gives you more contrast. | $L_1$ or $L_.5$ metrics for clustering?
The key here is understanding the "curse of dimensionality" the paper references. From wikipedia: when the number of dimensions is very large,
nearly all of the high-dimensional space is "far away" f |
19,190 | $L_1$ or $L_.5$ metrics for clustering? | There is a paper using the Lp metric with p between 1 and 5 that you may wish to take a look:
Amorim, R.C. and Mirkin, B., Minkowski Metric, Feature Weighting and Anomalous Cluster Initialisation in K-Means Clustering, Pattern Recognition, vol. 45(3), pp. 1061-1075, 2012
Download,
https://www.researchgate.net/publication/232282003_Author's_personal_copy_Minkowski_metric_feature_weighting_and_anomalous_cluster_initializing_in_K-Means_clustering/file/d912f508115a040b45.pdf | $L_1$ or $L_.5$ metrics for clustering? | There is a paper using the Lp metric with p between 1 and 5 that you may wish to take a look:
Amorim, R.C. and Mirkin, B., Minkowski Metric, Feature Weighting and Anomalous Cluster Initialisation in K | $L_1$ or $L_.5$ metrics for clustering?
There is a paper using the Lp metric with p between 1 and 5 that you may wish to take a look:
Amorim, R.C. and Mirkin, B., Minkowski Metric, Feature Weighting and Anomalous Cluster Initialisation in K-Means Clustering, Pattern Recognition, vol. 45(3), pp. 1061-1075, 2012
Download,
https://www.researchgate.net/publication/232282003_Author's_personal_copy_Minkowski_metric_feature_weighting_and_anomalous_cluster_initializing_in_K-Means_clustering/file/d912f508115a040b45.pdf | $L_1$ or $L_.5$ metrics for clustering?
There is a paper using the Lp metric with p between 1 and 5 that you may wish to take a look:
Amorim, R.C. and Mirkin, B., Minkowski Metric, Feature Weighting and Anomalous Cluster Initialisation in K |
19,191 | $L_1$ or $L_.5$ metrics for clustering? | I don't know whether yours is a problem of inference. If the problem is of inferring a vector from $\mathbb{R}^n$ under certain constraints(which should define a closed convex set) when a prior guess say $u$ is given then the vector is inferred by minimizing $\ell_2$-distance from $u$ over the constraint set (if the prior $u$ is not given then its just by minimizing the $\ell_2$-norm). The above principle is justified as the right thing to do under certain circumstances in this paper http://projecteuclid.org/DPubS?service=UI&version=1.0&verb=Display&handle=euclid.aos/1176348385. | $L_1$ or $L_.5$ metrics for clustering? | I don't know whether yours is a problem of inference. If the problem is of inferring a vector from $\mathbb{R}^n$ under certain constraints(which should define a closed convex set) when a prior guess | $L_1$ or $L_.5$ metrics for clustering?
I don't know whether yours is a problem of inference. If the problem is of inferring a vector from $\mathbb{R}^n$ under certain constraints(which should define a closed convex set) when a prior guess say $u$ is given then the vector is inferred by minimizing $\ell_2$-distance from $u$ over the constraint set (if the prior $u$ is not given then its just by minimizing the $\ell_2$-norm). The above principle is justified as the right thing to do under certain circumstances in this paper http://projecteuclid.org/DPubS?service=UI&version=1.0&verb=Display&handle=euclid.aos/1176348385. | $L_1$ or $L_.5$ metrics for clustering?
I don't know whether yours is a problem of inference. If the problem is of inferring a vector from $\mathbb{R}^n$ under certain constraints(which should define a closed convex set) when a prior guess |
19,192 | How can the number of connections be Gaussian if it cannot be negative? | When there are $n$ people and the number of connections made by person $i, 1 \le i \le n,$ is $X_i$, then the total number of connections is $S_n = \sum_{i=1}^n{X_i} / 2$. Now if we take the $X_i$ to be random variables, assume they are independent and their variances are not "too unequal" as more and more people are added to the mix, then the Lindeberg-Levy Central Limit Theorem applies. It asserts that the cumulative distribution function of the standardized sum converges to the cdf of the normal distribution. That means roughly that a histogram of the sum will look more and more like a Gaussian (a "bell curve") as $n$ grows large.
Let's review what this does not say:
It does not assert that the distribution of $S_n$ is ever exactly normal. It can't be, for the reasons you point out.
It does not imply the expected number of connections converges. In fact, it must diverge (go to infinity). The standardization is a recentering and rescaling of the distribution; the amount of rescaling is growing without limit.
It says nothing when the $X_i$ are not independent or when their variances change too much as $n$ grows. (However, there are generalizations of the CLT for "slightly" dependent series of variables.) | How can the number of connections be Gaussian if it cannot be negative? | When there are $n$ people and the number of connections made by person $i, 1 \le i \le n,$ is $X_i$, then the total number of connections is $S_n = \sum_{i=1}^n{X_i} / 2$. Now if we take the $X_i$ to | How can the number of connections be Gaussian if it cannot be negative?
When there are $n$ people and the number of connections made by person $i, 1 \le i \le n,$ is $X_i$, then the total number of connections is $S_n = \sum_{i=1}^n{X_i} / 2$. Now if we take the $X_i$ to be random variables, assume they are independent and their variances are not "too unequal" as more and more people are added to the mix, then the Lindeberg-Levy Central Limit Theorem applies. It asserts that the cumulative distribution function of the standardized sum converges to the cdf of the normal distribution. That means roughly that a histogram of the sum will look more and more like a Gaussian (a "bell curve") as $n$ grows large.
Let's review what this does not say:
It does not assert that the distribution of $S_n$ is ever exactly normal. It can't be, for the reasons you point out.
It does not imply the expected number of connections converges. In fact, it must diverge (go to infinity). The standardization is a recentering and rescaling of the distribution; the amount of rescaling is growing without limit.
It says nothing when the $X_i$ are not independent or when their variances change too much as $n$ grows. (However, there are generalizations of the CLT for "slightly" dependent series of variables.) | How can the number of connections be Gaussian if it cannot be negative?
When there are $n$ people and the number of connections made by person $i, 1 \le i \le n,$ is $X_i$, then the total number of connections is $S_n = \sum_{i=1}^n{X_i} / 2$. Now if we take the $X_i$ to |
19,193 | How can the number of connections be Gaussian if it cannot be negative? | The answer is dependent on the assumptions that you are willing to make. A social network constantly evolves over time and hence is not a static entity. Therefore, you need to make some assumptions about how the network evolves over time.
The trivial answer under the stated conditions is: If the network size is $n$ then as asymptotically (in the sense of 'as time goes to infinity')
$Prob(\mbox{No of connections for any individual} = n-1) =1$.
If a person selects another person at random to connect to then eventually everyone will be connected.
However, real life networks do not behave this way. People differ in several aspects.
At any time a person has a fixed network size and the probability of another connection being made is a function of his/her network size (as people introduce other people etc).
A person has his/her own intrinsic tendency to form a connection (as some are introvert/exterovert etc).
These probabilities change over time, context etc. I am not sure there is a straightforward answer unless we make some assumptions about the structure of the network (e.g., density of the network, how people behave etc). | How can the number of connections be Gaussian if it cannot be negative? | The answer is dependent on the assumptions that you are willing to make. A social network constantly evolves over time and hence is not a static entity. Therefore, you need to make some assumptions ab | How can the number of connections be Gaussian if it cannot be negative?
The answer is dependent on the assumptions that you are willing to make. A social network constantly evolves over time and hence is not a static entity. Therefore, you need to make some assumptions about how the network evolves over time.
The trivial answer under the stated conditions is: If the network size is $n$ then as asymptotically (in the sense of 'as time goes to infinity')
$Prob(\mbox{No of connections for any individual} = n-1) =1$.
If a person selects another person at random to connect to then eventually everyone will be connected.
However, real life networks do not behave this way. People differ in several aspects.
At any time a person has a fixed network size and the probability of another connection being made is a function of his/her network size (as people introduce other people etc).
A person has his/her own intrinsic tendency to form a connection (as some are introvert/exterovert etc).
These probabilities change over time, context etc. I am not sure there is a straightforward answer unless we make some assumptions about the structure of the network (e.g., density of the network, how people behave etc). | How can the number of connections be Gaussian if it cannot be negative?
The answer is dependent on the assumptions that you are willing to make. A social network constantly evolves over time and hence is not a static entity. Therefore, you need to make some assumptions ab |
19,194 | Determining whether a website is active using daily visits | It sounds like you are looking for an "online changepoint detection method." (That's a useful phrase for Googling.) Some useful recent (and accessible) papers are Adams & MacKay (a Bayesian approach) and Keogh et al. You might be able to press the surveillance package for R into service. Isolated large numbers of hits can be found using statistical process control methods. | Determining whether a website is active using daily visits | It sounds like you are looking for an "online changepoint detection method." (That's a useful phrase for Googling.) Some useful recent (and accessible) papers are Adams & MacKay (a Bayesian approach | Determining whether a website is active using daily visits
It sounds like you are looking for an "online changepoint detection method." (That's a useful phrase for Googling.) Some useful recent (and accessible) papers are Adams & MacKay (a Bayesian approach) and Keogh et al. You might be able to press the surveillance package for R into service. Isolated large numbers of hits can be found using statistical process control methods. | Determining whether a website is active using daily visits
It sounds like you are looking for an "online changepoint detection method." (That's a useful phrase for Googling.) Some useful recent (and accessible) papers are Adams & MacKay (a Bayesian approach |
19,195 | Determining whether a website is active using daily visits | There are definitely more and less complex ways to address this kind of problem. From the sound of things, you started out with a fairly simple solution (the formula you found on SO). With that kind of simplicity in mind, I thought I would revisit a few key points you make in (the current version of) your post.
So far, you've said you want your measurement of "site activity" to capture:
Slope changes in visits/day over "the past few
days"
Magnitude changes in visits/day over "the past few days"
As @jan-galkowski points out, you also seem to be (at least tacitly) interested in the rank of the sites relative to each other along these dimensions.
If that description is accurate, I would propose exploring the simplest possible solution that incorporates those three measures (change, magnitude, rank) as separate components. For example, you could grab:
The results of your SO solution to capture slope variation (although I would incorporate 3 or 4 days of data)
Magnitude of each site's most recent visits/day value (y2) divided by the mean visits/day for that site (Y):
y2 / mean(Y)
For W0, W1, and W2 respectively, that yields 0.16, 1.45, and 2.35. (For the sake of interpretation, consider that a site whose most recent visits-per-day value was equal to it's mean visits-per-day would generate a result of 1). Note that you could also adjust this measure to capture the most recent 2 (or more) days:
y2 + y1 / 2 * mean(Y)
That yields: 0.12, 1.33, 1.91 for your three sample sites.
If you do, in fact, use the mean of each site's visit/day distribution for this kind of measure, I would also look at the distribution's standard deviation to get a sense of its relative volatility. The standard deviation for each site's visit/day distribution is: 12.69, 12.12, and 17.62. Thinking about the y2/mean(Y) measure relative to the standard deviation is helpful because it allows you to keep the recent magnitude of activity on site W2 in perspective (bigger standard deviation = less stable/consistent overall).
Finally, if you're interested in ranks, you can extend these approaches in that direction too. For example, I would think that knowing a site's rank in terms of the most recent visits per day values as well as the rank of each site's mean visits per day (the rank of mean (Y) for each W in Wn) could be useful. Again, you can tailor to suit your needs.
You could present the results of all these calculations as a table, or create a regularly-updated visualization to track them on a daily basis. | Determining whether a website is active using daily visits | There are definitely more and less complex ways to address this kind of problem. From the sound of things, you started out with a fairly simple solution (the formula you found on SO). With that kind o | Determining whether a website is active using daily visits
There are definitely more and less complex ways to address this kind of problem. From the sound of things, you started out with a fairly simple solution (the formula you found on SO). With that kind of simplicity in mind, I thought I would revisit a few key points you make in (the current version of) your post.
So far, you've said you want your measurement of "site activity" to capture:
Slope changes in visits/day over "the past few
days"
Magnitude changes in visits/day over "the past few days"
As @jan-galkowski points out, you also seem to be (at least tacitly) interested in the rank of the sites relative to each other along these dimensions.
If that description is accurate, I would propose exploring the simplest possible solution that incorporates those three measures (change, magnitude, rank) as separate components. For example, you could grab:
The results of your SO solution to capture slope variation (although I would incorporate 3 or 4 days of data)
Magnitude of each site's most recent visits/day value (y2) divided by the mean visits/day for that site (Y):
y2 / mean(Y)
For W0, W1, and W2 respectively, that yields 0.16, 1.45, and 2.35. (For the sake of interpretation, consider that a site whose most recent visits-per-day value was equal to it's mean visits-per-day would generate a result of 1). Note that you could also adjust this measure to capture the most recent 2 (or more) days:
y2 + y1 / 2 * mean(Y)
That yields: 0.12, 1.33, 1.91 for your three sample sites.
If you do, in fact, use the mean of each site's visit/day distribution for this kind of measure, I would also look at the distribution's standard deviation to get a sense of its relative volatility. The standard deviation for each site's visit/day distribution is: 12.69, 12.12, and 17.62. Thinking about the y2/mean(Y) measure relative to the standard deviation is helpful because it allows you to keep the recent magnitude of activity on site W2 in perspective (bigger standard deviation = less stable/consistent overall).
Finally, if you're interested in ranks, you can extend these approaches in that direction too. For example, I would think that knowing a site's rank in terms of the most recent visits per day values as well as the rank of each site's mean visits per day (the rank of mean (Y) for each W in Wn) could be useful. Again, you can tailor to suit your needs.
You could present the results of all these calculations as a table, or create a regularly-updated visualization to track them on a daily basis. | Determining whether a website is active using daily visits
There are definitely more and less complex ways to address this kind of problem. From the sound of things, you started out with a fairly simple solution (the formula you found on SO). With that kind o |
19,196 | Determining whether a website is active using daily visits | Caution that arrival rates of users at Web sites are nasty series, tend to be overdispersed (from a Poisson standpoint), so consider negative binominal distributions to look at arrivals, and their fitting. Also, you may want to examine the order statistics of the sites on each day rather than their numbers. | Determining whether a website is active using daily visits | Caution that arrival rates of users at Web sites are nasty series, tend to be overdispersed (from a Poisson standpoint), so consider negative binominal distributions to look at arrivals, and their fit | Determining whether a website is active using daily visits
Caution that arrival rates of users at Web sites are nasty series, tend to be overdispersed (from a Poisson standpoint), so consider negative binominal distributions to look at arrivals, and their fitting. Also, you may want to examine the order statistics of the sites on each day rather than their numbers. | Determining whether a website is active using daily visits
Caution that arrival rates of users at Web sites are nasty series, tend to be overdispersed (from a Poisson standpoint), so consider negative binominal distributions to look at arrivals, and their fit |
19,197 | Does a Bayesian interpretation exist for REML? | Bayesian interpretations exist only within the framework of Bayesian analysis, for estimators that relate to a posterior distribution. Hence, the only way that the REML estimator could be given a Bayesian interpretation (i.e., an interpretation as an estimator taken from the posterior) is if we take the restricted log-likelihood in the REML analysis to be the log-posterior in a corresponding Bayes analysis; in this case the REML estimator would be a MAP estimator from Bayesian theory, with its corresponding Bayesian interpretation.
Setting the REML estimator to be a MAP estimator: It is relatively simple to see how to set the restricted log-likelihood in the REML analysis to be the log-posterior in a Bayes analysis. To do this, we require the log-prior to be the negative of the part of the log-likelihood that is removed by the REML process. Suppose we have log-likelihood $\ell_\mathbf{x}(\theta, \nu) = \ell_*(\theta, \nu) + \ell_{\text{RE}}(\theta)$ where $\ell_{\text{RE}}(\theta)$ is the residual log-likelihood and $\theta$ is the parameter of interest (with $\nu$ being our nuisance parameter). Setting the prior to $\pi(\theta, \nu) \propto \exp(-\ell_*(\theta, \nu))$ gives corresponding posterior:
$$\begin{equation} \begin{aligned}
\pi(\theta|\mathbf{x})
&\propto \int L_\mathbf{x}(\theta, \nu) \pi(\theta, \nu) d\nu \\[6pt]
&\propto \int \exp(\ell_\mathbf{x}(\theta, \nu)) \exp(-\ell_*(\theta, \nu)) d\nu \\[6pt]
&= \int \exp(\ell_\mathbf{x}(\theta, \nu) - \ell_*(\theta, \nu)) d\nu \\[6pt]
&= \int \exp(\ell_*(\theta, \nu) + \ell_{\text{RE}}(\theta) - \ell_*(\theta, \nu)) d\nu \\[6pt]
&= \int \exp(\ell_{\text{RE}}(\theta)) d\nu \\[6pt]
&= \int L_{\text{RE}}(\theta) d\nu \\[6pt]
&\propto L_{\text{RE}}(\theta). \\[6pt]
\end{aligned} \end{equation}$$
This gives us:
$$\hat{\theta}_\text{MAP} = \arg \max_\theta \pi(\theta|\mathbf{x}) = \arg \max_\theta L_{\text{RE}}(\theta) = \hat{\theta}_\text{REML}.$$
This result allows us to interpret the REML estimator as a MAP estimator, so the proper Bayesian interpretation of the REML estimator is that it is the estimator that maximises the posterior density under the above prior.
Having illustrated the method to give a Bayesian interpretation to the REML estimator, we now note that there are some big problems with this approach. One problem is that the prior is formed using the log-likelihood component $\ell_*(\theta, \nu)$, which depends on the data. Hence, the "prior" necessary to obtain this interpretation is not a real prior, in the sense of being a function that can be formed prior to seeing the data. Another problem is that the prior will often be improper (i.e., it does not integrate to one) and it may actually increase in weight as the parameter values become extreme. (We will show an example of this below.)
Based on these problems, one could argue that there is no reasonable Bayesian interpretation for the REML estimator. Alternatively, one could argue that the REML estimator still maintains the above Bayesian interpretation, being a maximum a posteriori estimator under a "prior" that must coincidentally align with the observed data in the specified form, and may be extremely improper.
Illustration with normal data: The classic example of REML estimation is for the case of normal data $x_1,...,x_n \sim \text{N}(\nu, 1/\theta)$ where you are interested in the precision $\theta$ and the mean $\nu$ is a nuisance parameter. In this case you have the log-likelihood function:
$$\ell_\mathbf{x}(\nu,\theta) = - \frac{n}{2} \ln \theta - \frac{\theta}{2} \sum_{i=1}^n (x_i-\nu)^2.$$
In REML we split this log-likelihood into the two components:
$$\begin{equation} \begin{aligned}
\ell_*(\nu,\theta) &= - \frac{n}{2} \ln \theta - \frac{\theta}{2} \sum_{i=1}^n (x_i-\nu)^2 \\[10pt]
\ell_\text{RE}(\theta) &= - \frac{n-1}{2} \ln \theta - \frac{\theta}{2} \sum_{i=1}^n (x_i-\bar{x})^2.
\end{aligned} \end{equation}$$
We obtain the REML estimator for the precision parameter by maximising the residual likelihood, which gives an unbiased estimator for the variance:
$$\frac{1}{\hat{\theta}_\text{REML}} = \frac{1}{n-1} \sum_{i=1}^n (x_i-\bar{x})^2.$$
In this case, the REML estimator will correspond to a MAP estimator for the "prior" density:
$$\pi(\theta) \propto \theta^{n/2} \exp \Bigg( \frac{\theta}{2} \sum_{i=1}^n (x_i-\nu)^2 \Bigg).$$
As you can see, this "prior" actually depends on the observed data values, so it cannot actually be formed prior to seeing the data. Moreover, we can see that it is clearly an "improper" prior that puts more and more weight on extreme values of $\theta$ and $\nu$. (Actually, this prior is pretty bonkers.) If by "coincidence" you were to form a prior that happened to correspond to this outcome then the REML estimator would be a MAP estimator under that prior, and hence would have a Bayesian interpretation as the estimator that maximises the posterior under that prior. | Does a Bayesian interpretation exist for REML? | Bayesian interpretations exist only within the framework of Bayesian analysis, for estimators that relate to a posterior distribution. Hence, the only way that the REML estimator could be given a Bay | Does a Bayesian interpretation exist for REML?
Bayesian interpretations exist only within the framework of Bayesian analysis, for estimators that relate to a posterior distribution. Hence, the only way that the REML estimator could be given a Bayesian interpretation (i.e., an interpretation as an estimator taken from the posterior) is if we take the restricted log-likelihood in the REML analysis to be the log-posterior in a corresponding Bayes analysis; in this case the REML estimator would be a MAP estimator from Bayesian theory, with its corresponding Bayesian interpretation.
Setting the REML estimator to be a MAP estimator: It is relatively simple to see how to set the restricted log-likelihood in the REML analysis to be the log-posterior in a Bayes analysis. To do this, we require the log-prior to be the negative of the part of the log-likelihood that is removed by the REML process. Suppose we have log-likelihood $\ell_\mathbf{x}(\theta, \nu) = \ell_*(\theta, \nu) + \ell_{\text{RE}}(\theta)$ where $\ell_{\text{RE}}(\theta)$ is the residual log-likelihood and $\theta$ is the parameter of interest (with $\nu$ being our nuisance parameter). Setting the prior to $\pi(\theta, \nu) \propto \exp(-\ell_*(\theta, \nu))$ gives corresponding posterior:
$$\begin{equation} \begin{aligned}
\pi(\theta|\mathbf{x})
&\propto \int L_\mathbf{x}(\theta, \nu) \pi(\theta, \nu) d\nu \\[6pt]
&\propto \int \exp(\ell_\mathbf{x}(\theta, \nu)) \exp(-\ell_*(\theta, \nu)) d\nu \\[6pt]
&= \int \exp(\ell_\mathbf{x}(\theta, \nu) - \ell_*(\theta, \nu)) d\nu \\[6pt]
&= \int \exp(\ell_*(\theta, \nu) + \ell_{\text{RE}}(\theta) - \ell_*(\theta, \nu)) d\nu \\[6pt]
&= \int \exp(\ell_{\text{RE}}(\theta)) d\nu \\[6pt]
&= \int L_{\text{RE}}(\theta) d\nu \\[6pt]
&\propto L_{\text{RE}}(\theta). \\[6pt]
\end{aligned} \end{equation}$$
This gives us:
$$\hat{\theta}_\text{MAP} = \arg \max_\theta \pi(\theta|\mathbf{x}) = \arg \max_\theta L_{\text{RE}}(\theta) = \hat{\theta}_\text{REML}.$$
This result allows us to interpret the REML estimator as a MAP estimator, so the proper Bayesian interpretation of the REML estimator is that it is the estimator that maximises the posterior density under the above prior.
Having illustrated the method to give a Bayesian interpretation to the REML estimator, we now note that there are some big problems with this approach. One problem is that the prior is formed using the log-likelihood component $\ell_*(\theta, \nu)$, which depends on the data. Hence, the "prior" necessary to obtain this interpretation is not a real prior, in the sense of being a function that can be formed prior to seeing the data. Another problem is that the prior will often be improper (i.e., it does not integrate to one) and it may actually increase in weight as the parameter values become extreme. (We will show an example of this below.)
Based on these problems, one could argue that there is no reasonable Bayesian interpretation for the REML estimator. Alternatively, one could argue that the REML estimator still maintains the above Bayesian interpretation, being a maximum a posteriori estimator under a "prior" that must coincidentally align with the observed data in the specified form, and may be extremely improper.
Illustration with normal data: The classic example of REML estimation is for the case of normal data $x_1,...,x_n \sim \text{N}(\nu, 1/\theta)$ where you are interested in the precision $\theta$ and the mean $\nu$ is a nuisance parameter. In this case you have the log-likelihood function:
$$\ell_\mathbf{x}(\nu,\theta) = - \frac{n}{2} \ln \theta - \frac{\theta}{2} \sum_{i=1}^n (x_i-\nu)^2.$$
In REML we split this log-likelihood into the two components:
$$\begin{equation} \begin{aligned}
\ell_*(\nu,\theta) &= - \frac{n}{2} \ln \theta - \frac{\theta}{2} \sum_{i=1}^n (x_i-\nu)^2 \\[10pt]
\ell_\text{RE}(\theta) &= - \frac{n-1}{2} \ln \theta - \frac{\theta}{2} \sum_{i=1}^n (x_i-\bar{x})^2.
\end{aligned} \end{equation}$$
We obtain the REML estimator for the precision parameter by maximising the residual likelihood, which gives an unbiased estimator for the variance:
$$\frac{1}{\hat{\theta}_\text{REML}} = \frac{1}{n-1} \sum_{i=1}^n (x_i-\bar{x})^2.$$
In this case, the REML estimator will correspond to a MAP estimator for the "prior" density:
$$\pi(\theta) \propto \theta^{n/2} \exp \Bigg( \frac{\theta}{2} \sum_{i=1}^n (x_i-\nu)^2 \Bigg).$$
As you can see, this "prior" actually depends on the observed data values, so it cannot actually be formed prior to seeing the data. Moreover, we can see that it is clearly an "improper" prior that puts more and more weight on extreme values of $\theta$ and $\nu$. (Actually, this prior is pretty bonkers.) If by "coincidence" you were to form a prior that happened to correspond to this outcome then the REML estimator would be a MAP estimator under that prior, and hence would have a Bayesian interpretation as the estimator that maximises the posterior under that prior. | Does a Bayesian interpretation exist for REML?
Bayesian interpretations exist only within the framework of Bayesian analysis, for estimators that relate to a posterior distribution. Hence, the only way that the REML estimator could be given a Bay |
19,198 | What is Oblivious Decision Tree and Why? | 1. - correct
2. - false.
The definition of the oblivious tree can be found here:
Bottom-Up Induction of Oblivious Read-Once Decision Graphs: Strengths and Limitations (1994)
Short extract: | What is Oblivious Decision Tree and Why? | 1. - correct
2. - false.
The definition of the oblivious tree can be found here:
Bottom-Up Induction of Oblivious Read-Once Decision Graphs: Strengths and Limitations (1994)
Short extract: | What is Oblivious Decision Tree and Why?
1. - correct
2. - false.
The definition of the oblivious tree can be found here:
Bottom-Up Induction of Oblivious Read-Once Decision Graphs: Strengths and Limitations (1994)
Short extract: | What is Oblivious Decision Tree and Why?
1. - correct
2. - false.
The definition of the oblivious tree can be found here:
Bottom-Up Induction of Oblivious Read-Once Decision Graphs: Strengths and Limitations (1994)
Short extract: |
19,199 | GBM package vs. Caret using GBM | Use with the default grid to optimize parameters and use predict to have the same results:
R2.caret-R2.gbm=0.0009125435
rmse.caret-rmse.gbm=-0.001680319
library(caret)
library(gbm)
library(hydroGOF)
library(Metrics)
data(iris)
# Using caret with the default grid to optimize tune parameters automatically
# GBM Tuning parameters:
# n.trees (# Boosting Iterations)
# interaction.depth (Max Tree Depth)
# shrinkage (Shrinkage)
# n.minobsinnode (Min. Terminal Node Size)
metric <- "RMSE"
trainControl <- trainControl(method="cv", number=10)
set.seed(99)
gbm.caret <- train(Sepal.Length ~ .
, data=iris
, distribution="gaussian"
, method="gbm"
, trControl=trainControl
, verbose=FALSE
#, tuneGrid=caretGrid
, metric=metric
, bag.fraction=0.75
)
print(gbm.caret)
caret.predict <- predict(gbm.caret, newdata=iris, type="raw")
rmse.caret<-rmse(iris$Sepal.Length, caret.predict)
print(rmse.caret)
R2.caret <- cor(gbm.caret$finalModel$fit, iris$Sepal.Length)^2
print(R2.caret)
#using gbm without caret with the same parameters
set.seed(99)
gbm.gbm <- gbm(Sepal.Length ~ .
, data=iris
, distribution="gaussian"
, n.trees=150
, interaction.depth=3
, n.minobsinnode=10
, shrinkage=0.1
, bag.fraction=0.75
, cv.folds=10
, verbose=FALSE
)
best.iter <- gbm.perf(gbm.gbm, method="cv")
print(best.iter)
train.predict <- predict.gbm(object=gbm.gbm, newdata=iris, 150)
rmse.gbm<-rmse(iris$Sepal.Length, train.predict)
print(rmse.gbm)
R2.gbm <- cor(gbm.gbm$fit, iris$Sepal.Length)^2
print(R2.gbm)
print(R2.caret-R2.gbm)
print(rmse.caret-rmse.gbm) | GBM package vs. Caret using GBM | Use with the default grid to optimize parameters and use predict to have the same results:
R2.caret-R2.gbm=0.0009125435
rmse.caret-rmse.gbm=-0.001680319
library(caret)
library(gbm)
library(hydroGOF)
l | GBM package vs. Caret using GBM
Use with the default grid to optimize parameters and use predict to have the same results:
R2.caret-R2.gbm=0.0009125435
rmse.caret-rmse.gbm=-0.001680319
library(caret)
library(gbm)
library(hydroGOF)
library(Metrics)
data(iris)
# Using caret with the default grid to optimize tune parameters automatically
# GBM Tuning parameters:
# n.trees (# Boosting Iterations)
# interaction.depth (Max Tree Depth)
# shrinkage (Shrinkage)
# n.minobsinnode (Min. Terminal Node Size)
metric <- "RMSE"
trainControl <- trainControl(method="cv", number=10)
set.seed(99)
gbm.caret <- train(Sepal.Length ~ .
, data=iris
, distribution="gaussian"
, method="gbm"
, trControl=trainControl
, verbose=FALSE
#, tuneGrid=caretGrid
, metric=metric
, bag.fraction=0.75
)
print(gbm.caret)
caret.predict <- predict(gbm.caret, newdata=iris, type="raw")
rmse.caret<-rmse(iris$Sepal.Length, caret.predict)
print(rmse.caret)
R2.caret <- cor(gbm.caret$finalModel$fit, iris$Sepal.Length)^2
print(R2.caret)
#using gbm without caret with the same parameters
set.seed(99)
gbm.gbm <- gbm(Sepal.Length ~ .
, data=iris
, distribution="gaussian"
, n.trees=150
, interaction.depth=3
, n.minobsinnode=10
, shrinkage=0.1
, bag.fraction=0.75
, cv.folds=10
, verbose=FALSE
)
best.iter <- gbm.perf(gbm.gbm, method="cv")
print(best.iter)
train.predict <- predict.gbm(object=gbm.gbm, newdata=iris, 150)
rmse.gbm<-rmse(iris$Sepal.Length, train.predict)
print(rmse.gbm)
R2.gbm <- cor(gbm.gbm$fit, iris$Sepal.Length)^2
print(R2.gbm)
print(R2.caret-R2.gbm)
print(rmse.caret-rmse.gbm) | GBM package vs. Caret using GBM
Use with the default grid to optimize parameters and use predict to have the same results:
R2.caret-R2.gbm=0.0009125435
rmse.caret-rmse.gbm=-0.001680319
library(caret)
library(gbm)
library(hydroGOF)
l |
19,200 | How to choose optimal bin width while calibrating probability models? | Any statistical method that uses binning has ultimately been deemed obsolete. Continuous calibration curve estimation has been commonplace since the mid 1990s. Commonly used methods are loess (with outlier detection turned off), linear logistic calibration, and spline logistic calibration. I go into this in detail in my Regression Modeling Strategies book and course notes. See https://hbiostat.org/rms. The R rms package makes smooth nonparametric calibration curves easy to get, either using an independent external sample or using the bootstrap on the original model development sample. | How to choose optimal bin width while calibrating probability models? | Any statistical method that uses binning has ultimately been deemed obsolete. Continuous calibration curve estimation has been commonplace since the mid 1990s. Commonly used methods are loess (with | How to choose optimal bin width while calibrating probability models?
Any statistical method that uses binning has ultimately been deemed obsolete. Continuous calibration curve estimation has been commonplace since the mid 1990s. Commonly used methods are loess (with outlier detection turned off), linear logistic calibration, and spline logistic calibration. I go into this in detail in my Regression Modeling Strategies book and course notes. See https://hbiostat.org/rms. The R rms package makes smooth nonparametric calibration curves easy to get, either using an independent external sample or using the bootstrap on the original model development sample. | How to choose optimal bin width while calibrating probability models?
Any statistical method that uses binning has ultimately been deemed obsolete. Continuous calibration curve estimation has been commonplace since the mid 1990s. Commonly used methods are loess (with |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.