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
40,801
ARIMA and external regressors in SAS and R
auto.arima can select the order of differencing automatically, and make appropriate forecasts taking account of these differences. It can also include regressors via the xreg argument, and select the appropriate model order taking account of the regressors. If you include regressors, these will be differenced along with the response variable as part of the estimation. You do not have to difference them first. Please read http://otexts.com/fpp/9/1 on how it works. When you refer to the "MA and AR for each external regressor", I assume you must be thinking of a transfer function model. This is not the model that is fitted using auto.arima. Please see http://robjhyndman.com/hyndsight/arimax/ for a discussion of the various models involving ARIMA like terms and regressors.
ARIMA and external regressors in SAS and R
auto.arima can select the order of differencing automatically, and make appropriate forecasts taking account of these differences. It can also include regressors via the xreg argument, and select the
ARIMA and external regressors in SAS and R auto.arima can select the order of differencing automatically, and make appropriate forecasts taking account of these differences. It can also include regressors via the xreg argument, and select the appropriate model order taking account of the regressors. If you include regressors, these will be differenced along with the response variable as part of the estimation. You do not have to difference them first. Please read http://otexts.com/fpp/9/1 on how it works. When you refer to the "MA and AR for each external regressor", I assume you must be thinking of a transfer function model. This is not the model that is fitted using auto.arima. Please see http://robjhyndman.com/hyndsight/arimax/ for a discussion of the various models involving ARIMA like terms and regressors.
ARIMA and external regressors in SAS and R auto.arima can select the order of differencing automatically, and make appropriate forecasts taking account of these differences. It can also include regressors via the xreg argument, and select the
40,802
Distribution for number of trials before a fixed sum is reached
Let $X_1,X_2,\dots$ be iid $\mathrm{Uniform}\{a,a+1,\dots,b\}$. Find the distibution of $S_n=\mathrm{constant} + X_1+\dots+X_n$ using the information starting on page 285 of this document. Use the Hitting Time Theorem to find the distribution of $T=\inf\,\{n\geq 1:S_n=0\}$.
Distribution for number of trials before a fixed sum is reached
Let $X_1,X_2,\dots$ be iid $\mathrm{Uniform}\{a,a+1,\dots,b\}$. Find the distibution of $S_n=\mathrm{constant} + X_1+\dots+X_n$ using the information starting on page 285 of this document. Use the Hit
Distribution for number of trials before a fixed sum is reached Let $X_1,X_2,\dots$ be iid $\mathrm{Uniform}\{a,a+1,\dots,b\}$. Find the distibution of $S_n=\mathrm{constant} + X_1+\dots+X_n$ using the information starting on page 285 of this document. Use the Hitting Time Theorem to find the distribution of $T=\inf\,\{n\geq 1:S_n=0\}$.
Distribution for number of trials before a fixed sum is reached Let $X_1,X_2,\dots$ be iid $\mathrm{Uniform}\{a,a+1,\dots,b\}$. Find the distibution of $S_n=\mathrm{constant} + X_1+\dots+X_n$ using the information starting on page 285 of this document. Use the Hit
40,803
Distribution for number of trials before a fixed sum is reached
My first step would be to just try this out. While writing such a program I typically get a better idea of how to proceed. Here is how I would write it in Stata (and Mata): clear all set obs 10000 mata // for 10,000 obs role a 6-sided die 24 times x = ceil(6*runiform(10000,24)) // compute a running sum for each observation for(i=1; i <= 10000; i++) { x[i,.] = runningsum(x[i,.]) } // number of roles till running sum passes 24 T = rowsum(x :< 24) // add that variable to the dataset idx =st_addvar("byte","T") st_store(.,idx,T) end // look at T: spikeplot T tab T T | Freq. Percent Cum. ------------+----------------------------------- 3 | 6 0.06 0.06 4 | 638 6.38 6.44 5 | 2,248 22.48 28.92 6 | 2,976 29.76 58.68 7 | 2,313 23.13 81.81 8 | 1,204 12.04 93.85 9 | 451 4.51 98.36 10 | 123 1.23 99.59 11 | 33 0.33 99.92 12 | 7 0.07 99.99 13 | 1 0.01 100.00 ------------+----------------------------------- Total | 10,000 100.00 sum T Variable | Obs Mean Std. Dev. Min Max -------------+-------------------------------------------------------- T | 10000 6.3238 1.344966 3 13 So T is an integer, it has minimum value $\lfloor Z/b\rfloor-1$ and a maximum of $\lfloor Z/a \rfloor - 1$. I would than take some manageble values of $a$, $b$ and $Z$ and write down the probability of each of the possible values of T and look for a pattern.
Distribution for number of trials before a fixed sum is reached
My first step would be to just try this out. While writing such a program I typically get a better idea of how to proceed. Here is how I would write it in Stata (and Mata): clear all set obs 10000 ma
Distribution for number of trials before a fixed sum is reached My first step would be to just try this out. While writing such a program I typically get a better idea of how to proceed. Here is how I would write it in Stata (and Mata): clear all set obs 10000 mata // for 10,000 obs role a 6-sided die 24 times x = ceil(6*runiform(10000,24)) // compute a running sum for each observation for(i=1; i <= 10000; i++) { x[i,.] = runningsum(x[i,.]) } // number of roles till running sum passes 24 T = rowsum(x :< 24) // add that variable to the dataset idx =st_addvar("byte","T") st_store(.,idx,T) end // look at T: spikeplot T tab T T | Freq. Percent Cum. ------------+----------------------------------- 3 | 6 0.06 0.06 4 | 638 6.38 6.44 5 | 2,248 22.48 28.92 6 | 2,976 29.76 58.68 7 | 2,313 23.13 81.81 8 | 1,204 12.04 93.85 9 | 451 4.51 98.36 10 | 123 1.23 99.59 11 | 33 0.33 99.92 12 | 7 0.07 99.99 13 | 1 0.01 100.00 ------------+----------------------------------- Total | 10,000 100.00 sum T Variable | Obs Mean Std. Dev. Min Max -------------+-------------------------------------------------------- T | 10000 6.3238 1.344966 3 13 So T is an integer, it has minimum value $\lfloor Z/b\rfloor-1$ and a maximum of $\lfloor Z/a \rfloor - 1$. I would than take some manageble values of $a$, $b$ and $Z$ and write down the probability of each of the possible values of T and look for a pattern.
Distribution for number of trials before a fixed sum is reached My first step would be to just try this out. While writing such a program I typically get a better idea of how to proceed. Here is how I would write it in Stata (and Mata): clear all set obs 10000 ma
40,804
Distribution for number of trials before a fixed sum is reached
Another interesting way to arrive at the same answer is to introduce a second random variable $Y$ which is defined through the following constraint $$ Y = Z - \sum_{i=1}^T X_i . $$ Intuitively, for any fixed number of trials, $Y$ will make up the remainder of the sum need to reach $Z$. We can clearly see that $$ \mathbb{E}[Y] = Z - T\mathbb{E}[X] $$ Setting the LHS equal to zero (no remainder), and solving for $T$, we have $$ T = \frac{Z}{\mathbb{E}[X]} $$ This only given the expected number of trials until there is no remainder, which is close, but maybe not exactly the same thing...
Distribution for number of trials before a fixed sum is reached
Another interesting way to arrive at the same answer is to introduce a second random variable $Y$ which is defined through the following constraint $$ Y = Z - \sum_{i=1}^T X_i . $$ Intuitively, for a
Distribution for number of trials before a fixed sum is reached Another interesting way to arrive at the same answer is to introduce a second random variable $Y$ which is defined through the following constraint $$ Y = Z - \sum_{i=1}^T X_i . $$ Intuitively, for any fixed number of trials, $Y$ will make up the remainder of the sum need to reach $Z$. We can clearly see that $$ \mathbb{E}[Y] = Z - T\mathbb{E}[X] $$ Setting the LHS equal to zero (no remainder), and solving for $T$, we have $$ T = \frac{Z}{\mathbb{E}[X]} $$ This only given the expected number of trials until there is no remainder, which is close, but maybe not exactly the same thing...
Distribution for number of trials before a fixed sum is reached Another interesting way to arrive at the same answer is to introduce a second random variable $Y$ which is defined through the following constraint $$ Y = Z - \sum_{i=1}^T X_i . $$ Intuitively, for a
40,805
Getting NaN value for X-Squared and N/A for p-value in Chi-Square Test
As Glen_B pointed out, your problem is that you can't have expected frequencies to be zero, because that would throw off the calculation of the chi-squared statistic (you'd have zeros in the denominator). For example, see that x1 <- matrix(c(0, 1, 0, 1), 2, 2) x1 [,1] [,2] [1,] 0 0 [2,] 1 1 and x2 <- matrix(c(0, 0, 1, 1), 2, 2) x2 [,1] [,2] [1,] 0 1 [2,] 0 1 will both fail to produce chi-squared tests (as they should), whereas x3 <- matrix(c(0, 1, 0, 1), 2, 2) x3 [,1] [,2] [1,] 0 1 [2,] 1 0 will give you no problems. BTW, this issue was also addressed here and here.
Getting NaN value for X-Squared and N/A for p-value in Chi-Square Test
As Glen_B pointed out, your problem is that you can't have expected frequencies to be zero, because that would throw off the calculation of the chi-squared statistic (you'd have zeros in the denominat
Getting NaN value for X-Squared and N/A for p-value in Chi-Square Test As Glen_B pointed out, your problem is that you can't have expected frequencies to be zero, because that would throw off the calculation of the chi-squared statistic (you'd have zeros in the denominator). For example, see that x1 <- matrix(c(0, 1, 0, 1), 2, 2) x1 [,1] [,2] [1,] 0 0 [2,] 1 1 and x2 <- matrix(c(0, 0, 1, 1), 2, 2) x2 [,1] [,2] [1,] 0 1 [2,] 0 1 will both fail to produce chi-squared tests (as they should), whereas x3 <- matrix(c(0, 1, 0, 1), 2, 2) x3 [,1] [,2] [1,] 0 1 [2,] 1 0 will give you no problems. BTW, this issue was also addressed here and here.
Getting NaN value for X-Squared and N/A for p-value in Chi-Square Test As Glen_B pointed out, your problem is that you can't have expected frequencies to be zero, because that would throw off the calculation of the chi-squared statistic (you'd have zeros in the denominat
40,806
Conditional Expectation has the minimum mean prediction error
You can adapt the following argument to get a full answer to your question. For random variables $X$ and $Y$, and a measurable function $f$, we have $$ \newcommand{\E}{\mathbb{E}} \E[(Y-f(X))^2] = \E[(Y-\E[Y\mid X]+\E[Y\mid X]-f(X))^2] $$ $$ = \E[(Y-\E[Y\mid X])^2] - 2\,\E[(Y-\E[Y\mid X])(\E[Y\mid X]-f(X))] + \E[(\E[Y\mid X]-f(X))^2] \, . $$ Consider the middle term of the last expression. By definition, $\E[Y\mid X]-f(X)$ is a function (call it $g$) of $X$. Hence, using the properties of the conditional expectation, we have $$ \E[(Y-\E[Y\mid X])(\E[Y\mid X]-f(X))] = \E[(Y-\E[Y\mid X])g(X)] $$ $$ = \E[g(X)Y] - \E[g(X)\E[Y\mid X]] $$ $$ = \E[g(X)Y] - \E[\E[g(X)Y\mid X]] $$ $$ = \E[g(X)Y] - \E[g(X)Y] = 0 \, . $$ Therefore, $$ \E[(Y-f(X))^2] = \E[(Y-\E[Y\mid X])^2] + \E[(\E[Y\mid X]-f(X))^2] \, , $$ implying that $$ \E[(Y-f(X))^2] \geq \E[(Y-\E[Y\mid X])^2] \, , $$ with equality if we choose $f(X)=\E[Y\mid X]$ a.s. $\newcommand{\cF}{\mathscr{F}}$ Your proof follows mutatis mutandis from this one. Define $\cF_t=\sigma(X_{t-k}:k\geq 0)$. Let $Z$ be $\cF_t$-measurable. Use what we just did to prove that $$ \E[(X_{t+k}-Z)^2\mid\cF_t] \geq \E[(X_{t+k}-\E[X_{t+k}\mid\cF_t])^2\mid\cF_t] $$ holds a.s. The result follows.
Conditional Expectation has the minimum mean prediction error
You can adapt the following argument to get a full answer to your question. For random variables $X$ and $Y$, and a measurable function $f$, we have $$ \newcommand{\E}{\mathbb{E}} \E[(Y-f(X))^2] =
Conditional Expectation has the minimum mean prediction error You can adapt the following argument to get a full answer to your question. For random variables $X$ and $Y$, and a measurable function $f$, we have $$ \newcommand{\E}{\mathbb{E}} \E[(Y-f(X))^2] = \E[(Y-\E[Y\mid X]+\E[Y\mid X]-f(X))^2] $$ $$ = \E[(Y-\E[Y\mid X])^2] - 2\,\E[(Y-\E[Y\mid X])(\E[Y\mid X]-f(X))] + \E[(\E[Y\mid X]-f(X))^2] \, . $$ Consider the middle term of the last expression. By definition, $\E[Y\mid X]-f(X)$ is a function (call it $g$) of $X$. Hence, using the properties of the conditional expectation, we have $$ \E[(Y-\E[Y\mid X])(\E[Y\mid X]-f(X))] = \E[(Y-\E[Y\mid X])g(X)] $$ $$ = \E[g(X)Y] - \E[g(X)\E[Y\mid X]] $$ $$ = \E[g(X)Y] - \E[\E[g(X)Y\mid X]] $$ $$ = \E[g(X)Y] - \E[g(X)Y] = 0 \, . $$ Therefore, $$ \E[(Y-f(X))^2] = \E[(Y-\E[Y\mid X])^2] + \E[(\E[Y\mid X]-f(X))^2] \, , $$ implying that $$ \E[(Y-f(X))^2] \geq \E[(Y-\E[Y\mid X])^2] \, , $$ with equality if we choose $f(X)=\E[Y\mid X]$ a.s. $\newcommand{\cF}{\mathscr{F}}$ Your proof follows mutatis mutandis from this one. Define $\cF_t=\sigma(X_{t-k}:k\geq 0)$. Let $Z$ be $\cF_t$-measurable. Use what we just did to prove that $$ \E[(X_{t+k}-Z)^2\mid\cF_t] \geq \E[(X_{t+k}-\E[X_{t+k}\mid\cF_t])^2\mid\cF_t] $$ holds a.s. The result follows.
Conditional Expectation has the minimum mean prediction error You can adapt the following argument to get a full answer to your question. For random variables $X$ and $Y$, and a measurable function $f$, we have $$ \newcommand{\E}{\mathbb{E}} \E[(Y-f(X))^2] =
40,807
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA?
PCA calculates the eigenvalues that explain most of the variation across the data, in this case it would operate per feature vector and does not take account of class labels. LDA maximizes Fishers discriminant ratio (or Mahalaobis distance), i.e. it maximizes the distance between classes. If you define the feature vector for each observation (case) as the data at an instantaneous time point, then the temporal components of the data are not relevant. In this case you can apply PCA as pre-processing stage to each feature vector to reduce dimensionality prior to classification. If however, you define each trial as a 10s epoch or segment around the point of interest, you could then calculate a summary statistic for each sensor across all time samples in the epoch. Each feature in your feature vector would then be a summary of the behaviour of each sensor over the 10s (e.g. mean amplitude across each 10s epoch). You could then apply PCA as pre-processing step to reduce the dimensionality of the feature vector from 306 to a more manageable number. This second approach assumes that summary statistics calculated over each 10s epoch contains more information relevant to your problem than the instantaneous feature detailed above.
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA?
PCA calculates the eigenvalues that explain most of the variation across the data, in this case it would operate per feature vector and does not take account of class labels. LDA maximizes Fishers di
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA? PCA calculates the eigenvalues that explain most of the variation across the data, in this case it would operate per feature vector and does not take account of class labels. LDA maximizes Fishers discriminant ratio (or Mahalaobis distance), i.e. it maximizes the distance between classes. If you define the feature vector for each observation (case) as the data at an instantaneous time point, then the temporal components of the data are not relevant. In this case you can apply PCA as pre-processing stage to each feature vector to reduce dimensionality prior to classification. If however, you define each trial as a 10s epoch or segment around the point of interest, you could then calculate a summary statistic for each sensor across all time samples in the epoch. Each feature in your feature vector would then be a summary of the behaviour of each sensor over the 10s (e.g. mean amplitude across each 10s epoch). You could then apply PCA as pre-processing step to reduce the dimensionality of the feature vector from 306 to a more manageable number. This second approach assumes that summary statistics calculated over each 10s epoch contains more information relevant to your problem than the instantaneous feature detailed above.
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA? PCA calculates the eigenvalues that explain most of the variation across the data, in this case it would operate per feature vector and does not take account of class labels. LDA maximizes Fishers di
40,808
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA?
Your problem is most likely overfitting - it is typical when you use small datasets with large number of dimensions. In case of LDA what usually happens that the covariance matrix is biased because of the small sample. In order to avoid it you may try to use regularization. One useful technique is to sphere covariance matrix by adding small terms to the diagonal (also called shrinkage). In this case there is no need to use PCA. You can read about the technique in this paper on single trial EEG analysis.
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA?
Your problem is most likely overfitting - it is typical when you use small datasets with large number of dimensions. In case of LDA what usually happens that the covariance matrix is biased because of
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA? Your problem is most likely overfitting - it is typical when you use small datasets with large number of dimensions. In case of LDA what usually happens that the covariance matrix is biased because of the small sample. In order to avoid it you may try to use regularization. One useful technique is to sphere covariance matrix by adding small terms to the diagonal (also called shrinkage). In this case there is no need to use PCA. You can read about the technique in this paper on single trial EEG analysis.
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA? Your problem is most likely overfitting - it is typical when you use small datasets with large number of dimensions. In case of LDA what usually happens that the covariance matrix is biased because of
40,809
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA?
I am doing the similar thing with neuronal spikes. Some papers I am following did PCA and selected components that explain 90% variance then did LDA, with the main purpose being "avoiding singular matrix", which to some extent makes sense, but can be avoided by "eigen solver" and "shrinkage". There are 3 reasons why I chose not to do so: very practically, your dataset is temporal, if you perform PCA at each epoch you lose the potential to compare the change across time (or at least harder). It's also harder to track back to individual neurons, but I think in your case it's not that important. as is suggested by another answer, PCA may impair your decoding performance - it is unsupervised. More importantly, I think scientifically it is interesting to see how different regions collectively give rise to a function. I don't think PCA before a classifier will help it. while I'm typing this answer, I just thought of that people also pool the dimensions of trials and epochs together as sample dimension for PCA. If you perform PCA this way, then at each time point your components are not orthogonal, and you somehow still can compare different epochs.
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA?
I am doing the similar thing with neuronal spikes. Some papers I am following did PCA and selected components that explain 90% variance then did LDA, with the main purpose being "avoiding singular mat
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA? I am doing the similar thing with neuronal spikes. Some papers I am following did PCA and selected components that explain 90% variance then did LDA, with the main purpose being "avoiding singular matrix", which to some extent makes sense, but can be avoided by "eigen solver" and "shrinkage". There are 3 reasons why I chose not to do so: very practically, your dataset is temporal, if you perform PCA at each epoch you lose the potential to compare the change across time (or at least harder). It's also harder to track back to individual neurons, but I think in your case it's not that important. as is suggested by another answer, PCA may impair your decoding performance - it is unsupervised. More importantly, I think scientifically it is interesting to see how different regions collectively give rise to a function. I don't think PCA before a classifier will help it. while I'm typing this answer, I just thought of that people also pool the dimensions of trials and epochs together as sample dimension for PCA. If you perform PCA this way, then at each time point your components are not orthogonal, and you somehow still can compare different epochs.
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA? I am doing the similar thing with neuronal spikes. Some papers I am following did PCA and selected components that explain 90% variance then did LDA, with the main purpose being "avoiding singular mat
40,810
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA?
BGreene's answer is a good one, but I would just add that it might make even more sense to go from PCA to the more closely related LDA classifier, which is Latent Dirichlet Allocation. As the name implies, it's a latent variable technique, like PCA. It's trending highly in the classification literature (I'm using it myself right now) particularly in text mining and unstructured data. Using PCA then Fischer's LDA is statistically valid ceteris paribus, but it's not necessarily a good idea. Though I and plenty of other people do use linear discriminate in some contexts because it's so quick and easy, in most applications it's not a very statistically efficient or practically effective choice. As a classifier it often performs particularlly poorly; I usually run and rank many classifiers for any algorithm I'm building and linear discriminate is usually at the bottom of the list. It's poor performance may be the reason for needing PCA to reduce dimensional, but I would just choose a single, more appropriate classifier.
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA?
BGreene's answer is a good one, but I would just add that it might make even more sense to go from PCA to the more closely related LDA classifier, which is Latent Dirichlet Allocation. As the name imp
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA? BGreene's answer is a good one, but I would just add that it might make even more sense to go from PCA to the more closely related LDA classifier, which is Latent Dirichlet Allocation. As the name implies, it's a latent variable technique, like PCA. It's trending highly in the classification literature (I'm using it myself right now) particularly in text mining and unstructured data. Using PCA then Fischer's LDA is statistically valid ceteris paribus, but it's not necessarily a good idea. Though I and plenty of other people do use linear discriminate in some contexts because it's so quick and easy, in most applications it's not a very statistically efficient or practically effective choice. As a classifier it often performs particularlly poorly; I usually run and rank many classifiers for any algorithm I'm building and linear discriminate is usually at the bottom of the list. It's poor performance may be the reason for needing PCA to reduce dimensional, but I would just choose a single, more appropriate classifier.
Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA? BGreene's answer is a good one, but I would just add that it might make even more sense to go from PCA to the more closely related LDA classifier, which is Latent Dirichlet Allocation. As the name imp
40,811
Histogram of uncertain data
It's not clear to me why this would be an issue in a simple plot of a univariate distribution. However, it's worth knowing that histograms aren't typically considered to be a very good way to visualize a univariate distribution. Kernel density plots are generally considered to be better. These are estimated by drawing a very small distribution (typically normal) for each data point. The mean is centered on the datum in question; what's needed then is to determine the SD for the distributions (there are some fairly standard algorithms for this). Once all of the distributions have been drawn, the vertical positions of these drawn distributions are summed at each point on the horizontal axis, and that set of (x,y) pairs forms the final curve that's plotted (there's a very good figure at the linked Wikipedia page). What you could do is use your known variances for each point instead. This will most likely require a little programming on your part, but shouldn't be too hard.
Histogram of uncertain data
It's not clear to me why this would be an issue in a simple plot of a univariate distribution. However, it's worth knowing that histograms aren't typically considered to be a very good way to visuali
Histogram of uncertain data It's not clear to me why this would be an issue in a simple plot of a univariate distribution. However, it's worth knowing that histograms aren't typically considered to be a very good way to visualize a univariate distribution. Kernel density plots are generally considered to be better. These are estimated by drawing a very small distribution (typically normal) for each data point. The mean is centered on the datum in question; what's needed then is to determine the SD for the distributions (there are some fairly standard algorithms for this). Once all of the distributions have been drawn, the vertical positions of these drawn distributions are summed at each point on the horizontal axis, and that set of (x,y) pairs forms the final curve that's plotted (there's a very good figure at the linked Wikipedia page). What you could do is use your known variances for each point instead. This will most likely require a little programming on your part, but shouldn't be too hard.
Histogram of uncertain data It's not clear to me why this would be an issue in a simple plot of a univariate distribution. However, it's worth knowing that histograms aren't typically considered to be a very good way to visuali
40,812
Histogram of uncertain data
While I think @gung's answer is probably the right approach here, I'd like to address the original question on its own terms; I think it's an interesting question that also deserves an answer. There are two issues here: 1) histogram bars already have an uncertainty associated with them. 2) You're apparently talking about an additional source of uncertainty (or, depending on how your means and standard deviations arise, arguably a different source for different circumstances) introduced by not being certain which bar an observation should "really" count in. We can compute that, if we make some assumptions about the distribution. Consider an "observation", $m_i$ with standard deviation of $s_i$. I am going to treat these like known rather than estimated values. Then, as in @gung's answer, we replace these values with kernels (of area $1/n$ if we want the histogram to estimate densities) with the same mean and standard deviation. I'm going to assume a Gaussian kernel but if you thought some other distributional assumption was more suitable, you would certainly use it instead. If you wanted to make if more efficient calculation-wise you could consider a kernel with finite range, such as an Epanechnikov. For each little kernel, there's a certain proportion in each histogram bin. Let's say the proportion of the area of point $i$ in bin $k$ is $p_{ik}$. Then the contribution of that proportion of the point's probability to the variance of that bin is just the Bernoulli variance, $p_{ik}(1-p_{ik})$. So for bin $k$, you just sum those contributions for each point: $$\sum_{i} p_{ik}(1-p_{ik})$$ If those $m$'s and $s$'s are estimated rather than known, it becomes more complex ... and you need to consider that first source of uncertainty.
Histogram of uncertain data
While I think @gung's answer is probably the right approach here, I'd like to address the original question on its own terms; I think it's an interesting question that also deserves an answer. There a
Histogram of uncertain data While I think @gung's answer is probably the right approach here, I'd like to address the original question on its own terms; I think it's an interesting question that also deserves an answer. There are two issues here: 1) histogram bars already have an uncertainty associated with them. 2) You're apparently talking about an additional source of uncertainty (or, depending on how your means and standard deviations arise, arguably a different source for different circumstances) introduced by not being certain which bar an observation should "really" count in. We can compute that, if we make some assumptions about the distribution. Consider an "observation", $m_i$ with standard deviation of $s_i$. I am going to treat these like known rather than estimated values. Then, as in @gung's answer, we replace these values with kernels (of area $1/n$ if we want the histogram to estimate densities) with the same mean and standard deviation. I'm going to assume a Gaussian kernel but if you thought some other distributional assumption was more suitable, you would certainly use it instead. If you wanted to make if more efficient calculation-wise you could consider a kernel with finite range, such as an Epanechnikov. For each little kernel, there's a certain proportion in each histogram bin. Let's say the proportion of the area of point $i$ in bin $k$ is $p_{ik}$. Then the contribution of that proportion of the point's probability to the variance of that bin is just the Bernoulli variance, $p_{ik}(1-p_{ik})$. So for bin $k$, you just sum those contributions for each point: $$\sum_{i} p_{ik}(1-p_{ik})$$ If those $m$'s and $s$'s are estimated rather than known, it becomes more complex ... and you need to consider that first source of uncertainty.
Histogram of uncertain data While I think @gung's answer is probably the right approach here, I'd like to address the original question on its own terms; I think it's an interesting question that also deserves an answer. There a
40,813
How to avoid 0 determinant when sample covariance matrix has very small values
Several things. The determinant is scale equivariant, so without loss of generality you can rescale your $x_i$'s (say multiply them by 10) and then factor back the scale after all the intermediate operations have been performed as shown in the following R code: p <- 10 n <- 100 a1 <- matrix(runif(n*p),n,p) a1 <- sweep(a1,1,sqrt(rowSums(a1*a1)),FUN="/") a2 <- a1*10 #you can re-scale your data log(det(cov(a1[1:(p+1),]))) log(det(cov(a2[1:(p+1),])))-log(10^(2*(p))) #and compensate for the rescaling 'at the end' You should work with the determinant rescaled to be expressed in the original units of your dataset (e.g. if $\varSigma$ is your covariance matrix and $p$ it's rank, use $|\varSigma|^{1/2p}$). This is similar to how the standard deviations are expressed in the original units but the variances in the square of the original units.
How to avoid 0 determinant when sample covariance matrix has very small values
Several things. The determinant is scale equivariant, so without loss of generality you can rescale your $x_i$'s (say multiply them by 10) and then factor back the scale after all the intermediate o
How to avoid 0 determinant when sample covariance matrix has very small values Several things. The determinant is scale equivariant, so without loss of generality you can rescale your $x_i$'s (say multiply them by 10) and then factor back the scale after all the intermediate operations have been performed as shown in the following R code: p <- 10 n <- 100 a1 <- matrix(runif(n*p),n,p) a1 <- sweep(a1,1,sqrt(rowSums(a1*a1)),FUN="/") a2 <- a1*10 #you can re-scale your data log(det(cov(a1[1:(p+1),]))) log(det(cov(a2[1:(p+1),])))-log(10^(2*(p))) #and compensate for the rescaling 'at the end' You should work with the determinant rescaled to be expressed in the original units of your dataset (e.g. if $\varSigma$ is your covariance matrix and $p$ it's rank, use $|\varSigma|^{1/2p}$). This is similar to how the standard deviations are expressed in the original units but the variances in the square of the original units.
How to avoid 0 determinant when sample covariance matrix has very small values Several things. The determinant is scale equivariant, so without loss of generality you can rescale your $x_i$'s (say multiply them by 10) and then factor back the scale after all the intermediate o
40,814
How to avoid 0 determinant when sample covariance matrix has very small values
Numerical stability will be a problem for you. One approach to make the calculation a little more stable - taking $X$ to be a mean-corrected matrix of the $x$-values, I think it makes sense to either form a QR decomposition of the $X$-matrix or failing that a Choleski decomposition of the $X'X$ matrix, and use the product of the diagonal of $R$ (or of the Choleski factor) which will be the square root of the determinant. There are other approaches (some of which may be better than computing the QR). You still need to scale for the $n-1$'s, though.
How to avoid 0 determinant when sample covariance matrix has very small values
Numerical stability will be a problem for you. One approach to make the calculation a little more stable - taking $X$ to be a mean-corrected matrix of the $x$-values, I think it makes sense to either
How to avoid 0 determinant when sample covariance matrix has very small values Numerical stability will be a problem for you. One approach to make the calculation a little more stable - taking $X$ to be a mean-corrected matrix of the $x$-values, I think it makes sense to either form a QR decomposition of the $X$-matrix or failing that a Choleski decomposition of the $X'X$ matrix, and use the product of the diagonal of $R$ (or of the Choleski factor) which will be the square root of the determinant. There are other approaches (some of which may be better than computing the QR). You still need to scale for the $n-1$'s, though.
How to avoid 0 determinant when sample covariance matrix has very small values Numerical stability will be a problem for you. One approach to make the calculation a little more stable - taking $X$ to be a mean-corrected matrix of the $x$-values, I think it makes sense to either
40,815
How to calculate cumulative Poisson probabilities without adding each one if no. of outcomes is large and hence, adding (without excel) is difficult?
The Skellam distribution is the distribution of the difference in counts of two independent Poisson variates: http://en.wikipedia.org/wiki/Skellam_distribution But you will still need a computer to calculate the modified Bessel function. Here is an Excel example. This image (which can be magnified by zooming in the browser) shows the formulas at the left and the values for the same sheet at the right. The spreadsheet accepts the (positive) means $\mu_1$ and $\mu_2$ as input (blue text), computes three intermediate quantities involved in the Skellam probabilities ($\exp(-\mu_1-\mu_2)$, $\sqrt{\mu_1 \mu_2}$, and $\sqrt{\mu_1/\mu_2}$, shown in green), and then uses those to compute a table of probabilities for the score difference $k$ using the hyperbolic Bessel function $I_{|k|}$. This table (shown as computed for $-12, -11, \ldots, 12$, but computable for any range of integers) is plotted at the right as a bar chart, with positive differences to the right (in red) and a zero difference (in gray) exactly in the middle. As a check, the sum of the probabilities is computed and displayed: if it is any less than $1.0000$, the table may be missing some important probabilities and should be extended in one or both directions. As usual, cumulative probabilities can be found with little extra effort by running a cumulative sum down a parallel column. (This distribution has no convenient, general, closed form formula for its CDF.)
How to calculate cumulative Poisson probabilities without adding each one if no. of outcomes is larg
The Skellam distribution is the distribution of the difference in counts of two independent Poisson variates: http://en.wikipedia.org/wiki/Skellam_distribution But you will still need a computer to ca
How to calculate cumulative Poisson probabilities without adding each one if no. of outcomes is large and hence, adding (without excel) is difficult? The Skellam distribution is the distribution of the difference in counts of two independent Poisson variates: http://en.wikipedia.org/wiki/Skellam_distribution But you will still need a computer to calculate the modified Bessel function. Here is an Excel example. This image (which can be magnified by zooming in the browser) shows the formulas at the left and the values for the same sheet at the right. The spreadsheet accepts the (positive) means $\mu_1$ and $\mu_2$ as input (blue text), computes three intermediate quantities involved in the Skellam probabilities ($\exp(-\mu_1-\mu_2)$, $\sqrt{\mu_1 \mu_2}$, and $\sqrt{\mu_1/\mu_2}$, shown in green), and then uses those to compute a table of probabilities for the score difference $k$ using the hyperbolic Bessel function $I_{|k|}$. This table (shown as computed for $-12, -11, \ldots, 12$, but computable for any range of integers) is plotted at the right as a bar chart, with positive differences to the right (in red) and a zero difference (in gray) exactly in the middle. As a check, the sum of the probabilities is computed and displayed: if it is any less than $1.0000$, the table may be missing some important probabilities and should be extended in one or both directions. As usual, cumulative probabilities can be found with little extra effort by running a cumulative sum down a parallel column. (This distribution has no convenient, general, closed form formula for its CDF.)
How to calculate cumulative Poisson probabilities without adding each one if no. of outcomes is larg The Skellam distribution is the distribution of the difference in counts of two independent Poisson variates: http://en.wikipedia.org/wiki/Skellam_distribution But you will still need a computer to ca
40,816
Smoothing a time series of ratios
It would be erroneous to compute the ratios of the smoothed counts, because it's possible many of the ratios would not be true proportions--they could (easily) wind up outside the valid range from $0$ to $1$. (This happens in the example described below.) Since the denominators $b_t$ vary substantially, and a count based on such a denominator typically has a variance proportional to the denominator, you should consider making weighted smooths of the ratios using the $b_t$ as the weights. To study this, I created time series $a_t$ and $b_t$ which vary substantially and are temporally correlated. The $a_t$ have binomial distributions based on the counts in $b_t$, with regularly (sinusoidally) varying probabilities. These, and their ratio $a_t/b_t$, are shown in the first row of the figure below. (The dots for the observations are scaled so their areas are proportional to $b_t$: larger dots represent more reliable data.) Then I compute four possible smooths: the ratio of the smooths, the smoothed ratio, and the two weighted versions. These occupy the next two rows: one for the unweighted version and another for the weighted version. Finally, the bottom row shows scatterplots of these four smooths against the true probabilities. In experimenting with various values of n (length of series, ranging from $40$ to $200$) and m (maximum possible value of $b_t$, ranging from $3$ to $600$), I find the weighted smoothed ratio is slightly--but visibly--better than the unweighted smoothed ratio, and both are consistently much better than the ratios of the smooths (weighted or not). Compare the bottom right scatterplot ("Wtd Smoothed Ratios") to its unweighted counterpart, second from the left at the bottom ("Smoothed Ratios"). Ideally, these plots would be diagonal lines. Notice the wild behavior of the ratios of smooths and their extreme departures from the ideal. That awfulness is equally apparent in the plots of smooths against the data shown in the first column (second and third rows). n <- 80 m <- 30 z <- 1.1 p <- (1 + sin(2 * pi * 1:n / n)) / (1+z) q <- (1 + sin(5/3 * 2 * pi * 1:n / n)) / (1+z) b <- ceiling(0.001 + m * q) scale <- sqrt(b/m)*3 set.seed(26) a <- rbinom(n, b, p) col = c(rgb(.8,.2,.2), rgb(.2,.2,.8), rgb(.2,.8,.2), "Black", "Gray") par(mfrow=c(4,4)) plot(p, type="l", lwd=2, col=col[1], main="Actual") plot(a, col=col[2], main="Numerators") plot(b, col=col[3], main="Denominators") plot(a/b, col=col[5], main="Observed Ratios", cex=scale) a.smooth <- loess(a ~ as.vector(1:n)) b.smooth <- loess(b ~ as.vector(1:n)) a.b.smooth <- loess(a/b ~ as.vector(1:n)) plot(a.smooth$fitted / b.smooth$fitted, col=col[1], type="l", lwd=2, main="Ratio of Smooths") points(a/b, col=col[5], cex=scale) plot(a.smooth$fitted, col=col[2], type="l", lwd=2, main="Smoothed Numerators") plot(b.smooth$fitted, col=col[3], type="l", lwd=2, main="Smoothed Denominators") plot(a.b.smooth$fitted, col=col[4], type="l", lwd=2, main="Smoothed Ratios") points(a/b, col=col[5], cex=scale) a.smooth.w <- loess(a ~ as.vector(1:n), weights=b) b.smooth.w <- loess(b ~ as.vector(1:n), weights=b) a.b.smooth.w <- loess(a/b ~ as.vector(1:n), weights=b) plot(a.smooth.w$fitted / b.smooth.w$fitted, col=col[1], type="l", lwd=2, main="(Weighted version)") points(a/b, col=col[5], cex=scale) plot(a.smooth.w$fitted, col=col[2], type="l", lwd=2, main="(Weighted version)") plot(b.smooth.w$fitted, col=col[3], type="l", lwd=2, main="(Weighted version)") plot(a.b.smooth.w$fitted, col=col[4], type="l", lwd=2, main="(Weighted version)") points(a/b, col=col[5], cex=scale) plot(p, a.smooth$fitted / b.smooth$fitted, col=col[1], type="l", lwd=2, main="Ratio of Smooths") plot(p, a.b.smooth$fitted, col=col[1], type="l", lwd=2, main="Smoothed Ratios") plot(p, a.smooth.w$fitted / b.smooth.w$fitted, col=col[1], type="l", lwd=2, main="Ratio of Wtd Smooths") plot(p, a.b.smooth.w$fitted, col=col[1], type="l", lwd=2, main="Wtd Smoothed Ratios")
Smoothing a time series of ratios
It would be erroneous to compute the ratios of the smoothed counts, because it's possible many of the ratios would not be true proportions--they could (easily) wind up outside the valid range from $0$
Smoothing a time series of ratios It would be erroneous to compute the ratios of the smoothed counts, because it's possible many of the ratios would not be true proportions--they could (easily) wind up outside the valid range from $0$ to $1$. (This happens in the example described below.) Since the denominators $b_t$ vary substantially, and a count based on such a denominator typically has a variance proportional to the denominator, you should consider making weighted smooths of the ratios using the $b_t$ as the weights. To study this, I created time series $a_t$ and $b_t$ which vary substantially and are temporally correlated. The $a_t$ have binomial distributions based on the counts in $b_t$, with regularly (sinusoidally) varying probabilities. These, and their ratio $a_t/b_t$, are shown in the first row of the figure below. (The dots for the observations are scaled so their areas are proportional to $b_t$: larger dots represent more reliable data.) Then I compute four possible smooths: the ratio of the smooths, the smoothed ratio, and the two weighted versions. These occupy the next two rows: one for the unweighted version and another for the weighted version. Finally, the bottom row shows scatterplots of these four smooths against the true probabilities. In experimenting with various values of n (length of series, ranging from $40$ to $200$) and m (maximum possible value of $b_t$, ranging from $3$ to $600$), I find the weighted smoothed ratio is slightly--but visibly--better than the unweighted smoothed ratio, and both are consistently much better than the ratios of the smooths (weighted or not). Compare the bottom right scatterplot ("Wtd Smoothed Ratios") to its unweighted counterpart, second from the left at the bottom ("Smoothed Ratios"). Ideally, these plots would be diagonal lines. Notice the wild behavior of the ratios of smooths and their extreme departures from the ideal. That awfulness is equally apparent in the plots of smooths against the data shown in the first column (second and third rows). n <- 80 m <- 30 z <- 1.1 p <- (1 + sin(2 * pi * 1:n / n)) / (1+z) q <- (1 + sin(5/3 * 2 * pi * 1:n / n)) / (1+z) b <- ceiling(0.001 + m * q) scale <- sqrt(b/m)*3 set.seed(26) a <- rbinom(n, b, p) col = c(rgb(.8,.2,.2), rgb(.2,.2,.8), rgb(.2,.8,.2), "Black", "Gray") par(mfrow=c(4,4)) plot(p, type="l", lwd=2, col=col[1], main="Actual") plot(a, col=col[2], main="Numerators") plot(b, col=col[3], main="Denominators") plot(a/b, col=col[5], main="Observed Ratios", cex=scale) a.smooth <- loess(a ~ as.vector(1:n)) b.smooth <- loess(b ~ as.vector(1:n)) a.b.smooth <- loess(a/b ~ as.vector(1:n)) plot(a.smooth$fitted / b.smooth$fitted, col=col[1], type="l", lwd=2, main="Ratio of Smooths") points(a/b, col=col[5], cex=scale) plot(a.smooth$fitted, col=col[2], type="l", lwd=2, main="Smoothed Numerators") plot(b.smooth$fitted, col=col[3], type="l", lwd=2, main="Smoothed Denominators") plot(a.b.smooth$fitted, col=col[4], type="l", lwd=2, main="Smoothed Ratios") points(a/b, col=col[5], cex=scale) a.smooth.w <- loess(a ~ as.vector(1:n), weights=b) b.smooth.w <- loess(b ~ as.vector(1:n), weights=b) a.b.smooth.w <- loess(a/b ~ as.vector(1:n), weights=b) plot(a.smooth.w$fitted / b.smooth.w$fitted, col=col[1], type="l", lwd=2, main="(Weighted version)") points(a/b, col=col[5], cex=scale) plot(a.smooth.w$fitted, col=col[2], type="l", lwd=2, main="(Weighted version)") plot(b.smooth.w$fitted, col=col[3], type="l", lwd=2, main="(Weighted version)") plot(a.b.smooth.w$fitted, col=col[4], type="l", lwd=2, main="(Weighted version)") points(a/b, col=col[5], cex=scale) plot(p, a.smooth$fitted / b.smooth$fitted, col=col[1], type="l", lwd=2, main="Ratio of Smooths") plot(p, a.b.smooth$fitted, col=col[1], type="l", lwd=2, main="Smoothed Ratios") plot(p, a.smooth.w$fitted / b.smooth.w$fitted, col=col[1], type="l", lwd=2, main="Ratio of Wtd Smooths") plot(p, a.b.smooth.w$fitted, col=col[1], type="l", lwd=2, main="Wtd Smoothed Ratios")
Smoothing a time series of ratios It would be erroneous to compute the ratios of the smoothed counts, because it's possible many of the ratios would not be true proportions--they could (easily) wind up outside the valid range from $0$
40,817
Smoothing a time series of ratios
I am no expert in time series, but no one has answered so.... A little playing on a Thursday afternoon: #MAKE UP DATA set.seed(16549678) time <- 1:100 a <- round(runif(100, 5, 10) + rnorm(100,0,1)) b <- round(a*4+rnorm(100)) x <- a/b #PLOTS OF RAW DATA, RED IS FOR B plot(time, a, ylim = c(0,50), type = 'l') lines(x = time, y=b, col = 2 ) #SMOOTH THE DATA a.lowess <- lowess(a~time) b.lowess <- lowess(b~time) x.lowess <- lowess(x~time) x.abfirst <- a.lowess$y/b.lowess$y #Compare plot(x.lowess$y,x.abfirst) plot(time,x.lowess$y, ylim = c(.2,.3)) lines(time, x.abfirst, col = 2) At least for this example, it doesn't seem to matter much.
Smoothing a time series of ratios
I am no expert in time series, but no one has answered so.... A little playing on a Thursday afternoon: #MAKE UP DATA set.seed(16549678) time <- 1:100 a <- round(runif(100, 5, 10) + rnorm(100,0,1)) b
Smoothing a time series of ratios I am no expert in time series, but no one has answered so.... A little playing on a Thursday afternoon: #MAKE UP DATA set.seed(16549678) time <- 1:100 a <- round(runif(100, 5, 10) + rnorm(100,0,1)) b <- round(a*4+rnorm(100)) x <- a/b #PLOTS OF RAW DATA, RED IS FOR B plot(time, a, ylim = c(0,50), type = 'l') lines(x = time, y=b, col = 2 ) #SMOOTH THE DATA a.lowess <- lowess(a~time) b.lowess <- lowess(b~time) x.lowess <- lowess(x~time) x.abfirst <- a.lowess$y/b.lowess$y #Compare plot(x.lowess$y,x.abfirst) plot(time,x.lowess$y, ylim = c(.2,.3)) lines(time, x.abfirst, col = 2) At least for this example, it doesn't seem to matter much.
Smoothing a time series of ratios I am no expert in time series, but no one has answered so.... A little playing on a Thursday afternoon: #MAKE UP DATA set.seed(16549678) time <- 1:100 a <- round(runif(100, 5, 10) + rnorm(100,0,1)) b
40,818
How to deal with repeated measurements in the same condition of a factorial experiment?
Multi-level models (aka mixed models etc) are designed to deal with the case where you have multiple measures on one person. In the typical 2x2 design (not repeated measures) you have multiple observations in each cell, but these are on different and unrelated subjects (people or whatever), thus, they are independent, and ANOVA or regression (both are the general linear model) are fine (provided other assumptions are met). If you have repeated measures on each subject, those data are not independent. There are various ways to deal with this. One way is to average the data for each person, but this isn't a very good way. Much better methods are multi-level models or general estimating equations (GEE). Unfortunately, the terminology here can get very confusing. Better to write equations. The general linear model (regular ANOVA or regression): $Y = X\beta + \epsilon $ where Y is a vector of the dependent variable, X a matrix of independent variables, $\beta$ a vector of parameters to be estimated and $\epsilon$ is error. This assumes that $\epsilon \sim \text{iid } \mathcal{N}(0, \sigma) $ Multi-level: $Y = X\beta + Z\gamma + \epsilon$ where Z is the (known) design matrix and $\gamma$ is a vector of random effect parameters. Assumes $\gamma \sim \mathcal{N} (0, \sigma) $ and that the covariance between $\gamma$ and $\epsilon$ is 0.
How to deal with repeated measurements in the same condition of a factorial experiment?
Multi-level models (aka mixed models etc) are designed to deal with the case where you have multiple measures on one person. In the typical 2x2 design (not repeated measures) you have multiple observa
How to deal with repeated measurements in the same condition of a factorial experiment? Multi-level models (aka mixed models etc) are designed to deal with the case where you have multiple measures on one person. In the typical 2x2 design (not repeated measures) you have multiple observations in each cell, but these are on different and unrelated subjects (people or whatever), thus, they are independent, and ANOVA or regression (both are the general linear model) are fine (provided other assumptions are met). If you have repeated measures on each subject, those data are not independent. There are various ways to deal with this. One way is to average the data for each person, but this isn't a very good way. Much better methods are multi-level models or general estimating equations (GEE). Unfortunately, the terminology here can get very confusing. Better to write equations. The general linear model (regular ANOVA or regression): $Y = X\beta + \epsilon $ where Y is a vector of the dependent variable, X a matrix of independent variables, $\beta$ a vector of parameters to be estimated and $\epsilon$ is error. This assumes that $\epsilon \sim \text{iid } \mathcal{N}(0, \sigma) $ Multi-level: $Y = X\beta + Z\gamma + \epsilon$ where Z is the (known) design matrix and $\gamma$ is a vector of random effect parameters. Assumes $\gamma \sim \mathcal{N} (0, \sigma) $ and that the covariance between $\gamma$ and $\epsilon$ is 0.
How to deal with repeated measurements in the same condition of a factorial experiment? Multi-level models (aka mixed models etc) are designed to deal with the case where you have multiple measures on one person. In the typical 2x2 design (not repeated measures) you have multiple observa
40,819
How to deal with repeated measurements in the same condition of a factorial experiment?
I think that you don't have to include trial as a random factor (unless it makes any sense, but you said they were just repetitions in random order). You only have to declare subjects as a random factor and R will detect that you have 4 observations per subject*B cell. Check df in the output (if you use nlme) to confirm. In a classical ANOVA-design context, that will allow the evaluation of the B*subject interaction [i.e., if the within-factor effect differs enough among subjects]. I think the full model for that would be m1 = lmer(DV ~ A * B + (B|Subject), data=data) (if using lmer) or m1 = lme(DV ~ A * B), random= ~B|Subject, data=data (if using nlme)
How to deal with repeated measurements in the same condition of a factorial experiment?
I think that you don't have to include trial as a random factor (unless it makes any sense, but you said they were just repetitions in random order). You only have to declare subjects as a random fact
How to deal with repeated measurements in the same condition of a factorial experiment? I think that you don't have to include trial as a random factor (unless it makes any sense, but you said they were just repetitions in random order). You only have to declare subjects as a random factor and R will detect that you have 4 observations per subject*B cell. Check df in the output (if you use nlme) to confirm. In a classical ANOVA-design context, that will allow the evaluation of the B*subject interaction [i.e., if the within-factor effect differs enough among subjects]. I think the full model for that would be m1 = lmer(DV ~ A * B + (B|Subject), data=data) (if using lmer) or m1 = lme(DV ~ A * B), random= ~B|Subject, data=data (if using nlme)
How to deal with repeated measurements in the same condition of a factorial experiment? I think that you don't have to include trial as a random factor (unless it makes any sense, but you said they were just repetitions in random order). You only have to declare subjects as a random fact
40,820
Deep learning libraries/software with good tutorials or examples
http://www.deeplearning.net/tutorial/ uses Theano, which can run on a GPU.
Deep learning libraries/software with good tutorials or examples
http://www.deeplearning.net/tutorial/ uses Theano, which can run on a GPU.
Deep learning libraries/software with good tutorials or examples http://www.deeplearning.net/tutorial/ uses Theano, which can run on a GPU.
Deep learning libraries/software with good tutorials or examples http://www.deeplearning.net/tutorial/ uses Theano, which can run on a GPU.
40,821
Deep learning libraries/software with good tutorials or examples
@Adrian already mentioned Theano. The other big player here is Torch7, which runs on Lua and also has GPU integration. There's a bit of discussion of their relative strengths and weaknesses here.
Deep learning libraries/software with good tutorials or examples
@Adrian already mentioned Theano. The other big player here is Torch7, which runs on Lua and also has GPU integration. There's a bit of discussion of their relative strengths and weaknesses here.
Deep learning libraries/software with good tutorials or examples @Adrian already mentioned Theano. The other big player here is Torch7, which runs on Lua and also has GPU integration. There's a bit of discussion of their relative strengths and weaknesses here.
Deep learning libraries/software with good tutorials or examples @Adrian already mentioned Theano. The other big player here is Torch7, which runs on Lua and also has GPU integration. There's a bit of discussion of their relative strengths and weaknesses here.
40,822
Deep learning libraries/software with good tutorials or examples
The course from Hinton at https://class.coursera.org/neuralnets-2012-001/class is the best basic tutorial I found online. I think before you use tutorials from deeplearning.net, this would offer more insight.
Deep learning libraries/software with good tutorials or examples
The course from Hinton at https://class.coursera.org/neuralnets-2012-001/class is the best basic tutorial I found online. I think before you use tutorials from deeplearning.net, this would offer more
Deep learning libraries/software with good tutorials or examples The course from Hinton at https://class.coursera.org/neuralnets-2012-001/class is the best basic tutorial I found online. I think before you use tutorials from deeplearning.net, this would offer more insight.
Deep learning libraries/software with good tutorials or examples The course from Hinton at https://class.coursera.org/neuralnets-2012-001/class is the best basic tutorial I found online. I think before you use tutorials from deeplearning.net, this would offer more
40,823
Random Balls in Random Buckets: What are the characteristics of the distribution?
Presuming each bucket is chosen with equal probability, and the balls are dropped independently, then the number of balls in each bucket would follow a multinomial distribution with $k$ trials and $p_1 = p_2 = \cdots = p_N = 1/N$. The probability of a particular bucket containing $x$ balls would be given by the binomial probability, which in this case is $\Pr(X=x) = \frac{k!}{x!(k-x)!} \frac{(N-1)^{k-x}}{N^k}$. You can use this to obtain $\Pr(X \geq x)$. If $k$ is large and $k/N$ is of reasonable magnitude, then we can use a Poisson distribution approximation (or a normal approximation). The expected number of buckets containing exactly $x$ balls would just be $N\Pr(X=x)$. Of course, the totals in the buckets are not independent, but the totals of a few (say $M$) buckets will be approximately independent if $k$ is large compared to $M$. Thus we could approximate the variance of the number of buckets containing $x$ balls by $N\Pr(X=x) (1 - \Pr(X=x))$. For example, if we have 1000 balls and 100 buckets, we'd expect 9.5 buckets to contain exactly 12 balls, but the standard deviation of this number is 2.9, so there is approximately a 95% probability it would lie between 4 and 15. (See R code). > p = dbinom(12, size=1000, prob=1/100) > 100*p [1] 9.516152 > sqrt(100*p*(1-p)) [1] 2.934379 > 100*p + c(-1, 1)*1.96*sqrt(100*p*(1-p)) [1] 3.764769 15.267534
Random Balls in Random Buckets: What are the characteristics of the distribution?
Presuming each bucket is chosen with equal probability, and the balls are dropped independently, then the number of balls in each bucket would follow a multinomial distribution with $k$ trials and $p_
Random Balls in Random Buckets: What are the characteristics of the distribution? Presuming each bucket is chosen with equal probability, and the balls are dropped independently, then the number of balls in each bucket would follow a multinomial distribution with $k$ trials and $p_1 = p_2 = \cdots = p_N = 1/N$. The probability of a particular bucket containing $x$ balls would be given by the binomial probability, which in this case is $\Pr(X=x) = \frac{k!}{x!(k-x)!} \frac{(N-1)^{k-x}}{N^k}$. You can use this to obtain $\Pr(X \geq x)$. If $k$ is large and $k/N$ is of reasonable magnitude, then we can use a Poisson distribution approximation (or a normal approximation). The expected number of buckets containing exactly $x$ balls would just be $N\Pr(X=x)$. Of course, the totals in the buckets are not independent, but the totals of a few (say $M$) buckets will be approximately independent if $k$ is large compared to $M$. Thus we could approximate the variance of the number of buckets containing $x$ balls by $N\Pr(X=x) (1 - \Pr(X=x))$. For example, if we have 1000 balls and 100 buckets, we'd expect 9.5 buckets to contain exactly 12 balls, but the standard deviation of this number is 2.9, so there is approximately a 95% probability it would lie between 4 and 15. (See R code). > p = dbinom(12, size=1000, prob=1/100) > 100*p [1] 9.516152 > sqrt(100*p*(1-p)) [1] 2.934379 > 100*p + c(-1, 1)*1.96*sqrt(100*p*(1-p)) [1] 3.764769 15.267534
Random Balls in Random Buckets: What are the characteristics of the distribution? Presuming each bucket is chosen with equal probability, and the balls are dropped independently, then the number of balls in each bucket would follow a multinomial distribution with $k$ trials and $p_
40,824
Is listwise deletion / complete case analysis biased if data are not missing completely at random?
You are not wrong. From: Statistical Analysis with Missing Data, Second Edition, Roderick J.A. Little & Donald B Rubin, John Wiley and Sons, 2002. p41: Complete Case analysis confines attention to cases where all variables are present. Advantages of this approach are .... . Disadvantages stem from the potential loss of information in discarding incomplete cases. This loss of information has two aspects: loss of precision, and bias when the missing-data mechanism is not MCAR, and the complete cases are not a random sample of all the cases". From: Bias and efficiency of multiple imputation compared with complete-case analysis for missing covariate values. Ian R.White and John B. Carlin. Statistics in Medicine, Volume 29, Issue 28, 2010 In particular, while MI has negligible bias and CC is biased under MAR mechanisms, there are other mechanisms under which CC has negligible bias and MI is biased. This point is widely misunderstood, but it has important implications. http://onlinelibrary.wiley.com/doi/10.1002/sim.3944/pdf
Is listwise deletion / complete case analysis biased if data are not missing completely at random?
You are not wrong. From: Statistical Analysis with Missing Data, Second Edition, Roderick J.A. Little & Donald B Rubin, John Wiley and Sons, 2002. p41: Complete Case analysis confines attention to c
Is listwise deletion / complete case analysis biased if data are not missing completely at random? You are not wrong. From: Statistical Analysis with Missing Data, Second Edition, Roderick J.A. Little & Donald B Rubin, John Wiley and Sons, 2002. p41: Complete Case analysis confines attention to cases where all variables are present. Advantages of this approach are .... . Disadvantages stem from the potential loss of information in discarding incomplete cases. This loss of information has two aspects: loss of precision, and bias when the missing-data mechanism is not MCAR, and the complete cases are not a random sample of all the cases". From: Bias and efficiency of multiple imputation compared with complete-case analysis for missing covariate values. Ian R.White and John B. Carlin. Statistics in Medicine, Volume 29, Issue 28, 2010 In particular, while MI has negligible bias and CC is biased under MAR mechanisms, there are other mechanisms under which CC has negligible bias and MI is biased. This point is widely misunderstood, but it has important implications. http://onlinelibrary.wiley.com/doi/10.1002/sim.3944/pdf
Is listwise deletion / complete case analysis biased if data are not missing completely at random? You are not wrong. From: Statistical Analysis with Missing Data, Second Edition, Roderick J.A. Little & Donald B Rubin, John Wiley and Sons, 2002. p41: Complete Case analysis confines attention to c
40,825
Is listwise deletion / complete case analysis biased if data are not missing completely at random?
In general, complete case analysis is biased when data are not MCAR. However, when the analysis consists of fitting a regression model, complete case analysis is unbiased under the weaker condition that missingness is independent of the outcome variable, conditional on the covariates. Depending on which variable(s) contain missing values, this condition sometimes corresponds to MAR mechanisms, and sometimes to MNAR mechanisms. For example, suppose the outcome Y is the variable with missing values. Then missingness being independent of outcome conditional on covariates corresponds to the MAR assumption, which says the probability of missingness is independent of the partially observed variable conditional on the fully observed variables. Alternatively, suppose that missingness in a covariate X depends on the value of that covariate, so that data are MNAR. Provided missingness in X is independent of Y, conditional on X and other covariates in the analysis model, complete case analysis is unbiased. For more on this, see: 1) the paper cited in a previous answer by White and Carlin: Bias and efficiency of multiple imputation compared with complete-case analysis for missing covariate values. Ian R.White and John B. Carlin. Statistics in Medicine, Volume 29, Issue 28, 2010 2) a paper by myself and colleagues published in Biostatistics: http://doi.org/10.1093/biostatistics/kxu023 3) a blog post I previously wrote about this here: http://thestatsgeek.com/2013/07/06/when-is-complete-case-analysis-unbiased/
Is listwise deletion / complete case analysis biased if data are not missing completely at random?
In general, complete case analysis is biased when data are not MCAR. However, when the analysis consists of fitting a regression model, complete case analysis is unbiased under the weaker condition th
Is listwise deletion / complete case analysis biased if data are not missing completely at random? In general, complete case analysis is biased when data are not MCAR. However, when the analysis consists of fitting a regression model, complete case analysis is unbiased under the weaker condition that missingness is independent of the outcome variable, conditional on the covariates. Depending on which variable(s) contain missing values, this condition sometimes corresponds to MAR mechanisms, and sometimes to MNAR mechanisms. For example, suppose the outcome Y is the variable with missing values. Then missingness being independent of outcome conditional on covariates corresponds to the MAR assumption, which says the probability of missingness is independent of the partially observed variable conditional on the fully observed variables. Alternatively, suppose that missingness in a covariate X depends on the value of that covariate, so that data are MNAR. Provided missingness in X is independent of Y, conditional on X and other covariates in the analysis model, complete case analysis is unbiased. For more on this, see: 1) the paper cited in a previous answer by White and Carlin: Bias and efficiency of multiple imputation compared with complete-case analysis for missing covariate values. Ian R.White and John B. Carlin. Statistics in Medicine, Volume 29, Issue 28, 2010 2) a paper by myself and colleagues published in Biostatistics: http://doi.org/10.1093/biostatistics/kxu023 3) a blog post I previously wrote about this here: http://thestatsgeek.com/2013/07/06/when-is-complete-case-analysis-unbiased/
Is listwise deletion / complete case analysis biased if data are not missing completely at random? In general, complete case analysis is biased when data are not MCAR. However, when the analysis consists of fitting a regression model, complete case analysis is unbiased under the weaker condition th
40,826
What is the correct sample size when calculating CI for a subset of results?
As I interpret the question, this problem can easily be resolved through some careful reasoning about what is going on and what the survey objectives are. We can even do some simple mental calculations as a check on the confidence interval produced by the software. Consider this model of the survey. In a population, members have the following attributes: their answer to Q1a ("yes" or "no") and their QualityB (present or absent). However, a QualityB value is available and meaningful only for those who answered "yes". One purpose of the survey is to estimate the proportion of "yes" answerers who have QualityB present. To this end, the survey has selected 3031 people independently and randomly from the population. If this model reasonably approximates the survey and its objective, then notice that the randomization procedure by which all 3031 people were selected constitutes a fortiori a random procedure to select among the "yes" answerers. However (unlike specifying the sample size of 3031, which is usually determined by the investigator), the number of "yes" answerers was not determined in advance: it, too, is a random quantity. Nevertheless, in part because the subsample size of 616 is so large, it is a reasonable approximation to analyze it as if it were a random sample of 616 people chosen from just the "yes" answerers in the population. (As a partial justification of why we can consider 616 "large," by using the approximate Binomial theory calculations below, one can figure out that a comparable survey would likely have included between 579 and 653 "yes" answerers; this amount of variation would not change the calculation of the confidence limits much at all.) Accordingly, the analysis of the 34 people with QualityB present can proceed as usual. The binomial theory is applicable: we estimate the proportion of QualityB people out of the "yes" answerers as $34/616$ = $5.5$% and we estimate the variance of that proportion as $(34/616)(1 - 34/616)$, for an estimated standard deviation of $0.22836$. Because the subsample size is $616$, the standard error of the proportion is $0.22836/\sqrt{616}$ = $0.92$%. So--just to see where this is headed--we could use a normal approximation as a rough check. This tells us to expect the confidence interval procedure to give us a range from about $5.5$ - $1.65 \times 0.92$ = $4.0$% to $5.5 + 1.65 \times 0.92$ = $7.0$%. This range is very close to the quoted value of $5.5 \pm 1.54$%. (The multiplier of $1.65$ should give, approximately, a $90$% two-sided confidence interval.) We conclude that the proportion of people with QualityB among all "yes" answerers in the population is likely to be between $4$% and $7$%. To deduce this, we have used a procedure that will mislead us (by the luck of the draw) at most $10$% of the time it is appropriately applied; that's where our "confidence" comes from. Edit Because some questions about the validity of this answer have been raised in comments, let's check. One way is to bootstrap the data to assess the bias. But before proceeding, let's recast the problem in a more concrete form. Suppose, then, we are interested in the proportion of U.S. senior citizens (defined, say, as age 55 or older on January 1, 2012 and were resident in the U.S. on that date) who have ever tried recreational drugs. To this end, we identify all resident adults and send out a questionnaire to 3011 randomly selected adults. On it are two questions, analogs of the Q1a and QualityB questions discussed earlier: What was your age on January 1, 2012? If you answered 55 or older to question 1, have you ever knowingly consumed a drug, for recreational purposes, that at the time either required a physician's prescription or was illegal to use or sell in the U.S.? Miraculously--perhaps through incredibly diligent followup--you receive valid responses on all 3011 questionnaires. The data are: 616 of the responses are ages 55 or older. Of those 616, 34 answered "yes" to the second question. What proportion should you estimate? Is there any valid way to estimate a proportion at all? One form of the bootstrap studies this problem by adopting a synthetic population having exactly the same proportions observed in the data and recreates the experiment and its analysis many, many times, independently. Here is reproducible R code to do that for 100,000 independent trials, using the Binomial estimate recommended above: trial <- function(n.trials, n=1, p1=1/2, p2=1/2) { x <- rmultinom(n.trials, n, c(p2,1-p2) %o% c(p1,1-p1)) m <- x[1,]+x[2,] # Total who answer the second question mean <- x[1,]/m # Proportion of "yeses" in the second question se <- sqrt(mean*(1-mean)/m) rbind(mean, se) # Estimate and standard error of the estimate for each trial } set.seed(17) sim <- trial(100000, 3031, 616/3031, 34/616) The average estimate, mean(sim[1,), is $0.0551537$: almost identical to the correct value of $34/616 \approx 0.0551948$ in the synthetic population. There is no bias. How about the approximate confidence interval procedure? We can check in each of the 100,000 trials whether the confidence interval covered the true value of $34/616$ or not: coverage.upper <- sim[2,] * 1.65 + sim[1,] > 34/616 coverage.lower <- -sim[2,] * 1.65 + sim[1,] < 34/616 (sum(coverage.upper) + sum(coverage.lower))/100000 - 1 The result, $0.89542$, is within one-half of one percent of the desired coverage of $0.90$: that's excellent, especially given the approximations that were made. Given these (hypothetical) data we may legitimately conclude, then, that approximately $5.52$% of all U.S. senior citizens have used recreational drugs. With $90$% confidence that proportion is between $4$% and $7$%.
What is the correct sample size when calculating CI for a subset of results?
As I interpret the question, this problem can easily be resolved through some careful reasoning about what is going on and what the survey objectives are. We can even do some simple mental calculatio
What is the correct sample size when calculating CI for a subset of results? As I interpret the question, this problem can easily be resolved through some careful reasoning about what is going on and what the survey objectives are. We can even do some simple mental calculations as a check on the confidence interval produced by the software. Consider this model of the survey. In a population, members have the following attributes: their answer to Q1a ("yes" or "no") and their QualityB (present or absent). However, a QualityB value is available and meaningful only for those who answered "yes". One purpose of the survey is to estimate the proportion of "yes" answerers who have QualityB present. To this end, the survey has selected 3031 people independently and randomly from the population. If this model reasonably approximates the survey and its objective, then notice that the randomization procedure by which all 3031 people were selected constitutes a fortiori a random procedure to select among the "yes" answerers. However (unlike specifying the sample size of 3031, which is usually determined by the investigator), the number of "yes" answerers was not determined in advance: it, too, is a random quantity. Nevertheless, in part because the subsample size of 616 is so large, it is a reasonable approximation to analyze it as if it were a random sample of 616 people chosen from just the "yes" answerers in the population. (As a partial justification of why we can consider 616 "large," by using the approximate Binomial theory calculations below, one can figure out that a comparable survey would likely have included between 579 and 653 "yes" answerers; this amount of variation would not change the calculation of the confidence limits much at all.) Accordingly, the analysis of the 34 people with QualityB present can proceed as usual. The binomial theory is applicable: we estimate the proportion of QualityB people out of the "yes" answerers as $34/616$ = $5.5$% and we estimate the variance of that proportion as $(34/616)(1 - 34/616)$, for an estimated standard deviation of $0.22836$. Because the subsample size is $616$, the standard error of the proportion is $0.22836/\sqrt{616}$ = $0.92$%. So--just to see where this is headed--we could use a normal approximation as a rough check. This tells us to expect the confidence interval procedure to give us a range from about $5.5$ - $1.65 \times 0.92$ = $4.0$% to $5.5 + 1.65 \times 0.92$ = $7.0$%. This range is very close to the quoted value of $5.5 \pm 1.54$%. (The multiplier of $1.65$ should give, approximately, a $90$% two-sided confidence interval.) We conclude that the proportion of people with QualityB among all "yes" answerers in the population is likely to be between $4$% and $7$%. To deduce this, we have used a procedure that will mislead us (by the luck of the draw) at most $10$% of the time it is appropriately applied; that's where our "confidence" comes from. Edit Because some questions about the validity of this answer have been raised in comments, let's check. One way is to bootstrap the data to assess the bias. But before proceeding, let's recast the problem in a more concrete form. Suppose, then, we are interested in the proportion of U.S. senior citizens (defined, say, as age 55 or older on January 1, 2012 and were resident in the U.S. on that date) who have ever tried recreational drugs. To this end, we identify all resident adults and send out a questionnaire to 3011 randomly selected adults. On it are two questions, analogs of the Q1a and QualityB questions discussed earlier: What was your age on January 1, 2012? If you answered 55 or older to question 1, have you ever knowingly consumed a drug, for recreational purposes, that at the time either required a physician's prescription or was illegal to use or sell in the U.S.? Miraculously--perhaps through incredibly diligent followup--you receive valid responses on all 3011 questionnaires. The data are: 616 of the responses are ages 55 or older. Of those 616, 34 answered "yes" to the second question. What proportion should you estimate? Is there any valid way to estimate a proportion at all? One form of the bootstrap studies this problem by adopting a synthetic population having exactly the same proportions observed in the data and recreates the experiment and its analysis many, many times, independently. Here is reproducible R code to do that for 100,000 independent trials, using the Binomial estimate recommended above: trial <- function(n.trials, n=1, p1=1/2, p2=1/2) { x <- rmultinom(n.trials, n, c(p2,1-p2) %o% c(p1,1-p1)) m <- x[1,]+x[2,] # Total who answer the second question mean <- x[1,]/m # Proportion of "yeses" in the second question se <- sqrt(mean*(1-mean)/m) rbind(mean, se) # Estimate and standard error of the estimate for each trial } set.seed(17) sim <- trial(100000, 3031, 616/3031, 34/616) The average estimate, mean(sim[1,), is $0.0551537$: almost identical to the correct value of $34/616 \approx 0.0551948$ in the synthetic population. There is no bias. How about the approximate confidence interval procedure? We can check in each of the 100,000 trials whether the confidence interval covered the true value of $34/616$ or not: coverage.upper <- sim[2,] * 1.65 + sim[1,] > 34/616 coverage.lower <- -sim[2,] * 1.65 + sim[1,] < 34/616 (sum(coverage.upper) + sum(coverage.lower))/100000 - 1 The result, $0.89542$, is within one-half of one percent of the desired coverage of $0.90$: that's excellent, especially given the approximations that were made. Given these (hypothetical) data we may legitimately conclude, then, that approximately $5.52$% of all U.S. senior citizens have used recreational drugs. With $90$% confidence that proportion is between $4$% and $7$%.
What is the correct sample size when calculating CI for a subset of results? As I interpret the question, this problem can easily be resolved through some careful reasoning about what is going on and what the survey objectives are. We can even do some simple mental calculatio
40,827
What is the correct sample size when calculating CI for a subset of results?
No the 616 does not constitute a random sample from the population. It is a specific subset that answered yes to question 1a. Is quality B only assessed on those 616 or is it also studied for the remaining 2415? There is no simple answer to your question. You could bootstrap the 3031 and for each bootstrap sample you will get a subset of the 616 that answered yes to Q1a and from that you will have a subset of 34 with quality B. The bootstrap will give you a distribution of percentages from which you could construct a bootstrap confidence interval. Sorry to make it complicated but I don't see an easy way.
What is the correct sample size when calculating CI for a subset of results?
No the 616 does not constitute a random sample from the population. It is a specific subset that answered yes to question 1a. Is quality B only assessed on those 616 or is it also studied for the rem
What is the correct sample size when calculating CI for a subset of results? No the 616 does not constitute a random sample from the population. It is a specific subset that answered yes to question 1a. Is quality B only assessed on those 616 or is it also studied for the remaining 2415? There is no simple answer to your question. You could bootstrap the 3031 and for each bootstrap sample you will get a subset of the 616 that answered yes to Q1a and from that you will have a subset of 34 with quality B. The bootstrap will give you a distribution of percentages from which you could construct a bootstrap confidence interval. Sorry to make it complicated but I don't see an easy way.
What is the correct sample size when calculating CI for a subset of results? No the 616 does not constitute a random sample from the population. It is a specific subset that answered yes to question 1a. Is quality B only assessed on those 616 or is it also studied for the rem
40,828
Combining results from (GBM or any other) model based on samples from a very large database
This paper follows an approach very similar to the one you suggest, but they stratify the samples. In their case, each model sees a particular part of the geographic space, which lets the different submodels specialize. Figures 6 and 8 show that this partitioning can lead to better results than trying to fit the whole country with a single model. I haven't read the paper in detail yet, but when I spoke with the first author about it last week, he seemed to indicate that no fancy procedure was needed to combine the results--he just took the average prediction from all the relevant models.
Combining results from (GBM or any other) model based on samples from a very large database
This paper follows an approach very similar to the one you suggest, but they stratify the samples. In their case, each model sees a particular part of the geographic space, which lets the different s
Combining results from (GBM or any other) model based on samples from a very large database This paper follows an approach very similar to the one you suggest, but they stratify the samples. In their case, each model sees a particular part of the geographic space, which lets the different submodels specialize. Figures 6 and 8 show that this partitioning can lead to better results than trying to fit the whole country with a single model. I haven't read the paper in detail yet, but when I spoke with the first author about it last week, he seemed to indicate that no fancy procedure was needed to combine the results--he just took the average prediction from all the relevant models.
Combining results from (GBM or any other) model based on samples from a very large database This paper follows an approach very similar to the one you suggest, but they stratify the samples. In their case, each model sees a particular part of the geographic space, which lets the different s
40,829
Combining results from (GBM or any other) model based on samples from a very large database
Not quite the answer you are looking for but... Do you really need to use that much data? How many predictors do you have? If the number of predictors is small, how much of the data is redundant and just filling in the predictor space? Is it all relevant? Are there data points that are not really in the application domain of the model (i.e. 20 year old cases)? Just because you have it doesn't mean you must use it. I would sample the data based on similarity - come up with a subset of points that are most dissimilar from the other points n the training set. Finally, why use a tree ensemble method? I love RF but it is perhaps the model that will give you the largest possible footprint (i.e. thousands of very large unpruned trees). Try 100 bagged trees if you want to use a tree ensemble. Heck, boosted C5 trees probably need a much smaller number of iterations that CART-like boosting methods (from what I've seen so far) You may have no idea going into this process which model will be best or even good enough. Again, this depends on $p$, but start with some high bias models (LDA, logistic regression, naive Bayes) and see what you can get out of them before bringing out the big, complex, computational expensive (or infeasible) tools. Try logistic regression with cubic smoothing splines to approximate any non-linearities.
Combining results from (GBM or any other) model based on samples from a very large database
Not quite the answer you are looking for but... Do you really need to use that much data? How many predictors do you have? If the number of predictors is small, how much of the data is redundant and j
Combining results from (GBM or any other) model based on samples from a very large database Not quite the answer you are looking for but... Do you really need to use that much data? How many predictors do you have? If the number of predictors is small, how much of the data is redundant and just filling in the predictor space? Is it all relevant? Are there data points that are not really in the application domain of the model (i.e. 20 year old cases)? Just because you have it doesn't mean you must use it. I would sample the data based on similarity - come up with a subset of points that are most dissimilar from the other points n the training set. Finally, why use a tree ensemble method? I love RF but it is perhaps the model that will give you the largest possible footprint (i.e. thousands of very large unpruned trees). Try 100 bagged trees if you want to use a tree ensemble. Heck, boosted C5 trees probably need a much smaller number of iterations that CART-like boosting methods (from what I've seen so far) You may have no idea going into this process which model will be best or even good enough. Again, this depends on $p$, but start with some high bias models (LDA, logistic regression, naive Bayes) and see what you can get out of them before bringing out the big, complex, computational expensive (or infeasible) tools. Try logistic regression with cubic smoothing splines to approximate any non-linearities.
Combining results from (GBM or any other) model based on samples from a very large database Not quite the answer you are looking for but... Do you really need to use that much data? How many predictors do you have? If the number of predictors is small, how much of the data is redundant and j
40,830
Combining results from (GBM or any other) model based on samples from a very large database
In the spirit of using summaries to avoid using all that data. May be going in quite a different from your original request. Just a very naive way to get started - this could probably be done on a very large Postgres instance. This is an initial exploration step so it uses crude sums and counts to get some rough insights. you get some power from very efficient sum/count capabilities of a DBMS and use it to do some rough analysis. I am from a database and massively parallel data analysis background so take this as a somewhat of a stat newbies approach, (I do have an MS in Appl Math not used actively till very recently) So with all those caveats here goes a) consider naively, the attributes (date, itemsold, price, zipcode) as columns of your table. I am sure you have more but let's focus on these. b) create a secondary table in the database by adding up all the $ amts for a day's sales by zipcode now you get (date, dailysales, zipcode). Some simple SQL ( select date, zipcode, sum(price) as dailysales from table group by .... ) gets you this table. A much smaller table with 365 rows per zip code X # of zipcodes in your data. Use this table for initial explorations and also when you sample you can use this as a reality check. Depending on how much CPU and memory you give it this step could take minutes or hours. Suggest not trying it on a laptop (I blew my motherboard after a few 100 runs of similar sized problem on a circa 2005 laptop back then :-) ) c) for each zipcode separately do "your favorite regression", (dailysales dependent variable, date independent variable). See the MADlib project http://MADlib.net if you want to do this in-place (MADlib does in-database analytics by embedding C++ math, array and stats libs in Postgres) d) one plot per zip code, 365 data points (if you have daily data) - look for increasing, decreasing or inconclusive. or just get the correlation coefficients and partition into three buckets +, - and "dontknow". This now allows you to separate out, via Pareto thinking, the top 20 (or 10 or ..) zip codes with the most increase in sales by % and by $amt. Similar for most decrease ... You can now separately strategize how to drill down for the increasing, inconclusive and decreasing buckets of zipcodes, in a divide and conquer fashion. MADlib also allows you to run in-database R routines via PL/R but for Linear/Logistic Regression and SVM the embedded C++ is some 100 times faster. C4.5 is also available. If your data size gets too big for Postgres (dont think so, but just in case) then there's the Greenplum MPP database. For 75 million rows you should be able to do this on a X-Large EC2 instance or similar with Postgres. If you don't want to do this in a dbms there are ways to write some Python code and iterate over the disk file or database table pulling a few thousand or hundred thousand rows at a time into memory. If you do put it into Postgres there's ways to get small random samples of the rows. Hope this makes some sense or at least is not complete nonsense in your context :-)
Combining results from (GBM or any other) model based on samples from a very large database
In the spirit of using summaries to avoid using all that data. May be going in quite a different from your original request. Just a very naive way to get started - this could probably be done on a ver
Combining results from (GBM or any other) model based on samples from a very large database In the spirit of using summaries to avoid using all that data. May be going in quite a different from your original request. Just a very naive way to get started - this could probably be done on a very large Postgres instance. This is an initial exploration step so it uses crude sums and counts to get some rough insights. you get some power from very efficient sum/count capabilities of a DBMS and use it to do some rough analysis. I am from a database and massively parallel data analysis background so take this as a somewhat of a stat newbies approach, (I do have an MS in Appl Math not used actively till very recently) So with all those caveats here goes a) consider naively, the attributes (date, itemsold, price, zipcode) as columns of your table. I am sure you have more but let's focus on these. b) create a secondary table in the database by adding up all the $ amts for a day's sales by zipcode now you get (date, dailysales, zipcode). Some simple SQL ( select date, zipcode, sum(price) as dailysales from table group by .... ) gets you this table. A much smaller table with 365 rows per zip code X # of zipcodes in your data. Use this table for initial explorations and also when you sample you can use this as a reality check. Depending on how much CPU and memory you give it this step could take minutes or hours. Suggest not trying it on a laptop (I blew my motherboard after a few 100 runs of similar sized problem on a circa 2005 laptop back then :-) ) c) for each zipcode separately do "your favorite regression", (dailysales dependent variable, date independent variable). See the MADlib project http://MADlib.net if you want to do this in-place (MADlib does in-database analytics by embedding C++ math, array and stats libs in Postgres) d) one plot per zip code, 365 data points (if you have daily data) - look for increasing, decreasing or inconclusive. or just get the correlation coefficients and partition into three buckets +, - and "dontknow". This now allows you to separate out, via Pareto thinking, the top 20 (or 10 or ..) zip codes with the most increase in sales by % and by $amt. Similar for most decrease ... You can now separately strategize how to drill down for the increasing, inconclusive and decreasing buckets of zipcodes, in a divide and conquer fashion. MADlib also allows you to run in-database R routines via PL/R but for Linear/Logistic Regression and SVM the embedded C++ is some 100 times faster. C4.5 is also available. If your data size gets too big for Postgres (dont think so, but just in case) then there's the Greenplum MPP database. For 75 million rows you should be able to do this on a X-Large EC2 instance or similar with Postgres. If you don't want to do this in a dbms there are ways to write some Python code and iterate over the disk file or database table pulling a few thousand or hundred thousand rows at a time into memory. If you do put it into Postgres there's ways to get small random samples of the rows. Hope this makes some sense or at least is not complete nonsense in your context :-)
Combining results from (GBM or any other) model based on samples from a very large database In the spirit of using summaries to avoid using all that data. May be going in quite a different from your original request. Just a very naive way to get started - this could probably be done on a ver
40,831
Understanding the calculation of the independent samples Cohen's d from t & df
The SD used in the t calculation is that of the effect, not of the individual groups. In the paired case the SD to use in Cohen's d and t are the same. But the SD used in the d calculation for independent samples is the pooled SD of the individual groups, not the theoretical SD of the effect. Under the assumptions of 0 correlation and equal variance (the independent case) the variance of the effect is double the variance of the individual conditions. Try the following R code to demonstrate the effect x <- rnorm(1000, 0, 10) var(x) y <- rnorm(1000, 5, 10) var(y) cor(x,y) var(x-y) Run the example a few times. The first two lines get random independent samples of 1000 with variances of 100 (sd = 10). What you'll see is that with the correlation between x and y close to 0 the variance of x-y (the effect) tends toward 200. This is also true for x+y. With the large samples in the code above spurious correlations are rare but in real experiments with large sampled they happen all the time (reduce the n in the sample above and they'll happen there). Therefore, what we do is stick to the theory and average the variance across the groups (pooled variance) and then double it. One could alternatively just sum var(x) + var(y). This turns out to be mathematically the same but hides the assumption of equal variance. For comparison, try some correlated data made from effect calculations. m <- rnorm(1000, 2.5, 10) x <- m - rnorm(1000, 2.5, 10) y <- m + rnorm(1000, 2.5, 10) var(x) var(y) cor(x,y) var(x-y) I didn't bother equating the variances to the above (an sd = sqrt(50) in all samples above would do it). What you'll see this time is that the variance of x and y are each 200. This should result in a final variance of x-y of 400, if all was true as before. However, because x and y are correlated (about 0.5) you'll get a much lower variance. This is the mathematical property that a paired t-test takes advantage of. That's part of it, but why does cohen's d use different calculations? With the paired measures design, the correlation between conditions is part of the calculation of the effect. You typically only collect enough of an N to really measure the effect and you're not really about measuring the true values in each condition, just the effect. Future experiments will tend to be of a similar design and the effect size from repeated measures provides a more accurate prognosticator of the likelihood of replication. A similar argument holds for the independent design. Some have argued that you should use a pooled variance of the individual conditions all of the time. There's debate about that with some people coming down firmly that the d formula should always be the same and use the independent groups version. This insures a common reference point for when you do and don't use repeated measures designs. I think the argument has some merit if an independent design is possible, and probable. But I see this argument made in things like differences between people's ears. That can never be an independent groups design, will have very highly correlated measurements, and therefore should always have an effect size calculated through the paired or correlated effect measurement.
Understanding the calculation of the independent samples Cohen's d from t & df
The SD used in the t calculation is that of the effect, not of the individual groups. In the paired case the SD to use in Cohen's d and t are the same. But the SD used in the d calculation for indepe
Understanding the calculation of the independent samples Cohen's d from t & df The SD used in the t calculation is that of the effect, not of the individual groups. In the paired case the SD to use in Cohen's d and t are the same. But the SD used in the d calculation for independent samples is the pooled SD of the individual groups, not the theoretical SD of the effect. Under the assumptions of 0 correlation and equal variance (the independent case) the variance of the effect is double the variance of the individual conditions. Try the following R code to demonstrate the effect x <- rnorm(1000, 0, 10) var(x) y <- rnorm(1000, 5, 10) var(y) cor(x,y) var(x-y) Run the example a few times. The first two lines get random independent samples of 1000 with variances of 100 (sd = 10). What you'll see is that with the correlation between x and y close to 0 the variance of x-y (the effect) tends toward 200. This is also true for x+y. With the large samples in the code above spurious correlations are rare but in real experiments with large sampled they happen all the time (reduce the n in the sample above and they'll happen there). Therefore, what we do is stick to the theory and average the variance across the groups (pooled variance) and then double it. One could alternatively just sum var(x) + var(y). This turns out to be mathematically the same but hides the assumption of equal variance. For comparison, try some correlated data made from effect calculations. m <- rnorm(1000, 2.5, 10) x <- m - rnorm(1000, 2.5, 10) y <- m + rnorm(1000, 2.5, 10) var(x) var(y) cor(x,y) var(x-y) I didn't bother equating the variances to the above (an sd = sqrt(50) in all samples above would do it). What you'll see this time is that the variance of x and y are each 200. This should result in a final variance of x-y of 400, if all was true as before. However, because x and y are correlated (about 0.5) you'll get a much lower variance. This is the mathematical property that a paired t-test takes advantage of. That's part of it, but why does cohen's d use different calculations? With the paired measures design, the correlation between conditions is part of the calculation of the effect. You typically only collect enough of an N to really measure the effect and you're not really about measuring the true values in each condition, just the effect. Future experiments will tend to be of a similar design and the effect size from repeated measures provides a more accurate prognosticator of the likelihood of replication. A similar argument holds for the independent design. Some have argued that you should use a pooled variance of the individual conditions all of the time. There's debate about that with some people coming down firmly that the d formula should always be the same and use the independent groups version. This insures a common reference point for when you do and don't use repeated measures designs. I think the argument has some merit if an independent design is possible, and probable. But I see this argument made in things like differences between people's ears. That can never be an independent groups design, will have very highly correlated measurements, and therefore should always have an effect size calculated through the paired or correlated effect measurement.
Understanding the calculation of the independent samples Cohen's d from t & df The SD used in the t calculation is that of the effect, not of the individual groups. In the paired case the SD to use in Cohen's d and t are the same. But the SD used in the d calculation for indepe
40,832
Goodness of fit test for a mixture in R
You can write a function that calculates the relevant value for a given test under the null hypothesis based on the outputs from, say, normalmixEM, then do the test using that. For example, for the Kolmogorov-Smirnov test, we need the CDF given a set of parameters: # CDF of mixture of two normals pmnorm <- function(x, mu, sigma, pmix) { pmix[1]*pnorm(x,mu[1],sigma[1]) + (1-pmix[1])*pnorm(x,mu[2],sigma[2]) } We then run the K-S test in the usual way: # Sample run x <- c(rnorm(50), rnorm(50,2)) foo <- normalmixEM(x) test <- ks.test(x, pmnorm, mu=foo$mu, sigma=foo$sigma, pmix=foo$lambda) test One-sample Kolmogorov-Smirnov test data: x D = 0.0559, p-value = 0.914 alternative hypothesis: two-sided Always keeping in mind the fact that we estimated the parameters from the same data we are using to do the test, thus biasing the test towards failure to reject H0. We can overcome that latter bias to some extent via a parametric bootstrap - generating many samples from a mixture of normals parameterized by the estimates from normalmixEM, then estimating the parameters of the samples and calculating the test statistics for each sample using the estimated parameters. Under this construction, the null hypothesis is always true. In the code below, I'm helping the EM algorithm out by starting at the true parameters for the sample, which is also cheating a little, as it makes the EM algorithm more likely to find values near the true values than with the original sample, but greatly reduces the number of error messages. # Bootstrap estimation of ks statistic distribution N <- length(x) ks.boot <- rep(0,1000) for (i in 1:1000) { z <- rbinom(N, 1, foo$lambda[1]) x.b <- z*rnorm(N, foo$mu[1], foo$sigma[1]) + (1-z)*rnorm(N, foo$mu[2], foo$sigma[2]) foo.b <- normalmixEM(x.b, maxit=10000, lambda=foo$lambda, mu=foo$mu, sigma=foo$sigma) ks.boot[i] <- ks.test(x.b, pmnorm, mu=foo.b$mu, sigma=foo.b$sigma, pmix=foo.b$lambda)$statistic } mean(test$statistic <= ks.boot) [1] 0.323 So instead of a p-value of 0.914, we get a p-value of 0.323. Interesting, but not particularly important in this case.
Goodness of fit test for a mixture in R
You can write a function that calculates the relevant value for a given test under the null hypothesis based on the outputs from, say, normalmixEM, then do the test using that. For example, for the K
Goodness of fit test for a mixture in R You can write a function that calculates the relevant value for a given test under the null hypothesis based on the outputs from, say, normalmixEM, then do the test using that. For example, for the Kolmogorov-Smirnov test, we need the CDF given a set of parameters: # CDF of mixture of two normals pmnorm <- function(x, mu, sigma, pmix) { pmix[1]*pnorm(x,mu[1],sigma[1]) + (1-pmix[1])*pnorm(x,mu[2],sigma[2]) } We then run the K-S test in the usual way: # Sample run x <- c(rnorm(50), rnorm(50,2)) foo <- normalmixEM(x) test <- ks.test(x, pmnorm, mu=foo$mu, sigma=foo$sigma, pmix=foo$lambda) test One-sample Kolmogorov-Smirnov test data: x D = 0.0559, p-value = 0.914 alternative hypothesis: two-sided Always keeping in mind the fact that we estimated the parameters from the same data we are using to do the test, thus biasing the test towards failure to reject H0. We can overcome that latter bias to some extent via a parametric bootstrap - generating many samples from a mixture of normals parameterized by the estimates from normalmixEM, then estimating the parameters of the samples and calculating the test statistics for each sample using the estimated parameters. Under this construction, the null hypothesis is always true. In the code below, I'm helping the EM algorithm out by starting at the true parameters for the sample, which is also cheating a little, as it makes the EM algorithm more likely to find values near the true values than with the original sample, but greatly reduces the number of error messages. # Bootstrap estimation of ks statistic distribution N <- length(x) ks.boot <- rep(0,1000) for (i in 1:1000) { z <- rbinom(N, 1, foo$lambda[1]) x.b <- z*rnorm(N, foo$mu[1], foo$sigma[1]) + (1-z)*rnorm(N, foo$mu[2], foo$sigma[2]) foo.b <- normalmixEM(x.b, maxit=10000, lambda=foo$lambda, mu=foo$mu, sigma=foo$sigma) ks.boot[i] <- ks.test(x.b, pmnorm, mu=foo.b$mu, sigma=foo.b$sigma, pmix=foo.b$lambda)$statistic } mean(test$statistic <= ks.boot) [1] 0.323 So instead of a p-value of 0.914, we get a p-value of 0.323. Interesting, but not particularly important in this case.
Goodness of fit test for a mixture in R You can write a function that calculates the relevant value for a given test under the null hypothesis based on the outputs from, say, normalmixEM, then do the test using that. For example, for the K
40,833
How to determine if there is a drop in revenue after a change in the system?
You could do a simple t test of the means of the two periods. Be sure that there is not some kind of upward or downward trend in the data over the two years, because this can lead to the wrong conclusions of the t test value. you may need to use Welch's t test(R uses this as standard) which is a modification of the standard Student's t test to take into account different variance and sample sizes. It should be a one sided alternative hypothesis since you are testing of whether with period_after_change is less than period_before_change. This is the simplest test of whether the change has had a negative or no effect. You can calculate the t test score in excel using Welch's t test (googles first hit) if the test is significant then you have done something wrong and the drop can be explained by the relaunch(if we only look at that as an explanatory variable). if it is not significant then you have done nothing wrong. this is the statistically method, another side of this is to explain it to the client... I won't dive in to this here ... ;)
How to determine if there is a drop in revenue after a change in the system?
You could do a simple t test of the means of the two periods. Be sure that there is not some kind of upward or downward trend in the data over the two years, because this can lead to the wrong conclus
How to determine if there is a drop in revenue after a change in the system? You could do a simple t test of the means of the two periods. Be sure that there is not some kind of upward or downward trend in the data over the two years, because this can lead to the wrong conclusions of the t test value. you may need to use Welch's t test(R uses this as standard) which is a modification of the standard Student's t test to take into account different variance and sample sizes. It should be a one sided alternative hypothesis since you are testing of whether with period_after_change is less than period_before_change. This is the simplest test of whether the change has had a negative or no effect. You can calculate the t test score in excel using Welch's t test (googles first hit) if the test is significant then you have done something wrong and the drop can be explained by the relaunch(if we only look at that as an explanatory variable). if it is not significant then you have done nothing wrong. this is the statistically method, another side of this is to explain it to the client... I won't dive in to this here ... ;)
How to determine if there is a drop in revenue after a change in the system? You could do a simple t test of the means of the two periods. Be sure that there is not some kind of upward or downward trend in the data over the two years, because this can lead to the wrong conclus
40,834
How to determine if there is a drop in revenue after a change in the system?
Nothing will be able to prove it one way or another, because even if you find revenue has dropped from that time, you will not be able to dismiss the possibility of other structural change (eg new competitor, changed regulatory environment, changed fashion, something you can't even think of...). You can use time series techniques to identify if the timing of the changed system is associated with a decline in revenue; or, better for your aims, you might be able to dismiss that claim (and if there's no obvious decline, there's nothing to explain, right? well, maybe... the problem is constructing a counterfactual.). Problems you will have to deal with will include; seasonality (both micro eg weekly and macro eg summer v winter); growth or other trends; and serial correlation of your observations. In the plot below from simulated data you can see one way of going about this. You can fit a model of some sort based on there being no change over time - in this case, I've fit a linear model with the response variable on a logarithmic scale, which is equivalent to saying the daily revenue is growing at a constant rate. This null hypothesis is shown with the black line. The red and blue lines, on the other hand, show an alternative, more complex model, which allows both a change in the level of revenue and a change in the growth rate (in this case to negative) as a result of the introduction of the new system. Once you've fit this more complex model as well, you can then test for statistically significant evidence that this model is needed rather than the simple black line model. (Note that in this case, if you did a simple t test comparing before and after situations as @pgericson suggests, you'd conclude you'd significantly increased revenue with the new system, because of the underlying growth rate in the months leading up to the new system.) Now, the danger to look out for, is you can't just fit a model in the way you would with cross sectional data. You need to allow for the fact that a revenue observation one day does not add that much to the revenue observation the day before - they are probably highly correlated and not completely new information. Any stats or econometric package worth its salt will allow this; in R you can use either gls() in the nlme library or arima() to do it. My R code that simulated this data and did some basic analysis on it is pasted below. #simulate data set.seed(80) x <- ts(100*exp(1:1000*0.001), frequency=7) e <- rnorm(1002,0,10) x <- x+ 0.5*e[1:1000] + 0.8*e[2:1001] + e[3:1002] changed <- rep(c(0,1), c(800,200)) x <- x + cumsum(changed)^0.4 * rnorm(1000, -8,1) # check it looks ok par(mfrow=c(2,1)) plot(x, main="Daily revenue ($'000)", xlab="weeks", ylab="(original)") abline(v=801/7, col="grey50") plot(x, ylab="(logarithmic)", xlab="weeks", log="y") abline(v=801/7, col="grey50") # t test makes it look like you've increased revenue! - # because it ignores the trend t.test(x~changed) # Much better is to illustrate in some kind of model # that can take into account any growth trend. # With real data this will be quite complex, but # in my simulated data the growth is nice and regular # so it is easy to see if it is disrupted. x.df <- data.frame(x=x, changed=changed, day=1:1000) win.graph() x.lm1 <- lm(log(x)~day, data=x.df) plot(x, ylab="(logarithmic)", xlab="weeks", log="y", bty="l") abline(v=801/7, col="grey50") lines(1:1000/7, exp(predict(x.lm1)), lwd=3) x.lm2 <- lm(log(x)~day*changed, data=x.df) lines(1:800/7, exp(predict(x.lm2))[1:800], col="red", lwd=3) lines(801:1000/7, exp(predict(x.lm2))[801:1000], col="blue", lwd=3) anova(x.lm2) # shows "changed" is significant summary(x.lm2) # could be used to estimate how much change has happened # The problem with this approach though is that # the errors are serially correlated and hence the inferences # based on them being iid will not be justifiable. As shown by this diagnostic # plot: acf(residuals(x.lm2)) library(nlme) x.lm3 <- gls(log(x)~day*changed, data=x.df, correlation=corAR1()) anova(x.lm3) # "changed" is still significant but much higher p values summary(x.lm3) # I'd like to fit a model with more lags in the autoregression structure # but the following code takes frigging ages for some reason (eventually came out OK) x.lm4 <- update(x.lm3, correlation=corARMA(c(0.6, 0.2), p=2, q=0), control=glsControl(msVerbose=TRUE))
How to determine if there is a drop in revenue after a change in the system?
Nothing will be able to prove it one way or another, because even if you find revenue has dropped from that time, you will not be able to dismiss the possibility of other structural change (eg new com
How to determine if there is a drop in revenue after a change in the system? Nothing will be able to prove it one way or another, because even if you find revenue has dropped from that time, you will not be able to dismiss the possibility of other structural change (eg new competitor, changed regulatory environment, changed fashion, something you can't even think of...). You can use time series techniques to identify if the timing of the changed system is associated with a decline in revenue; or, better for your aims, you might be able to dismiss that claim (and if there's no obvious decline, there's nothing to explain, right? well, maybe... the problem is constructing a counterfactual.). Problems you will have to deal with will include; seasonality (both micro eg weekly and macro eg summer v winter); growth or other trends; and serial correlation of your observations. In the plot below from simulated data you can see one way of going about this. You can fit a model of some sort based on there being no change over time - in this case, I've fit a linear model with the response variable on a logarithmic scale, which is equivalent to saying the daily revenue is growing at a constant rate. This null hypothesis is shown with the black line. The red and blue lines, on the other hand, show an alternative, more complex model, which allows both a change in the level of revenue and a change in the growth rate (in this case to negative) as a result of the introduction of the new system. Once you've fit this more complex model as well, you can then test for statistically significant evidence that this model is needed rather than the simple black line model. (Note that in this case, if you did a simple t test comparing before and after situations as @pgericson suggests, you'd conclude you'd significantly increased revenue with the new system, because of the underlying growth rate in the months leading up to the new system.) Now, the danger to look out for, is you can't just fit a model in the way you would with cross sectional data. You need to allow for the fact that a revenue observation one day does not add that much to the revenue observation the day before - they are probably highly correlated and not completely new information. Any stats or econometric package worth its salt will allow this; in R you can use either gls() in the nlme library or arima() to do it. My R code that simulated this data and did some basic analysis on it is pasted below. #simulate data set.seed(80) x <- ts(100*exp(1:1000*0.001), frequency=7) e <- rnorm(1002,0,10) x <- x+ 0.5*e[1:1000] + 0.8*e[2:1001] + e[3:1002] changed <- rep(c(0,1), c(800,200)) x <- x + cumsum(changed)^0.4 * rnorm(1000, -8,1) # check it looks ok par(mfrow=c(2,1)) plot(x, main="Daily revenue ($'000)", xlab="weeks", ylab="(original)") abline(v=801/7, col="grey50") plot(x, ylab="(logarithmic)", xlab="weeks", log="y") abline(v=801/7, col="grey50") # t test makes it look like you've increased revenue! - # because it ignores the trend t.test(x~changed) # Much better is to illustrate in some kind of model # that can take into account any growth trend. # With real data this will be quite complex, but # in my simulated data the growth is nice and regular # so it is easy to see if it is disrupted. x.df <- data.frame(x=x, changed=changed, day=1:1000) win.graph() x.lm1 <- lm(log(x)~day, data=x.df) plot(x, ylab="(logarithmic)", xlab="weeks", log="y", bty="l") abline(v=801/7, col="grey50") lines(1:1000/7, exp(predict(x.lm1)), lwd=3) x.lm2 <- lm(log(x)~day*changed, data=x.df) lines(1:800/7, exp(predict(x.lm2))[1:800], col="red", lwd=3) lines(801:1000/7, exp(predict(x.lm2))[801:1000], col="blue", lwd=3) anova(x.lm2) # shows "changed" is significant summary(x.lm2) # could be used to estimate how much change has happened # The problem with this approach though is that # the errors are serially correlated and hence the inferences # based on them being iid will not be justifiable. As shown by this diagnostic # plot: acf(residuals(x.lm2)) library(nlme) x.lm3 <- gls(log(x)~day*changed, data=x.df, correlation=corAR1()) anova(x.lm3) # "changed" is still significant but much higher p values summary(x.lm3) # I'd like to fit a model with more lags in the autoregression structure # but the following code takes frigging ages for some reason (eventually came out OK) x.lm4 <- update(x.lm3, correlation=corARMA(c(0.6, 0.2), p=2, q=0), control=glsControl(msVerbose=TRUE))
How to determine if there is a drop in revenue after a change in the system? Nothing will be able to prove it one way or another, because even if you find revenue has dropped from that time, you will not be able to dismiss the possibility of other structural change (eg new com
40,835
How to determine if there is a drop in revenue after a change in the system?
You might consider using either CausalImpact in R to estimate the difference, but CausalImpact wants a secondary dataset (control) to compare the "treated" data - in this case website data in question. CausalImpact requires a secondary dataset to model against the exploratory data, something like an separate but very similar market. You could also provide a regression model as your comparative dataset. A better explanation is here: https://google.github.io/CausalImpact/ You might also consider using ITS, Interrupted Time Series analysis. This would entail building a strong time series model that includes variables x1) change has/has not occurred and x2) day 1,2,3... of the new website changes. My recommendation would be to use ITS if you do not have a parallel dataset or model to plug into CausalImpact. Using ITS would require the following: Build a strong time-series model of the "pre-period", hopefully something that accounts for any and all seasonality and cyclical trends leading into the treatment or post-period. You will want a model that you feel would have accurately predicted the "counter-factual," or what would have happened had no changes to the website been made. This is model 1. Add the two variables I mentioned above to your model to signify the start and trend of the "test". Re-run your model to include the test days and new test variables, and see if your test shows it is statistically significant or not (very low p-values). This is model 2. Plot the resulting prediction points for these two models into Excel - all the way through the test. The difference between the two models during the test days is your result, as long as the two new "test variable" coefficients from the previous step are statistically significant. They will also begin to show your the magnitude of the change if there is one. Of course, you have to know for certain that there wasn't some other event that happened at the exact same time as the new event - correlation is not causation, yada yada.
How to determine if there is a drop in revenue after a change in the system?
You might consider using either CausalImpact in R to estimate the difference, but CausalImpact wants a secondary dataset (control) to compare the "treated" data - in this case website data in question
How to determine if there is a drop in revenue after a change in the system? You might consider using either CausalImpact in R to estimate the difference, but CausalImpact wants a secondary dataset (control) to compare the "treated" data - in this case website data in question. CausalImpact requires a secondary dataset to model against the exploratory data, something like an separate but very similar market. You could also provide a regression model as your comparative dataset. A better explanation is here: https://google.github.io/CausalImpact/ You might also consider using ITS, Interrupted Time Series analysis. This would entail building a strong time series model that includes variables x1) change has/has not occurred and x2) day 1,2,3... of the new website changes. My recommendation would be to use ITS if you do not have a parallel dataset or model to plug into CausalImpact. Using ITS would require the following: Build a strong time-series model of the "pre-period", hopefully something that accounts for any and all seasonality and cyclical trends leading into the treatment or post-period. You will want a model that you feel would have accurately predicted the "counter-factual," or what would have happened had no changes to the website been made. This is model 1. Add the two variables I mentioned above to your model to signify the start and trend of the "test". Re-run your model to include the test days and new test variables, and see if your test shows it is statistically significant or not (very low p-values). This is model 2. Plot the resulting prediction points for these two models into Excel - all the way through the test. The difference between the two models during the test days is your result, as long as the two new "test variable" coefficients from the previous step are statistically significant. They will also begin to show your the magnitude of the change if there is one. Of course, you have to know for certain that there wasn't some other event that happened at the exact same time as the new event - correlation is not causation, yada yada.
How to determine if there is a drop in revenue after a change in the system? You might consider using either CausalImpact in R to estimate the difference, but CausalImpact wants a secondary dataset (control) to compare the "treated" data - in this case website data in question
40,836
Variability in k-means clusters results: setting set.seed() before?
You say that set.seed doesn't work for you, but your example doesn't use set.seed so it's hard to know if you use it correctly! This is an example close to yours that seem to work: scores <- matrix(runif(1000), 100, 10) set.seed(42) k1 = kmeans(scores, 5, iter.max=500) set.seed(42) k2 = kmeans(scores, 5, iter.max=500) identical(k1, k2) # TRUE ...note that you need to call set.seed with the same seed before calling kmeans, and you have to give the same parameters to kmeans if you want to expect the same answer. When you specify an integer for the centers parameter, kmeans uses random numbers to come up with the centers. If you instead specify the centers your self, it should be reproducible. Here I choose the 5 first rows as centers (probably a bad idea though): k1 = kmeans(scores, scores[1:5,], iter.max=500) k2 = kmeans(scores, scores[1:5,], iter.max=500) identical(k1, k2) # TRUE
Variability in k-means clusters results: setting set.seed() before?
You say that set.seed doesn't work for you, but your example doesn't use set.seed so it's hard to know if you use it correctly! This is an example close to yours that seem to work: scores <- matrix(ru
Variability in k-means clusters results: setting set.seed() before? You say that set.seed doesn't work for you, but your example doesn't use set.seed so it's hard to know if you use it correctly! This is an example close to yours that seem to work: scores <- matrix(runif(1000), 100, 10) set.seed(42) k1 = kmeans(scores, 5, iter.max=500) set.seed(42) k2 = kmeans(scores, 5, iter.max=500) identical(k1, k2) # TRUE ...note that you need to call set.seed with the same seed before calling kmeans, and you have to give the same parameters to kmeans if you want to expect the same answer. When you specify an integer for the centers parameter, kmeans uses random numbers to come up with the centers. If you instead specify the centers your self, it should be reproducible. Here I choose the 5 first rows as centers (probably a bad idea though): k1 = kmeans(scores, scores[1:5,], iter.max=500) k2 = kmeans(scores, scores[1:5,], iter.max=500) identical(k1, k2) # TRUE
Variability in k-means clusters results: setting set.seed() before? You say that set.seed doesn't work for you, but your example doesn't use set.seed so it's hard to know if you use it correctly! This is an example close to yours that seem to work: scores <- matrix(ru
40,837
Variability in k-means clusters results: setting set.seed() before?
Adding to Tommy's answer, To identify the optimal K value for your k-means cluster , the best method is to try Elbow curve, by plotting your withinss against your K value gives you the elbow curve and select the value at elbow as the optimal K value. https://stackoverflow.com/questions/6645895/calculating-the-percentage-of-variance-measure-for-k-means https://www.r-bloggers.com/finding-optimal-number-of-clusters/
Variability in k-means clusters results: setting set.seed() before?
Adding to Tommy's answer, To identify the optimal K value for your k-means cluster , the best method is to try Elbow curve, by plotting your withinss against your K value gives you the elbow curve an
Variability in k-means clusters results: setting set.seed() before? Adding to Tommy's answer, To identify the optimal K value for your k-means cluster , the best method is to try Elbow curve, by plotting your withinss against your K value gives you the elbow curve and select the value at elbow as the optimal K value. https://stackoverflow.com/questions/6645895/calculating-the-percentage-of-variance-measure-for-k-means https://www.r-bloggers.com/finding-optimal-number-of-clusters/
Variability in k-means clusters results: setting set.seed() before? Adding to Tommy's answer, To identify the optimal K value for your k-means cluster , the best method is to try Elbow curve, by plotting your withinss against your K value gives you the elbow curve an
40,838
Comparing two binary variables of unequal sizes
Chi Square doesn't require equal size groups. In R you can use either prop.test() or chisq.test(). I do this often with A/B direct mail tests with unequal size groups. For example, 100K donors are split 90% and 10%: the 90% are sent an email appeal, and 10% are sent nothing. The binary outcome is whether they donated to the appeal. The nice thing about prop.test vs chisq.test is that prop.test will both calculate the p-value of the hypothesis that the groups are equal and calculate the confidence interval for the difference This page gives an example of prop.test() with two groups: http://cran.r-project.org/doc/contrib/Lemon-kickstart/kr_prop.html sexsmoke<-matrix(c(70,120,65,140),ncol=2,byrow=T) rownames(sexsmoke)<-c("male","female") colnames(sexsmoke)<-c("smoke","nosmoke") prop.test(sexsmoke)
Comparing two binary variables of unequal sizes
Chi Square doesn't require equal size groups. In R you can use either prop.test() or chisq.test(). I do this often with A/B direct mail tests with unequal size groups. For example, 100K donors a
Comparing two binary variables of unequal sizes Chi Square doesn't require equal size groups. In R you can use either prop.test() or chisq.test(). I do this often with A/B direct mail tests with unequal size groups. For example, 100K donors are split 90% and 10%: the 90% are sent an email appeal, and 10% are sent nothing. The binary outcome is whether they donated to the appeal. The nice thing about prop.test vs chisq.test is that prop.test will both calculate the p-value of the hypothesis that the groups are equal and calculate the confidence interval for the difference This page gives an example of prop.test() with two groups: http://cran.r-project.org/doc/contrib/Lemon-kickstart/kr_prop.html sexsmoke<-matrix(c(70,120,65,140),ncol=2,byrow=T) rownames(sexsmoke)<-c("male","female") colnames(sexsmoke)<-c("smoke","nosmoke") prop.test(sexsmoke)
Comparing two binary variables of unequal sizes Chi Square doesn't require equal size groups. In R you can use either prop.test() or chisq.test(). I do this often with A/B direct mail tests with unequal size groups. For example, 100K donors a
40,839
Comparing two binary variables of unequal sizes
You can do a two sample t-test, perhaps after transforming the proportions using e.g. the arcsine transformation.
Comparing two binary variables of unequal sizes
You can do a two sample t-test, perhaps after transforming the proportions using e.g. the arcsine transformation.
Comparing two binary variables of unequal sizes You can do a two sample t-test, perhaps after transforming the proportions using e.g. the arcsine transformation.
Comparing two binary variables of unequal sizes You can do a two sample t-test, perhaps after transforming the proportions using e.g. the arcsine transformation.
40,840
Comparing two binary variables of unequal sizes
You can actually use logistic regression / glm with the outcome as dependent variable and group belonging as explanatory factor variable.
Comparing two binary variables of unequal sizes
You can actually use logistic regression / glm with the outcome as dependent variable and group belonging as explanatory factor variable.
Comparing two binary variables of unequal sizes You can actually use logistic regression / glm with the outcome as dependent variable and group belonging as explanatory factor variable.
Comparing two binary variables of unequal sizes You can actually use logistic regression / glm with the outcome as dependent variable and group belonging as explanatory factor variable.
40,841
Comparing two binary variables of unequal sizes
Weighting by sample size is built into how the expected vaues are computed. The only thing to worry about are the rules about how small an expected value can be.
Comparing two binary variables of unequal sizes
Weighting by sample size is built into how the expected vaues are computed. The only thing to worry about are the rules about how small an expected value can be.
Comparing two binary variables of unequal sizes Weighting by sample size is built into how the expected vaues are computed. The only thing to worry about are the rules about how small an expected value can be.
Comparing two binary variables of unequal sizes Weighting by sample size is built into how the expected vaues are computed. The only thing to worry about are the rules about how small an expected value can be.
40,842
ANCOVA or repeated measures ANOVA?
Actually, the post minus pre approach is one that you should always try to avoid. The issue is not about statistics. It is about measurement. When you calculate difference scores, the reliability of the measures become very low. You don't want that. I prefer ANCOVA if the assumptions are met (and it will in most cases), because the interpretation is easier. The readers of your study will have to look at only the post averages, 3 averages in your case, instead of all 6. If you get an interaction effect, which is expected that you do, you'd have to do a post hoc comparison of that effect. This will give you even more p-values that make reading your paper even harder. If you want others to cite your study, make it easier to read.
ANCOVA or repeated measures ANOVA?
Actually, the post minus pre approach is one that you should always try to avoid. The issue is not about statistics. It is about measurement. When you calculate difference scores, the reliability of t
ANCOVA or repeated measures ANOVA? Actually, the post minus pre approach is one that you should always try to avoid. The issue is not about statistics. It is about measurement. When you calculate difference scores, the reliability of the measures become very low. You don't want that. I prefer ANCOVA if the assumptions are met (and it will in most cases), because the interpretation is easier. The readers of your study will have to look at only the post averages, 3 averages in your case, instead of all 6. If you get an interaction effect, which is expected that you do, you'd have to do a post hoc comparison of that effect. This will give you even more p-values that make reading your paper even harder. If you want others to cite your study, make it easier to read.
ANCOVA or repeated measures ANOVA? Actually, the post minus pre approach is one that you should always try to avoid. The issue is not about statistics. It is about measurement. When you calculate difference scores, the reliability of t
40,843
ANCOVA or repeated measures ANOVA?
I suspect the best approach would be to get difference scores (i.e., post - pre) for each experimental unit, and then run a simple one-way ANOVA.
ANCOVA or repeated measures ANOVA?
I suspect the best approach would be to get difference scores (i.e., post - pre) for each experimental unit, and then run a simple one-way ANOVA.
ANCOVA or repeated measures ANOVA? I suspect the best approach would be to get difference scores (i.e., post - pre) for each experimental unit, and then run a simple one-way ANOVA.
ANCOVA or repeated measures ANOVA? I suspect the best approach would be to get difference scores (i.e., post - pre) for each experimental unit, and then run a simple one-way ANOVA.
40,844
ANCOVA or repeated measures ANOVA?
I would generally say that you need a repeated measures model with group, pre_post, and an interaction term. What you want to know is whether the post-test score is dependent upon the intervention, so you need to see an interaction. The meaning of that interaction would depend on actual scores. A simpler method might be to use a pre_post subtraction score. That would make the assumption that pre-test differences (significant or otherwise), do not affect the outcome at all, or are not present at all. Check your groups, and if they are very highly similar then the subtraction score and one-way ANOVA is an easy thing to do. The ANCOVA is much more like the difference scores or also an ANOVA on the residuals left after removing pre-test. It's not wrong, and some people prefer it. I believe I read a paper once recommending it but even they qualified it because pre-test may be correlated with group. In that case interpretation becomes difficult. Why not run the full ANOVA and the ANCOVA? If they reach similar conclusions you're safe. If they reach different conclusions then think much more about what your data mean and maybe come back on here and ask for help at the interpretation stage.
ANCOVA or repeated measures ANOVA?
I would generally say that you need a repeated measures model with group, pre_post, and an interaction term. What you want to know is whether the post-test score is dependent upon the intervention, s
ANCOVA or repeated measures ANOVA? I would generally say that you need a repeated measures model with group, pre_post, and an interaction term. What you want to know is whether the post-test score is dependent upon the intervention, so you need to see an interaction. The meaning of that interaction would depend on actual scores. A simpler method might be to use a pre_post subtraction score. That would make the assumption that pre-test differences (significant or otherwise), do not affect the outcome at all, or are not present at all. Check your groups, and if they are very highly similar then the subtraction score and one-way ANOVA is an easy thing to do. The ANCOVA is much more like the difference scores or also an ANOVA on the residuals left after removing pre-test. It's not wrong, and some people prefer it. I believe I read a paper once recommending it but even they qualified it because pre-test may be correlated with group. In that case interpretation becomes difficult. Why not run the full ANOVA and the ANCOVA? If they reach similar conclusions you're safe. If they reach different conclusions then think much more about what your data mean and maybe come back on here and ask for help at the interpretation stage.
ANCOVA or repeated measures ANOVA? I would generally say that you need a repeated measures model with group, pre_post, and an interaction term. What you want to know is whether the post-test score is dependent upon the intervention, s
40,845
ANCOVA or repeated measures ANOVA?
ANCOVA gives the same results asymptotically as the contrained repeated measures model (no treatment main effect term). The usual repeated measures model including time, treatment, time*treatment terms assumes the baseline scores are not balanced so its estimator is less efficient. Article: https://www.researchgate.net/publication/326881265_Analyzing_pre-post_randomized_studies_with_one_post-randomization_score_using_repeated_measures_and_ANCOVA_models
ANCOVA or repeated measures ANOVA?
ANCOVA gives the same results asymptotically as the contrained repeated measures model (no treatment main effect term). The usual repeated measures model including time, treatment, time*treatment term
ANCOVA or repeated measures ANOVA? ANCOVA gives the same results asymptotically as the contrained repeated measures model (no treatment main effect term). The usual repeated measures model including time, treatment, time*treatment terms assumes the baseline scores are not balanced so its estimator is less efficient. Article: https://www.researchgate.net/publication/326881265_Analyzing_pre-post_randomized_studies_with_one_post-randomization_score_using_repeated_measures_and_ANCOVA_models
ANCOVA or repeated measures ANOVA? ANCOVA gives the same results asymptotically as the contrained repeated measures model (no treatment main effect term). The usual repeated measures model including time, treatment, time*treatment term
40,846
Convergence in probability and $L_2$ for normal random variables
Unfortunately, the quoted statement in the question is a muddled version of the one I originally intended. Thank you for catching this. I've also updated the statement in the original question. A counterexample to the former is given at the end of this answer. Here is the intended statement: Lemma: Let $X_1,X_2,\ldots$ be a sequence of zero-mean normal random variables defined on the same space with variances $\sigma_n^2$. Then, $X_n \to X_\infty$ in probability if and only if $X_n \xrightarrow{\,L_2\,} X_\infty$, in which case $X_\infty \sim \mathcal N(0,\sigma^2)$ where $\sigma^2 = \lim_{n\to\infty} \sigma_n^2$. Remark: The main points here are that (a) we can "upgrade" convergence in probability to $L_2$ convergence in the case of sequences of normals, (b) we are guaranteed that the distribution of the limit is normal (which is not otherwise obvious) and (c) we get both of the above without specifying anything about the joint distributions of the elements in the sequence. Proof (sketch): One direction is easy: Convergence in $L_2$ always implies convergence in probability. To prove to the other direction: If $X_n \to X$ in probability, then $$\varphi_n(t) = \mathbb E e^{it X_n} \to \mathbb E e^{it X_{\infty}}$$ by dominated convergence. But, $\varphi_n(t) = e^{t^2 \sigma_n^2 / 2}$, and $e^{t^2 \sigma_n^2 / 2}$ converges for each $t$ as $n \to \infty$ if and only if $\sigma_n^2 \to \sigma^2$. This is enough to imply that $\sup_n \sigma_n^2 < \infty$, and hence the collection $\{X_n^2\}$ is uniformly integrable. Thus, $X_n \xrightarrow{\,L_2\,} X_\infty$. This further shows the limit $X_\infty$ must be normal since then $\mathbb E e^{it X_\infty} = e^{t^2 \sigma^2 / 2}$, which is the characteristic function of a normally distribution random variable. Notes The convergence of the sequence $\sigma_n^2$ and the fact that the limiting distribution $X_\infty$ is normally distributed are part of the conclusion. By the same exact argument, we can also replace $L_2$ convergence with the more general $L_p$ convergence by recognizing that the variance determines the distribution in this case and all moments are finite, so $\{X_n^p\}$ is also uniformly integrable. From this it is clear that we have the following weaker result on convergence in distribution, which is well-known and given as an exercise in some probability textbooks. Lemma: Let $X_1,X_2,\ldots$ be a sequence of normal random variables. Then, $X_n \to X_\infty$ in distribution if and only if $\mu_n \to \mu$ and $\sigma_n^2 \to \sigma^2$, in which case $X_\infty \sim \mathcal N(\mu,\sigma^2)$. A nice application of the second lemma is to consider the marginal distribution of the Riemann integral of Brownian motion, $$ I_t = \int_0^t B_s \, \mathrm{d} s \> . $$ By considering the Riemann sums and using the second lemma, we see that $I_t \sim \mathcal N(0, t^3/3)$. A counterexample to the quoted statement in the question can be found by considering $X_\infty \sim \mathcal N(0,1)$ and $X_n = (-1)^n X_\infty$. Here, $\sigma_n^2 = 1$ for all $n$ so $\sigma_n^2 \to 1$, but $X_n$ does not converge to $X_\infty$ in probability or $L_2$.
Convergence in probability and $L_2$ for normal random variables
Unfortunately, the quoted statement in the question is a muddled version of the one I originally intended. Thank you for catching this. I've also updated the statement in the original question. A coun
Convergence in probability and $L_2$ for normal random variables Unfortunately, the quoted statement in the question is a muddled version of the one I originally intended. Thank you for catching this. I've also updated the statement in the original question. A counterexample to the former is given at the end of this answer. Here is the intended statement: Lemma: Let $X_1,X_2,\ldots$ be a sequence of zero-mean normal random variables defined on the same space with variances $\sigma_n^2$. Then, $X_n \to X_\infty$ in probability if and only if $X_n \xrightarrow{\,L_2\,} X_\infty$, in which case $X_\infty \sim \mathcal N(0,\sigma^2)$ where $\sigma^2 = \lim_{n\to\infty} \sigma_n^2$. Remark: The main points here are that (a) we can "upgrade" convergence in probability to $L_2$ convergence in the case of sequences of normals, (b) we are guaranteed that the distribution of the limit is normal (which is not otherwise obvious) and (c) we get both of the above without specifying anything about the joint distributions of the elements in the sequence. Proof (sketch): One direction is easy: Convergence in $L_2$ always implies convergence in probability. To prove to the other direction: If $X_n \to X$ in probability, then $$\varphi_n(t) = \mathbb E e^{it X_n} \to \mathbb E e^{it X_{\infty}}$$ by dominated convergence. But, $\varphi_n(t) = e^{t^2 \sigma_n^2 / 2}$, and $e^{t^2 \sigma_n^2 / 2}$ converges for each $t$ as $n \to \infty$ if and only if $\sigma_n^2 \to \sigma^2$. This is enough to imply that $\sup_n \sigma_n^2 < \infty$, and hence the collection $\{X_n^2\}$ is uniformly integrable. Thus, $X_n \xrightarrow{\,L_2\,} X_\infty$. This further shows the limit $X_\infty$ must be normal since then $\mathbb E e^{it X_\infty} = e^{t^2 \sigma^2 / 2}$, which is the characteristic function of a normally distribution random variable. Notes The convergence of the sequence $\sigma_n^2$ and the fact that the limiting distribution $X_\infty$ is normally distributed are part of the conclusion. By the same exact argument, we can also replace $L_2$ convergence with the more general $L_p$ convergence by recognizing that the variance determines the distribution in this case and all moments are finite, so $\{X_n^p\}$ is also uniformly integrable. From this it is clear that we have the following weaker result on convergence in distribution, which is well-known and given as an exercise in some probability textbooks. Lemma: Let $X_1,X_2,\ldots$ be a sequence of normal random variables. Then, $X_n \to X_\infty$ in distribution if and only if $\mu_n \to \mu$ and $\sigma_n^2 \to \sigma^2$, in which case $X_\infty \sim \mathcal N(\mu,\sigma^2)$. A nice application of the second lemma is to consider the marginal distribution of the Riemann integral of Brownian motion, $$ I_t = \int_0^t B_s \, \mathrm{d} s \> . $$ By considering the Riemann sums and using the second lemma, we see that $I_t \sim \mathcal N(0, t^3/3)$. A counterexample to the quoted statement in the question can be found by considering $X_\infty \sim \mathcal N(0,1)$ and $X_n = (-1)^n X_\infty$. Here, $\sigma_n^2 = 1$ for all $n$ so $\sigma_n^2 \to 1$, but $X_n$ does not converge to $X_\infty$ in probability or $L_2$.
Convergence in probability and $L_2$ for normal random variables Unfortunately, the quoted statement in the question is a muddled version of the one I originally intended. Thank you for catching this. I've also updated the statement in the original question. A coun
40,847
Gower's (dis)similarity index
Gower dissimilarity is just 1 minus Gower similarity, $1-GS$. So, they are "the same", and limitations of one are the limitations of the other. Ward clustering computes cluster centroids and in order for those to be geometrically "real" it demands (squared) euclidean distances as its input. Euclidean distance is metric. Not every metric distance is euclidean. Thus, not every metric distance is correct for Ward. Still, in practice, metric distances that are not euclidean distance could be used with Ward method heuristically. Non-metric distances - they are not recommended with Ward at all. By origin, Gower dissimilarity is non-euclidean and non-metric (even when all variables to compute it had been interval, Gower index will be closer to Manhattan distance, not euclidean distance), so you cannot use Ward. However, geometrically, a concrete matrix of Gower dissimilarity could happen to be close to euclidean distance, and then you may be licensed using Ward (just with these specific data!). To check if a dissimilarity matrix is (or is close to be) euclidean or not geometrically, one should double-center it and inspect the eigenvalues of the resultant matrix. The smaller is the sum of negative eigenvalues relative to the sum of positive ones, the closer is the dissimilarities to euclidean distances. But even in this occured case using Ward with Gower distance is purely heuristic. Read about the properties of double centered scalar product matrix here. Gower dissimilarity defined as $\sqrt {1-GS}$ is actually a Euclidean distance (therefore metric, automatically) when no specially processed ordinal variables were used. After double-centering the matrix of this dissimilarity, the obtained scalar product (Gram) matrix has no negative eigenvalues at all (therefore it spans euclidean space with full convergence). So, just use this version of the dissimilarity if you want to use methods demanding euclidean space and if taking square root is an acceptable transform for your study settings.
Gower's (dis)similarity index
Gower dissimilarity is just 1 minus Gower similarity, $1-GS$. So, they are "the same", and limitations of one are the limitations of the other. Ward clustering computes cluster centroids and in order
Gower's (dis)similarity index Gower dissimilarity is just 1 minus Gower similarity, $1-GS$. So, they are "the same", and limitations of one are the limitations of the other. Ward clustering computes cluster centroids and in order for those to be geometrically "real" it demands (squared) euclidean distances as its input. Euclidean distance is metric. Not every metric distance is euclidean. Thus, not every metric distance is correct for Ward. Still, in practice, metric distances that are not euclidean distance could be used with Ward method heuristically. Non-metric distances - they are not recommended with Ward at all. By origin, Gower dissimilarity is non-euclidean and non-metric (even when all variables to compute it had been interval, Gower index will be closer to Manhattan distance, not euclidean distance), so you cannot use Ward. However, geometrically, a concrete matrix of Gower dissimilarity could happen to be close to euclidean distance, and then you may be licensed using Ward (just with these specific data!). To check if a dissimilarity matrix is (or is close to be) euclidean or not geometrically, one should double-center it and inspect the eigenvalues of the resultant matrix. The smaller is the sum of negative eigenvalues relative to the sum of positive ones, the closer is the dissimilarities to euclidean distances. But even in this occured case using Ward with Gower distance is purely heuristic. Read about the properties of double centered scalar product matrix here. Gower dissimilarity defined as $\sqrt {1-GS}$ is actually a Euclidean distance (therefore metric, automatically) when no specially processed ordinal variables were used. After double-centering the matrix of this dissimilarity, the obtained scalar product (Gram) matrix has no negative eigenvalues at all (therefore it spans euclidean space with full convergence). So, just use this version of the dissimilarity if you want to use methods demanding euclidean space and if taking square root is an acceptable transform for your study settings.
Gower's (dis)similarity index Gower dissimilarity is just 1 minus Gower similarity, $1-GS$. So, they are "the same", and limitations of one are the limitations of the other. Ward clustering computes cluster centroids and in order
40,848
Gower's (dis)similarity index
I'm a little puzzled by the answer above because of the following paragraph from Gower (1971): POSITIVE SEMI-DEFINITE PROPERTY OF THE SIMILARITY MATRIX With n individuals, the n X n matrix S can be formed whose element Sij is the similarity, as described in section 2, between individuals i and j. We often require to represent the n individuals of a sample as a set of points in Euclidean space. Gower (1966) has discussed this problem and shown that a convenient representation can be obtained by taking the distance between the ith and jth individuals as proportional to (1 - Sij)^(1/2). The coordinates of points with these distances are the elements of the latent vectors of S scaled so that their sums of squares equal the latent roots. Thus to get a real Euclidean representation with distances (1 - Sij)^(1/2) it is sufficient for S to be positive semi-definite (p.s.d.). It is shown in the Appendix that when there are no missing values S is p.s.d. By my read of this, although it's true that the output of a Gower's distance function (e.g. D=as.matrix(daisy(data, metric="gower"))) isn't Euclidean on its own, if there is no missing data, a Euclidean transform should be obtainable -- and if there is missing data, but you find that S=1-D is positive semidefinite (e.g. using matrixcalc::is.positive.semi.definite(S)), then you should still be able to do that same transform. (Incidentally, I think whether Ward's method wants Euclidean distances or squared Euclidean distances depends on the implementation. Based on the documentation, I believe the version in agnes() wants Euclidean distances.)
Gower's (dis)similarity index
I'm a little puzzled by the answer above because of the following paragraph from Gower (1971): POSITIVE SEMI-DEFINITE PROPERTY OF THE SIMILARITY MATRIX With n individuals, the n X n matrix S can be
Gower's (dis)similarity index I'm a little puzzled by the answer above because of the following paragraph from Gower (1971): POSITIVE SEMI-DEFINITE PROPERTY OF THE SIMILARITY MATRIX With n individuals, the n X n matrix S can be formed whose element Sij is the similarity, as described in section 2, between individuals i and j. We often require to represent the n individuals of a sample as a set of points in Euclidean space. Gower (1966) has discussed this problem and shown that a convenient representation can be obtained by taking the distance between the ith and jth individuals as proportional to (1 - Sij)^(1/2). The coordinates of points with these distances are the elements of the latent vectors of S scaled so that their sums of squares equal the latent roots. Thus to get a real Euclidean representation with distances (1 - Sij)^(1/2) it is sufficient for S to be positive semi-definite (p.s.d.). It is shown in the Appendix that when there are no missing values S is p.s.d. By my read of this, although it's true that the output of a Gower's distance function (e.g. D=as.matrix(daisy(data, metric="gower"))) isn't Euclidean on its own, if there is no missing data, a Euclidean transform should be obtainable -- and if there is missing data, but you find that S=1-D is positive semidefinite (e.g. using matrixcalc::is.positive.semi.definite(S)), then you should still be able to do that same transform. (Incidentally, I think whether Ward's method wants Euclidean distances or squared Euclidean distances depends on the implementation. Based on the documentation, I believe the version in agnes() wants Euclidean distances.)
Gower's (dis)similarity index I'm a little puzzled by the answer above because of the following paragraph from Gower (1971): POSITIVE SEMI-DEFINITE PROPERTY OF THE SIMILARITY MATRIX With n individuals, the n X n matrix S can be
40,849
Max Entropy Solver in R
Making the change of variables $x = l + (u-l)y$ puts the problem into the same form with $u=1, l=0$. Rewrite the density in the form $f(x,\nu,\tau)=\exp(-1/2((x-\nu)\tau)^2)/(\sqrt{2\pi}\tau)$ and rewrite the equations as $$\eqalign{ \int_0^1 x f(x,\nu,\tau) dx &= \mu \int_0^1 f(x,\nu,\tau)\\ \int_0^1 x^2 f(x,\nu,\tau)dx &= (\mu^2+\sigma^2) \int_0^1 f(x,\nu,\tau). }$$ All three integrals can be written explicitly in terms of the exponential exp and the cumulative standard normal distribution pnorm. This suggests the following R code for the core calculations; straightforward algebraic manipulations will produce the desired values of $a$, $b$, and $c$: f0 <- function(x){ # Normalization factor mu<-x[1];sigma<-x[2] pnorm((1-mu)/sigma)-pnorm(-mu/sigma) } f1 <- function(x){ # First moment mu<-x[1];sigma<-x[2] (-exp(-0.5*((1-mu)/sigma)^2)+exp(-0.5*(mu/sigma)^2))*sigma*0.39894228040143268 + mu * f0(x) } f2 <- function(x){ # Second moment mu<-x[1];sigma<-x[2] (-(1+mu)*exp(-0.5*((1-mu)/sigma)^2)+mu*exp(-0.5*(mu/sigma)^2))*sigma*0.39894228040143268 + (mu^2+sigma^2) * f0(x) } f <- function(x,y){ # Discrepancy between first two moments determined by parameters x and target values (y) mu<-y[1];sigma<-y[2] c<-f0(x) (mu-f1(x)/c)^2 + (mu^2+sigma^2-f2(x)/c)^2 } fit <- function(mu, sigma) { # Computes a truncated normal distribution on [0,1] with mean mu and SD sigma # (the "max ent" solution--but see the comments). # NB: naively takes (mu,sigma) as starting values. optim(c(mu,sigma), function(x){f(x,c(mu,sigma))}) } As an example of running and checking this code, consider the problem with $\mu=0.2$, $\sigma=0.1$: > mu <- .2 > sigma <- .1 > z <- fit(mu, sigma) > z$par [1] 0.1897255 0.1097969 > f1(z$par) / f0(z$par) # Should equal mu 0.2000000 > mu^2 + sigma^2 .05 > f2(z$par) / f0(z$par) # Should equal mu^2 + sigma^2 0.05000045 > nu <- z$par[1] > tau <- z$par[2] > gamma <- f0(z$par) > curve(exp(-0.5*((x-nu)/tau)^2)/(tau*gamma) * 0.39894, 0, 1) As required, this is a truncated normal distribution with the desired mean and variance. Shift and rescale it to arbitrary intervals $[l,u]$ as needed. This example was easy--the truncated distribution is close to normal anyway--but you will find that more extreme examples (such as $(\mu,\sigma)=(0.1,0.4)$) work just fine. (The speed is reasonable, too: on my system fit is taking 4 to 7 milliseconds.)
Max Entropy Solver in R
Making the change of variables $x = l + (u-l)y$ puts the problem into the same form with $u=1, l=0$. Rewrite the density in the form $f(x,\nu,\tau)=\exp(-1/2((x-\nu)\tau)^2)/(\sqrt{2\pi}\tau)$ and re
Max Entropy Solver in R Making the change of variables $x = l + (u-l)y$ puts the problem into the same form with $u=1, l=0$. Rewrite the density in the form $f(x,\nu,\tau)=\exp(-1/2((x-\nu)\tau)^2)/(\sqrt{2\pi}\tau)$ and rewrite the equations as $$\eqalign{ \int_0^1 x f(x,\nu,\tau) dx &= \mu \int_0^1 f(x,\nu,\tau)\\ \int_0^1 x^2 f(x,\nu,\tau)dx &= (\mu^2+\sigma^2) \int_0^1 f(x,\nu,\tau). }$$ All three integrals can be written explicitly in terms of the exponential exp and the cumulative standard normal distribution pnorm. This suggests the following R code for the core calculations; straightforward algebraic manipulations will produce the desired values of $a$, $b$, and $c$: f0 <- function(x){ # Normalization factor mu<-x[1];sigma<-x[2] pnorm((1-mu)/sigma)-pnorm(-mu/sigma) } f1 <- function(x){ # First moment mu<-x[1];sigma<-x[2] (-exp(-0.5*((1-mu)/sigma)^2)+exp(-0.5*(mu/sigma)^2))*sigma*0.39894228040143268 + mu * f0(x) } f2 <- function(x){ # Second moment mu<-x[1];sigma<-x[2] (-(1+mu)*exp(-0.5*((1-mu)/sigma)^2)+mu*exp(-0.5*(mu/sigma)^2))*sigma*0.39894228040143268 + (mu^2+sigma^2) * f0(x) } f <- function(x,y){ # Discrepancy between first two moments determined by parameters x and target values (y) mu<-y[1];sigma<-y[2] c<-f0(x) (mu-f1(x)/c)^2 + (mu^2+sigma^2-f2(x)/c)^2 } fit <- function(mu, sigma) { # Computes a truncated normal distribution on [0,1] with mean mu and SD sigma # (the "max ent" solution--but see the comments). # NB: naively takes (mu,sigma) as starting values. optim(c(mu,sigma), function(x){f(x,c(mu,sigma))}) } As an example of running and checking this code, consider the problem with $\mu=0.2$, $\sigma=0.1$: > mu <- .2 > sigma <- .1 > z <- fit(mu, sigma) > z$par [1] 0.1897255 0.1097969 > f1(z$par) / f0(z$par) # Should equal mu 0.2000000 > mu^2 + sigma^2 .05 > f2(z$par) / f0(z$par) # Should equal mu^2 + sigma^2 0.05000045 > nu <- z$par[1] > tau <- z$par[2] > gamma <- f0(z$par) > curve(exp(-0.5*((x-nu)/tau)^2)/(tau*gamma) * 0.39894, 0, 1) As required, this is a truncated normal distribution with the desired mean and variance. Shift and rescale it to arbitrary intervals $[l,u]$ as needed. This example was easy--the truncated distribution is close to normal anyway--but you will find that more extreme examples (such as $(\mu,\sigma)=(0.1,0.4)$) work just fine. (The speed is reasonable, too: on my system fit is taking 4 to 7 milliseconds.)
Max Entropy Solver in R Making the change of variables $x = l + (u-l)y$ puts the problem into the same form with $u=1, l=0$. Rewrite the density in the form $f(x,\nu,\tau)=\exp(-1/2((x-\nu)\tau)^2)/(\sqrt{2\pi}\tau)$ and re
40,850
Can compressed sensing be applied to data mining?
Yes, compressed sensing can be used for data mining when the data are sparse. For example, see Calderbank et al. Compressed Learning. The intuition is that if the data are sparse then one can perfectly reconstruct the data w.h.p from its randomly projected representation, provided that the projection dimension, $k$, satisfies $k \in \mathcal{O}(\|\Phi(x)\|_0 \text{log}\ d)$, where $d$ is the data dimension, and $\|\Phi(x)\|_0$ is the number of non-zero entries in the sparse representation of the data. It follows that w.h.p no information was lost by carrying out the random projection. However, one can do much better. For example, classification is a considerably simpler task than perfect signal reconstruction and so one can give guarantees for randomly projected classifiers with no sparsity requirement on the data and which require only that the projection dimension is logarithmic in the number of classes. For example, see our KDD paper from 2010: Durrant and Kaban. Compressed Fisher Linear Discriminant Analysis. It is also not necessary for data to be sparse in order to carry out regression in the randomly projected domain, for example see this NIPS 2009 paper: Mailard and Munos. Compressed Least-Squares Regression There is quite a sizeable literature on machine learning with randomly projected data and on compressed learning. Chasing down the references in the papers I've cited above should give you a good start if you want to look deeper.
Can compressed sensing be applied to data mining?
Yes, compressed sensing can be used for data mining when the data are sparse. For example, see Calderbank et al. Compressed Learning. The intuition is that if the data are sparse then one can perfectl
Can compressed sensing be applied to data mining? Yes, compressed sensing can be used for data mining when the data are sparse. For example, see Calderbank et al. Compressed Learning. The intuition is that if the data are sparse then one can perfectly reconstruct the data w.h.p from its randomly projected representation, provided that the projection dimension, $k$, satisfies $k \in \mathcal{O}(\|\Phi(x)\|_0 \text{log}\ d)$, where $d$ is the data dimension, and $\|\Phi(x)\|_0$ is the number of non-zero entries in the sparse representation of the data. It follows that w.h.p no information was lost by carrying out the random projection. However, one can do much better. For example, classification is a considerably simpler task than perfect signal reconstruction and so one can give guarantees for randomly projected classifiers with no sparsity requirement on the data and which require only that the projection dimension is logarithmic in the number of classes. For example, see our KDD paper from 2010: Durrant and Kaban. Compressed Fisher Linear Discriminant Analysis. It is also not necessary for data to be sparse in order to carry out regression in the randomly projected domain, for example see this NIPS 2009 paper: Mailard and Munos. Compressed Least-Squares Regression There is quite a sizeable literature on machine learning with randomly projected data and on compressed learning. Chasing down the references in the papers I've cited above should give you a good start if you want to look deeper.
Can compressed sensing be applied to data mining? Yes, compressed sensing can be used for data mining when the data are sparse. For example, see Calderbank et al. Compressed Learning. The intuition is that if the data are sparse then one can perfectl
40,851
Reference for generalized linear mixed models using Laplace approximation
Here are some papers: Breslow and Clayton, 1993: Approximate Inference in Generalized Linear Mixed Models. Tierney and Kadane, 1986: Accurate Approximations for Posterior Moments and Marginal Densities. Breslow, 2003: Whither PQL?. Tuerlinckx, et al. 2006: Statistical Inference in generalized linear mixed models: A review. Wolfinger, 1993: Laplace's approximation for nonlinear mixed models. Vonesh, 1996: A Note on the Use of Laplace's Approximation for Nonlinear Mixed-Effects Models.
Reference for generalized linear mixed models using Laplace approximation
Here are some papers: Breslow and Clayton, 1993: Approximate Inference in Generalized Linear Mixed Models. Tierney and Kadane, 1986: Accurate Approximations for Posterior Moments and Marginal Densiti
Reference for generalized linear mixed models using Laplace approximation Here are some papers: Breslow and Clayton, 1993: Approximate Inference in Generalized Linear Mixed Models. Tierney and Kadane, 1986: Accurate Approximations for Posterior Moments and Marginal Densities. Breslow, 2003: Whither PQL?. Tuerlinckx, et al. 2006: Statistical Inference in generalized linear mixed models: A review. Wolfinger, 1993: Laplace's approximation for nonlinear mixed models. Vonesh, 1996: A Note on the Use of Laplace's Approximation for Nonlinear Mixed-Effects Models.
Reference for generalized linear mixed models using Laplace approximation Here are some papers: Breslow and Clayton, 1993: Approximate Inference in Generalized Linear Mixed Models. Tierney and Kadane, 1986: Accurate Approximations for Posterior Moments and Marginal Densiti
40,852
Back-transformation and interpretation of $\log(X+1)$ estimates in multiple linear regression
According to Wooldridge 2009 (p. 192), the log(1 + x) transformation may retain the usual interpretation of log(x): In cases where a variable $y$ is nonnegative but can take on the value 0, $log(1+y)$ is sometimes used. The percentage change interpretations are often closely preserved, except for changes beginning at $y=0$ (where the percentage change is not even defined). Generally, using $log(1+y)$ and then interpreting the estimates as if the variable were $log(y)$ is acceptable when the data contain relatively few zeros. I suspect this extends to log2 or log10 bases. See also: Interpretation of log(1 + x) transformed predictor
Back-transformation and interpretation of $\log(X+1)$ estimates in multiple linear regression
According to Wooldridge 2009 (p. 192), the log(1 + x) transformation may retain the usual interpretation of log(x): In cases where a variable $y$ is nonnegative but can take on the value 0, $log(1+y
Back-transformation and interpretation of $\log(X+1)$ estimates in multiple linear regression According to Wooldridge 2009 (p. 192), the log(1 + x) transformation may retain the usual interpretation of log(x): In cases where a variable $y$ is nonnegative but can take on the value 0, $log(1+y)$ is sometimes used. The percentage change interpretations are often closely preserved, except for changes beginning at $y=0$ (where the percentage change is not even defined). Generally, using $log(1+y)$ and then interpreting the estimates as if the variable were $log(y)$ is acceptable when the data contain relatively few zeros. I suspect this extends to log2 or log10 bases. See also: Interpretation of log(1 + x) transformed predictor
Back-transformation and interpretation of $\log(X+1)$ estimates in multiple linear regression According to Wooldridge 2009 (p. 192), the log(1 + x) transformation may retain the usual interpretation of log(x): In cases where a variable $y$ is nonnegative but can take on the value 0, $log(1+y
40,853
Back-transformation and interpretation of $\log(X+1)$ estimates in multiple linear regression
For $0 < x \ll 1$, $\log(1+x) \approx x$. For $x \gg 1$, $\log(1+x) \approx \log(x)$. When $x$ is much smaller or much bigger than 1 you can use those equations to get your interpretation. As a side note: when applying transforms to your data, you should be concerned less about normality of X and Y in distribution, and more about the X-Y functional relationship implied by your regression formula. Specifically, use scatterplots and other diagnostics to see whether the fit curve is consistent with the actual X-Y relationship in your data. Normality is much less important particularly if you use robust empirical analytical methodologies like bootstrap.
Back-transformation and interpretation of $\log(X+1)$ estimates in multiple linear regression
For $0 < x \ll 1$, $\log(1+x) \approx x$. For $x \gg 1$, $\log(1+x) \approx \log(x)$. When $x$ is much smaller or much bigger than 1 you can use those equations to get your interpretation. As a side n
Back-transformation and interpretation of $\log(X+1)$ estimates in multiple linear regression For $0 < x \ll 1$, $\log(1+x) \approx x$. For $x \gg 1$, $\log(1+x) \approx \log(x)$. When $x$ is much smaller or much bigger than 1 you can use those equations to get your interpretation. As a side note: when applying transforms to your data, you should be concerned less about normality of X and Y in distribution, and more about the X-Y functional relationship implied by your regression formula. Specifically, use scatterplots and other diagnostics to see whether the fit curve is consistent with the actual X-Y relationship in your data. Normality is much less important particularly if you use robust empirical analytical methodologies like bootstrap.
Back-transformation and interpretation of $\log(X+1)$ estimates in multiple linear regression For $0 < x \ll 1$, $\log(1+x) \approx x$. For $x \gg 1$, $\log(1+x) \approx \log(x)$. When $x$ is much smaller or much bigger than 1 you can use those equations to get your interpretation. As a side n
40,854
How do I parameterize a Weibull distribution in JAGS / BUGS?
Doing the algebra, we have $\lambda= (1/b)^a$ (by equating the constant term within the exponent): since $a=\nu$, this is consistent with $a (1/b)^{a} = \nu \lambda$. You're right that my answer elsewhere is wrong; feel free to edit it yourself if I don't get around to it sooner (at least the link is there to warn people) ...)
How do I parameterize a Weibull distribution in JAGS / BUGS?
Doing the algebra, we have $\lambda= (1/b)^a$ (by equating the constant term within the exponent): since $a=\nu$, this is consistent with $a (1/b)^{a} = \nu \lambda$. You're right that my answer else
How do I parameterize a Weibull distribution in JAGS / BUGS? Doing the algebra, we have $\lambda= (1/b)^a$ (by equating the constant term within the exponent): since $a=\nu$, this is consistent with $a (1/b)^{a} = \nu \lambda$. You're right that my answer elsewhere is wrong; feel free to edit it yourself if I don't get around to it sooner (at least the link is there to warn people) ...)
How do I parameterize a Weibull distribution in JAGS / BUGS? Doing the algebra, we have $\lambda= (1/b)^a$ (by equating the constant term within the exponent): since $a=\nu$, this is consistent with $a (1/b)^{a} = \nu \lambda$. You're right that my answer else
40,855
Simulated annealing and k-means
It sounds like you're carrying out a cluster analysis on a dataset that has a pretty large number of variables; having difficulty obtaining good results because of the large number of variables (the curse of dimensionality, as you mention); and you're considering using an optimization technique such as simulated annealing to carry out a search through your variables to discover whether you might be able to use just a subset - is that right? If so, that activity is typically called feature selection (sometimes feature extraction), and there's plenty of literature out there that describes how you might approach it. Feature selection involves selecting a subset of the original variables, and is not quite the same as dimensionality reduction, which typically involves creating a small number of linear combinations of the original variables that summarise them (this is what a technique such as PCA or SVD does). A suggestion I might give is to note that you're trying to search through what is a discrete space (the power set of your variables). Simulated annealing, as an optimization technique, is in my experience more easily applied to searching through continuous spaces. This is particularly true of the implementation in MATLAB Global Optimization Toolbox (since I note you added the MATLAB tag). If you're using MATLAB for this, I'd suggest that a genetic algorithm might be easier to adapt to searching through discrete spaces. I wrote an article for MATLAB Digest a while ago that applies genetic algorithms to a related problem (classification rather than cluster analysis), which comes with example code. You might find that it's possible to adapt that code to your needs. The article carries out feature selection on a classification problem though, so it's maximizing classification accuracy - you'd need to provide a clustering metric for the algorithm to optimize, such as separation, heterogeneity, or a gap statistic. Hope that helps!
Simulated annealing and k-means
It sounds like you're carrying out a cluster analysis on a dataset that has a pretty large number of variables; having difficulty obtaining good results because of the large number of variables (the c
Simulated annealing and k-means It sounds like you're carrying out a cluster analysis on a dataset that has a pretty large number of variables; having difficulty obtaining good results because of the large number of variables (the curse of dimensionality, as you mention); and you're considering using an optimization technique such as simulated annealing to carry out a search through your variables to discover whether you might be able to use just a subset - is that right? If so, that activity is typically called feature selection (sometimes feature extraction), and there's plenty of literature out there that describes how you might approach it. Feature selection involves selecting a subset of the original variables, and is not quite the same as dimensionality reduction, which typically involves creating a small number of linear combinations of the original variables that summarise them (this is what a technique such as PCA or SVD does). A suggestion I might give is to note that you're trying to search through what is a discrete space (the power set of your variables). Simulated annealing, as an optimization technique, is in my experience more easily applied to searching through continuous spaces. This is particularly true of the implementation in MATLAB Global Optimization Toolbox (since I note you added the MATLAB tag). If you're using MATLAB for this, I'd suggest that a genetic algorithm might be easier to adapt to searching through discrete spaces. I wrote an article for MATLAB Digest a while ago that applies genetic algorithms to a related problem (classification rather than cluster analysis), which comes with example code. You might find that it's possible to adapt that code to your needs. The article carries out feature selection on a classification problem though, so it's maximizing classification accuracy - you'd need to provide a clustering metric for the algorithm to optimize, such as separation, heterogeneity, or a gap statistic. Hope that helps!
Simulated annealing and k-means It sounds like you're carrying out a cluster analysis on a dataset that has a pretty large number of variables; having difficulty obtaining good results because of the large number of variables (the c
40,856
Simulated annealing and k-means
Simulated Annealing is heuristic search optimization algorithm. You need to define a loss function. SA will optimize this and will converge to local minumum. K-means clustering by definition also includes optimization. It minimizes instances' distance to cluster centers. This distance can be eucledean or manhattan distance. Look to http://www.iro.umontreal.ca/~lisa/pointeurs/kmeans-nips7.pdf for its convergence properties and similarities to gradient descent. From my limited understanding only way to use to SA ve K-Means together is to define K-Means loss differently than distance minimization. For example you may define a loss function : using different distance metrics or different feature subsets. Loss Function = sum of metric distance of features and different combinations of features SA will try to minimize this Loss Function.
Simulated annealing and k-means
Simulated Annealing is heuristic search optimization algorithm. You need to define a loss function. SA will optimize this and will converge to local minumum. K-means clustering by definition also in
Simulated annealing and k-means Simulated Annealing is heuristic search optimization algorithm. You need to define a loss function. SA will optimize this and will converge to local minumum. K-means clustering by definition also includes optimization. It minimizes instances' distance to cluster centers. This distance can be eucledean or manhattan distance. Look to http://www.iro.umontreal.ca/~lisa/pointeurs/kmeans-nips7.pdf for its convergence properties and similarities to gradient descent. From my limited understanding only way to use to SA ve K-Means together is to define K-Means loss differently than distance minimization. For example you may define a loss function : using different distance metrics or different feature subsets. Loss Function = sum of metric distance of features and different combinations of features SA will try to minimize this Loss Function.
Simulated annealing and k-means Simulated Annealing is heuristic search optimization algorithm. You need to define a loss function. SA will optimize this and will converge to local minumum. K-means clustering by definition also in
40,857
Desired effect size vs. expected effect size
There are many ways to perform power calculations to determine the ideal sample size. One such way, as you mention, is to pick a threshold value of "Someone will care". This may be governed by prior knowledge, the belief that your field doesn't particular get interested until an effect is of a particular size, etc. My suggestion is instead to look at a range of possible effect sizes. It is trivially easy, if you are performing one power calculation, to perform several to evaluate the sensitivity of your threshold. For example, will you really be alright with your study being underpowered if you set your threshold at 5% and it turns out to be 4.9%? Or 3%. Or a real effect at all? The figure below for example is asking (for a fixed sample size in this case), what the power of the study is under a range of possible Exposed:Unexposed ratios and effect sizes. It would be just as easy to compose a similar plot varying study population to more fully understand your study's power. You also seem to be asking if you can use a small sample size to "suppress" particular results. You can design a study and acknowledge that sample size constraints will result in it being underpowered for particular effect sizes, but I wouldn't deliberately do so. A null or small effect finding is still a finding, and deliberately underpowering a study seems...flawed. Also, the optimal sample size obtained from power analysis is often somewhat optimistic - it hardly ever includes missing data, an interesting sub-group analysis, or other problems that will necessitate a bigger sample. Drawing a hard line is a bad idea.
Desired effect size vs. expected effect size
There are many ways to perform power calculations to determine the ideal sample size. One such way, as you mention, is to pick a threshold value of "Someone will care". This may be governed by prior k
Desired effect size vs. expected effect size There are many ways to perform power calculations to determine the ideal sample size. One such way, as you mention, is to pick a threshold value of "Someone will care". This may be governed by prior knowledge, the belief that your field doesn't particular get interested until an effect is of a particular size, etc. My suggestion is instead to look at a range of possible effect sizes. It is trivially easy, if you are performing one power calculation, to perform several to evaluate the sensitivity of your threshold. For example, will you really be alright with your study being underpowered if you set your threshold at 5% and it turns out to be 4.9%? Or 3%. Or a real effect at all? The figure below for example is asking (for a fixed sample size in this case), what the power of the study is under a range of possible Exposed:Unexposed ratios and effect sizes. It would be just as easy to compose a similar plot varying study population to more fully understand your study's power. You also seem to be asking if you can use a small sample size to "suppress" particular results. You can design a study and acknowledge that sample size constraints will result in it being underpowered for particular effect sizes, but I wouldn't deliberately do so. A null or small effect finding is still a finding, and deliberately underpowering a study seems...flawed. Also, the optimal sample size obtained from power analysis is often somewhat optimistic - it hardly ever includes missing data, an interesting sub-group analysis, or other problems that will necessitate a bigger sample. Drawing a hard line is a bad idea.
Desired effect size vs. expected effect size There are many ways to perform power calculations to determine the ideal sample size. One such way, as you mention, is to pick a threshold value of "Someone will care". This may be governed by prior k
40,858
Desired effect size vs. expected effect size
@EpiGrad makes some nice points here. I thought I would throw in one extra bit of information. He mentions that power analyses are often optimistic, and you mention that it is often suggested to estimate the effect size you want to capture from a pilot analysis. I just want to make it explicit, that this procedure is known to be biased such that the estimated power will be higher than the true power. There is considerable uncertainty in the estimated effect size based on a pilot study, or even a full study. If the true effect size is larger than the estimate, you will have more power, and if it is smaller, you will have less power, than you believe. However, the rate of change in power is not the same in both directions. Specifically, power diminishes faster as the effect size shrinks than it increases as the effect size expands. In this way, even though the distribution of effect sizes is symmetrical, the distribution of power is not. To compute a more robust estimate of power, compute the full distribution for the effect size and integrate over it. (A quick and dirty approach is to compute a 95% CI for the ES, and get a weighted average of the power at your estimate and at the CI endpoints.)
Desired effect size vs. expected effect size
@EpiGrad makes some nice points here. I thought I would throw in one extra bit of information. He mentions that power analyses are often optimistic, and you mention that it is often suggested to est
Desired effect size vs. expected effect size @EpiGrad makes some nice points here. I thought I would throw in one extra bit of information. He mentions that power analyses are often optimistic, and you mention that it is often suggested to estimate the effect size you want to capture from a pilot analysis. I just want to make it explicit, that this procedure is known to be biased such that the estimated power will be higher than the true power. There is considerable uncertainty in the estimated effect size based on a pilot study, or even a full study. If the true effect size is larger than the estimate, you will have more power, and if it is smaller, you will have less power, than you believe. However, the rate of change in power is not the same in both directions. Specifically, power diminishes faster as the effect size shrinks than it increases as the effect size expands. In this way, even though the distribution of effect sizes is symmetrical, the distribution of power is not. To compute a more robust estimate of power, compute the full distribution for the effect size and integrate over it. (A quick and dirty approach is to compute a 95% CI for the ES, and get a weighted average of the power at your estimate and at the CI endpoints.)
Desired effect size vs. expected effect size @EpiGrad makes some nice points here. I thought I would throw in one extra bit of information. He mentions that power analyses are often optimistic, and you mention that it is often suggested to est
40,859
Probability of circles intersecting
I can see many possible approaches, but let me outline one approach that I think might be effective and might give reasonable accuracy with a reasonable amount of effort. It uses Monte Carlo simulation, independence, and linearity of expectation. I'm going to break it down into bite-sized pieces, by identifying a set of smaller subproblems and explaining how to solve each subproblem, then showing how to combine those solutions to the subproblems to solve the original programming contest problem. Subproblem 1. Given two circles $C,C'$ in the square, determine whether they intersect. Solution 1. Let $C$ be centered at the point $(x,y)$ and have radius $r$, and $C'$ be centered at $(x',y')$ with radius $r'$. Note that the two circles overlap if and only if the distance between the two centers is at most $r+r'$, i.e., if and only if $(x-x')^2 + (y-y')^2 \le (r+r')^2$. This condition is easy to test, as a function of $x,y,r,x',y',r'$. Subproblem 2. Suppose the first circle is given by $C$. Compute the probability $p(C)$ that the second circle will not intersect $C$, as a function of $C$. Solution 2. We will use Monte Carlo simulation. In particular, perform 10,000 trials, where in each trial, we randomly drop the second circle $C'$ and test whether $C,C'$ intersect (using solution 1 above to test for an intersection). Count the number of trials where they do not intersect and divide by 10,000; that is your estimate of $p(C)$. (It may be possible to solve this subproblem analytically, by solving a three-dimensional integral; however, that does not sound fun. Monte Carlo simulation is easier.) Subproblem 3. Suppose the first circle is given by $C$. Compute the probability $p'(C)$ that none of the remaining $N-1$ circles will intersect $C$, as a function of $C$. Solution 3. Note that, by independence, $p'(C) = p(C) \times \cdots \times p(C) = p(C)^{N-1}$. This is easy to compute. Subproblem 4. Compute the probability $q_1$ that, if you drop $N$ circles randomly, none of the last $N-1$ circles has any intersection with the first circle. Solution 4. Note that, if we let $C$ be a random variable, we have $q_1 = E[p'(C)]$, where the expectation is taken over $C$. Use Monte Carlo simulation. Perform 10,000 trials, where in each trial you randomly choose a circle $C$, then you compute $p'(C)$ (using solution 3). Average the results over all of the trials. That is your estimate of the probability $q_1$. Subproblem 5. Compute the probability $q_i$ that, if you drop $N$ circles randomly, the $i$th circle has no intersection with any of the other $N-1$ circles. Solution 5. By symmetry, $q_i = q_1$, so solution 4 already provides the answer. The original problem. Compute the expected number of circles that have no intersection with any other circle, if you drop $N$ circles randomly. Solution. By linearity of expectation, this is $q_1+q_2+\cdots+q_N$. By solution 5, this is $N \times q_1$. Now use solution 4 to compute $q_1$, and you have your answer to the original problem.
Probability of circles intersecting
I can see many possible approaches, but let me outline one approach that I think might be effective and might give reasonable accuracy with a reasonable amount of effort. It uses Monte Carlo simulati
Probability of circles intersecting I can see many possible approaches, but let me outline one approach that I think might be effective and might give reasonable accuracy with a reasonable amount of effort. It uses Monte Carlo simulation, independence, and linearity of expectation. I'm going to break it down into bite-sized pieces, by identifying a set of smaller subproblems and explaining how to solve each subproblem, then showing how to combine those solutions to the subproblems to solve the original programming contest problem. Subproblem 1. Given two circles $C,C'$ in the square, determine whether they intersect. Solution 1. Let $C$ be centered at the point $(x,y)$ and have radius $r$, and $C'$ be centered at $(x',y')$ with radius $r'$. Note that the two circles overlap if and only if the distance between the two centers is at most $r+r'$, i.e., if and only if $(x-x')^2 + (y-y')^2 \le (r+r')^2$. This condition is easy to test, as a function of $x,y,r,x',y',r'$. Subproblem 2. Suppose the first circle is given by $C$. Compute the probability $p(C)$ that the second circle will not intersect $C$, as a function of $C$. Solution 2. We will use Monte Carlo simulation. In particular, perform 10,000 trials, where in each trial, we randomly drop the second circle $C'$ and test whether $C,C'$ intersect (using solution 1 above to test for an intersection). Count the number of trials where they do not intersect and divide by 10,000; that is your estimate of $p(C)$. (It may be possible to solve this subproblem analytically, by solving a three-dimensional integral; however, that does not sound fun. Monte Carlo simulation is easier.) Subproblem 3. Suppose the first circle is given by $C$. Compute the probability $p'(C)$ that none of the remaining $N-1$ circles will intersect $C$, as a function of $C$. Solution 3. Note that, by independence, $p'(C) = p(C) \times \cdots \times p(C) = p(C)^{N-1}$. This is easy to compute. Subproblem 4. Compute the probability $q_1$ that, if you drop $N$ circles randomly, none of the last $N-1$ circles has any intersection with the first circle. Solution 4. Note that, if we let $C$ be a random variable, we have $q_1 = E[p'(C)]$, where the expectation is taken over $C$. Use Monte Carlo simulation. Perform 10,000 trials, where in each trial you randomly choose a circle $C$, then you compute $p'(C)$ (using solution 3). Average the results over all of the trials. That is your estimate of the probability $q_1$. Subproblem 5. Compute the probability $q_i$ that, if you drop $N$ circles randomly, the $i$th circle has no intersection with any of the other $N-1$ circles. Solution 5. By symmetry, $q_i = q_1$, so solution 4 already provides the answer. The original problem. Compute the expected number of circles that have no intersection with any other circle, if you drop $N$ circles randomly. Solution. By linearity of expectation, this is $q_1+q_2+\cdots+q_N$. By solution 5, this is $N \times q_1$. Now use solution 4 to compute $q_1$, and you have your answer to the original problem.
Probability of circles intersecting I can see many possible approaches, but let me outline one approach that I think might be effective and might give reasonable accuracy with a reasonable amount of effort. It uses Monte Carlo simulati
40,860
GDA and LDA terminology
According to Wikipedia: "The terms Fisher's linear discriminant and LDA are often used interchangeably, although Fisher's original article actually describes a slightly different discriminant, which does not make some of the assumptions of LDA such as normally distributed classes or equal class covariances." LDA is equivalent to maximum likelihood classification assuming Gaussian distributions for each class. I would have said that "Gaussian Discriminant Analysis" could actually refer to either formulation, as it's an ambiguous name. However, normally I would associate GDA with the acronym "General Discriminant Analysis" or "Generalised Discriminant Analysis". General Discriminant Analysis is called a "general" because it applies the methods of the general linear model (see also General Linear Models (GLM)) to the discriminant function analysis problem. Generalised Discriminant Analysis also refers to nonlinear methods, but it instead achieved using kernel functions (see e.g. Generalized Discriminant Analysis Using a Kernel Approach), and is also known variously as Kernel Discriminant Analysis (KDA) and Kernel Fisher Discriminant Analysis (KDFA).
GDA and LDA terminology
According to Wikipedia: "The terms Fisher's linear discriminant and LDA are often used interchangeably, although Fisher's original article actually describes a slightly different discriminant, which
GDA and LDA terminology According to Wikipedia: "The terms Fisher's linear discriminant and LDA are often used interchangeably, although Fisher's original article actually describes a slightly different discriminant, which does not make some of the assumptions of LDA such as normally distributed classes or equal class covariances." LDA is equivalent to maximum likelihood classification assuming Gaussian distributions for each class. I would have said that "Gaussian Discriminant Analysis" could actually refer to either formulation, as it's an ambiguous name. However, normally I would associate GDA with the acronym "General Discriminant Analysis" or "Generalised Discriminant Analysis". General Discriminant Analysis is called a "general" because it applies the methods of the general linear model (see also General Linear Models (GLM)) to the discriminant function analysis problem. Generalised Discriminant Analysis also refers to nonlinear methods, but it instead achieved using kernel functions (see e.g. Generalized Discriminant Analysis Using a Kernel Approach), and is also known variously as Kernel Discriminant Analysis (KDA) and Kernel Fisher Discriminant Analysis (KDFA).
GDA and LDA terminology According to Wikipedia: "The terms Fisher's linear discriminant and LDA are often used interchangeably, although Fisher's original article actually describes a slightly different discriminant, which
40,861
GDA and LDA terminology
GDA (Gaussian Dcriminant Analysis) is a general term for both LDA (Linear Discriminant Analysis) and QDA (Quadratic Discriminant Analysis) where the likelihood probability of each observation given the class, i.e., P(x|y) can be modeled by the multivariate Gaussian distribution. Here, x is a n-dimensional observation random vector (n=number of features in each observation). y is a label, i.e., one of K classes (say, y=1, y=2, .... y=K). LDA is a case where each observation is drawn from the multivariate Gaussian distribution with class-specific mean vector and 'shared' covariance matrix. i.e., P(x|y=1) ~ N(u1, sigma), P(x|y=2) ~ N(u2, sigma), . . . . P(x|y=K) ~ N(uK, sigma). where, N(uK, sigma) denotes Gaussian distribution with mean uK (nx1 vector) and covariance sigma (nxn matrix). QDA is a special case where each observation is drawn from the multivariate Gaussian distribution with class-specific mean vector and 'class-specific' covariance matrix. i.e., P(x|y=1) ~ N(u1, sigma1), P(x|y=2) ~ N(u2, sigma2), . . . . P(x|y=K) ~ N(uK, sigmaK). QDA is more flexible (i.e., curvy) than LDA. However, it may suffer from the overfitting problem (i.e., high variance).
GDA and LDA terminology
GDA (Gaussian Dcriminant Analysis) is a general term for both LDA (Linear Discriminant Analysis) and QDA (Quadratic Discriminant Analysis) where the likelihood probability of each observation given th
GDA and LDA terminology GDA (Gaussian Dcriminant Analysis) is a general term for both LDA (Linear Discriminant Analysis) and QDA (Quadratic Discriminant Analysis) where the likelihood probability of each observation given the class, i.e., P(x|y) can be modeled by the multivariate Gaussian distribution. Here, x is a n-dimensional observation random vector (n=number of features in each observation). y is a label, i.e., one of K classes (say, y=1, y=2, .... y=K). LDA is a case where each observation is drawn from the multivariate Gaussian distribution with class-specific mean vector and 'shared' covariance matrix. i.e., P(x|y=1) ~ N(u1, sigma), P(x|y=2) ~ N(u2, sigma), . . . . P(x|y=K) ~ N(uK, sigma). where, N(uK, sigma) denotes Gaussian distribution with mean uK (nx1 vector) and covariance sigma (nxn matrix). QDA is a special case where each observation is drawn from the multivariate Gaussian distribution with class-specific mean vector and 'class-specific' covariance matrix. i.e., P(x|y=1) ~ N(u1, sigma1), P(x|y=2) ~ N(u2, sigma2), . . . . P(x|y=K) ~ N(uK, sigmaK). QDA is more flexible (i.e., curvy) than LDA. However, it may suffer from the overfitting problem (i.e., high variance).
GDA and LDA terminology GDA (Gaussian Dcriminant Analysis) is a general term for both LDA (Linear Discriminant Analysis) and QDA (Quadratic Discriminant Analysis) where the likelihood probability of each observation given th
40,862
GDA and LDA terminology
In the theory of classification the linear form of the discriminant function is optimal when the class conditional densities are Gaussian with the same covariance matrix. So in that sense I could understand the term Gaussian sneaking in as a term for LDA. However QDA quadratic discrimination is optimal when the class conditional densities are Gaussian and the covariances are different. So that could be termed Gaussian too. So what tdc said is not quite right because he left off the equal covariance matrix condition.
GDA and LDA terminology
In the theory of classification the linear form of the discriminant function is optimal when the class conditional densities are Gaussian with the same covariance matrix. So in that sense I could und
GDA and LDA terminology In the theory of classification the linear form of the discriminant function is optimal when the class conditional densities are Gaussian with the same covariance matrix. So in that sense I could understand the term Gaussian sneaking in as a term for LDA. However QDA quadratic discrimination is optimal when the class conditional densities are Gaussian and the covariances are different. So that could be termed Gaussian too. So what tdc said is not quite right because he left off the equal covariance matrix condition.
GDA and LDA terminology In the theory of classification the linear form of the discriminant function is optimal when the class conditional densities are Gaussian with the same covariance matrix. So in that sense I could und
40,863
Statistics on mathematical "data"?
Any time you do computer simulations to evaluate the performance of a statistical method (eg, power), you are approximating a calculation that might conceivably be calculated analytically (power is a probability). You could also conceive of doing exact-ish numerical calculations: summing exhaustively across all possible outcomes. In a paper to appear in Genetics, I wrote: Simulations are most flexible and are generally simpler to obtain, but lack precision. Numeric calculations can be precise, but can be computationally intensive. Symbolic results are more general than numeric calculations, can enable quicker calculations in software, and have the potential to provide more clear insight. I was trying to justify some crazy efforts I put into some analytical calulations that could easily be obtained numerically. So regarding your question, I think numeric results can be quite compelling—not real proof, but likely sufficient to make the point in the range of parameter values considered. Subjecting the results of numerical calculations to regression analysis can be really useful. (I've done that to figure out and/or verify an answer that ultimately I derived analytically.) But again it's not real proof, though if correct to within round-off error it would be pretty compelling just not completely satisfying. The advantage of numerical calculations over simulations is that you can get to $10^{-13}$ error whereas for simulations you'd never get that precise.
Statistics on mathematical "data"?
Any time you do computer simulations to evaluate the performance of a statistical method (eg, power), you are approximating a calculation that might conceivably be calculated analytically (power is a
Statistics on mathematical "data"? Any time you do computer simulations to evaluate the performance of a statistical method (eg, power), you are approximating a calculation that might conceivably be calculated analytically (power is a probability). You could also conceive of doing exact-ish numerical calculations: summing exhaustively across all possible outcomes. In a paper to appear in Genetics, I wrote: Simulations are most flexible and are generally simpler to obtain, but lack precision. Numeric calculations can be precise, but can be computationally intensive. Symbolic results are more general than numeric calculations, can enable quicker calculations in software, and have the potential to provide more clear insight. I was trying to justify some crazy efforts I put into some analytical calulations that could easily be obtained numerically. So regarding your question, I think numeric results can be quite compelling—not real proof, but likely sufficient to make the point in the range of parameter values considered. Subjecting the results of numerical calculations to regression analysis can be really useful. (I've done that to figure out and/or verify an answer that ultimately I derived analytically.) But again it's not real proof, though if correct to within round-off error it would be pretty compelling just not completely satisfying. The advantage of numerical calculations over simulations is that you can get to $10^{-13}$ error whereas for simulations you'd never get that precise.
Statistics on mathematical "data"? Any time you do computer simulations to evaluate the performance of a statistical method (eg, power), you are approximating a calculation that might conceivably be calculated analytically (power is a
40,864
Statistics on mathematical "data"?
This is akin (Update: see below) to methods used in automated probabilistic proof systems or cryptographic verification systems. An example would be a zero knowledge proof. Several other areas to explore: Interactive proof systems Probabilistically checkable proofs In general, one does not try to do statistical analyses on the relationships found over the the input and the response (i.e. ${x}$ and ${F(x}$) spaces, though these may be analyzed probabilistically over finite spaces. Infinite spaces are a bit more of a challenge, though you may be able to construct some mappings to finite classes (i.e. subspaces that may be infinite, but where a solution in a subspace is representative for all points in the subspace, even if this is only the case with some probability). Update 1: This is akin to such methods, with the caveat that such methods are usually applied in the context of someone claiming to have a proof, as opposed to probabilistically reasoning about a proof. The distinction is important. Such reasoning cannot generally be accepted as a proof, so one could say it is like probabilistic conjecture verification. This is more like the numerical verifications done for the Goldbach Conjecture or the Riemann Hypothesis.
Statistics on mathematical "data"?
This is akin (Update: see below) to methods used in automated probabilistic proof systems or cryptographic verification systems. An example would be a zero knowledge proof. Several other areas to exp
Statistics on mathematical "data"? This is akin (Update: see below) to methods used in automated probabilistic proof systems or cryptographic verification systems. An example would be a zero knowledge proof. Several other areas to explore: Interactive proof systems Probabilistically checkable proofs In general, one does not try to do statistical analyses on the relationships found over the the input and the response (i.e. ${x}$ and ${F(x}$) spaces, though these may be analyzed probabilistically over finite spaces. Infinite spaces are a bit more of a challenge, though you may be able to construct some mappings to finite classes (i.e. subspaces that may be infinite, but where a solution in a subspace is representative for all points in the subspace, even if this is only the case with some probability). Update 1: This is akin to such methods, with the caveat that such methods are usually applied in the context of someone claiming to have a proof, as opposed to probabilistically reasoning about a proof. The distinction is important. Such reasoning cannot generally be accepted as a proof, so one could say it is like probabilistic conjecture verification. This is more like the numerical verifications done for the Goldbach Conjecture or the Riemann Hypothesis.
Statistics on mathematical "data"? This is akin (Update: see below) to methods used in automated probabilistic proof systems or cryptographic verification systems. An example would be a zero knowledge proof. Several other areas to exp
40,865
Algorithms to eliminate or display outliers in a dataset
Outliers are usually removed for analysis (fitting a model), not for visualization, where you can just change your focus so the outliers are out of view. The plots you mention, parallel coordinate chart and a scatterplot matrix, should be fine since each variable has its own scale. If your software forces all scales to be the same, the usual trick is to "standardize" the values by subtracting the mean and dividing by the standard deviation. However, doing anything with standard deviation counts as analysis (so you may need to remove outliers after all) and assumes a Normal distribution. So first perform a distribution analysis of each variable -- at least look at a histogram and preferably do some kind of goodness of fit test against a normal curve. If the distribution is more like a Log Normal or something else, you can apply a transform to the data to make it Normal for better visualization (or use a log scale in the visualization). Removing outliers is a bit of an art and should require knowledge of the data (because often the outliers are the interesting parts). The most common definition of outliers for box plots is points beyond 1.5 times the inter-quartile range from the box quartiles, which is usually farther than two standard deviation. Another technique is often called "robust" fitting. You fit a Normal curve to the data and remove points from the tails that where the value of the fitted curve is very small. Repeat those two steps until it stabilizes (usually 1 to 3 times).
Algorithms to eliminate or display outliers in a dataset
Outliers are usually removed for analysis (fitting a model), not for visualization, where you can just change your focus so the outliers are out of view. The plots you mention, parallel coordinate cha
Algorithms to eliminate or display outliers in a dataset Outliers are usually removed for analysis (fitting a model), not for visualization, where you can just change your focus so the outliers are out of view. The plots you mention, parallel coordinate chart and a scatterplot matrix, should be fine since each variable has its own scale. If your software forces all scales to be the same, the usual trick is to "standardize" the values by subtracting the mean and dividing by the standard deviation. However, doing anything with standard deviation counts as analysis (so you may need to remove outliers after all) and assumes a Normal distribution. So first perform a distribution analysis of each variable -- at least look at a histogram and preferably do some kind of goodness of fit test against a normal curve. If the distribution is more like a Log Normal or something else, you can apply a transform to the data to make it Normal for better visualization (or use a log scale in the visualization). Removing outliers is a bit of an art and should require knowledge of the data (because often the outliers are the interesting parts). The most common definition of outliers for box plots is points beyond 1.5 times the inter-quartile range from the box quartiles, which is usually farther than two standard deviation. Another technique is often called "robust" fitting. You fit a Normal curve to the data and remove points from the tails that where the value of the fitted curve is very small. Repeat those two steps until it stabilizes (usually 1 to 3 times).
Algorithms to eliminate or display outliers in a dataset Outliers are usually removed for analysis (fitting a model), not for visualization, where you can just change your focus so the outliers are out of view. The plots you mention, parallel coordinate cha
40,866
Algorithms to eliminate or display outliers in a dataset
Here is how I would go about doing it in SQL Server. The query below will get the average weight from a fictional Scale table holding a single weigh-in for each person while not permitting those who are overly fat or thin to throw off the more realistic average: select w.Gender, Avg(w.Weight) as AvgWeight from ScaleData w join ( select d.Gender, Avg(d.Weight) as AvgWeight, 2*STDDEVP(d.Weight) StdDeviation from ScaleData d group by d.Gender ) d on w.Gender = d.Gender and w.Weight between d.AvgWeight-d.StdDeviation and d.AvgWeight+d.StdDeviation group by w.Gender There may be a better way to go about this, but it works and works well. If you have come across another more efficient solution, I’d love to hear about it. NOTE: the above removes the top and bottom 5% of outliers out of the picture for purpose of the Average. You can adjust the number of outliers removed by adjusting the 2* in the 2*STDDEVP as per: http://en.wikipedia.org/wiki/Standard_deviation
Algorithms to eliminate or display outliers in a dataset
Here is how I would go about doing it in SQL Server. The query below will get the average weight from a fictional Scale table holding a single weigh-in for each person while not permitting those who a
Algorithms to eliminate or display outliers in a dataset Here is how I would go about doing it in SQL Server. The query below will get the average weight from a fictional Scale table holding a single weigh-in for each person while not permitting those who are overly fat or thin to throw off the more realistic average: select w.Gender, Avg(w.Weight) as AvgWeight from ScaleData w join ( select d.Gender, Avg(d.Weight) as AvgWeight, 2*STDDEVP(d.Weight) StdDeviation from ScaleData d group by d.Gender ) d on w.Gender = d.Gender and w.Weight between d.AvgWeight-d.StdDeviation and d.AvgWeight+d.StdDeviation group by w.Gender There may be a better way to go about this, but it works and works well. If you have come across another more efficient solution, I’d love to hear about it. NOTE: the above removes the top and bottom 5% of outliers out of the picture for purpose of the Average. You can adjust the number of outliers removed by adjusting the 2* in the 2*STDDEVP as per: http://en.wikipedia.org/wiki/Standard_deviation
Algorithms to eliminate or display outliers in a dataset Here is how I would go about doing it in SQL Server. The query below will get the average weight from a fictional Scale table holding a single weigh-in for each person while not permitting those who a
40,867
Classifying IP addresses with a decision tree
As a Postmaster I find this not only a really cool problem, but a daily problem in my work. So I have a few questions for you: Is your dataset comprised only of IPv4 addresses? Is your dataset comprised of "known" spam address blocks, or just addresses that may belong to a botnet? Besides using IP addresses as ordered tupples, you can use them as integers too. There have been people using PATRICIA this way My R-Fu is very low, so I cannot help you with that :(
Classifying IP addresses with a decision tree
As a Postmaster I find this not only a really cool problem, but a daily problem in my work. So I have a few questions for you: Is your dataset comprised only of IPv4 addresses? Is your dataset compri
Classifying IP addresses with a decision tree As a Postmaster I find this not only a really cool problem, but a daily problem in my work. So I have a few questions for you: Is your dataset comprised only of IPv4 addresses? Is your dataset comprised of "known" spam address blocks, or just addresses that may belong to a botnet? Besides using IP addresses as ordered tupples, you can use them as integers too. There have been people using PATRICIA this way My R-Fu is very low, so I cannot help you with that :(
Classifying IP addresses with a decision tree As a Postmaster I find this not only a really cool problem, but a daily problem in my work. So I have a few questions for you: Is your dataset comprised only of IPv4 addresses? Is your dataset compri
40,868
Classifying IP addresses with a decision tree
The general rule for trees is that you shouldn't expect them to do anything with an order of attributes because they cannot "see" it. Moreover the attributes should be somewhat "orthogonal" description of the objects. Thus I think you should rather use some descriptors of IPs, like country, provider, commercial/home (plus possibly mix it with other info you have about the messages). Or drop learning at all, do some prefix tree as adamo and Henry suggested and try to find nodes with significant spam to no-spam differences and infer something from that.
Classifying IP addresses with a decision tree
The general rule for trees is that you shouldn't expect them to do anything with an order of attributes because they cannot "see" it. Moreover the attributes should be somewhat "orthogonal" descriptio
Classifying IP addresses with a decision tree The general rule for trees is that you shouldn't expect them to do anything with an order of attributes because they cannot "see" it. Moreover the attributes should be somewhat "orthogonal" description of the objects. Thus I think you should rather use some descriptors of IPs, like country, provider, commercial/home (plus possibly mix it with other info you have about the messages). Or drop learning at all, do some prefix tree as adamo and Henry suggested and try to find nodes with significant spam to no-spam differences and infer something from that.
Classifying IP addresses with a decision tree The general rule for trees is that you shouldn't expect them to do anything with an order of attributes because they cannot "see" it. Moreover the attributes should be somewhat "orthogonal" descriptio
40,869
Classifying IP addresses with a decision tree
Admittedly two years since you asked this question..., but this article is just too perfect to not share here. Here is your answer and algorithm. Well, at least when they made it, although if you check out the authors they have personal webpages with more work in the same area. This is how Microsoft did it or began to do it a few years back: UDMAP. Yinglian Xie, Fang Yu, Kannan Achan, Eliot Gillum+, Moises Goldszmidt, Ted Wobber. "How Dynamic are IP Addresses?" Microsoft Research, Silicon Valley Microsoft Corporation. research.microsoft.com/pubs/63680/sigcomm07-onefile.pdf Don't be fooled by the title of the article too much, although they do focus on that a bit - the reason behind them trying to identify dynamic IP addresses is for spammers - and they have followed up in more recent works (and built on this quite a bit, although they had some clever ideas in here) - all of this is posted on the leader authors' page.
Classifying IP addresses with a decision tree
Admittedly two years since you asked this question..., but this article is just too perfect to not share here. Here is your answer and algorithm. Well, at least when they made it, although if you ch
Classifying IP addresses with a decision tree Admittedly two years since you asked this question..., but this article is just too perfect to not share here. Here is your answer and algorithm. Well, at least when they made it, although if you check out the authors they have personal webpages with more work in the same area. This is how Microsoft did it or began to do it a few years back: UDMAP. Yinglian Xie, Fang Yu, Kannan Achan, Eliot Gillum+, Moises Goldszmidt, Ted Wobber. "How Dynamic are IP Addresses?" Microsoft Research, Silicon Valley Microsoft Corporation. research.microsoft.com/pubs/63680/sigcomm07-onefile.pdf Don't be fooled by the title of the article too much, although they do focus on that a bit - the reason behind them trying to identify dynamic IP addresses is for spammers - and they have followed up in more recent works (and built on this quite a bit, although they had some clever ideas in here) - all of this is posted on the leader authors' page.
Classifying IP addresses with a decision tree Admittedly two years since you asked this question..., but this article is just too perfect to not share here. Here is your answer and algorithm. Well, at least when they made it, although if you ch
40,870
Classifying IP addresses with a decision tree
It sounds like you're whacking a mole with a nuclear bomb there, why not just: 1.) Sort all the IP addresses 2.) Do a sliding window over all of them where if one of them is marked spam, the ones before it get a probability associated with them, and the ones after it do as well 3.) Make the probability weights you're assigning decline with some function of distance, and maybe stop assigning when one of the octets run out. This way, if xxx.xxx.xx.125 is between .124 and .126, and both of those are marked as spammers, but it is not, .125 should get some spam value assigned from both. I suppose you could do a similar sliding thing at each octet level if you want spam "value" to propagate up the octet tree. Anyway, this sounds like something that 3 or 4 sorts, and three or 4 traversals of those sorts, could probably handle. T
Classifying IP addresses with a decision tree
It sounds like you're whacking a mole with a nuclear bomb there, why not just: 1.) Sort all the IP addresses 2.) Do a sliding window over all of them where if one of them is marked spam, the ones befo
Classifying IP addresses with a decision tree It sounds like you're whacking a mole with a nuclear bomb there, why not just: 1.) Sort all the IP addresses 2.) Do a sliding window over all of them where if one of them is marked spam, the ones before it get a probability associated with them, and the ones after it do as well 3.) Make the probability weights you're assigning decline with some function of distance, and maybe stop assigning when one of the octets run out. This way, if xxx.xxx.xx.125 is between .124 and .126, and both of those are marked as spammers, but it is not, .125 should get some spam value assigned from both. I suppose you could do a similar sliding thing at each octet level if you want spam "value" to propagate up the octet tree. Anyway, this sounds like something that 3 or 4 sorts, and three or 4 traversals of those sorts, could probably handle. T
Classifying IP addresses with a decision tree It sounds like you're whacking a mole with a nuclear bomb there, why not just: 1.) Sort all the IP addresses 2.) Do a sliding window over all of them where if one of them is marked spam, the ones befo
40,871
Fitting a beta-binomial model in the case of overdispersion in R
Beta binomial does sound like a good choice. Ben Bolker has a nice example of how to do it with his bbmle package here. I believe his book has more, some kind of tadpole-related example. You can get preprints of the book here. Hope this helps!
Fitting a beta-binomial model in the case of overdispersion in R
Beta binomial does sound like a good choice. Ben Bolker has a nice example of how to do it with his bbmle package here. I believe his book has more, some kind of tadpole-related example. You can get p
Fitting a beta-binomial model in the case of overdispersion in R Beta binomial does sound like a good choice. Ben Bolker has a nice example of how to do it with his bbmle package here. I believe his book has more, some kind of tadpole-related example. You can get preprints of the book here. Hope this helps!
Fitting a beta-binomial model in the case of overdispersion in R Beta binomial does sound like a good choice. Ben Bolker has a nice example of how to do it with his bbmle package here. I believe his book has more, some kind of tadpole-related example. You can get p
40,872
Probability of a certain sum of values from a set of dice rolls
In the comments to Glen's answer you seem to have used a normal approximation pnorm(300, 350, sqrt(3500/12)) to get 0.001707396. This is not a bad answer, though you can do better. If you used the continuity correction the continuity correction pnorm(299.5, 350, sqrt(3500/12)) you would get 0.001553355. I suspect this is what was being asked for. It is in fact possible to calculate this more precisely. The following R code does so (yes, I know it has for loops). sides <- 6 throws <- 100 ## p[j,i] is probability of exactly (j+sides) after (i+1) throws p <- matrix(rep(0, sides*(throws+1)^2 ), ncol=throws+1 ) p[sides,1] <- 1 # probability 1 of score of 0 after 0 throws for (i in 2:(throws+1) ){ for (j in (sides+1):(sides*(throws+1)) ){ p[j,i] <- sum(p[(j-sides):(j-1), i-1]) / sides } } sum( p[0:(299+sides), throws+1] ) This gives the result 0.001505810. The normal approximation with continuity correction is within 0.00005, which looks good, though the relative error is about 3%, which looks slightly less impressive; this often happens using the normal approximation in the tail of the distribution.
Probability of a certain sum of values from a set of dice rolls
In the comments to Glen's answer you seem to have used a normal approximation pnorm(300, 350, sqrt(3500/12)) to get 0.001707396. This is not a bad answer, though you can do better. If you used the co
Probability of a certain sum of values from a set of dice rolls In the comments to Glen's answer you seem to have used a normal approximation pnorm(300, 350, sqrt(3500/12)) to get 0.001707396. This is not a bad answer, though you can do better. If you used the continuity correction the continuity correction pnorm(299.5, 350, sqrt(3500/12)) you would get 0.001553355. I suspect this is what was being asked for. It is in fact possible to calculate this more precisely. The following R code does so (yes, I know it has for loops). sides <- 6 throws <- 100 ## p[j,i] is probability of exactly (j+sides) after (i+1) throws p <- matrix(rep(0, sides*(throws+1)^2 ), ncol=throws+1 ) p[sides,1] <- 1 # probability 1 of score of 0 after 0 throws for (i in 2:(throws+1) ){ for (j in (sides+1):(sides*(throws+1)) ){ p[j,i] <- sum(p[(j-sides):(j-1), i-1]) / sides } } sum( p[0:(299+sides), throws+1] ) This gives the result 0.001505810. The normal approximation with continuity correction is within 0.00005, which looks good, though the relative error is about 3%, which looks slightly less impressive; this often happens using the normal approximation in the tail of the distribution.
Probability of a certain sum of values from a set of dice rolls In the comments to Glen's answer you seem to have used a normal approximation pnorm(300, 350, sqrt(3500/12)) to get 0.001707396. This is not a bad answer, though you can do better. If you used the co
40,873
Probability of a certain sum of values from a set of dice rolls
Due to the CLT, a sum of i.i.d. random variables is distributed: $$ \sum_{i=1}^nX_i \sim N\left(\mu =n\cdot\mu_{X_i},\sigma^2 = n\cdot\sigma^2_{X_i}\right) $$ The mean of a single dice roll ($X_i$) is 3.5 and the variance is 35/12. That should help you find the answer.
Probability of a certain sum of values from a set of dice rolls
Due to the CLT, a sum of i.i.d. random variables is distributed: $$ \sum_{i=1}^nX_i \sim N\left(\mu =n\cdot\mu_{X_i},\sigma^2 = n\cdot\sigma^2_{X_i}\right) $$ The mean of a single dice roll ($X_i$)
Probability of a certain sum of values from a set of dice rolls Due to the CLT, a sum of i.i.d. random variables is distributed: $$ \sum_{i=1}^nX_i \sim N\left(\mu =n\cdot\mu_{X_i},\sigma^2 = n\cdot\sigma^2_{X_i}\right) $$ The mean of a single dice roll ($X_i$) is 3.5 and the variance is 35/12. That should help you find the answer.
Probability of a certain sum of values from a set of dice rolls Due to the CLT, a sum of i.i.d. random variables is distributed: $$ \sum_{i=1}^nX_i \sim N\left(\mu =n\cdot\mu_{X_i},\sigma^2 = n\cdot\sigma^2_{X_i}\right) $$ The mean of a single dice roll ($X_i$)
40,874
Difference in means in multiple-choice poll
Find out if there's any difference at all through Pearson's Chi Square. If this turns out significant, then do a (set of) post-hoc test(s), e.g. Tukey's HSD.
Difference in means in multiple-choice poll
Find out if there's any difference at all through Pearson's Chi Square. If this turns out significant, then do a (set of) post-hoc test(s), e.g. Tukey's HSD.
Difference in means in multiple-choice poll Find out if there's any difference at all through Pearson's Chi Square. If this turns out significant, then do a (set of) post-hoc test(s), e.g. Tukey's HSD.
Difference in means in multiple-choice poll Find out if there's any difference at all through Pearson's Chi Square. If this turns out significant, then do a (set of) post-hoc test(s), e.g. Tukey's HSD.
40,875
Difference in means in multiple-choice poll
You would need to use the "Simultaneous Score Intervals for Difference of Proportions" to solve your question. The reference is " Agresti et al. 2008. Simultaneous confidence interval for comparing binomial parameters. Biometrics 64, 1270-1275. The corresponding R code is available in http://www.stat.ufl.edu/~aa/cda/software.html Sincerely,
Difference in means in multiple-choice poll
You would need to use the "Simultaneous Score Intervals for Difference of Proportions" to solve your question. The reference is " Agresti et al. 2008. Simultaneous confidence interval for comparing bi
Difference in means in multiple-choice poll You would need to use the "Simultaneous Score Intervals for Difference of Proportions" to solve your question. The reference is " Agresti et al. 2008. Simultaneous confidence interval for comparing binomial parameters. Biometrics 64, 1270-1275. The corresponding R code is available in http://www.stat.ufl.edu/~aa/cda/software.html Sincerely,
Difference in means in multiple-choice poll You would need to use the "Simultaneous Score Intervals for Difference of Proportions" to solve your question. The reference is " Agresti et al. 2008. Simultaneous confidence interval for comparing bi
40,876
Centroid matching problem
Because K-means minimizes variances, a good criterion is to minimize the sum of squared distances between the pairs of points. This is an integral (0/1) linear program. Specifically, the pairing can be specified by a matrix $\Lambda = (\lambda_{ij})$ where $\lambda_{ij} = 1$ if $c_i$ is paired with $k_j$ and $\lambda_{ij}=0$ otherwise. We seek to minimize $$\sum_{i,j}\lambda_{ij}|c_i - k_j|^2$$ subject to the constraints (which enforce the one-to-one pairing) $$\sum_{j}\lambda_{ij}=1$$ $$\sum_{i}\lambda_{ij}=1$$ $$\lambda_{ij} \in\{0,1\}.$$ Provided the centroids do not number more than a few hundred, this is quickly solved. (The matrices involved in setting up the problem will quickly exhaust RAM with more than a few hundred centroids, because they scale as $O(n^3)$, and then you might have to be a little fussier with the programming.) For instance, Mathematica 8's `LinearProgramming' function takes no measurable time with fewer than $n=20$ centroids, escalating to about 5 seconds with 400 centroids. By means of line segments to show the pairings, this figure depicts an optimal solution with $n=20$ bivariate normal centroids $c_i$ and independent bivariate normal K-means solutions $k_i$.
Centroid matching problem
Because K-means minimizes variances, a good criterion is to minimize the sum of squared distances between the pairs of points. This is an integral (0/1) linear program. Specifically, the pairing can
Centroid matching problem Because K-means minimizes variances, a good criterion is to minimize the sum of squared distances between the pairs of points. This is an integral (0/1) linear program. Specifically, the pairing can be specified by a matrix $\Lambda = (\lambda_{ij})$ where $\lambda_{ij} = 1$ if $c_i$ is paired with $k_j$ and $\lambda_{ij}=0$ otherwise. We seek to minimize $$\sum_{i,j}\lambda_{ij}|c_i - k_j|^2$$ subject to the constraints (which enforce the one-to-one pairing) $$\sum_{j}\lambda_{ij}=1$$ $$\sum_{i}\lambda_{ij}=1$$ $$\lambda_{ij} \in\{0,1\}.$$ Provided the centroids do not number more than a few hundred, this is quickly solved. (The matrices involved in setting up the problem will quickly exhaust RAM with more than a few hundred centroids, because they scale as $O(n^3)$, and then you might have to be a little fussier with the programming.) For instance, Mathematica 8's `LinearProgramming' function takes no measurable time with fewer than $n=20$ centroids, escalating to about 5 seconds with 400 centroids. By means of line segments to show the pairings, this figure depicts an optimal solution with $n=20$ bivariate normal centroids $c_i$ and independent bivariate normal K-means solutions $k_i$.
Centroid matching problem Because K-means minimizes variances, a good criterion is to minimize the sum of squared distances between the pairs of points. This is an integral (0/1) linear program. Specifically, the pairing can
40,877
Centroid matching problem
The problem you're trying to solve is a min-cost matching problem, specifically the problem of minimizing the functional $F(\pi) = \sum_i \|c_i - k_{\pi(i)}\|^2 $ where $\pi$ is over all permutations in $S_n$. This can be solved by the Hungarian algorithm (which is a primal-dual method in disguise) and takes $n^3$ time.
Centroid matching problem
The problem you're trying to solve is a min-cost matching problem, specifically the problem of minimizing the functional $F(\pi) = \sum_i \|c_i - k_{\pi(i)}\|^2 $ where $\pi$ is over all permutations
Centroid matching problem The problem you're trying to solve is a min-cost matching problem, specifically the problem of minimizing the functional $F(\pi) = \sum_i \|c_i - k_{\pi(i)}\|^2 $ where $\pi$ is over all permutations in $S_n$. This can be solved by the Hungarian algorithm (which is a primal-dual method in disguise) and takes $n^3$ time.
Centroid matching problem The problem you're trying to solve is a min-cost matching problem, specifically the problem of minimizing the functional $F(\pi) = \sum_i \|c_i - k_{\pi(i)}\|^2 $ where $\pi$ is over all permutations
40,878
Centroid matching problem
Sounds like you might want to consider using/writing an energy function. More here: http://en.wikipedia.org/wiki/Optimization_%28mathematics%29#Multi-objective_optimization I suppose if your number of k centroids is "small" you can run a distance function for all c k pairings and select the set which minimizes total distance as the 'best' solution. Hope that helps - Perry
Centroid matching problem
Sounds like you might want to consider using/writing an energy function. More here: http://en.wikipedia.org/wiki/Optimization_%28mathematics%29#Multi-objective_optimization I suppose if your number
Centroid matching problem Sounds like you might want to consider using/writing an energy function. More here: http://en.wikipedia.org/wiki/Optimization_%28mathematics%29#Multi-objective_optimization I suppose if your number of k centroids is "small" you can run a distance function for all c k pairings and select the set which minimizes total distance as the 'best' solution. Hope that helps - Perry
Centroid matching problem Sounds like you might want to consider using/writing an energy function. More here: http://en.wikipedia.org/wiki/Optimization_%28mathematics%29#Multi-objective_optimization I suppose if your number
40,879
Plotting multiple binhex with the same z levels
Have you thought about using the faceting capabilities within ggplot2 directly? You can allow for free scales as a parameter in the call to facet_wrap(). Here's an example for you: library(ggplot2) library(hexbin) #Sample data.frame. dat <- data.frame( rating = sample(500:2500, 1000, TRUE) , Solar.Radiation = sample(0:1200, 1000, TRUE) , Ambient.Temperature = sample(-10:25, 1000, TRUE) ) #Melt data.frame for plotting dat.m <- melt(dat, id.vars = "rating") #Plotting ggplot(dat.m, aes(value, rating, fill = ..density..)) + stat_binhex(na.rm = TRUE) + opts(aspect.ratio = 1) + facet_wrap(facets = ~ variable, scales = "free_x")
Plotting multiple binhex with the same z levels
Have you thought about using the faceting capabilities within ggplot2 directly? You can allow for free scales as a parameter in the call to facet_wrap(). Here's an example for you: library(ggplot2) li
Plotting multiple binhex with the same z levels Have you thought about using the faceting capabilities within ggplot2 directly? You can allow for free scales as a parameter in the call to facet_wrap(). Here's an example for you: library(ggplot2) library(hexbin) #Sample data.frame. dat <- data.frame( rating = sample(500:2500, 1000, TRUE) , Solar.Radiation = sample(0:1200, 1000, TRUE) , Ambient.Temperature = sample(-10:25, 1000, TRUE) ) #Melt data.frame for plotting dat.m <- melt(dat, id.vars = "rating") #Plotting ggplot(dat.m, aes(value, rating, fill = ..density..)) + stat_binhex(na.rm = TRUE) + opts(aspect.ratio = 1) + facet_wrap(facets = ~ variable, scales = "free_x")
Plotting multiple binhex with the same z levels Have you thought about using the faceting capabilities within ggplot2 directly? You can allow for free scales as a parameter in the call to facet_wrap(). Here's an example for you: library(ggplot2) li
40,880
Linear model with random coefficient
I will try to answer the questions 2 to 4. Suppose that we observe sample $(y_i,\mathbf{x}_i,z_i,\gamma_i,\varepsilon_i)$. Suppose that our model is $$y_i=\mathbf{x}_i\beta+\gamma_iz_i+\varepsilon_i$$ and $$E(\varepsilon_i|\mathbf{x}_i,z_i,\gamma_i)=0.$$ The least squares estimate of the regression will be \begin{align} (\hat{\beta},\hat{\gamma})'=\left(\sum_{i=1}^n \begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix} [\mathbf{x}_i,z_i]\right)^{-1}\sum_{i=1}^n\begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix}y_i \end{align} Now since we assumed sample due to law of large numbers we get that \begin{align} \frac{1}{n}\sum_{i=1}^n \begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix} [\mathbf{x}_i,z_i]\to \begin{bmatrix} E\mathbf{x}_1'\mathbf{x}_1 & E\mathbf{x_1}'z_1\\ E\mathbf{x}_1z_1 & Ez_1^2 \end{bmatrix} \end{align} Now \begin{align} \sum_{i=1}^n\begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix}y_i=\sum_{i=1}^n\begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix}\varepsilon_i+\sum_{i=1}^n \begin{bmatrix} \mathbf{x}_i'\mathbf{x}_i\beta +\mathbf{x}_i'z_i\gamma_i \\ \mathbf{x}_iz_i\beta + z_i^2\gamma_i \end{bmatrix} \end{align} Due to law of large numbers and our conditional expectation condition we get that \begin{align} \frac{1}{n}\sum_{i=1}^n\begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix}\varepsilon_i\to 0. \end{align} Now comes the part where we need more assumptions. Assume that $(\mathbf{x}_i,z_i)$ is independent of the $\gamma_i$. Then due to law of large numbers \begin{align} \frac{1}{n}\sum_{i=1}^n\mathbf{x}_iz_i\gamma_i\to E\mathbf{x}_1z_1\gamma_1=pE\mathbf{x}_1z_1 \end{align} where $p=P(\gamma_i=1)$. Similarly \begin{align} \frac{1}{n}\sum_{i=1}^nz_i^2\gamma_i\to Ez_1^2\gamma_1=pEz_1^2 \end{align} Gathering all the results we get \begin{align} (\hat{\beta},\hat{\gamma})'\to \left(\begin{bmatrix} E\mathbf{x}_1'\mathbf{x}_1 & E\mathbf{x_1}'z_1\\ E\mathbf{x}_1z_1 & Ez_1^2 \end{bmatrix}\right)^{-1}\begin{bmatrix} E\mathbf{x}_1'\mathbf{x}_1\beta + pE\mathbf{x_1}'z_1\\ E\mathbf{x}_1z_1\beta + pEz_1^2 \end{bmatrix}=(\beta,p)' \end{align} So the answer to second question is yes. Simple experiment in R confirms this: > g<-sample(0:1,1000,prob=c(1/3,1-1/3),replace=TRUE) > z <- rnorm(1000) > y<-1+g*z+rnorm(1000)/3 > dt <- data.frame(y=y,z=z) > lm(y~z,data=dt) Call: lm(formula = y ~ z, data = dt) Coefficients: (Intercept) z 1.0050 0.6595 Now let us proceed to question 3. Introduce notation $X_i=(\mathbf{x}_i,z_i)$. Then \begin{align} \sqrt{n}\begin{bmatrix} \hat{\beta}-\beta\\ \hat{\gamma}-p \end{bmatrix}=\left(\frac{1}{n}\sum_{i=1}^nX_i'X_i\right)^{-1}\frac{1}{\sqrt{n}}\left(\sum_{i=1}^nX_i'\varepsilon_i+\sum_{i=1}^n \begin{bmatrix} \mathbf{x}_i'z_i\\\ z_i^2 \end{bmatrix}(\gamma_i-p)\right) \end{align} Introduce notation $Z_i=(\mathbf{x}_iz_i,z_i^2)$ and $C_i=(X_i\varepsilon_i,Z_i(\gamma_i-p))$. We have that $EC_i=0$ and since we have sample we can apply multivariate central limit theorem for $C_i$: \begin{align} \frac{1}{\sqrt{n}}\sum_{i=1}^nC_i'\to N(0,\Sigma_C) \end{align} where \begin{align} \Sigma_C=EC_i'C_i&= \begin{bmatrix} EX_1'X_1\varepsilon_1^2 & EX_1'Z_1\varepsilon_1(\gamma_1-p)\\ EZ_1'X_1\varepsilon_1(\gamma_1-p) & EZ_1'Z_1(\gamma_1-p)^2 \end{bmatrix}\\ &=\begin{bmatrix} EX_1'X_1\varepsilon_1^2 & 0\\ 0 & EZ_1'Z_1(\gamma_1-p)^2 \end{bmatrix} \end{align} due to condition $E(\varepsilon_i|\mathbf{x}_i,z_i,\gamma_i)=0$. Now assume further that $E(\varepsilon_i^2|\mathbf{x}_i,z_i,\gamma_i)=\sigma^2$. Denote \begin{align} \mathbf{A}=EX_1'X_1, \quad \mathbf{B}=EZ_1'Z_1 \end{align} Then we get \begin{align} \left(\frac{1}{n}\sum_{i=1}^nX_i'X_i\right)^{-1}\frac{1}{\sqrt{n}}\left(\sum_{i=1}^nX_i'\varepsilon_i+\sum_{i=1}^n \begin{bmatrix} \mathbf{x}_i'z_i\\\ z_i^2 \end{bmatrix}(\gamma_i-p)\right)\to N(0,\sigma^2A+p(1-p)B) \end{align} so \begin{align} \sqrt{n}\begin{bmatrix} \hat{\beta}-\beta\\ \hat{\gamma}-p \end{bmatrix}\to N(0,\sigma^2A^{-1}+p(1-p)A^{-1}BA^{-1}) \end{align} This should give an idea how to construct the test for testing $H_0:p=p_0$. I am not happy about the presence of $p$ in the variance matrix, this could pose some problems. Now given the above the answer to the fourth question is that random coefficient influences only the covariance matrix of the other coefficients. If there is bias, it vanishes asymptotically. I should note that the way I derived these results is pretty straightforward application of LLN and CLT. If there is some elegant way to avoid this I would really like to know.
Linear model with random coefficient
I will try to answer the questions 2 to 4. Suppose that we observe sample $(y_i,\mathbf{x}_i,z_i,\gamma_i,\varepsilon_i)$. Suppose that our model is $$y_i=\mathbf{x}_i\beta+\gamma_iz_i+\varepsilon_i$
Linear model with random coefficient I will try to answer the questions 2 to 4. Suppose that we observe sample $(y_i,\mathbf{x}_i,z_i,\gamma_i,\varepsilon_i)$. Suppose that our model is $$y_i=\mathbf{x}_i\beta+\gamma_iz_i+\varepsilon_i$$ and $$E(\varepsilon_i|\mathbf{x}_i,z_i,\gamma_i)=0.$$ The least squares estimate of the regression will be \begin{align} (\hat{\beta},\hat{\gamma})'=\left(\sum_{i=1}^n \begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix} [\mathbf{x}_i,z_i]\right)^{-1}\sum_{i=1}^n\begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix}y_i \end{align} Now since we assumed sample due to law of large numbers we get that \begin{align} \frac{1}{n}\sum_{i=1}^n \begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix} [\mathbf{x}_i,z_i]\to \begin{bmatrix} E\mathbf{x}_1'\mathbf{x}_1 & E\mathbf{x_1}'z_1\\ E\mathbf{x}_1z_1 & Ez_1^2 \end{bmatrix} \end{align} Now \begin{align} \sum_{i=1}^n\begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix}y_i=\sum_{i=1}^n\begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix}\varepsilon_i+\sum_{i=1}^n \begin{bmatrix} \mathbf{x}_i'\mathbf{x}_i\beta +\mathbf{x}_i'z_i\gamma_i \\ \mathbf{x}_iz_i\beta + z_i^2\gamma_i \end{bmatrix} \end{align} Due to law of large numbers and our conditional expectation condition we get that \begin{align} \frac{1}{n}\sum_{i=1}^n\begin{bmatrix} \mathbf{x}_i'\\ z_i \end{bmatrix}\varepsilon_i\to 0. \end{align} Now comes the part where we need more assumptions. Assume that $(\mathbf{x}_i,z_i)$ is independent of the $\gamma_i$. Then due to law of large numbers \begin{align} \frac{1}{n}\sum_{i=1}^n\mathbf{x}_iz_i\gamma_i\to E\mathbf{x}_1z_1\gamma_1=pE\mathbf{x}_1z_1 \end{align} where $p=P(\gamma_i=1)$. Similarly \begin{align} \frac{1}{n}\sum_{i=1}^nz_i^2\gamma_i\to Ez_1^2\gamma_1=pEz_1^2 \end{align} Gathering all the results we get \begin{align} (\hat{\beta},\hat{\gamma})'\to \left(\begin{bmatrix} E\mathbf{x}_1'\mathbf{x}_1 & E\mathbf{x_1}'z_1\\ E\mathbf{x}_1z_1 & Ez_1^2 \end{bmatrix}\right)^{-1}\begin{bmatrix} E\mathbf{x}_1'\mathbf{x}_1\beta + pE\mathbf{x_1}'z_1\\ E\mathbf{x}_1z_1\beta + pEz_1^2 \end{bmatrix}=(\beta,p)' \end{align} So the answer to second question is yes. Simple experiment in R confirms this: > g<-sample(0:1,1000,prob=c(1/3,1-1/3),replace=TRUE) > z <- rnorm(1000) > y<-1+g*z+rnorm(1000)/3 > dt <- data.frame(y=y,z=z) > lm(y~z,data=dt) Call: lm(formula = y ~ z, data = dt) Coefficients: (Intercept) z 1.0050 0.6595 Now let us proceed to question 3. Introduce notation $X_i=(\mathbf{x}_i,z_i)$. Then \begin{align} \sqrt{n}\begin{bmatrix} \hat{\beta}-\beta\\ \hat{\gamma}-p \end{bmatrix}=\left(\frac{1}{n}\sum_{i=1}^nX_i'X_i\right)^{-1}\frac{1}{\sqrt{n}}\left(\sum_{i=1}^nX_i'\varepsilon_i+\sum_{i=1}^n \begin{bmatrix} \mathbf{x}_i'z_i\\\ z_i^2 \end{bmatrix}(\gamma_i-p)\right) \end{align} Introduce notation $Z_i=(\mathbf{x}_iz_i,z_i^2)$ and $C_i=(X_i\varepsilon_i,Z_i(\gamma_i-p))$. We have that $EC_i=0$ and since we have sample we can apply multivariate central limit theorem for $C_i$: \begin{align} \frac{1}{\sqrt{n}}\sum_{i=1}^nC_i'\to N(0,\Sigma_C) \end{align} where \begin{align} \Sigma_C=EC_i'C_i&= \begin{bmatrix} EX_1'X_1\varepsilon_1^2 & EX_1'Z_1\varepsilon_1(\gamma_1-p)\\ EZ_1'X_1\varepsilon_1(\gamma_1-p) & EZ_1'Z_1(\gamma_1-p)^2 \end{bmatrix}\\ &=\begin{bmatrix} EX_1'X_1\varepsilon_1^2 & 0\\ 0 & EZ_1'Z_1(\gamma_1-p)^2 \end{bmatrix} \end{align} due to condition $E(\varepsilon_i|\mathbf{x}_i,z_i,\gamma_i)=0$. Now assume further that $E(\varepsilon_i^2|\mathbf{x}_i,z_i,\gamma_i)=\sigma^2$. Denote \begin{align} \mathbf{A}=EX_1'X_1, \quad \mathbf{B}=EZ_1'Z_1 \end{align} Then we get \begin{align} \left(\frac{1}{n}\sum_{i=1}^nX_i'X_i\right)^{-1}\frac{1}{\sqrt{n}}\left(\sum_{i=1}^nX_i'\varepsilon_i+\sum_{i=1}^n \begin{bmatrix} \mathbf{x}_i'z_i\\\ z_i^2 \end{bmatrix}(\gamma_i-p)\right)\to N(0,\sigma^2A+p(1-p)B) \end{align} so \begin{align} \sqrt{n}\begin{bmatrix} \hat{\beta}-\beta\\ \hat{\gamma}-p \end{bmatrix}\to N(0,\sigma^2A^{-1}+p(1-p)A^{-1}BA^{-1}) \end{align} This should give an idea how to construct the test for testing $H_0:p=p_0$. I am not happy about the presence of $p$ in the variance matrix, this could pose some problems. Now given the above the answer to the fourth question is that random coefficient influences only the covariance matrix of the other coefficients. If there is bias, it vanishes asymptotically. I should note that the way I derived these results is pretty straightforward application of LLN and CLT. If there is some elegant way to avoid this I would really like to know.
Linear model with random coefficient I will try to answer the questions 2 to 4. Suppose that we observe sample $(y_i,\mathbf{x}_i,z_i,\gamma_i,\varepsilon_i)$. Suppose that our model is $$y_i=\mathbf{x}_i\beta+\gamma_iz_i+\varepsilon_i$
40,881
Linear model with random coefficient
Maybe I'm missing something here, but couldn't you rearrange the equation and do a logit or probit analysis on gamma?
Linear model with random coefficient
Maybe I'm missing something here, but couldn't you rearrange the equation and do a logit or probit analysis on gamma?
Linear model with random coefficient Maybe I'm missing something here, but couldn't you rearrange the equation and do a logit or probit analysis on gamma?
Linear model with random coefficient Maybe I'm missing something here, but couldn't you rearrange the equation and do a logit or probit analysis on gamma?
40,882
Is the matrix dimension important for performing a valid PCA?
PCA of variables. Number of observations n is low relative to number of variables. 1) Mathematical aspect. Whenever n<=m correlation matrix is singular which means some of last m principle components are zero-variance, that is, they are not existant. This is not a problem to PCA, generally speaking, since you could just ignore those. However, many software (mostly those uniting PCA and Factor Analysis in one command or procedure) will not allow you to have singular correlation matrix. 2) Statistical aspect. To have your results reliable you must have correlations reliable; that requires considerable sample size which always should be larger than number of variables. They say, if you have m=20 you ought to have n=100 or so. But if you have m=100 you should have n=300 or so. As m grows, minimal recommended n/m proportion diminishes.
Is the matrix dimension important for performing a valid PCA?
PCA of variables. Number of observations n is low relative to number of variables. 1) Mathematical aspect. Whenever n<=m correlation matrix is singular which means some of last m principle components
Is the matrix dimension important for performing a valid PCA? PCA of variables. Number of observations n is low relative to number of variables. 1) Mathematical aspect. Whenever n<=m correlation matrix is singular which means some of last m principle components are zero-variance, that is, they are not existant. This is not a problem to PCA, generally speaking, since you could just ignore those. However, many software (mostly those uniting PCA and Factor Analysis in one command or procedure) will not allow you to have singular correlation matrix. 2) Statistical aspect. To have your results reliable you must have correlations reliable; that requires considerable sample size which always should be larger than number of variables. They say, if you have m=20 you ought to have n=100 or so. But if you have m=100 you should have n=300 or so. As m grows, minimal recommended n/m proportion diminishes.
Is the matrix dimension important for performing a valid PCA? PCA of variables. Number of observations n is low relative to number of variables. 1) Mathematical aspect. Whenever n<=m correlation matrix is singular which means some of last m principle components
40,883
Is the matrix dimension important for performing a valid PCA?
Matrix dimension by itself have little todo with PCA validity. What will change is the interpretation of your data and it's all dependent on how you want to use the result. PCA is very powerful to use to find anomalys or outliers in your data. Maybe you have performed an experiment on two different days, used different machines in the experiment etc. If the purpose is to get an overview of data PCA is one of the most efficient way to do that regardless of any n/m ratios. If your main interest is to investigate clusters or relations between samples, then #variables are not very important. (But other type of statistics on the result might be important if #samples are low). If you look at individual variables, then they will be less reliable if you have few samples. However, this is a problem you will have with any other method as well. If you find patterns among variables that make sense then you should certainly not disregard your findings because you have a low n/m ratio. However, few observations are almost allways problematic and should lead to caution in interpretation and the more samples you have the less important is the #sample/#variable relation.
Is the matrix dimension important for performing a valid PCA?
Matrix dimension by itself have little todo with PCA validity. What will change is the interpretation of your data and it's all dependent on how you want to use the result. PCA is very powerful to us
Is the matrix dimension important for performing a valid PCA? Matrix dimension by itself have little todo with PCA validity. What will change is the interpretation of your data and it's all dependent on how you want to use the result. PCA is very powerful to use to find anomalys or outliers in your data. Maybe you have performed an experiment on two different days, used different machines in the experiment etc. If the purpose is to get an overview of data PCA is one of the most efficient way to do that regardless of any n/m ratios. If your main interest is to investigate clusters or relations between samples, then #variables are not very important. (But other type of statistics on the result might be important if #samples are low). If you look at individual variables, then they will be less reliable if you have few samples. However, this is a problem you will have with any other method as well. If you find patterns among variables that make sense then you should certainly not disregard your findings because you have a low n/m ratio. However, few observations are almost allways problematic and should lead to caution in interpretation and the more samples you have the less important is the #sample/#variable relation.
Is the matrix dimension important for performing a valid PCA? Matrix dimension by itself have little todo with PCA validity. What will change is the interpretation of your data and it's all dependent on how you want to use the result. PCA is very powerful to us
40,884
Is the matrix dimension important for performing a valid PCA?
I do not think that you would get any useful information from such an analysis, as lore in my subject area (psychology) suggests a 10;1 ratio in favour of n as a precondition. In some circumstances (where communalities are high) you can get away with 5 or 3 to 1, but a ratio of less than 1 is probably a recipe for disaster.
Is the matrix dimension important for performing a valid PCA?
I do not think that you would get any useful information from such an analysis, as lore in my subject area (psychology) suggests a 10;1 ratio in favour of n as a precondition. In some circumstances (w
Is the matrix dimension important for performing a valid PCA? I do not think that you would get any useful information from such an analysis, as lore in my subject area (psychology) suggests a 10;1 ratio in favour of n as a precondition. In some circumstances (where communalities are high) you can get away with 5 or 3 to 1, but a ratio of less than 1 is probably a recipe for disaster.
Is the matrix dimension important for performing a valid PCA? I do not think that you would get any useful information from such an analysis, as lore in my subject area (psychology) suggests a 10;1 ratio in favour of n as a precondition. In some circumstances (w
40,885
How to calculate the difference of two standard deviations?
The standard deviation of the difference between two independent random variables is the square root of the sum of the squares of their individual standard deviations (easier to express as variances) so in this case $$\sqrt{6.4^2 + 1.5^2} \approx 6.6$$
How to calculate the difference of two standard deviations?
The standard deviation of the difference between two independent random variables is the square root of the sum of the squares of their individual standard deviations (easier to express as variances)
How to calculate the difference of two standard deviations? The standard deviation of the difference between two independent random variables is the square root of the sum of the squares of their individual standard deviations (easier to express as variances) so in this case $$\sqrt{6.4^2 + 1.5^2} \approx 6.6$$
How to calculate the difference of two standard deviations? The standard deviation of the difference between two independent random variables is the square root of the sum of the squares of their individual standard deviations (easier to express as variances)
40,886
The difference between linear SVM and other linear classifiers?
There are two things going on here. Difference between primal and dual problem. The "original" objective function of SVM is to minimize $1/2 ||w||^2$. This is called "primal form". Turns out that the objective function you wrote (the one involving $L_D$) is the dual form of this problem. So the two lead to equivalent solutions and can be used interchangeably. The second formulation you describe is called "soft margin SVM". It is obtained by taking the primal form of (1) above and replacing the constraint $y_i f_w(x_i) \geq 1$ by the penalty term $C \cdot \max(0, 1 - y_i f_w(x_i))$. The effect is that you allow violations of the constraint. This is useful e.g. if your data is not linearly separable. You can obtain a dual formulation of this (similar to your expression with $L_D$) as well.
The difference between linear SVM and other linear classifiers?
There are two things going on here. Difference between primal and dual problem. The "original" objective function of SVM is to minimize $1/2 ||w||^2$. This is called "primal form". Turns out that the
The difference between linear SVM and other linear classifiers? There are two things going on here. Difference between primal and dual problem. The "original" objective function of SVM is to minimize $1/2 ||w||^2$. This is called "primal form". Turns out that the objective function you wrote (the one involving $L_D$) is the dual form of this problem. So the two lead to equivalent solutions and can be used interchangeably. The second formulation you describe is called "soft margin SVM". It is obtained by taking the primal form of (1) above and replacing the constraint $y_i f_w(x_i) \geq 1$ by the penalty term $C \cdot \max(0, 1 - y_i f_w(x_i))$. The effect is that you allow violations of the constraint. This is useful e.g. if your data is not linearly separable. You can obtain a dual formulation of this (similar to your expression with $L_D$) as well.
The difference between linear SVM and other linear classifiers? There are two things going on here. Difference between primal and dual problem. The "original" objective function of SVM is to minimize $1/2 ||w||^2$. This is called "primal form". Turns out that the
40,887
How to express error as a percentage?
It may be meaningful to just divide by the average. E.g. the average number is 1000 and the std is 200, so in a sense this means the actual number can vary by 20% from the baseline. Also, if you could say who the user of the data are and what they are doing with it, it might be useful.
How to express error as a percentage?
It may be meaningful to just divide by the average. E.g. the average number is 1000 and the std is 200, so in a sense this means the actual number can vary by 20% from the baseline. Also, if you could
How to express error as a percentage? It may be meaningful to just divide by the average. E.g. the average number is 1000 and the std is 200, so in a sense this means the actual number can vary by 20% from the baseline. Also, if you could say who the user of the data are and what they are doing with it, it might be useful.
How to express error as a percentage? It may be meaningful to just divide by the average. E.g. the average number is 1000 and the std is 200, so in a sense this means the actual number can vary by 20% from the baseline. Also, if you could
40,888
How to express error as a percentage?
The standard error of the mean tells you how precise your estimate of the mean is; that doesn't seem to capture what you're trying to do. I would use either a) a histogram, if you care mostly about showing variation, or b) a line chart or area chart, if you want to say something about variation while also showing progression over time.
How to express error as a percentage?
The standard error of the mean tells you how precise your estimate of the mean is; that doesn't seem to capture what you're trying to do. I would use either a) a histogram, if you care mostly about s
How to express error as a percentage? The standard error of the mean tells you how precise your estimate of the mean is; that doesn't seem to capture what you're trying to do. I would use either a) a histogram, if you care mostly about showing variation, or b) a line chart or area chart, if you want to say something about variation while also showing progression over time.
How to express error as a percentage? The standard error of the mean tells you how precise your estimate of the mean is; that doesn't seem to capture what you're trying to do. I would use either a) a histogram, if you care mostly about s
40,889
How to express error as a percentage?
Assuming your distribution remotely resembles a normal curve, you could convert the standard errors into a more intuitive percentage value pretty easily. For example, if the distribution is pretty normal, approximately 95% of your population falls within +/-1.96*SE of the mean. Building from SheldonCooper's sample values, you could say, "The average was 1000 and about 95% of the population was between 600 and 1400." Likewise, about 70% of the population falls within +/- 1*SE, etc. If your sample distribution tends to deviate from normal by a lot, don't despair, but try to provide more details so we can help.
How to express error as a percentage?
Assuming your distribution remotely resembles a normal curve, you could convert the standard errors into a more intuitive percentage value pretty easily. For example, if the distribution is pretty nor
How to express error as a percentage? Assuming your distribution remotely resembles a normal curve, you could convert the standard errors into a more intuitive percentage value pretty easily. For example, if the distribution is pretty normal, approximately 95% of your population falls within +/-1.96*SE of the mean. Building from SheldonCooper's sample values, you could say, "The average was 1000 and about 95% of the population was between 600 and 1400." Likewise, about 70% of the population falls within +/- 1*SE, etc. If your sample distribution tends to deviate from normal by a lot, don't despair, but try to provide more details so we can help.
How to express error as a percentage? Assuming your distribution remotely resembles a normal curve, you could convert the standard errors into a more intuitive percentage value pretty easily. For example, if the distribution is pretty nor
40,890
How to express error as a percentage?
As @rolando2 mentioned, the histogram might be a tool for displaying the variations; and also, as @ashaw stated, you might need to find where 95% percentage of number go to, then, you can probably just use box plot to generate the basic features of your dataset, and put the data to the dashboard that is shown in the company without the box plot. For box plot, you might check here: http://en.wikipedia.org/wiki/Box_plot Hope this helps, at least for inspiration...
How to express error as a percentage?
As @rolando2 mentioned, the histogram might be a tool for displaying the variations; and also, as @ashaw stated, you might need to find where 95% percentage of number go to, then, you can probably jus
How to express error as a percentage? As @rolando2 mentioned, the histogram might be a tool for displaying the variations; and also, as @ashaw stated, you might need to find where 95% percentage of number go to, then, you can probably just use box plot to generate the basic features of your dataset, and put the data to the dashboard that is shown in the company without the box plot. For box plot, you might check here: http://en.wikipedia.org/wiki/Box_plot Hope this helps, at least for inspiration...
How to express error as a percentage? As @rolando2 mentioned, the histogram might be a tool for displaying the variations; and also, as @ashaw stated, you might need to find where 95% percentage of number go to, then, you can probably jus
40,891
How to express error as a percentage?
$$\text{Percent Error} = \frac{\text{Error}}{\text{Theoretical value}}\times 100$$
How to express error as a percentage?
$$\text{Percent Error} = \frac{\text{Error}}{\text{Theoretical value}}\times 100$$
How to express error as a percentage? $$\text{Percent Error} = \frac{\text{Error}}{\text{Theoretical value}}\times 100$$
How to express error as a percentage? $$\text{Percent Error} = \frac{\text{Error}}{\text{Theoretical value}}\times 100$$
40,892
How to express error as a percentage?
The more intuitive form to express the Standard Error in terms of percent is called Relative Standard Error $(RSE)$ which is the expression of the Standard Error $(SE)$ as percent, this is the formula: $$ RSE\%=\frac{SE}{\bar{x}}\times 100 $$ where, $RSE\%$ is the Relative Standard Error in percent $SE$ is the Standard Error $\bar{x}$ is the mean value of the sample and, $$ SE=\frac{\sigma}{\sqrt{n}} $$ where, $\sigma$ is the sample standard deviation, and $n$ is the size (number of observations) of the sample. I was dealing time before with the same problem because I had many variables with different units, and I found the $RSE$ as a good alternative to show my results. I hope it can be useful for you too. You can find additional information here: Australian Bureau of Statistics, and Investopedia. Regards
How to express error as a percentage?
The more intuitive form to express the Standard Error in terms of percent is called Relative Standard Error $(RSE)$ which is the expression of the Standard Error $(SE)$ as percent, this is the formul
How to express error as a percentage? The more intuitive form to express the Standard Error in terms of percent is called Relative Standard Error $(RSE)$ which is the expression of the Standard Error $(SE)$ as percent, this is the formula: $$ RSE\%=\frac{SE}{\bar{x}}\times 100 $$ where, $RSE\%$ is the Relative Standard Error in percent $SE$ is the Standard Error $\bar{x}$ is the mean value of the sample and, $$ SE=\frac{\sigma}{\sqrt{n}} $$ where, $\sigma$ is the sample standard deviation, and $n$ is the size (number of observations) of the sample. I was dealing time before with the same problem because I had many variables with different units, and I found the $RSE$ as a good alternative to show my results. I hope it can be useful for you too. You can find additional information here: Australian Bureau of Statistics, and Investopedia. Regards
How to express error as a percentage? The more intuitive form to express the Standard Error in terms of percent is called Relative Standard Error $(RSE)$ which is the expression of the Standard Error $(SE)$ as percent, this is the formul
40,893
Analysis of covariance in R
Here is a detailed presentation
Analysis of covariance in R
Here is a detailed presentation
Analysis of covariance in R Here is a detailed presentation
Analysis of covariance in R Here is a detailed presentation
40,894
Analysis of covariance in R
This is a very clear presentation from a biologist: R in Ecology & Evolution: Comparing two regression slopes by means of an ANCOVA
Analysis of covariance in R
This is a very clear presentation from a biologist: R in Ecology & Evolution: Comparing two regression slopes by means of an ANCOVA
Analysis of covariance in R This is a very clear presentation from a biologist: R in Ecology & Evolution: Comparing two regression slopes by means of an ANCOVA
Analysis of covariance in R This is a very clear presentation from a biologist: R in Ecology & Evolution: Comparing two regression slopes by means of an ANCOVA
40,895
Reading in SVM files in R (libsvm)
The e1071 package has a means for exporting to the libsvm "svm" format in the write.svm function. But to the best of my knowledge, there is no read.svm function.
Reading in SVM files in R (libsvm)
The e1071 package has a means for exporting to the libsvm "svm" format in the write.svm function. But to the best of my knowledge, there is no read.svm function.
Reading in SVM files in R (libsvm) The e1071 package has a means for exporting to the libsvm "svm" format in the write.svm function. But to the best of my knowledge, there is no read.svm function.
Reading in SVM files in R (libsvm) The e1071 package has a means for exporting to the libsvm "svm" format in the write.svm function. But to the best of my knowledge, there is no read.svm function.
40,896
Reading in SVM files in R (libsvm)
I found a way that is at least now feasible. Instead of the sparseM package I use the Matrix package to build the sparse matrices. Store the entries and columns in separate lists and then build the matrix by: data=sparseMatrix(i=rep(1,length[[1]]),j=columns[[loop]], x=entires[[loop]],dims=c(120000,47235)) for(loop in 2:120000){ if(loop %% 1000==0){ print(loop) print(Sys.time()) } data[loop,columns[[loop]]]=entries[[loop]] } This still takes awhile (about 2 hours) but at least it works. I store the corresponding classes in another list not in the sparse matrix.
Reading in SVM files in R (libsvm)
I found a way that is at least now feasible. Instead of the sparseM package I use the Matrix package to build the sparse matrices. Store the entries and columns in separate lists and then build the m
Reading in SVM files in R (libsvm) I found a way that is at least now feasible. Instead of the sparseM package I use the Matrix package to build the sparse matrices. Store the entries and columns in separate lists and then build the matrix by: data=sparseMatrix(i=rep(1,length[[1]]),j=columns[[loop]], x=entires[[loop]],dims=c(120000,47235)) for(loop in 2:120000){ if(loop %% 1000==0){ print(loop) print(Sys.time()) } data[loop,columns[[loop]]]=entries[[loop]] } This still takes awhile (about 2 hours) but at least it works. I store the corresponding classes in another list not in the sparse matrix.
Reading in SVM files in R (libsvm) I found a way that is at least now feasible. Instead of the sparseM package I use the Matrix package to build the sparse matrices. Store the entries and columns in separate lists and then build the m
40,897
Estimation of probability of a success in binomial distribution
The estimator is biased, regardless. Note first that $\alpha$ is not identifiable because you cannot distinguish between $\alpha$ and $1-\alpha$. Let's accommodate this problem by allowing that we don't care which coin is which and stipulating (arbitrarily, but with no loss of generality), that $0 \le \alpha \le 1/2$. It's reasonable, and conventional, to fix the estimator $g$ as follows: $$\eqalign{ g(k,n) =& \frac{1 - \sqrt{\delta}}{2} \cr \delta =& \max(0, 1 - 4 k / n) }$$ No matter what you do, though, this will be a nonlinear function of the outcome $k$ and therefore is certain to be biased for almost all $\alpha$. A better approach is to search for estimators $h(k,n)$ among some functional class of estimators (such as ones that are linear in $k$) that minimize the expectation of some loss function. In many situations an estimator that works well for quadratic loss also works well for many reasonable types of losses, so let's look at this. What we're talking about, then, is (for each $n$) to minimize the expectation $\mathbb{E}[(h(k,n) - \alpha)^2]$ among all estimators $h$. Let's look graphically at what's going on. The bias of any estimator $h$ of the parameter $\alpha$ is the difference between its expectation and the parameter, $\mathbb{E}[h(k,n) - \alpha]$. We can study any proposed estimator, then, by graphing its bias (if we really care about that) and its loss. For any value of $n$ they are functions of $\alpha$, which (of course) is unknown. That's why we have to look at the entire graph. Here are the bias (blue, dashed) and square root of the expected quadratic loss (red) for $g$ when $n=16$: (I use the root of the loss because this is directly comparable to the bias.) For example, $g$ is unbiased for $\alpha \approx 1/3$ but otherwise is biased, with the size of the bias largest for $\alpha = 1/2$. The root expected loss is roughly between 0.15 and 0.2 provided $\alpha$ exceeds $1/6$, approximately. As an alternative, consider linear estimators $h_\lambda(k,n)$ of the form $h_\lambda(k,n) = \lambda(n) k/n$. Here is a plot of $h_2$ also for $n=16$ (but please note the change in scale on the vertical axis): For most $\alpha$ its bias exceeds that of $g$, but for some $\alpha$ (near 0.4) it actually has less bias. For a wide range of $\alpha$, though, its root expected loss is less than that of $g$. Provided $\alpha \gt 1/5$ or so, this simple estimator clearly outperforms the "obvious" one! This is not necessarily "the best" linear estimator, however. To illustrate, here is a plot of $h_{4/3}$: It outperforms both $g$ and $h_2$ for $1/8 \lt \alpha \lt 3/8$, approximately. Note, though, that $g$ outperforms the $h_{\lambda}$ for sufficiently small $\alpha$. These considerations suggest there is value in knowing something about what $\alpha$ might be: that will tell you which portions of the loss graphs to focus on in selecting among alternative estimators. If, in addition, you have a prior distribution for $\alpha$ you can compute the expected loss (this is now a single number) and use that to compare estimators: your task becomes one of finding an estimator with lowest possible expected loss. This, of course, is a Bayesian estimator. Regardless, using plots of expected loss is a standard and effective way to compare estimators and to choose ones that are appropriate for any particular problem.
Estimation of probability of a success in binomial distribution
The estimator is biased, regardless. Note first that $\alpha$ is not identifiable because you cannot distinguish between $\alpha$ and $1-\alpha$. Let's accommodate this problem by allowing that we
Estimation of probability of a success in binomial distribution The estimator is biased, regardless. Note first that $\alpha$ is not identifiable because you cannot distinguish between $\alpha$ and $1-\alpha$. Let's accommodate this problem by allowing that we don't care which coin is which and stipulating (arbitrarily, but with no loss of generality), that $0 \le \alpha \le 1/2$. It's reasonable, and conventional, to fix the estimator $g$ as follows: $$\eqalign{ g(k,n) =& \frac{1 - \sqrt{\delta}}{2} \cr \delta =& \max(0, 1 - 4 k / n) }$$ No matter what you do, though, this will be a nonlinear function of the outcome $k$ and therefore is certain to be biased for almost all $\alpha$. A better approach is to search for estimators $h(k,n)$ among some functional class of estimators (such as ones that are linear in $k$) that minimize the expectation of some loss function. In many situations an estimator that works well for quadratic loss also works well for many reasonable types of losses, so let's look at this. What we're talking about, then, is (for each $n$) to minimize the expectation $\mathbb{E}[(h(k,n) - \alpha)^2]$ among all estimators $h$. Let's look graphically at what's going on. The bias of any estimator $h$ of the parameter $\alpha$ is the difference between its expectation and the parameter, $\mathbb{E}[h(k,n) - \alpha]$. We can study any proposed estimator, then, by graphing its bias (if we really care about that) and its loss. For any value of $n$ they are functions of $\alpha$, which (of course) is unknown. That's why we have to look at the entire graph. Here are the bias (blue, dashed) and square root of the expected quadratic loss (red) for $g$ when $n=16$: (I use the root of the loss because this is directly comparable to the bias.) For example, $g$ is unbiased for $\alpha \approx 1/3$ but otherwise is biased, with the size of the bias largest for $\alpha = 1/2$. The root expected loss is roughly between 0.15 and 0.2 provided $\alpha$ exceeds $1/6$, approximately. As an alternative, consider linear estimators $h_\lambda(k,n)$ of the form $h_\lambda(k,n) = \lambda(n) k/n$. Here is a plot of $h_2$ also for $n=16$ (but please note the change in scale on the vertical axis): For most $\alpha$ its bias exceeds that of $g$, but for some $\alpha$ (near 0.4) it actually has less bias. For a wide range of $\alpha$, though, its root expected loss is less than that of $g$. Provided $\alpha \gt 1/5$ or so, this simple estimator clearly outperforms the "obvious" one! This is not necessarily "the best" linear estimator, however. To illustrate, here is a plot of $h_{4/3}$: It outperforms both $g$ and $h_2$ for $1/8 \lt \alpha \lt 3/8$, approximately. Note, though, that $g$ outperforms the $h_{\lambda}$ for sufficiently small $\alpha$. These considerations suggest there is value in knowing something about what $\alpha$ might be: that will tell you which portions of the loss graphs to focus on in selecting among alternative estimators. If, in addition, you have a prior distribution for $\alpha$ you can compute the expected loss (this is now a single number) and use that to compare estimators: your task becomes one of finding an estimator with lowest possible expected loss. This, of course, is a Bayesian estimator. Regardless, using plots of expected loss is a standard and effective way to compare estimators and to choose ones that are appropriate for any particular problem.
Estimation of probability of a success in binomial distribution The estimator is biased, regardless. Note first that $\alpha$ is not identifiable because you cannot distinguish between $\alpha$ and $1-\alpha$. Let's accommodate this problem by allowing that we
40,898
How to tell if the slope of a line is 0 or there is just no relationship?
Well, your colleague definitely is incorrect, as many standard examples will show. For example, for the data $(x, x(1-x))$ with values of $x$ equal to $0, 1/n, 2/n, \ldots, 1$, the slope is exactly zero but obviously there's a strong (quadratic) relationship between "predictor" ($x$) and "response" ($x(1-x)$). Your colleague would be correct to say "there is no significant evidence of a linear relationship in year 2." But you can do more than that, as you know. You can assess the change between the two years. Asserting that the "slope has declined" compares two estimates to each other. As such, you need to account for the uncertainty in both estimates, not just in the one for year two. From the mere fact that one slope is significantly different from zero and the other slope is not, you cannot legitimately conclude their difference is significant. However, a valid comparison is simple to do: associated with each slope is a standard error (a routine part of regression software output) and a degree of freedom (usually equal to the number of data values minus the number of parameters). Assuming no temporal correlation in the error terms, you can compute the standard error for the difference in slopes as usual: take the root of the sum of squares of their SEs. Refer the t-statistic (i.e., the ratio of the slope difference to the SE of their difference) to Student's t distribution. The degree of freedom to use equals the sum of the DFs of the individual slopes. The usual caveats and assumptions about tests hold, of course. But presumably, because you're already using linear regressions in each of the years separately, you have checked that suitable assumptions are reasonable for these data. About the only additional thing you might want to check is that the variances of the residuals are approximately the same in the two years. (You could use an F-test for this.) If not, that's worth exploring further in order to understand just how the change came about. Assuming it was abrupt and there's no sign of temporal trends in the residuals (no heteroscedasticity), you might consider using a t-test for unequal variances instead of the simpler test described above.
How to tell if the slope of a line is 0 or there is just no relationship?
Well, your colleague definitely is incorrect, as many standard examples will show. For example, for the data $(x, x(1-x))$ with values of $x$ equal to $0, 1/n, 2/n, \ldots, 1$, the slope is exactly z
How to tell if the slope of a line is 0 or there is just no relationship? Well, your colleague definitely is incorrect, as many standard examples will show. For example, for the data $(x, x(1-x))$ with values of $x$ equal to $0, 1/n, 2/n, \ldots, 1$, the slope is exactly zero but obviously there's a strong (quadratic) relationship between "predictor" ($x$) and "response" ($x(1-x)$). Your colleague would be correct to say "there is no significant evidence of a linear relationship in year 2." But you can do more than that, as you know. You can assess the change between the two years. Asserting that the "slope has declined" compares two estimates to each other. As such, you need to account for the uncertainty in both estimates, not just in the one for year two. From the mere fact that one slope is significantly different from zero and the other slope is not, you cannot legitimately conclude their difference is significant. However, a valid comparison is simple to do: associated with each slope is a standard error (a routine part of regression software output) and a degree of freedom (usually equal to the number of data values minus the number of parameters). Assuming no temporal correlation in the error terms, you can compute the standard error for the difference in slopes as usual: take the root of the sum of squares of their SEs. Refer the t-statistic (i.e., the ratio of the slope difference to the SE of their difference) to Student's t distribution. The degree of freedom to use equals the sum of the DFs of the individual slopes. The usual caveats and assumptions about tests hold, of course. But presumably, because you're already using linear regressions in each of the years separately, you have checked that suitable assumptions are reasonable for these data. About the only additional thing you might want to check is that the variances of the residuals are approximately the same in the two years. (You could use an F-test for this.) If not, that's worth exploring further in order to understand just how the change came about. Assuming it was abrupt and there's no sign of temporal trends in the residuals (no heteroscedasticity), you might consider using a t-test for unequal variances instead of the simpler test described above.
How to tell if the slope of a line is 0 or there is just no relationship? Well, your colleague definitely is incorrect, as many standard examples will show. For example, for the data $(x, x(1-x))$ with values of $x$ equal to $0, 1/n, 2/n, \ldots, 1$, the slope is exactly z
40,899
How do I setup up repeated measures data for analysis with nlme()?
Yes, you need to set up your data so that each grouping factor, dependendent variable and covariate corresponds to a column and every row contains one observation (i.e. long format): Everything that you enter into the model formulas for the random and fixed parts has to be a column in your data set. You can use reshape to get your data from wide to long format and back. If you are transitioning to R and do a lot of mixed models, try to get a copy of Pinheiro/Bates "Mixed-Effects Models in S and S-PLUS", it's a comprehensive reference from the guys who wrote nlme with a lot of worked examples.
How do I setup up repeated measures data for analysis with nlme()?
Yes, you need to set up your data so that each grouping factor, dependendent variable and covariate corresponds to a column and every row contains one observation (i.e. long format): Everything that y
How do I setup up repeated measures data for analysis with nlme()? Yes, you need to set up your data so that each grouping factor, dependendent variable and covariate corresponds to a column and every row contains one observation (i.e. long format): Everything that you enter into the model formulas for the random and fixed parts has to be a column in your data set. You can use reshape to get your data from wide to long format and back. If you are transitioning to R and do a lot of mixed models, try to get a copy of Pinheiro/Bates "Mixed-Effects Models in S and S-PLUS", it's a comprehensive reference from the guys who wrote nlme with a lot of worked examples.
How do I setup up repeated measures data for analysis with nlme()? Yes, you need to set up your data so that each grouping factor, dependendent variable and covariate corresponds to a column and every row contains one observation (i.e. long format): Everything that y
40,900
How do I setup up repeated measures data for analysis with nlme()?
It's unlikely reshape will help you out if you're coming straight from SPSS files because you not only need it set up differently, you probably need different data than you were using in SPSS. In the standard repeated measures analysis you enter means of each individual condition for each subject into the analysis but for nlme you enter each individual data point. You'll have to go back to the raw data files. If those have a data point on each line and columns to identify the condition of each point then you can just basically concatenate each file together, identifying the separate subjects along the way. Something like the following would work in that case fList <- list.files('myDataF/') dList <- lapply(fList, function(f) {x <- read.table(paste('myDataF', f, sep = '/'), header = TRUE) x$subj <- f return(x)}) myData <- do.call(rbind, dList) (this could be even simpler if you knew that there was exactly the same number of lines in each file)
How do I setup up repeated measures data for analysis with nlme()?
It's unlikely reshape will help you out if you're coming straight from SPSS files because you not only need it set up differently, you probably need different data than you were using in SPSS. In the
How do I setup up repeated measures data for analysis with nlme()? It's unlikely reshape will help you out if you're coming straight from SPSS files because you not only need it set up differently, you probably need different data than you were using in SPSS. In the standard repeated measures analysis you enter means of each individual condition for each subject into the analysis but for nlme you enter each individual data point. You'll have to go back to the raw data files. If those have a data point on each line and columns to identify the condition of each point then you can just basically concatenate each file together, identifying the separate subjects along the way. Something like the following would work in that case fList <- list.files('myDataF/') dList <- lapply(fList, function(f) {x <- read.table(paste('myDataF', f, sep = '/'), header = TRUE) x$subj <- f return(x)}) myData <- do.call(rbind, dList) (this could be even simpler if you knew that there was exactly the same number of lines in each file)
How do I setup up repeated measures data for analysis with nlme()? It's unlikely reshape will help you out if you're coming straight from SPSS files because you not only need it set up differently, you probably need different data than you were using in SPSS. In the