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
36,601
Goodness of fit test on sparse contigency tables with high dimensionality
Instead of an exact test you can do a Chi-squared test based on Monte Carlo simulations. You would make N 2x3500 tables consisting of your "known distribution vector" and each of your N other vectors, and run N tests. For each test, essentially the test is simulating a bunch of tables according to the null hypothesis that the two distributions are the same, and then comparing the observed table with the simulated tables. The paper behind the method can be found here: http://www.jstor.org/stable/2984263?seq=1#page_scan_tab_contents If you use R, the information on the code to do this is available here: https://stat.ethz.ch/R-manual/R-devel/library/stats/html/chisq.test.html You would set simulate.p.value = TRUE The limitation is that you cannot have rows or columns composed of only 0's in the table that you feed to the function. Also unless if you use a seed, each time you run the simulation you will get different p-values.
Goodness of fit test on sparse contigency tables with high dimensionality
Instead of an exact test you can do a Chi-squared test based on Monte Carlo simulations. You would make N 2x3500 tables consisting of your "known distribution vector" and each of your N other vectors,
Goodness of fit test on sparse contigency tables with high dimensionality Instead of an exact test you can do a Chi-squared test based on Monte Carlo simulations. You would make N 2x3500 tables consisting of your "known distribution vector" and each of your N other vectors, and run N tests. For each test, essentially the test is simulating a bunch of tables according to the null hypothesis that the two distributions are the same, and then comparing the observed table with the simulated tables. The paper behind the method can be found here: http://www.jstor.org/stable/2984263?seq=1#page_scan_tab_contents If you use R, the information on the code to do this is available here: https://stat.ethz.ch/R-manual/R-devel/library/stats/html/chisq.test.html You would set simulate.p.value = TRUE The limitation is that you cannot have rows or columns composed of only 0's in the table that you feed to the function. Also unless if you use a seed, each time you run the simulation you will get different p-values.
Goodness of fit test on sparse contigency tables with high dimensionality Instead of an exact test you can do a Chi-squared test based on Monte Carlo simulations. You would make N 2x3500 tables consisting of your "known distribution vector" and each of your N other vectors,
36,602
Goodness of fit test on sparse contigency tables with high dimensionality
I assume that you want to test whether the number of occurences is independent of the county. In this case, may you can try the following: First, transform your $1\times 3500$ tables to $2\times 3500$ tables (as in this post). Let $T$ be one of the $2\times 3500$ tables you have observed. A test on independence which is independent of the sample size is Fisher's exact test. I don't know how familiar you are with the framework of this test, but roughly speaking it requires to estimate the probability of all $2\times 3500$ that have the same row and column sums as $T$ but a larger $\chi^2$-statistics. For two-rowed tables, there exist efficient algorithms that approximate this $p$-value (have a look at Theorem 4 in this paper). Hope that helps. EDIT: Since it was not clear that my answer describes an approximative method instead of an exact one, I will extend my anwer. Again, let $T$ be one of your observed tables and let $n$ be its sample size (that is, the sum of all its entries). Let $\theta\in[0,1]^{2\times 3500}$ be the log-likelihood estimators for the independence model and define for a table $v\in\mathbb{N}^{2\times 3500}$ the $\chi^2$ statistics as $$\chi^2(v)=\sum_{i=1}^2\sum_{j=1}^{3500}\frac{(v_{ij}-n\cdot\theta_{ij})^2}{n\cdot\theta_{ij}}.$$ Let $\mathcal{F}(T)\subset\mathbb{N}^{2\times 3500}$ be the set of all tables that have the same rows- and column sums than $T$, then the conditional $p$-value of Fisher's exact test is $$\frac{\sum_{v\in\mathcal{F}(T), \chi^2(v)\ge\chi^2(T)} \frac{1}{\prod_{i=1}^2\prod_{j=1}^{3500}v_{ij}!} }{\sum_{v\in\mathcal{F}} \frac{1}{\prod_{i=1}^2\prod_{j=1}^{3500}v_{ij}!}}$$ Of course, this value is impossible to compute exactly, since the size of $\mathcal{F}(T)$ is humongous. However, it can be approximated efficiently with the following adapted version of the algorithm in this paper. For an observed table $T$, do the following Initialize with $i=0$, $w=T$ $i=i+1$ get another table $w'$ from $\mathcal{F}(T)$ by applying one step of the algorithm in this paper (Section 4) With probability $\min\left\{1,\frac{\prod_{ij}w_{ij}!}{\prod_{ij}w'_{ij}!}\right\}$, set $w:=w'$, otherwise let $w$ untouched (that is the Metropolis-Hastings rejection step) If $\chi^2(w)\ge\chi^2(T)$, then $p_i:=1$, otherwise $p_i=0$ If $|\frac{1}{i-1}\sum_{k=1}^{i-1}p_k-\frac{1}{i}\sum_{k=1}^{i}p_k|>tol$, GOTO (2) Return $\frac{1}{i}\sum_{k=1}^ip_k$ The output is an estimation of the conditional $p$-value.
Goodness of fit test on sparse contigency tables with high dimensionality
I assume that you want to test whether the number of occurences is independent of the county. In this case, may you can try the following: First, transform your $1\times 3500$ tables to $2\times 3500
Goodness of fit test on sparse contigency tables with high dimensionality I assume that you want to test whether the number of occurences is independent of the county. In this case, may you can try the following: First, transform your $1\times 3500$ tables to $2\times 3500$ tables (as in this post). Let $T$ be one of the $2\times 3500$ tables you have observed. A test on independence which is independent of the sample size is Fisher's exact test. I don't know how familiar you are with the framework of this test, but roughly speaking it requires to estimate the probability of all $2\times 3500$ that have the same row and column sums as $T$ but a larger $\chi^2$-statistics. For two-rowed tables, there exist efficient algorithms that approximate this $p$-value (have a look at Theorem 4 in this paper). Hope that helps. EDIT: Since it was not clear that my answer describes an approximative method instead of an exact one, I will extend my anwer. Again, let $T$ be one of your observed tables and let $n$ be its sample size (that is, the sum of all its entries). Let $\theta\in[0,1]^{2\times 3500}$ be the log-likelihood estimators for the independence model and define for a table $v\in\mathbb{N}^{2\times 3500}$ the $\chi^2$ statistics as $$\chi^2(v)=\sum_{i=1}^2\sum_{j=1}^{3500}\frac{(v_{ij}-n\cdot\theta_{ij})^2}{n\cdot\theta_{ij}}.$$ Let $\mathcal{F}(T)\subset\mathbb{N}^{2\times 3500}$ be the set of all tables that have the same rows- and column sums than $T$, then the conditional $p$-value of Fisher's exact test is $$\frac{\sum_{v\in\mathcal{F}(T), \chi^2(v)\ge\chi^2(T)} \frac{1}{\prod_{i=1}^2\prod_{j=1}^{3500}v_{ij}!} }{\sum_{v\in\mathcal{F}} \frac{1}{\prod_{i=1}^2\prod_{j=1}^{3500}v_{ij}!}}$$ Of course, this value is impossible to compute exactly, since the size of $\mathcal{F}(T)$ is humongous. However, it can be approximated efficiently with the following adapted version of the algorithm in this paper. For an observed table $T$, do the following Initialize with $i=0$, $w=T$ $i=i+1$ get another table $w'$ from $\mathcal{F}(T)$ by applying one step of the algorithm in this paper (Section 4) With probability $\min\left\{1,\frac{\prod_{ij}w_{ij}!}{\prod_{ij}w'_{ij}!}\right\}$, set $w:=w'$, otherwise let $w$ untouched (that is the Metropolis-Hastings rejection step) If $\chi^2(w)\ge\chi^2(T)$, then $p_i:=1$, otherwise $p_i=0$ If $|\frac{1}{i-1}\sum_{k=1}^{i-1}p_k-\frac{1}{i}\sum_{k=1}^{i}p_k|>tol$, GOTO (2) Return $\frac{1}{i}\sum_{k=1}^ip_k$ The output is an estimation of the conditional $p$-value.
Goodness of fit test on sparse contigency tables with high dimensionality I assume that you want to test whether the number of occurences is independent of the county. In this case, may you can try the following: First, transform your $1\times 3500$ tables to $2\times 3500
36,603
Goodness of fit test on sparse contigency tables with high dimensionality
Hmm... wouldn't you use something like the Gini coefficient (or its related methods). From my understanding they are developed for exactly this kind of situation
Goodness of fit test on sparse contigency tables with high dimensionality
Hmm... wouldn't you use something like the Gini coefficient (or its related methods). From my understanding they are developed for exactly this kind of situation
Goodness of fit test on sparse contigency tables with high dimensionality Hmm... wouldn't you use something like the Gini coefficient (or its related methods). From my understanding they are developed for exactly this kind of situation
Goodness of fit test on sparse contigency tables with high dimensionality Hmm... wouldn't you use something like the Gini coefficient (or its related methods). From my understanding they are developed for exactly this kind of situation
36,604
Probabilistic models for partial least squares, reduced rank regression, and canonical correlation analysis?
Probabilistic canonical correlation analysis (probabilistic CCA, PCCA) was introduced in Bach & Jordan, 2005, A Probabilistic Interpretation of Canonical Correlation Analysis, several years after Tipping & Bishop presented their probabilistic principal component analysis (probabilistic PCA, PPCA). Very briefly, it is based on the following probabilistic model: \begin{align} \newcommand{\z}{\mathbf z} \newcommand{\x}{\mathbf x} \newcommand{\y}{\mathbf y} \newcommand{\m}{\boldsymbol \mu} \newcommand{\P}{\boldsymbol \Psi} \newcommand{\S}{\boldsymbol \Sigma} \newcommand{\W}{\mathbf W} \newcommand{\I}{\mathbf I} \newcommand{\w}{\mathbf w} \newcommand{\u}{\mathbf u} \newcommand{\0}{\mathbf 0} \z &\sim \mathcal N(\0,\I) \\ \x|\z &\sim \mathcal N(\W_x \z + \boldsymbol \m_x, \P_x)\\ \y|\z &\sim \mathcal N(\W_y \z + \boldsymbol \m_y, \P_y) \end{align} Here noise covariances $\P_x$ and $\P_y$ are arbitrary full rank symmetric matrices. If we consider 1-dimensional latent variable $z$, assume that all means are zero $\m_x=\m_y=0$, and combine $\x$ and $\y$ into one vector, then we get: $$\begin{pmatrix} \x\\ \y\end{pmatrix}\sim\mathcal N (\0,\S),\quad\quad\quad\S=\begin{pmatrix}\w_x\w_x^\top+\P_x & \w_x\w_y^\top \\ \w_y\w_x^\top & \w_y\w_y^\top+\P_y\end{pmatrix}.$$ Bach & Jordan proved that this is equivalent to standard CCA. Specifically, the maximum likelihood (ML) solution is given by $$\w_i = \S_i\u_i m_i,$$ where $\S_i$ are sample covariance matrices of both datasets, $\u_i$ is the first canonical pair of axes, and $m_x m_y = \rho_1$ are arbitrary numbers (both between $0$ and $1$) giving first canonical correlation as a product. As you see, $\w_i$ are not directly equal to the CCA axes, but are given by some transformation of those. See Bach & Jordan for more details. I don't have a good intuitive grasp of PCCA. As you can see, the cross-covariance matrix between $X$ and $Y$ is modeled by $\w_x \w_y^\top$, so one could naively expect $\w_i$ to rather yield PLS axes. The ML solution is however related to the CCA axes. It probably is somehow due to the block-diagonal structure of $\P=\begin{pmatrix}\P_x & \0\\ \0 & \P_y\end{pmatrix}$. I am not aware of any similar probabilistic versions of RRR or PLS, and have failed to come up with any myself. Note that if $\P$ is diagonal then we obtain FA on the combined $X+Y$ dataset, and if it is diagonal and isotropic then we get PPCA on the combined dataset. So there is a progression from CCA to FA to PPCA, as $\P$ gets more and more constrained. I don't see what other choices of $\P$ can be reasonable.
Probabilistic models for partial least squares, reduced rank regression, and canonical correlation a
Probabilistic canonical correlation analysis (probabilistic CCA, PCCA) was introduced in Bach & Jordan, 2005, A Probabilistic Interpretation of Canonical Correlation Analysis, several years after Tipp
Probabilistic models for partial least squares, reduced rank regression, and canonical correlation analysis? Probabilistic canonical correlation analysis (probabilistic CCA, PCCA) was introduced in Bach & Jordan, 2005, A Probabilistic Interpretation of Canonical Correlation Analysis, several years after Tipping & Bishop presented their probabilistic principal component analysis (probabilistic PCA, PPCA). Very briefly, it is based on the following probabilistic model: \begin{align} \newcommand{\z}{\mathbf z} \newcommand{\x}{\mathbf x} \newcommand{\y}{\mathbf y} \newcommand{\m}{\boldsymbol \mu} \newcommand{\P}{\boldsymbol \Psi} \newcommand{\S}{\boldsymbol \Sigma} \newcommand{\W}{\mathbf W} \newcommand{\I}{\mathbf I} \newcommand{\w}{\mathbf w} \newcommand{\u}{\mathbf u} \newcommand{\0}{\mathbf 0} \z &\sim \mathcal N(\0,\I) \\ \x|\z &\sim \mathcal N(\W_x \z + \boldsymbol \m_x, \P_x)\\ \y|\z &\sim \mathcal N(\W_y \z + \boldsymbol \m_y, \P_y) \end{align} Here noise covariances $\P_x$ and $\P_y$ are arbitrary full rank symmetric matrices. If we consider 1-dimensional latent variable $z$, assume that all means are zero $\m_x=\m_y=0$, and combine $\x$ and $\y$ into one vector, then we get: $$\begin{pmatrix} \x\\ \y\end{pmatrix}\sim\mathcal N (\0,\S),\quad\quad\quad\S=\begin{pmatrix}\w_x\w_x^\top+\P_x & \w_x\w_y^\top \\ \w_y\w_x^\top & \w_y\w_y^\top+\P_y\end{pmatrix}.$$ Bach & Jordan proved that this is equivalent to standard CCA. Specifically, the maximum likelihood (ML) solution is given by $$\w_i = \S_i\u_i m_i,$$ where $\S_i$ are sample covariance matrices of both datasets, $\u_i$ is the first canonical pair of axes, and $m_x m_y = \rho_1$ are arbitrary numbers (both between $0$ and $1$) giving first canonical correlation as a product. As you see, $\w_i$ are not directly equal to the CCA axes, but are given by some transformation of those. See Bach & Jordan for more details. I don't have a good intuitive grasp of PCCA. As you can see, the cross-covariance matrix between $X$ and $Y$ is modeled by $\w_x \w_y^\top$, so one could naively expect $\w_i$ to rather yield PLS axes. The ML solution is however related to the CCA axes. It probably is somehow due to the block-diagonal structure of $\P=\begin{pmatrix}\P_x & \0\\ \0 & \P_y\end{pmatrix}$. I am not aware of any similar probabilistic versions of RRR or PLS, and have failed to come up with any myself. Note that if $\P$ is diagonal then we obtain FA on the combined $X+Y$ dataset, and if it is diagonal and isotropic then we get PPCA on the combined dataset. So there is a progression from CCA to FA to PPCA, as $\P$ gets more and more constrained. I don't see what other choices of $\P$ can be reasonable.
Probabilistic models for partial least squares, reduced rank regression, and canonical correlation a Probabilistic canonical correlation analysis (probabilistic CCA, PCCA) was introduced in Bach & Jordan, 2005, A Probabilistic Interpretation of Canonical Correlation Analysis, several years after Tipp
36,605
Surrogate Time Series using Fourier Transform
You need to use the Fourier transform (and inverse transform) for real time series, i.e., rfft and irfft, respectively. This way you ensure that your surrogate is real. You can do this by replacing the respective lines of your code with the following: ts_fourier = numpy.fft.rfft(ts) random_phases = numpy.exp(numpy.random.uniform(0,numpy.pi,len(ts)/2+1)*1.0j) ts_fourier_new = ts_fourier*random_phases new_ts = numpy.fft.irfft(ts_fourier_new) (Alternatively, you can take the regular Fourier transform and shuffle the phases in an antisymmetric manner.) The remaining deviations originate from the finiteness of your time series: The identity of the autocorrelation functions is based on the fact that the original time series and the surrogate have per construction the same power spectrum, which in turn is linked to the autocorrelation function via the Wiener–Khinchin theorem. However the latter only holds in approximation for finite time series as it is actually about processes. This effect is somewhat alleviated if you look at time series with “actual” prominent frequency components and not just noise.
Surrogate Time Series using Fourier Transform
You need to use the Fourier transform (and inverse transform) for real time series, i.e., rfft and irfft, respectively. This way you ensure that your surrogate is real. You can do this by replacing th
Surrogate Time Series using Fourier Transform You need to use the Fourier transform (and inverse transform) for real time series, i.e., rfft and irfft, respectively. This way you ensure that your surrogate is real. You can do this by replacing the respective lines of your code with the following: ts_fourier = numpy.fft.rfft(ts) random_phases = numpy.exp(numpy.random.uniform(0,numpy.pi,len(ts)/2+1)*1.0j) ts_fourier_new = ts_fourier*random_phases new_ts = numpy.fft.irfft(ts_fourier_new) (Alternatively, you can take the regular Fourier transform and shuffle the phases in an antisymmetric manner.) The remaining deviations originate from the finiteness of your time series: The identity of the autocorrelation functions is based on the fact that the original time series and the surrogate have per construction the same power spectrum, which in turn is linked to the autocorrelation function via the Wiener–Khinchin theorem. However the latter only holds in approximation for finite time series as it is actually about processes. This effect is somewhat alleviated if you look at time series with “actual” prominent frequency components and not just noise.
Surrogate Time Series using Fourier Transform You need to use the Fourier transform (and inverse transform) for real time series, i.e., rfft and irfft, respectively. This way you ensure that your surrogate is real. You can do this by replacing th
36,606
Why aren't Gaussian Activation Functions used more often in Neural Networks?
@Glen_b notes in comments that it's expensive to compute exact Normal CDF probabilities. Accurate approximations exist, but one still must ask Why do this? Logit and probit functions look basically the same, up to rescaling. (Image reproduced from @gung's answer here.) From a practical standpoint, it's hard see how the small differences between the two would be significant. Moreover, recent work on ReLUs (and similar) activation functions have found substantial improvement over logistic units. Due to the similarity of logistic and probit units, we can surmise that ReLUs will likewise also out-perform probit units. All together, then, probit units are a more expensive way to get worse results than ReLU (or its variants).
Why aren't Gaussian Activation Functions used more often in Neural Networks?
@Glen_b notes in comments that it's expensive to compute exact Normal CDF probabilities. Accurate approximations exist, but one still must ask Why do this? Logit and probit functions look basically t
Why aren't Gaussian Activation Functions used more often in Neural Networks? @Glen_b notes in comments that it's expensive to compute exact Normal CDF probabilities. Accurate approximations exist, but one still must ask Why do this? Logit and probit functions look basically the same, up to rescaling. (Image reproduced from @gung's answer here.) From a practical standpoint, it's hard see how the small differences between the two would be significant. Moreover, recent work on ReLUs (and similar) activation functions have found substantial improvement over logistic units. Due to the similarity of logistic and probit units, we can surmise that ReLUs will likewise also out-perform probit units. All together, then, probit units are a more expensive way to get worse results than ReLU (or its variants).
Why aren't Gaussian Activation Functions used more often in Neural Networks? @Glen_b notes in comments that it's expensive to compute exact Normal CDF probabilities. Accurate approximations exist, but one still must ask Why do this? Logit and probit functions look basically t
36,607
Understanding weight distribution in neural network
This is expected. Weights in a CNN form feature detectors, so that a certain pattern in an image is connected to strong weights, but the rest of the image pixels should not cause any activations in the next layer neurons. Only a small fraction of neurons in a layer is activated every time an image is shown, and a small fraction of weights is needed to be large to activate (or suppress) any particular neuron. Moreover, the number of patterns a network needs to detect is fairly small, especially in the early layers. Therefore, overall connectivity for the network is usually very sparse. The same reasoning applies to regulatization methods, such as L2/L1 - forcing the weights to be small makes the network more robust to noise in the data, and forces the network to learn only the features present in many images.
Understanding weight distribution in neural network
This is expected. Weights in a CNN form feature detectors, so that a certain pattern in an image is connected to strong weights, but the rest of the image pixels should not cause any activations in th
Understanding weight distribution in neural network This is expected. Weights in a CNN form feature detectors, so that a certain pattern in an image is connected to strong weights, but the rest of the image pixels should not cause any activations in the next layer neurons. Only a small fraction of neurons in a layer is activated every time an image is shown, and a small fraction of weights is needed to be large to activate (or suppress) any particular neuron. Moreover, the number of patterns a network needs to detect is fairly small, especially in the early layers. Therefore, overall connectivity for the network is usually very sparse. The same reasoning applies to regulatization methods, such as L2/L1 - forcing the weights to be small makes the network more robust to noise in the data, and forces the network to learn only the features present in many images.
Understanding weight distribution in neural network This is expected. Weights in a CNN form feature detectors, so that a certain pattern in an image is connected to strong weights, but the rest of the image pixels should not cause any activations in th
36,608
Understanding weight distribution in neural network
This is a really good question and there can be multiple explanations to this phenomenon. I will try to give out a non-exhaustive list for the same. Sparse data ? You mean sparse/binary feature set ? hmmm...this can happen. See in that case your network does not require much parameters to encode this function. Every neural network is a function that encodes the feature set to the set of labels (one hot or whatever !). Now lets talk about regularization because that has soooo much to do about the weight distribution of a network. You are not using dropout. Try using it. It is a great regularization technique which can actually help you to use all of your neurons. Without dropout on Sparse data, this is an expected event. Try using L2, it might have some effect to your weight distribution. You are using batchnorm and still getting this ? Hmm...I dont have an answer right now but if this post generates enough attention I will do a study on dropout vs batchnorm...!!
Understanding weight distribution in neural network
This is a really good question and there can be multiple explanations to this phenomenon. I will try to give out a non-exhaustive list for the same. Sparse data ? You mean sparse/binary feature set ?
Understanding weight distribution in neural network This is a really good question and there can be multiple explanations to this phenomenon. I will try to give out a non-exhaustive list for the same. Sparse data ? You mean sparse/binary feature set ? hmmm...this can happen. See in that case your network does not require much parameters to encode this function. Every neural network is a function that encodes the feature set to the set of labels (one hot or whatever !). Now lets talk about regularization because that has soooo much to do about the weight distribution of a network. You are not using dropout. Try using it. It is a great regularization technique which can actually help you to use all of your neurons. Without dropout on Sparse data, this is an expected event. Try using L2, it might have some effect to your weight distribution. You are using batchnorm and still getting this ? Hmm...I dont have an answer right now but if this post generates enough attention I will do a study on dropout vs batchnorm...!!
Understanding weight distribution in neural network This is a really good question and there can be multiple explanations to this phenomenon. I will try to give out a non-exhaustive list for the same. Sparse data ? You mean sparse/binary feature set ?
36,609
Proving that cosine distance function defined by cosine similarity between two unit vectors does not satisfy triangle inequality
$$\text{cos-dist}(A, B) = 1 - \text{cos-sim}(A, B)$$ $$\text{cos-sim}(A, B) = \frac{\langle A, B \rangle}{||A|| \cdot ||B||} = \frac{\sum\limits_{i=1}^n A_i \cdot B_i}{\sqrt{\sum\limits_{i=1}^n A_i^2} \cdot \sqrt{\sum\limits_{i=1}^n B_i^2}}$$ Triangle inequality for cosine distance tooks a form of (of course it doesn't hold): $$\text{cos-dist}(A,C) \nleq \text{cos-dist}(A, B) + \text{cos-dist}(B, C)$$ which is equivalent to: $$1 - \text{cos-sim}(A,C) \nleq 1 - \text{cos-sim}(A, B) + 1 - \text{cos-sim}(B, C)$$ and after simple transformations: $$1 + \text{cos-sim}(A, C) \ngeq \text{cos-sim}(A, B) + \text{cos-sim}(B, C)$$ Now, you're trying to find such three vectors A, B and C that: $$1 + \text{cos-sim}(A, C) < \text{cos-sim}(A, B) + \text{cos-sim}(B, C)$$ Let $A, B, C \in \mathbb{R}^2$ and all of them are of unit length A = [1, 0], B = $\left[\frac{\sqrt{2}}{2}, \frac{\sqrt{2}}{2}\right]$, C = [0, 1]. Note that vectors A and C are orthogonal, so we would get simply $0$: $$\text{cos-sim}(A, C) = \frac{0}{\sqrt{1}\sqrt{1}} = 0$$ Each pair of vectors A & B as well as B & C would give the same value: $$ \text{cos-sim}(A, B) = \frac{\frac{\sqrt{2}}{2} + 0}{\sqrt{1}\sqrt{1}} = \frac{\sqrt{2}}{2},~~~ \text{cos-sim}(B, C) = \frac{0+\frac{\sqrt{2}}{2}}{\sqrt{1}\sqrt{1}} = \frac{\sqrt{2}}{2}$$. Finally, we could defeat primary inequality by proving that: $$ 1 + 0 < \frac{\sqrt{2}}{2} + \frac{\sqrt{2}}{2}$$ $$ 1 < \sqrt{2} \approx 1.41 \dots$$
Proving that cosine distance function defined by cosine similarity between two unit vectors does not
$$\text{cos-dist}(A, B) = 1 - \text{cos-sim}(A, B)$$ $$\text{cos-sim}(A, B) = \frac{\langle A, B \rangle}{||A|| \cdot ||B||} = \frac{\sum\limits_{i=1}^n A_i \cdot B_i}{\sqrt{\sum\limits_{i=1}^n A_i^2}
Proving that cosine distance function defined by cosine similarity between two unit vectors does not satisfy triangle inequality $$\text{cos-dist}(A, B) = 1 - \text{cos-sim}(A, B)$$ $$\text{cos-sim}(A, B) = \frac{\langle A, B \rangle}{||A|| \cdot ||B||} = \frac{\sum\limits_{i=1}^n A_i \cdot B_i}{\sqrt{\sum\limits_{i=1}^n A_i^2} \cdot \sqrt{\sum\limits_{i=1}^n B_i^2}}$$ Triangle inequality for cosine distance tooks a form of (of course it doesn't hold): $$\text{cos-dist}(A,C) \nleq \text{cos-dist}(A, B) + \text{cos-dist}(B, C)$$ which is equivalent to: $$1 - \text{cos-sim}(A,C) \nleq 1 - \text{cos-sim}(A, B) + 1 - \text{cos-sim}(B, C)$$ and after simple transformations: $$1 + \text{cos-sim}(A, C) \ngeq \text{cos-sim}(A, B) + \text{cos-sim}(B, C)$$ Now, you're trying to find such three vectors A, B and C that: $$1 + \text{cos-sim}(A, C) < \text{cos-sim}(A, B) + \text{cos-sim}(B, C)$$ Let $A, B, C \in \mathbb{R}^2$ and all of them are of unit length A = [1, 0], B = $\left[\frac{\sqrt{2}}{2}, \frac{\sqrt{2}}{2}\right]$, C = [0, 1]. Note that vectors A and C are orthogonal, so we would get simply $0$: $$\text{cos-sim}(A, C) = \frac{0}{\sqrt{1}\sqrt{1}} = 0$$ Each pair of vectors A & B as well as B & C would give the same value: $$ \text{cos-sim}(A, B) = \frac{\frac{\sqrt{2}}{2} + 0}{\sqrt{1}\sqrt{1}} = \frac{\sqrt{2}}{2},~~~ \text{cos-sim}(B, C) = \frac{0+\frac{\sqrt{2}}{2}}{\sqrt{1}\sqrt{1}} = \frac{\sqrt{2}}{2}$$. Finally, we could defeat primary inequality by proving that: $$ 1 + 0 < \frac{\sqrt{2}}{2} + \frac{\sqrt{2}}{2}$$ $$ 1 < \sqrt{2} \approx 1.41 \dots$$
Proving that cosine distance function defined by cosine similarity between two unit vectors does not $$\text{cos-dist}(A, B) = 1 - \text{cos-sim}(A, B)$$ $$\text{cos-sim}(A, B) = \frac{\langle A, B \rangle}{||A|| \cdot ||B||} = \frac{\sum\limits_{i=1}^n A_i \cdot B_i}{\sqrt{\sum\limits_{i=1}^n A_i^2}
36,610
Two-sample Kolmogorov–Smirnov test with weights
I have found some information about how to modify the KS and AD tests for weighted samples in Numerical Methods of Statistics by Monohan, pg. 334 in 1E and pg. 358 in 2E. This Google Books link may show the relevant page. I have also attached a screenshot of the relevant page.
Two-sample Kolmogorov–Smirnov test with weights
I have found some information about how to modify the KS and AD tests for weighted samples in Numerical Methods of Statistics by Monohan, pg. 334 in 1E and pg. 358 in 2E. This Google Books link may sh
Two-sample Kolmogorov–Smirnov test with weights I have found some information about how to modify the KS and AD tests for weighted samples in Numerical Methods of Statistics by Monohan, pg. 334 in 1E and pg. 358 in 2E. This Google Books link may show the relevant page. I have also attached a screenshot of the relevant page.
Two-sample Kolmogorov–Smirnov test with weights I have found some information about how to modify the KS and AD tests for weighted samples in Numerical Methods of Statistics by Monohan, pg. 334 in 1E and pg. 358 in 2E. This Google Books link may sh
36,611
Concrete examples of a frequentist approach that is superior to a Bayesian one [closed]
A nice example would be a betting scenario where a frequentist and Bayesian bet against each other about some future outcome and the frequentist has positive expected value. I will not give you this example because such an example would favor a Bayesian approach unless the Bayesian chooses a bad prior which is a cop-out example not really worth writing about. The frequentest approach is not designed to obtain the highest expected value in betting scenarios (luckily the world of statistics and probability is much more broad than just that). Rather, frequentist techniques are designed to guarantee certain desirable frequency properties, particularly that of coverage. These properties are important for parameter estimation and inference in the context of scientific research and inquiry. I encourage you to check out this link here to a blog post by Dr. Larry Wasserman. In it he talks about frequency guarantees in more depth (see the examples he gives). Suppose we had some data $Y$ and we think it is distributed according to some conditional distribution $Y \sim f(Y|\theta^*)$ (if you like you can imagine that $Y$ is normally distributed and $\theta^*$ is the mean and\or variance). We do not know the value of $\theta^*$ , so we have to estimate it. We can use either a frequentist or Bayesian approach to do so. In the frequentist approach we would obtain a point estimate $\hat \theta$ and a confidence interval for that estimate. Assuming $\theta^*$ exists and the model is valid and well behaved, the frequentist $(1-\alpha)$ confidence interval is guaranteed to contain $\theta^*$ $(1-\alpha)$% of the time regardless of what $\theta^*$ actually is. $\theta^*$ could be 0, it could be 1,000,000, it could be -53.2, it doesn't matter, the above statement holds true. However, the above does not hold true for Bayesian confidence intervals otherwise known as credible intervals. This is because,in a Bayesian setting, we have to specify a prior $\theta \sim \pi(\theta)$ and simulate from the posterior, $\pi(\theta|Y) \propto f(Y|\theta)\pi(\theta)$. We can form $(1-\alpha)$% credible intervals using the resulting sample, but the probability that these intervals will contain $\theta^*$ depends upon how probable $\theta^*$ is under our prior. In a betting scenario, we may believe that certain values are less likely to be $\theta^*$ then others, and we can assign a prior to reflect these beliefs. If our beliefs are accurate the probability of containing $\theta^*$ in the credible interval is higher. This is why smart people using Bayesian techniques in betting scenarios beat frequentist. But consider a different scenario, like a study where you are testing the effect of education on wages, call it $\beta$, in a regression model. A lot of researchers would prefer the confidence interval of $\beta$ to have the frequency property of coverage rather than reflect their own degrees of belief regarding the effect education on wages. From a pragmatic standpoint, it should also be noted that in my earlier example, as the sample size approaches infinity, both the frequentist $\hat \theta$ and Bayesian posterior $\pi(\theta|Y)$ converge onto $\theta^*$. So as you obtain more and more data, the difference between the Bayesian and frequentist approach becomes negligible. Since Bayesian estimation is often (not always) more computationally and mathematically rigorous than frequentist estimation, practitioners often opt for frequentist techniques when they have "large" data sets. This is true even when the primary goal is prediction as opposed to parameter estimation/inference.
Concrete examples of a frequentist approach that is superior to a Bayesian one [closed]
A nice example would be a betting scenario where a frequentist and Bayesian bet against each other about some future outcome and the frequentist has positive expected value. I will not give you this
Concrete examples of a frequentist approach that is superior to a Bayesian one [closed] A nice example would be a betting scenario where a frequentist and Bayesian bet against each other about some future outcome and the frequentist has positive expected value. I will not give you this example because such an example would favor a Bayesian approach unless the Bayesian chooses a bad prior which is a cop-out example not really worth writing about. The frequentest approach is not designed to obtain the highest expected value in betting scenarios (luckily the world of statistics and probability is much more broad than just that). Rather, frequentist techniques are designed to guarantee certain desirable frequency properties, particularly that of coverage. These properties are important for parameter estimation and inference in the context of scientific research and inquiry. I encourage you to check out this link here to a blog post by Dr. Larry Wasserman. In it he talks about frequency guarantees in more depth (see the examples he gives). Suppose we had some data $Y$ and we think it is distributed according to some conditional distribution $Y \sim f(Y|\theta^*)$ (if you like you can imagine that $Y$ is normally distributed and $\theta^*$ is the mean and\or variance). We do not know the value of $\theta^*$ , so we have to estimate it. We can use either a frequentist or Bayesian approach to do so. In the frequentist approach we would obtain a point estimate $\hat \theta$ and a confidence interval for that estimate. Assuming $\theta^*$ exists and the model is valid and well behaved, the frequentist $(1-\alpha)$ confidence interval is guaranteed to contain $\theta^*$ $(1-\alpha)$% of the time regardless of what $\theta^*$ actually is. $\theta^*$ could be 0, it could be 1,000,000, it could be -53.2, it doesn't matter, the above statement holds true. However, the above does not hold true for Bayesian confidence intervals otherwise known as credible intervals. This is because,in a Bayesian setting, we have to specify a prior $\theta \sim \pi(\theta)$ and simulate from the posterior, $\pi(\theta|Y) \propto f(Y|\theta)\pi(\theta)$. We can form $(1-\alpha)$% credible intervals using the resulting sample, but the probability that these intervals will contain $\theta^*$ depends upon how probable $\theta^*$ is under our prior. In a betting scenario, we may believe that certain values are less likely to be $\theta^*$ then others, and we can assign a prior to reflect these beliefs. If our beliefs are accurate the probability of containing $\theta^*$ in the credible interval is higher. This is why smart people using Bayesian techniques in betting scenarios beat frequentist. But consider a different scenario, like a study where you are testing the effect of education on wages, call it $\beta$, in a regression model. A lot of researchers would prefer the confidence interval of $\beta$ to have the frequency property of coverage rather than reflect their own degrees of belief regarding the effect education on wages. From a pragmatic standpoint, it should also be noted that in my earlier example, as the sample size approaches infinity, both the frequentist $\hat \theta$ and Bayesian posterior $\pi(\theta|Y)$ converge onto $\theta^*$. So as you obtain more and more data, the difference between the Bayesian and frequentist approach becomes negligible. Since Bayesian estimation is often (not always) more computationally and mathematically rigorous than frequentist estimation, practitioners often opt for frequentist techniques when they have "large" data sets. This is true even when the primary goal is prediction as opposed to parameter estimation/inference.
Concrete examples of a frequentist approach that is superior to a Bayesian one [closed] A nice example would be a betting scenario where a frequentist and Bayesian bet against each other about some future outcome and the frequentist has positive expected value. I will not give you this
36,612
Interpretation of mixed model output in lme4 and stan
The main question was the result of a bug in rstanarm that has since been fixed on GitHub. However, in general, we do not recommend rstanarm models that exclude the intercept. A better alternative is to place a tight prior with mean zero on the intercept. In this case, including the intercept yields a better fit and similar results between lme4::lmer and rstanarm::stan_lmer.
Interpretation of mixed model output in lme4 and stan
The main question was the result of a bug in rstanarm that has since been fixed on GitHub. However, in general, we do not recommend rstanarm models that exclude the intercept. A better alternative is
Interpretation of mixed model output in lme4 and stan The main question was the result of a bug in rstanarm that has since been fixed on GitHub. However, in general, we do not recommend rstanarm models that exclude the intercept. A better alternative is to place a tight prior with mean zero on the intercept. In this case, including the intercept yields a better fit and similar results between lme4::lmer and rstanarm::stan_lmer.
Interpretation of mixed model output in lme4 and stan The main question was the result of a bug in rstanarm that has since been fixed on GitHub. However, in general, we do not recommend rstanarm models that exclude the intercept. A better alternative is
36,613
XG Boost vs Random Forest for Time Series Regression Forecasting
The easiest way to handle 'tuning' of the num_rounds parameter is to let XGBoost do it for you. You can set theearly_stopping_rounds parameter to n in the train method and the model will stop training once error hasn't decreased for n rounds. See this example from the Liberty Mutual Kaggle Competition: As noted in the code below, you'll need to also use the watchlist parameter to enable early stopping. # You can write R code here and then click "Run" to run it on our platform # The readr library is the best way to read and write CSV files in R library(readr) library(xgboost) library(data.table) library(Matrix) library(caret) # The competition datafiles are in the directory ../input # Read competition data files: train <- read_csv("../input/train.csv") test <- read_csv("../input/test.csv") # Generate output files with write_csv(), plot() or ggplot() # Any files you write to the current directory get shown as outputs # keep copy of ID variables for test and train data train_Id <- train$Id test_Id <- test$Id # response variable from training data train_y <- train$Hazard # predictor variables from training train_x <- subset(train, select = -c(Id, Hazard)) train_x <- sparse.model.matrix(~., data = train_x) # predictor variables from test test_x <- subset(test, select = -c(Id)) test_x <- sparse.model.matrix(~., data = test_x) # Set xgboost parameters param <- list("objective" = "reg:linear", "eta" = 0.05, "min_child_weight" = 10, "subsample" = .8, "colsample_bytree" = .8, "scale_pos_weight" = 1.0, "max_depth" = 5) # Using 5000 rows for early stopping. offset <- 5000 num_rounds <- 1000 # Set xgboost test and training and validation datasets xgtest <- xgb.DMatrix(data = test_x) xgtrain <- xgb.DMatrix(data = train_x[offset:nrow(train_x),], label= train_y[offset:nrow(train_x)]) xgval <- xgb.DMatrix(data = train_x[1:offset,], label= train_y[1:offset]) # setup watchlist to enable train and validation, validation must be first for early stopping watchlist <- list(val=xgval, train=xgtrain) # to train with watchlist, use xgb.train, which contains more advanced features # this will use default evaluation metric = rmse which we want to minimise bst1 <- xgb.train(params = param, data = xgtrain, nround=num_rounds, print.every.n = 20, watchlist=watchlist, early.stop.round = 50, maximize = FALSE)
XG Boost vs Random Forest for Time Series Regression Forecasting
The easiest way to handle 'tuning' of the num_rounds parameter is to let XGBoost do it for you. You can set theearly_stopping_rounds parameter to n in the train method and the model will stop trainin
XG Boost vs Random Forest for Time Series Regression Forecasting The easiest way to handle 'tuning' of the num_rounds parameter is to let XGBoost do it for you. You can set theearly_stopping_rounds parameter to n in the train method and the model will stop training once error hasn't decreased for n rounds. See this example from the Liberty Mutual Kaggle Competition: As noted in the code below, you'll need to also use the watchlist parameter to enable early stopping. # You can write R code here and then click "Run" to run it on our platform # The readr library is the best way to read and write CSV files in R library(readr) library(xgboost) library(data.table) library(Matrix) library(caret) # The competition datafiles are in the directory ../input # Read competition data files: train <- read_csv("../input/train.csv") test <- read_csv("../input/test.csv") # Generate output files with write_csv(), plot() or ggplot() # Any files you write to the current directory get shown as outputs # keep copy of ID variables for test and train data train_Id <- train$Id test_Id <- test$Id # response variable from training data train_y <- train$Hazard # predictor variables from training train_x <- subset(train, select = -c(Id, Hazard)) train_x <- sparse.model.matrix(~., data = train_x) # predictor variables from test test_x <- subset(test, select = -c(Id)) test_x <- sparse.model.matrix(~., data = test_x) # Set xgboost parameters param <- list("objective" = "reg:linear", "eta" = 0.05, "min_child_weight" = 10, "subsample" = .8, "colsample_bytree" = .8, "scale_pos_weight" = 1.0, "max_depth" = 5) # Using 5000 rows for early stopping. offset <- 5000 num_rounds <- 1000 # Set xgboost test and training and validation datasets xgtest <- xgb.DMatrix(data = test_x) xgtrain <- xgb.DMatrix(data = train_x[offset:nrow(train_x),], label= train_y[offset:nrow(train_x)]) xgval <- xgb.DMatrix(data = train_x[1:offset,], label= train_y[1:offset]) # setup watchlist to enable train and validation, validation must be first for early stopping watchlist <- list(val=xgval, train=xgtrain) # to train with watchlist, use xgb.train, which contains more advanced features # this will use default evaluation metric = rmse which we want to minimise bst1 <- xgb.train(params = param, data = xgtrain, nround=num_rounds, print.every.n = 20, watchlist=watchlist, early.stop.round = 50, maximize = FALSE)
XG Boost vs Random Forest for Time Series Regression Forecasting The easiest way to handle 'tuning' of the num_rounds parameter is to let XGBoost do it for you. You can set theearly_stopping_rounds parameter to n in the train method and the model will stop trainin
36,614
Find the rotation between set of points
This can be done using the Kabsch Algorithm. The algorithm finds the best least-squares estimate for rotation of $RX-Y$ where $R$ is rotation matrix, $X$ and $Y$ are your target and source matrices with 2 rows and n columns. In [1] it is shown that this problem can be solved using singular value decomposition. The algorithm is as follows: Center the datasets so their centroids are on origin. Compute the "covariance" matrix $C$=$XY^T$. Obtain the Singular Value Decomposition of $C=UDV^T$. Direction adjustment $d=sign(det(C))$. Then the optimal rotation $R=V\left( \begin{array}{ccc} 1 & 0 \\ 0 & d \\ \end{array} \right)U^T$ I don't know of any implementation in R so wrote a small function below. Your initial points: src <- matrix(c(712,960,968,1200,360,644,84,360), nrow=2, byrow=TRUE) trg <- matrix(c(744,996,980,1220,364,644,68,336), nrow=2, byrow=TRUE) Kabsch algorithm in an R funtion: kabsch2d <- function(Y, X) { X <- X-rowMeans(X) Y <- Y-rowMeans(Y) C <- X %*% t(Y) SVD <- svd(C) D <- diag(c(1, sign(det(C)))) t(SVD$v) %*% D %*% t(SVD$u) } Center the points: src <- src-rowMeans(src) trg <- trg-rowMeans(trg) Obtain rotation: rot <- kabsch2d(src, trg) Result (black - original source, red - original target, green - rotated target) plot(t(src), col="black", pch=19) points(t(trg), col="red", pch=19) points(t(rot %*% trg), col="green", pch=19) [1] http://www.math.pku.edu.cn/teachers/yaoy/Fall2011/arun.pdf
Find the rotation between set of points
This can be done using the Kabsch Algorithm. The algorithm finds the best least-squares estimate for rotation of $RX-Y$ where $R$ is rotation matrix, $X$ and $Y$ are your target and source matrices wi
Find the rotation between set of points This can be done using the Kabsch Algorithm. The algorithm finds the best least-squares estimate for rotation of $RX-Y$ where $R$ is rotation matrix, $X$ and $Y$ are your target and source matrices with 2 rows and n columns. In [1] it is shown that this problem can be solved using singular value decomposition. The algorithm is as follows: Center the datasets so their centroids are on origin. Compute the "covariance" matrix $C$=$XY^T$. Obtain the Singular Value Decomposition of $C=UDV^T$. Direction adjustment $d=sign(det(C))$. Then the optimal rotation $R=V\left( \begin{array}{ccc} 1 & 0 \\ 0 & d \\ \end{array} \right)U^T$ I don't know of any implementation in R so wrote a small function below. Your initial points: src <- matrix(c(712,960,968,1200,360,644,84,360), nrow=2, byrow=TRUE) trg <- matrix(c(744,996,980,1220,364,644,68,336), nrow=2, byrow=TRUE) Kabsch algorithm in an R funtion: kabsch2d <- function(Y, X) { X <- X-rowMeans(X) Y <- Y-rowMeans(Y) C <- X %*% t(Y) SVD <- svd(C) D <- diag(c(1, sign(det(C)))) t(SVD$v) %*% D %*% t(SVD$u) } Center the points: src <- src-rowMeans(src) trg <- trg-rowMeans(trg) Obtain rotation: rot <- kabsch2d(src, trg) Result (black - original source, red - original target, green - rotated target) plot(t(src), col="black", pch=19) points(t(trg), col="red", pch=19) points(t(rot %*% trg), col="green", pch=19) [1] http://www.math.pku.edu.cn/teachers/yaoy/Fall2011/arun.pdf
Find the rotation between set of points This can be done using the Kabsch Algorithm. The algorithm finds the best least-squares estimate for rotation of $RX-Y$ where $R$ is rotation matrix, $X$ and $Y$ are your target and source matrices wi
36,615
Find the rotation between set of points
I've done this with an iterative optimum-search, and tested 2 versions. I've taken the original arrays and centered them calling this arrays cSRC and cTAR . Then I've done a loop with angles $\varphi$ between $0$ and $2 \pi$ , and for each angle I computed the error-criterion using the difference between the rotated $\small D=rot(\text{cSRC} ,\varphi)- \text{cTAR}$. In version 1) I took as criterion the sum-of-squares of all entries in $\small D$ as $$err_1 = \small \sum_{k=1}^4 \small((D_{k,1})^2+(D_{k,2})^2)$$and the angle $\small \varphi$ at which the minimal error occured is equivalent the kabsch2d-procedure in @Karolis' answer. In version 2) I took as criterion the sum of the absolute distances, that means, the sum $$err_2=\small \sum_{k=1}^4 \small\sqrt{(D_{k,1})^2+(D_{k,2})^2}$$ and got a slightly different rotation angle $\small \varphi$ for the smallest error. I don't know, which criterion fits your needs better. Here are some results from the protocol. $$ \small \begin{array} {r|cc} & \text{version } 1 & \text{version } 2\\ \hline \varphi & -0.04895304& -0.05093647 \\ \text{rotation} & \begin{bmatrix} 0.99880204& -0.04893349\\ 0.04893349& 0.99880204\\ \end{bmatrix} & \begin{bmatrix} 0.99870302 & -0.05091444\\ 0.05091444 & 0.99870302\\ \end{bmatrix} \\ \text{distances} & \begin{bmatrix} -6.80077266 & -0.86209739\\ 2.79924551 & -9.33782500\\ -0.61309522 & 6.94156520\\ 4.61462237 & 3.25835719\\ \end{bmatrix} & \begin{bmatrix} -6.78017751& -0.37062404 \\ 3.35787307 & -9.36574874 \\ -1.16459115 & 6.95324527 \\ 4.58689559 & 2.78312752 \\ \end{bmatrix} \end{array} $$
Find the rotation between set of points
I've done this with an iterative optimum-search, and tested 2 versions. I've taken the original arrays and centered them calling this arrays cSRC and cTAR . Then I've done a loop with angles $\varphi$
Find the rotation between set of points I've done this with an iterative optimum-search, and tested 2 versions. I've taken the original arrays and centered them calling this arrays cSRC and cTAR . Then I've done a loop with angles $\varphi$ between $0$ and $2 \pi$ , and for each angle I computed the error-criterion using the difference between the rotated $\small D=rot(\text{cSRC} ,\varphi)- \text{cTAR}$. In version 1) I took as criterion the sum-of-squares of all entries in $\small D$ as $$err_1 = \small \sum_{k=1}^4 \small((D_{k,1})^2+(D_{k,2})^2)$$and the angle $\small \varphi$ at which the minimal error occured is equivalent the kabsch2d-procedure in @Karolis' answer. In version 2) I took as criterion the sum of the absolute distances, that means, the sum $$err_2=\small \sum_{k=1}^4 \small\sqrt{(D_{k,1})^2+(D_{k,2})^2}$$ and got a slightly different rotation angle $\small \varphi$ for the smallest error. I don't know, which criterion fits your needs better. Here are some results from the protocol. $$ \small \begin{array} {r|cc} & \text{version } 1 & \text{version } 2\\ \hline \varphi & -0.04895304& -0.05093647 \\ \text{rotation} & \begin{bmatrix} 0.99880204& -0.04893349\\ 0.04893349& 0.99880204\\ \end{bmatrix} & \begin{bmatrix} 0.99870302 & -0.05091444\\ 0.05091444 & 0.99870302\\ \end{bmatrix} \\ \text{distances} & \begin{bmatrix} -6.80077266 & -0.86209739\\ 2.79924551 & -9.33782500\\ -0.61309522 & 6.94156520\\ 4.61462237 & 3.25835719\\ \end{bmatrix} & \begin{bmatrix} -6.78017751& -0.37062404 \\ 3.35787307 & -9.36574874 \\ -1.16459115 & 6.95324527 \\ 4.58689559 & 2.78312752 \\ \end{bmatrix} \end{array} $$
Find the rotation between set of points I've done this with an iterative optimum-search, and tested 2 versions. I've taken the original arrays and centered them calling this arrays cSRC and cTAR . Then I've done a loop with angles $\varphi$
36,616
How to generate samples uniformly at random from multiple discrete variables subject to constraints?
Let $n_i$ denote the number of balls of color $C_i$. Also, let $m_i$ and $M_i$ denote the minimum and the maximum number of balls of color $C_i$, respectively. We want to sample $(n_1, \dots, n_I)$ uniformly at random subject to the following constraints: $m_i \leq n_i \leq M_i$ $\sum_{i=1}^I n_i = N$ First of all, you can remove the lower bound constraints (i.e. $m_i \leq n_i$) by picking $m_i$ balls of color $C_i$ initially. This modifies the two constraints as follows: $0 \leq n_i \leq b_i = M_i - m_i$ $\sum_{i=1}^I n_i = B = N - \sum_{i=1}^I m_i$ Let $P(n_1, \dots, n_I \mid B, b_{1:I})$ denote the uniform distribution that we are interested in. We can use chain rule and dynamic programming to sample from $P$ efficiently. First, we use chain rule to write $P$ as follows: $$ \begin{align} P(n_1, \dots, n_I \mid B, b_{1:I}) &= P(n_I \mid B, b_{1:I}) P(n_1, \dots, n_{I-1} \mid n_I, B, b_{1:I}) \\ &= P(n_I \mid B, b_{1:I}) P(n_1, \dots, n_{I-1} \mid B-n_I, b_{1:I-1}) \quad (1) \end{align} $$ where $P(n_I | B, b_{1:I}) = \sum_{n_1, \dots, n_{I-1}} P(n_1, \dots, n_I | B, b_{1:I})$ is the marginal distribution of $n_I$. Note that $P(n_I | B, b_{1:I})$ is a discrete distribution and can be computed efficiently using dynamic programming. Also, note that the second term in (1) can be computed recursively. We sample $n_I$ in the first round of the recursion, update the total number of balls to $B - n_I$ and recurse to sample $n_{I-1}$ in the next round. The following is a Matlab implementation of the idea. The complexity of the algorithm is $O(I \times B \times K)$ where $K = \max_{i=1}^I b_i$. The code uses randomly generated $m_i$s in each run. As a result, some of the generated test cases may not have any valid solution, in which case the code prints out a warning message. global dpm b I = 5; % number of colors N = 300; % total number of balls m = randi(50, 1, I)-1; % minimum number of balls from each from each color M = 99*ones(1, I); % maximum number of balls from each color % print original constraints print_constraints(I, N, m, M, 'original constraints'); % remove the lower bound constraints b = M - m; B = N - sum(m); m = zeros(size(m)); % print transformed constraints print_constraints(I, B, zeros(1, I), b, 'transformed constraints'); % initialize the dynamic programming matrix (dpm) % if dpm(i, n) <> -1, it denotes the value of the following marginal probability % \sum_{k=1}^{i-1} P(n_1, ..., n_i | dpm = -ones(I, B); % sample the number of balls of each color, one at a time, using chain rule running_B = B; % we change the value of "running_B" on the fly, as we sample balls of different colors for i = I : -1 : 1 % compute marginal distribution P(n_i) % instead of P(n_i) we compute q(n_i) which is un-normalized. q_ni = zeros(1, b(i) + 1); % possibilities for ni are 0, 1, ..., b(i) for ni = 0 : b(i) q_ni(ni+1) = dpfunc(i-1, running_B-ni); end if(sum(q_ni) == 0) fprintf('Impossible!!! constraints can not be satisfied!\n'); return; end P_ni = q_ni / sum(q_ni); ni = discretesample(P_ni, 1) - 1; fprintf('n_%d=%d\n', i, ni); running_B = running_B - ni; end where the function print_constraints is function [] = print_constraints(I, N, m, M, note) fprintf('\n------ %s ------ \n', note); fprintf('%d <= n_%d <= %d\n', [m; [1:I]; M]); fprintf('========================\n'); fprintf('sum_{i=1}^%d n_i = %d\n', I, N); end and the function dpfunc performs the dynamic programming computation as follows: function res = dpfunc(i, n) global dpm b % check boundary cases if(n == 0) res = 1; return; end if(i == 0) % gets here only if n <> 0 res = 0; return; end if(n < 0) res = 0; return; end if(dpm(i, n) == -1) % if <> -1, it has been compute before, so, just use it! % compute the value of dpm(i, n) = \sum_{n_1, ..., n_i} valid(n, n_1, ..., n_i) % where "valid" return 1 if \sum_{j=1}^i n_i = n and 0 <= n_i <= b_i, for all i % and 0 otherwise. dpm(i, n) = 0; for ni = 0 : b(i) dpm(i, n) = dpm(i, n) + dpfunc(i-1, n-ni); end end res = dpm(i, n); end and finally, the function discretesample(p, 1) draws a random sample from the discrete distribution $p$. You can find one implementation of this function here.
How to generate samples uniformly at random from multiple discrete variables subject to constraints?
Let $n_i$ denote the number of balls of color $C_i$. Also, let $m_i$ and $M_i$ denote the minimum and the maximum number of balls of color $C_i$, respectively. We want to sample $(n_1, \dots, n_I)$ un
How to generate samples uniformly at random from multiple discrete variables subject to constraints? Let $n_i$ denote the number of balls of color $C_i$. Also, let $m_i$ and $M_i$ denote the minimum and the maximum number of balls of color $C_i$, respectively. We want to sample $(n_1, \dots, n_I)$ uniformly at random subject to the following constraints: $m_i \leq n_i \leq M_i$ $\sum_{i=1}^I n_i = N$ First of all, you can remove the lower bound constraints (i.e. $m_i \leq n_i$) by picking $m_i$ balls of color $C_i$ initially. This modifies the two constraints as follows: $0 \leq n_i \leq b_i = M_i - m_i$ $\sum_{i=1}^I n_i = B = N - \sum_{i=1}^I m_i$ Let $P(n_1, \dots, n_I \mid B, b_{1:I})$ denote the uniform distribution that we are interested in. We can use chain rule and dynamic programming to sample from $P$ efficiently. First, we use chain rule to write $P$ as follows: $$ \begin{align} P(n_1, \dots, n_I \mid B, b_{1:I}) &= P(n_I \mid B, b_{1:I}) P(n_1, \dots, n_{I-1} \mid n_I, B, b_{1:I}) \\ &= P(n_I \mid B, b_{1:I}) P(n_1, \dots, n_{I-1} \mid B-n_I, b_{1:I-1}) \quad (1) \end{align} $$ where $P(n_I | B, b_{1:I}) = \sum_{n_1, \dots, n_{I-1}} P(n_1, \dots, n_I | B, b_{1:I})$ is the marginal distribution of $n_I$. Note that $P(n_I | B, b_{1:I})$ is a discrete distribution and can be computed efficiently using dynamic programming. Also, note that the second term in (1) can be computed recursively. We sample $n_I$ in the first round of the recursion, update the total number of balls to $B - n_I$ and recurse to sample $n_{I-1}$ in the next round. The following is a Matlab implementation of the idea. The complexity of the algorithm is $O(I \times B \times K)$ where $K = \max_{i=1}^I b_i$. The code uses randomly generated $m_i$s in each run. As a result, some of the generated test cases may not have any valid solution, in which case the code prints out a warning message. global dpm b I = 5; % number of colors N = 300; % total number of balls m = randi(50, 1, I)-1; % minimum number of balls from each from each color M = 99*ones(1, I); % maximum number of balls from each color % print original constraints print_constraints(I, N, m, M, 'original constraints'); % remove the lower bound constraints b = M - m; B = N - sum(m); m = zeros(size(m)); % print transformed constraints print_constraints(I, B, zeros(1, I), b, 'transformed constraints'); % initialize the dynamic programming matrix (dpm) % if dpm(i, n) <> -1, it denotes the value of the following marginal probability % \sum_{k=1}^{i-1} P(n_1, ..., n_i | dpm = -ones(I, B); % sample the number of balls of each color, one at a time, using chain rule running_B = B; % we change the value of "running_B" on the fly, as we sample balls of different colors for i = I : -1 : 1 % compute marginal distribution P(n_i) % instead of P(n_i) we compute q(n_i) which is un-normalized. q_ni = zeros(1, b(i) + 1); % possibilities for ni are 0, 1, ..., b(i) for ni = 0 : b(i) q_ni(ni+1) = dpfunc(i-1, running_B-ni); end if(sum(q_ni) == 0) fprintf('Impossible!!! constraints can not be satisfied!\n'); return; end P_ni = q_ni / sum(q_ni); ni = discretesample(P_ni, 1) - 1; fprintf('n_%d=%d\n', i, ni); running_B = running_B - ni; end where the function print_constraints is function [] = print_constraints(I, N, m, M, note) fprintf('\n------ %s ------ \n', note); fprintf('%d <= n_%d <= %d\n', [m; [1:I]; M]); fprintf('========================\n'); fprintf('sum_{i=1}^%d n_i = %d\n', I, N); end and the function dpfunc performs the dynamic programming computation as follows: function res = dpfunc(i, n) global dpm b % check boundary cases if(n == 0) res = 1; return; end if(i == 0) % gets here only if n <> 0 res = 0; return; end if(n < 0) res = 0; return; end if(dpm(i, n) == -1) % if <> -1, it has been compute before, so, just use it! % compute the value of dpm(i, n) = \sum_{n_1, ..., n_i} valid(n, n_1, ..., n_i) % where "valid" return 1 if \sum_{j=1}^i n_i = n and 0 <= n_i <= b_i, for all i % and 0 otherwise. dpm(i, n) = 0; for ni = 0 : b(i) dpm(i, n) = dpm(i, n) + dpfunc(i-1, n-ni); end end res = dpm(i, n); end and finally, the function discretesample(p, 1) draws a random sample from the discrete distribution $p$. You can find one implementation of this function here.
How to generate samples uniformly at random from multiple discrete variables subject to constraints? Let $n_i$ denote the number of balls of color $C_i$. Also, let $m_i$ and $M_i$ denote the minimum and the maximum number of balls of color $C_i$, respectively. We want to sample $(n_1, \dots, n_I)$ un
36,617
How to generate samples uniformly at random from multiple discrete variables subject to constraints?
Let's consider a generalization of this problem. There are $m=4$ cans of paint of $m=4$ distinct colors and $n^{(0)}=100$ balls. Can $i$ can hold up to $a^{(0)}_i = (100, 100, 50, 75)$ balls. You wish to generate configurations of balls in the cans having at least $b_i = (0, 50, 0, 25)$ balls in can $i$ for each $i$, each configuration with equal probability. Such configurations are in one-to-one correspondence with the configurations obtained after removing $b_i$ balls from can $i$, limiting the $n = n^{(0)} - \sum_i b_i = 100 - (0+50+0+25)=25$ remaining balls to at most $a_i = a^{(0)}_i - b_i = (100, 50, 50, 50)$ per can. I will therefore just generate these and let you adjust them afterwards (by putting $b_i$ balls back into can $i$ for every $i$). To count these configurations up, fix all but two of the indices, say $i$ and $j$. Suppose there are $s_k$ balls already in can $k$ for each $k$ differing from $i$ and $j$. That leaves $s_i+s_j$ balls. Conditional on where the other $n - (s_i+s_j)$ balls are, these are distributed uniformly within cans $i$ and $j$. The possible configurations are $1 + \min(a_i + a_j - s_i - s_j, s_i+s_j)$ in number (see the comments), ranging from placing as many balls in can $i$ as possible all the way through placing as many balls in can $j$ as possible. If you wish, you could count the total number of configurations by applying this argument recursively to the remaining $m-2$ cans. However, to obtain samples we don't even need to know this count. All we need to do is repeatedly visit all possible unordered pairs $\{i,j\}$ of cans and randomly (and uniformly) change the distribution of balls within those two cans. This is a Markov chain with a limiting probability distribution that is uniform over all possible states (as is readily shown using standard methods). Therefore it suffices to start in any state, run the chain long enough to reach the limiting distribution, and then keep track of the states visited by this procedure. As usual, to avoid serial correlation, this sequence of states should be "thinned" by skipping through them (or revisited randomly). Thinning by a factor of about half the number of cans tends to work well, because after that many steps on average each can has been affected, producing a genuinely new configuration. This algorithm costs $O(m)$ effort to generate each random configuration on average. Although other $O(m)$ algorithms exist, this one has the advantage of not needing to do the combinatorial calculations beforehand. As an example, let's work out a smaller situation manually. Let $a=(4,3,2,1)$ and $n=3$, for instance. There are 15 valid configurations, which may be written as strings of occupancy numbers. For example, 0201 places two balls into the second can and one ball in the fourth can. Emulating the argument, let's consider the total occupancy of the first two cans. When that is $s_1+s_2=3$ balls, no balls are left for the last two cans. That gives the states 30**, 21**, 12**, 03** where ** represents all the possible occupancy numbers for the last two cans: namely, 00. When $s_1+s_2=2$, the states are 20**, 11**, 02** where now ** can be either 10 or 01. That gives $3\times 2=6$ more states. When $s_1+s_2=1$, the states are 10**, 01** where now ** can be 20, 11, but not 02 (due to the limit of one ball in the last can). That gives $2\times 2=4$ more states. Finally, when $s_1+s_2=0$, all balls are in the last two cans, which must be full to their limits of $2$ and $1$. The $4+6+4+1=15$ equally probable states therefore are 3000, 2100, 1200, 0300; 2010, 2001, 1110, 1101, 0210, 0201; 1020, 1011, 0120, 0111; 0021. Using the code below, a sequence of $10,009$ such configurations was generated and thinned to every third one, creating $3337$ configurations of the $15$ states. Their frequencies were the following: State: 3000 2100 1200 0300 2010 1110 0210 1020 0120 2001 1101 0201 1011 0111 0021 Count: 202 227 232 218 216 208 238 227 237 209 239 222 243 211 208 A $\chi^2$ test of uniformity gives a $\chi^2$ value of $11.2$, $p=0.67$ ($14$ degrees of freedom): that is beautiful agreement with the hypothesis that this procedure produces equally probable states. This R code is set up to handle the situation in the question. Change a and n to work with other situations. Set N to be large enough to generate the number of realizations you need after thinning. This code cheats a little bit by cycling systematically through all $(i,j)$ pairs. If you want to be strict about running the Markov chain, generate i, j, and ij randomly, as given in the commented code. # # Gibbs-like sampler. # # `a` is an array of maximum numbers of balls of each type. Its values should # all be integers greater than zero. # `n` is the total number of balls. #------------------------------------------------------------------------------# g <- function(j, state, a) { # # `state` contains the occupancy numbers. # `a` is the array of maximum occupancy numbers. # `j` is a pair of indexes into `a` to "rotate". # k <- sum(state[j]) # Total occupancy. x <- floor(runif(1, max(0, k - a[j[2]]), min(k, a[j[1]]) + 1)) state[j] <- c(x, k-x) return(state) } # # Set up the problem. # a <- c(100, 50, 50, 50) n <- 25 # a <- 4:1 # n <- 3 # # Initialize the state. # state <- round(n * a / sum(a)) i <- 1 while (sum(state) < n) { if (state[i] < a[i]) state[i] <- state[i] + 1 i <- i+1 } while (sum(state) > n) { i <- i-1 if (state[i] > 0) state[i] <- state[i] - 1 } # # Conduct a sequence of random changes. # set.seed(17) N <- 1e5 sim <- matrix(state, ncol=1) u <- ceiling(N / choose(length(state), 2) / 2) i <- rep(rep(1:length(state), each=length(state)-1), u) j <- rep(rep(length(state):1, length(state)-1), u) ij <- rbind(i, j) # # Alternatively, generate `ij` randomly: # i <- sample.int(length(state), N, replace=TRUE) # j <- sample.int(length(state)-1, N, replace=TRUE) # ij <- rbind(i, ((i+j-1) %% length(state))+1) # sim <- cbind(sim, apply(ij, 2, function(j) {state <<- g(j, state, a); state})) rownames(sim) <- paste("Can", 1:nrow(sim)) # # Thin them for use. Each column is a state. # thin <- function(x, stride=1, start=1) { i <- round(seq(start, ncol(x), by=stride)) x[, i] } # # Make a scatterplot of the results, to illustrate. # par(mfrow=c(1,1)) s <- thin(sim, stride=max(1, N/1e4)) pairs(t(s) + runif(length(s), -1/2, 1/2), cex=1/2, col="#00000005", pch=16)
How to generate samples uniformly at random from multiple discrete variables subject to constraints?
Let's consider a generalization of this problem. There are $m=4$ cans of paint of $m=4$ distinct colors and $n^{(0)}=100$ balls. Can $i$ can hold up to $a^{(0)}_i = (100, 100, 50, 75)$ balls. You w
How to generate samples uniformly at random from multiple discrete variables subject to constraints? Let's consider a generalization of this problem. There are $m=4$ cans of paint of $m=4$ distinct colors and $n^{(0)}=100$ balls. Can $i$ can hold up to $a^{(0)}_i = (100, 100, 50, 75)$ balls. You wish to generate configurations of balls in the cans having at least $b_i = (0, 50, 0, 25)$ balls in can $i$ for each $i$, each configuration with equal probability. Such configurations are in one-to-one correspondence with the configurations obtained after removing $b_i$ balls from can $i$, limiting the $n = n^{(0)} - \sum_i b_i = 100 - (0+50+0+25)=25$ remaining balls to at most $a_i = a^{(0)}_i - b_i = (100, 50, 50, 50)$ per can. I will therefore just generate these and let you adjust them afterwards (by putting $b_i$ balls back into can $i$ for every $i$). To count these configurations up, fix all but two of the indices, say $i$ and $j$. Suppose there are $s_k$ balls already in can $k$ for each $k$ differing from $i$ and $j$. That leaves $s_i+s_j$ balls. Conditional on where the other $n - (s_i+s_j)$ balls are, these are distributed uniformly within cans $i$ and $j$. The possible configurations are $1 + \min(a_i + a_j - s_i - s_j, s_i+s_j)$ in number (see the comments), ranging from placing as many balls in can $i$ as possible all the way through placing as many balls in can $j$ as possible. If you wish, you could count the total number of configurations by applying this argument recursively to the remaining $m-2$ cans. However, to obtain samples we don't even need to know this count. All we need to do is repeatedly visit all possible unordered pairs $\{i,j\}$ of cans and randomly (and uniformly) change the distribution of balls within those two cans. This is a Markov chain with a limiting probability distribution that is uniform over all possible states (as is readily shown using standard methods). Therefore it suffices to start in any state, run the chain long enough to reach the limiting distribution, and then keep track of the states visited by this procedure. As usual, to avoid serial correlation, this sequence of states should be "thinned" by skipping through them (or revisited randomly). Thinning by a factor of about half the number of cans tends to work well, because after that many steps on average each can has been affected, producing a genuinely new configuration. This algorithm costs $O(m)$ effort to generate each random configuration on average. Although other $O(m)$ algorithms exist, this one has the advantage of not needing to do the combinatorial calculations beforehand. As an example, let's work out a smaller situation manually. Let $a=(4,3,2,1)$ and $n=3$, for instance. There are 15 valid configurations, which may be written as strings of occupancy numbers. For example, 0201 places two balls into the second can and one ball in the fourth can. Emulating the argument, let's consider the total occupancy of the first two cans. When that is $s_1+s_2=3$ balls, no balls are left for the last two cans. That gives the states 30**, 21**, 12**, 03** where ** represents all the possible occupancy numbers for the last two cans: namely, 00. When $s_1+s_2=2$, the states are 20**, 11**, 02** where now ** can be either 10 or 01. That gives $3\times 2=6$ more states. When $s_1+s_2=1$, the states are 10**, 01** where now ** can be 20, 11, but not 02 (due to the limit of one ball in the last can). That gives $2\times 2=4$ more states. Finally, when $s_1+s_2=0$, all balls are in the last two cans, which must be full to their limits of $2$ and $1$. The $4+6+4+1=15$ equally probable states therefore are 3000, 2100, 1200, 0300; 2010, 2001, 1110, 1101, 0210, 0201; 1020, 1011, 0120, 0111; 0021. Using the code below, a sequence of $10,009$ such configurations was generated and thinned to every third one, creating $3337$ configurations of the $15$ states. Their frequencies were the following: State: 3000 2100 1200 0300 2010 1110 0210 1020 0120 2001 1101 0201 1011 0111 0021 Count: 202 227 232 218 216 208 238 227 237 209 239 222 243 211 208 A $\chi^2$ test of uniformity gives a $\chi^2$ value of $11.2$, $p=0.67$ ($14$ degrees of freedom): that is beautiful agreement with the hypothesis that this procedure produces equally probable states. This R code is set up to handle the situation in the question. Change a and n to work with other situations. Set N to be large enough to generate the number of realizations you need after thinning. This code cheats a little bit by cycling systematically through all $(i,j)$ pairs. If you want to be strict about running the Markov chain, generate i, j, and ij randomly, as given in the commented code. # # Gibbs-like sampler. # # `a` is an array of maximum numbers of balls of each type. Its values should # all be integers greater than zero. # `n` is the total number of balls. #------------------------------------------------------------------------------# g <- function(j, state, a) { # # `state` contains the occupancy numbers. # `a` is the array of maximum occupancy numbers. # `j` is a pair of indexes into `a` to "rotate". # k <- sum(state[j]) # Total occupancy. x <- floor(runif(1, max(0, k - a[j[2]]), min(k, a[j[1]]) + 1)) state[j] <- c(x, k-x) return(state) } # # Set up the problem. # a <- c(100, 50, 50, 50) n <- 25 # a <- 4:1 # n <- 3 # # Initialize the state. # state <- round(n * a / sum(a)) i <- 1 while (sum(state) < n) { if (state[i] < a[i]) state[i] <- state[i] + 1 i <- i+1 } while (sum(state) > n) { i <- i-1 if (state[i] > 0) state[i] <- state[i] - 1 } # # Conduct a sequence of random changes. # set.seed(17) N <- 1e5 sim <- matrix(state, ncol=1) u <- ceiling(N / choose(length(state), 2) / 2) i <- rep(rep(1:length(state), each=length(state)-1), u) j <- rep(rep(length(state):1, length(state)-1), u) ij <- rbind(i, j) # # Alternatively, generate `ij` randomly: # i <- sample.int(length(state), N, replace=TRUE) # j <- sample.int(length(state)-1, N, replace=TRUE) # ij <- rbind(i, ((i+j-1) %% length(state))+1) # sim <- cbind(sim, apply(ij, 2, function(j) {state <<- g(j, state, a); state})) rownames(sim) <- paste("Can", 1:nrow(sim)) # # Thin them for use. Each column is a state. # thin <- function(x, stride=1, start=1) { i <- round(seq(start, ncol(x), by=stride)) x[, i] } # # Make a scatterplot of the results, to illustrate. # par(mfrow=c(1,1)) s <- thin(sim, stride=max(1, N/1e4)) pairs(t(s) + runif(length(s), -1/2, 1/2), cex=1/2, col="#00000005", pch=16)
How to generate samples uniformly at random from multiple discrete variables subject to constraints? Let's consider a generalization of this problem. There are $m=4$ cans of paint of $m=4$ distinct colors and $n^{(0)}=100$ balls. Can $i$ can hold up to $a^{(0)}_i = (100, 100, 50, 75)$ balls. You w
36,618
Fisher information for $\rho$ in a bivariate normal distribution
The OP clarified in a comment that he examines the standard bivariate normal distribution, with means and variances fixed to zero and unity correspondingly, $$f(x,y) = \frac{1}{2 \pi \sqrt{1-\rho^2}} \exp\left\{-\frac{x^2 +y^2 -2\rho xy}{2(1-\rho^2)}\right\} $$ In turn, this makes the distribution a member of the curved exponential family, and, as I have shown in my answer to this post the maximum likelihood estimator for $\rho$ in such a case does not equal the sample correlation coefficient. Specifically the sample correlation coefficient is $$\tilde r = \frac 1n\sum_{i=1}^nx_iy_i$$ Denoting $\hat \rho$ the mle for $\rho$ and $(1/n)\sum_{i=1}^n(x_i^2 +y_i^2) = (1/n)S_2$, to be the sum of the sample variances of $X$ and $Y$, we obtain $$\hat \rho: \hat \rho^3 -\tilde r \hat \rho^2 + \big[(1/n)S_2-1\big]\hat \rho -\tilde r=0$$ $$\Rightarrow \hat \rho\Big(\hat \rho^2 -\tilde r \hat \rho + \big[(1/n)S_2-1\big] \Big) = \tilde r$$ Doing the algebra, it is not difficult to conclude that we will obtain $\hat \rho = \tilde r$ if,and only if, $(1/n)S_2 =2$, i.e. only if it so happens that the sum of sample variances equals the sum of true variances. So in general for finite samples, $$\hat \rho \neq \tilde r$$ Both remain consistent, but this alone does not imply that the asymptotic distribution of the sample correlation coefficient will attain the Cramer-Rao bound, which is the one found by the OP. And it doesn't.
Fisher information for $\rho$ in a bivariate normal distribution
The OP clarified in a comment that he examines the standard bivariate normal distribution, with means and variances fixed to zero and unity correspondingly, $$f(x,y) = \frac{1}{2 \pi \sqrt{1-\rho^2
Fisher information for $\rho$ in a bivariate normal distribution The OP clarified in a comment that he examines the standard bivariate normal distribution, with means and variances fixed to zero and unity correspondingly, $$f(x,y) = \frac{1}{2 \pi \sqrt{1-\rho^2}} \exp\left\{-\frac{x^2 +y^2 -2\rho xy}{2(1-\rho^2)}\right\} $$ In turn, this makes the distribution a member of the curved exponential family, and, as I have shown in my answer to this post the maximum likelihood estimator for $\rho$ in such a case does not equal the sample correlation coefficient. Specifically the sample correlation coefficient is $$\tilde r = \frac 1n\sum_{i=1}^nx_iy_i$$ Denoting $\hat \rho$ the mle for $\rho$ and $(1/n)\sum_{i=1}^n(x_i^2 +y_i^2) = (1/n)S_2$, to be the sum of the sample variances of $X$ and $Y$, we obtain $$\hat \rho: \hat \rho^3 -\tilde r \hat \rho^2 + \big[(1/n)S_2-1\big]\hat \rho -\tilde r=0$$ $$\Rightarrow \hat \rho\Big(\hat \rho^2 -\tilde r \hat \rho + \big[(1/n)S_2-1\big] \Big) = \tilde r$$ Doing the algebra, it is not difficult to conclude that we will obtain $\hat \rho = \tilde r$ if,and only if, $(1/n)S_2 =2$, i.e. only if it so happens that the sum of sample variances equals the sum of true variances. So in general for finite samples, $$\hat \rho \neq \tilde r$$ Both remain consistent, but this alone does not imply that the asymptotic distribution of the sample correlation coefficient will attain the Cramer-Rao bound, which is the one found by the OP. And it doesn't.
Fisher information for $\rho$ in a bivariate normal distribution The OP clarified in a comment that he examines the standard bivariate normal distribution, with means and variances fixed to zero and unity correspondingly, $$f(x,y) = \frac{1}{2 \pi \sqrt{1-\rho^2
36,619
Uncertainty in random forest imputations from R missForest package
You're correct that understatements of imputation uncertainty is the reason that people use multiple imputation packages like MICE. I can't answer this question for the missForest example in particular, except to observe that by the same token that one might use multiple imputation in estimating a model, I see no reason to not use multiple missForest runs: the trees and bootstrap samples will be different (provided different random seeds), so you can quantify the uncertainty in your imputed data set this way. It sounds as though you have some strong notions of where and how the variables are related to each other, though, so perhaps a fully Bayesian approach is in order, wherein the modeling of missing data and the estimation of model parameters happens at the same time. One advantage to this approach is that uncertainty at all levels of the model -- parameter estimates and missing data imputation -- are all simultaneously accounted for, whereas in the standard imputation model, missing data is imputed and then models are estimated. The standard "two-stage" approach to imputation and modeling is what gives rise to the understatement of imputation uncertainty in the first place, so the Bayesian method avoids that entirely.
Uncertainty in random forest imputations from R missForest package
You're correct that understatements of imputation uncertainty is the reason that people use multiple imputation packages like MICE. I can't answer this question for the missForest example in particula
Uncertainty in random forest imputations from R missForest package You're correct that understatements of imputation uncertainty is the reason that people use multiple imputation packages like MICE. I can't answer this question for the missForest example in particular, except to observe that by the same token that one might use multiple imputation in estimating a model, I see no reason to not use multiple missForest runs: the trees and bootstrap samples will be different (provided different random seeds), so you can quantify the uncertainty in your imputed data set this way. It sounds as though you have some strong notions of where and how the variables are related to each other, though, so perhaps a fully Bayesian approach is in order, wherein the modeling of missing data and the estimation of model parameters happens at the same time. One advantage to this approach is that uncertainty at all levels of the model -- parameter estimates and missing data imputation -- are all simultaneously accounted for, whereas in the standard imputation model, missing data is imputed and then models are estimated. The standard "two-stage" approach to imputation and modeling is what gives rise to the understatement of imputation uncertainty in the first place, so the Bayesian method avoids that entirely.
Uncertainty in random forest imputations from R missForest package You're correct that understatements of imputation uncertainty is the reason that people use multiple imputation packages like MICE. I can't answer this question for the missForest example in particula
36,620
Uncertainty in random forest imputations from R missForest package
Using the mice package, you can conduct multiple imputation using random forest as the underlying modeling method. Modifying the example shown in the mice documentation: imp <- mice(nhanes,defaultMethod=c("rf","rf","rf")) This would create 5 imputed datasets, with all missing data, whether continuous or categorical, filled-in via random forest. The problem is how to pool the gam objects with smoothed terms fitted on each imputed dataset. From scanning the mice documentation, it seems that package has functions to pool results from lm, glm, lme, and lmer objects. So for other objects such as gam, the pooling would have to be done by hand, if feasible. So no advantage in this case. It would be the same as generating 5 imputed datasets with missForest and pooling results by hand.
Uncertainty in random forest imputations from R missForest package
Using the mice package, you can conduct multiple imputation using random forest as the underlying modeling method. Modifying the example shown in the mice documentation: imp <- mice(nhanes,defaultMeth
Uncertainty in random forest imputations from R missForest package Using the mice package, you can conduct multiple imputation using random forest as the underlying modeling method. Modifying the example shown in the mice documentation: imp <- mice(nhanes,defaultMethod=c("rf","rf","rf")) This would create 5 imputed datasets, with all missing data, whether continuous or categorical, filled-in via random forest. The problem is how to pool the gam objects with smoothed terms fitted on each imputed dataset. From scanning the mice documentation, it seems that package has functions to pool results from lm, glm, lme, and lmer objects. So for other objects such as gam, the pooling would have to be done by hand, if feasible. So no advantage in this case. It would be the same as generating 5 imputed datasets with missForest and pooling results by hand.
Uncertainty in random forest imputations from R missForest package Using the mice package, you can conduct multiple imputation using random forest as the underlying modeling method. Modifying the example shown in the mice documentation: imp <- mice(nhanes,defaultMeth
36,621
Uncertainty in random forest imputations from R missForest package
In the paper presenting the missForest package (see Ref below), it is mentioned in the abstract that: "By averaging over many unpruned classification or regression trees, random forest intrinsically constitutes a multiple imputation scheme." ...followed by:"Using the built-in out-of-bag error estimates of random forest, we are able to estimate the imputation error without the need of a test set." If I understand this right, the OOBerror represent the error accross multiple imputations (so it would include the error of imputed vs observed for individual trees AND the error across different trees ?). Still, I am not an expert and I think that previous answers for your questions provide a safe way to address your question (by using multiple missForest runs). Depending on the exact meaning of what the authors said in the abstract, I think you should obtain, accross your multiple missForest runs, an error close to the OOBerror of a single run ? Ref: Stekhoven, Daniel J., and Peter Bühlmann. "MissForest—non-parametric missing value imputation for mixed-type data." Bioinformatics 28.1 (2011): 112-118.
Uncertainty in random forest imputations from R missForest package
In the paper presenting the missForest package (see Ref below), it is mentioned in the abstract that: "By averaging over many unpruned classification or regression trees, random forest intrinsically c
Uncertainty in random forest imputations from R missForest package In the paper presenting the missForest package (see Ref below), it is mentioned in the abstract that: "By averaging over many unpruned classification or regression trees, random forest intrinsically constitutes a multiple imputation scheme." ...followed by:"Using the built-in out-of-bag error estimates of random forest, we are able to estimate the imputation error without the need of a test set." If I understand this right, the OOBerror represent the error accross multiple imputations (so it would include the error of imputed vs observed for individual trees AND the error across different trees ?). Still, I am not an expert and I think that previous answers for your questions provide a safe way to address your question (by using multiple missForest runs). Depending on the exact meaning of what the authors said in the abstract, I think you should obtain, accross your multiple missForest runs, an error close to the OOBerror of a single run ? Ref: Stekhoven, Daniel J., and Peter Bühlmann. "MissForest—non-parametric missing value imputation for mixed-type data." Bioinformatics 28.1 (2011): 112-118.
Uncertainty in random forest imputations from R missForest package In the paper presenting the missForest package (see Ref below), it is mentioned in the abstract that: "By averaging over many unpruned classification or regression trees, random forest intrinsically c
36,622
Ethics of publishing covariate matrix
Yes, there is no way to reverse engineer the information. But, the ethics of data remain as is, and one needs to respect them before sharing information which has been mined from that data. So, you need to take written permission from the lab which have done the experiments. If it is your lab, then include the permissions certificate you have obtained for the experiments.
Ethics of publishing covariate matrix
Yes, there is no way to reverse engineer the information. But, the ethics of data remain as is, and one needs to respect them before sharing information which has been mined from that data. So, you ne
Ethics of publishing covariate matrix Yes, there is no way to reverse engineer the information. But, the ethics of data remain as is, and one needs to respect them before sharing information which has been mined from that data. So, you need to take written permission from the lab which have done the experiments. If it is your lab, then include the permissions certificate you have obtained for the experiments.
Ethics of publishing covariate matrix Yes, there is no way to reverse engineer the information. But, the ethics of data remain as is, and one needs to respect them before sharing information which has been mined from that data. So, you ne
36,623
Relation between linear regression prediction accuracy and correlation
In a linear regression you are trying to find the best fit of a set of output $Y=(Y_1,\dots,Y_n)$ as a linear function of input $X=(X_1,\dots,X_n)$, i.e. you want the $a$ and $b$ that gives the smallest residuals: $$(a,b)= arg \min \sum_i (Y_i-aX_i-b)^2$$ if it is what you did and you formally get (if you are still working with the same $n$ observations) $$a=arg\min Var(Y-aX), \;\; b=\bar{Y}-a\bar{X},\;\; and \;\; R^2=\frac{var(aX)}{var(Y)}=corr(X,Y)$$ (where for any two vector $U,V$ $\bar{U}$ is the empirical mean $Var(U)$ and $corr(U,V)$ the correlation). You do not say how you compute your errors but if you are computing $var(Y-ax)$ then it is equal to $(1-R^2)*var(Y)$ so if you normalise the errors by $var(Y)$ then you have $$Error=\frac{var(Y-ax)}{var(Y)}=1-R^2$$ which in your case should be 0.03 (because $R^2$ is 0.97). But what you did (I guess :) ) is that you computed the root mean error divided by the standard deviation of the output wich is exactly $\sqrt{Error}$ (according to my definition). Your results are perfectly correct and conform to the theory because $$ \sqrt{Error}=\sqrt{0.03}=0.1732051$$ nothing surprising ! CQFD
Relation between linear regression prediction accuracy and correlation
In a linear regression you are trying to find the best fit of a set of output $Y=(Y_1,\dots,Y_n)$ as a linear function of input $X=(X_1,\dots,X_n)$, i.e. you want the $a$ and $b$ that gives the smalle
Relation between linear regression prediction accuracy and correlation In a linear regression you are trying to find the best fit of a set of output $Y=(Y_1,\dots,Y_n)$ as a linear function of input $X=(X_1,\dots,X_n)$, i.e. you want the $a$ and $b$ that gives the smallest residuals: $$(a,b)= arg \min \sum_i (Y_i-aX_i-b)^2$$ if it is what you did and you formally get (if you are still working with the same $n$ observations) $$a=arg\min Var(Y-aX), \;\; b=\bar{Y}-a\bar{X},\;\; and \;\; R^2=\frac{var(aX)}{var(Y)}=corr(X,Y)$$ (where for any two vector $U,V$ $\bar{U}$ is the empirical mean $Var(U)$ and $corr(U,V)$ the correlation). You do not say how you compute your errors but if you are computing $var(Y-ax)$ then it is equal to $(1-R^2)*var(Y)$ so if you normalise the errors by $var(Y)$ then you have $$Error=\frac{var(Y-ax)}{var(Y)}=1-R^2$$ which in your case should be 0.03 (because $R^2$ is 0.97). But what you did (I guess :) ) is that you computed the root mean error divided by the standard deviation of the output wich is exactly $\sqrt{Error}$ (according to my definition). Your results are perfectly correct and conform to the theory because $$ \sqrt{Error}=\sqrt{0.03}=0.1732051$$ nothing surprising ! CQFD
Relation between linear regression prediction accuracy and correlation In a linear regression you are trying to find the best fit of a set of output $Y=(Y_1,\dots,Y_n)$ as a linear function of input $X=(X_1,\dots,X_n)$, i.e. you want the $a$ and $b$ that gives the smalle
36,624
Relation between linear regression prediction accuracy and correlation
I think I know what's going on. Intuitiviely, your method of calculating prediction error seems OK - You take the residual value (i.e error) and see how big it is relative to your data (i.e., relative to either the predicted value or the value of your dependent variable) by dividing by that value. However, there's at lease one issue with calculating error in this way that I can think of: When you divide by the value of the dependent variable, you are expecting the divisor not be close to zero - when it is, your residual/(actual value) can become huge, simply because the actual value may be a fraction (i.e., close to zero...e.g., .005). I ran the following simulations and confirmed my suspicion: # we'll run about 150 linear models. The x value will be closely related to the y value (linear relationship), meaning that if x is close to 0, y will be close to 0. The mean of the independent variable (x) is stored in the following vector: seq(-50, 50, .7) -> mean_vals # dataframe to save our regression results in: data.frame(r_sqrd = NA, resid_over_value = NA, mean_vals = NA) -> frame for(i in 1:length(mean_vals)){ x <- rnorm(n = 1000, mean = mean_vals[i], sd = 10) x + rnorm(n = 1000, mean = 0, sd = 5) -> y lm(formula = y ~ x) -> k # This - or some close relative of this - is how you are calculating error k$residuals/y -> z mean(z) -> frame[i,"resid_over_value"] # THe Rsquared value is a much more typical measure of fit/prediction error for a linear model: summary(k)$r.squared -> frame[i, "r_sqrd"] # Put the mean of the x values in the frame so we can see how your method of prediction error changes as a function of mean mean_vals[i] -> frame[i, "mean_val"] } As you can see in the plot below, your method of error does not increase as a function of Rsquared (which is an issue in itself, though I'm not 100% sure on why this is happening)...The issue that I focused in on had to do with the outliers in the below graph. plot(frame$r_sqrd, frame$resid_over_value, xlab = "Rsquared", ylab = "Error according to your method") ...Those points generally occur when the mean of the predictor variable is close to zero, as can be seen in the below graph: plot(frame$mean_val, frame$resid_over_value, xlab = "Mean of independent variable", ylab = "Error according to your method") To conclude, I suggest you use a more standard version of model fit/prediction error such as the mean squared error (MSE) or the rquared.
Relation between linear regression prediction accuracy and correlation
I think I know what's going on. Intuitiviely, your method of calculating prediction error seems OK - You take the residual value (i.e error) and see how big it is relative to your data (i.e., relative
Relation between linear regression prediction accuracy and correlation I think I know what's going on. Intuitiviely, your method of calculating prediction error seems OK - You take the residual value (i.e error) and see how big it is relative to your data (i.e., relative to either the predicted value or the value of your dependent variable) by dividing by that value. However, there's at lease one issue with calculating error in this way that I can think of: When you divide by the value of the dependent variable, you are expecting the divisor not be close to zero - when it is, your residual/(actual value) can become huge, simply because the actual value may be a fraction (i.e., close to zero...e.g., .005). I ran the following simulations and confirmed my suspicion: # we'll run about 150 linear models. The x value will be closely related to the y value (linear relationship), meaning that if x is close to 0, y will be close to 0. The mean of the independent variable (x) is stored in the following vector: seq(-50, 50, .7) -> mean_vals # dataframe to save our regression results in: data.frame(r_sqrd = NA, resid_over_value = NA, mean_vals = NA) -> frame for(i in 1:length(mean_vals)){ x <- rnorm(n = 1000, mean = mean_vals[i], sd = 10) x + rnorm(n = 1000, mean = 0, sd = 5) -> y lm(formula = y ~ x) -> k # This - or some close relative of this - is how you are calculating error k$residuals/y -> z mean(z) -> frame[i,"resid_over_value"] # THe Rsquared value is a much more typical measure of fit/prediction error for a linear model: summary(k)$r.squared -> frame[i, "r_sqrd"] # Put the mean of the x values in the frame so we can see how your method of prediction error changes as a function of mean mean_vals[i] -> frame[i, "mean_val"] } As you can see in the plot below, your method of error does not increase as a function of Rsquared (which is an issue in itself, though I'm not 100% sure on why this is happening)...The issue that I focused in on had to do with the outliers in the below graph. plot(frame$r_sqrd, frame$resid_over_value, xlab = "Rsquared", ylab = "Error according to your method") ...Those points generally occur when the mean of the predictor variable is close to zero, as can be seen in the below graph: plot(frame$mean_val, frame$resid_over_value, xlab = "Mean of independent variable", ylab = "Error according to your method") To conclude, I suggest you use a more standard version of model fit/prediction error such as the mean squared error (MSE) or the rquared.
Relation between linear regression prediction accuracy and correlation I think I know what's going on. Intuitiviely, your method of calculating prediction error seems OK - You take the residual value (i.e error) and see how big it is relative to your data (i.e., relative
36,625
Is it legitimate to refit my best model with my test data as a final step in the model building process
Yes, Of course, the accuracy you should report is from training with the test set held out. But now it's time to make predictions and you want them to be as good as they can be. This is certainly legitimate and important for exactly the reasons you mention. Your most recent data is what you want to test against and what you want final predictions to be made based on. There are some things worth being careful of. In some machine learning algorithms, parameters are sensitive to the size of your training data for instance, in k-Nearest-Neighbour Regression, the optimal $k$ grows with $n$. So you may want to cross validate with several training sizes and extrapolate to find the best $k$ for your full training data. Another example is if you are using a regularized GLM, with an objective function of the form $f(\theta) = L(\theta) + \lambda R(\theta)$ where $L$ is your loss and $R$ is your regularization. If you Total Logloss as $L$ this will be sensitive to training set size, whereas Average Logloss will not. So using average logloss makes the $\lambda$ you establish in CV usable with more data.
Is it legitimate to refit my best model with my test data as a final step in the model building proc
Yes, Of course, the accuracy you should report is from training with the test set held out. But now it's time to make predictions and you want them to be as good as they can be. This is certainly le
Is it legitimate to refit my best model with my test data as a final step in the model building process Yes, Of course, the accuracy you should report is from training with the test set held out. But now it's time to make predictions and you want them to be as good as they can be. This is certainly legitimate and important for exactly the reasons you mention. Your most recent data is what you want to test against and what you want final predictions to be made based on. There are some things worth being careful of. In some machine learning algorithms, parameters are sensitive to the size of your training data for instance, in k-Nearest-Neighbour Regression, the optimal $k$ grows with $n$. So you may want to cross validate with several training sizes and extrapolate to find the best $k$ for your full training data. Another example is if you are using a regularized GLM, with an objective function of the form $f(\theta) = L(\theta) + \lambda R(\theta)$ where $L$ is your loss and $R$ is your regularization. If you Total Logloss as $L$ this will be sensitive to training set size, whereas Average Logloss will not. So using average logloss makes the $\lambda$ you establish in CV usable with more data.
Is it legitimate to refit my best model with my test data as a final step in the model building proc Yes, Of course, the accuracy you should report is from training with the test set held out. But now it's time to make predictions and you want them to be as good as they can be. This is certainly le
36,626
Is it legitimate to refit my best model with my test data as a final step in the model building process
It depends on the model you're using. Unless you're limiting yourself to a simple class of convex models/loss functions, you're considerably better off keeping a final test split. Here's why: Let's say you collect iid sample pairs from your data generating distribution, some set of (x, y). You then split this up into a training and test set, and train a model on the training set. Out of that training process you get a model instance, f(x; w). Where w denotes the model parameters. Let's say you have N observations in the test set. When you validate this model on that test set you form the set of test predictions, {f(x_i, w) : i=1,2,...,N} and compare it to the set of test labels {y_i : i=1,2,...,N} using a performance metric. What you're able to say using N independent observations is how you expect that model instance, i.e. the function given a specific w, will generalize to other iid data from the same distribution. Importantly, you only really have one observation (that w you found) to comment on your process for determining f(x, w), i.e. the training process. You can say a little more using something like k-fold cross validation, but unless your willing to do exhaustive cross-validation (which is not really feasible in many ML settings), you'll always have less data on the reliability of your training process. Take a pathological example, where you draw the model parameters at random, and you don't train them at all. You obtain some model instance f(x, w_a). Despite the absurdity of your (lack of) training process, your test set performance is still indicative of how that model instance will generalize to unseen data. Those N observations are still perfectly valid to use. Maybe you'll have gotten lucky and have landed on a pretty good w_a. However, if you combine the test and training set, then "retrain" the model to obtaining a w_b, you're in trouble. The results of your previous test performance amounts to basically a point estimate of how well your next random parameter draw will fare. There are statistical results that you can use to comment on the reliability of the entire training process. But they require some assumptions about your model class, loss function, and your ability to find the best f(x, w) from within that class for any given set of training observation. With all that, you can get some bounds on the probability that your performance on unseen data will deviate by more that a certain amount from what you measured on the training data. However, those results do not carry over (in a useful way) to overparameterized and non-convex models like modern neural networks. The pathological example above is a little over the top. But as an ML researcher and consultant, I have seen neural network training pipelines that occasionally latch on to terrible local minima, but otherwise perform great. Without a final test split, you'd have no way of being sure that hadn't happened on your final retraining. More generally, in a modern machine learning context, you cannot treat the models coming out of your training process as interchangeable. Even if they do perform similarly on a validation set. In fact, you may see considerable variation from one model to the next when using the full bag of stochastic optimization tricks. (For more details on that, check out this work on underspecification.)
Is it legitimate to refit my best model with my test data as a final step in the model building proc
It depends on the model you're using. Unless you're limiting yourself to a simple class of convex models/loss functions, you're considerably better off keeping a final test split. Here's why: Let's sa
Is it legitimate to refit my best model with my test data as a final step in the model building process It depends on the model you're using. Unless you're limiting yourself to a simple class of convex models/loss functions, you're considerably better off keeping a final test split. Here's why: Let's say you collect iid sample pairs from your data generating distribution, some set of (x, y). You then split this up into a training and test set, and train a model on the training set. Out of that training process you get a model instance, f(x; w). Where w denotes the model parameters. Let's say you have N observations in the test set. When you validate this model on that test set you form the set of test predictions, {f(x_i, w) : i=1,2,...,N} and compare it to the set of test labels {y_i : i=1,2,...,N} using a performance metric. What you're able to say using N independent observations is how you expect that model instance, i.e. the function given a specific w, will generalize to other iid data from the same distribution. Importantly, you only really have one observation (that w you found) to comment on your process for determining f(x, w), i.e. the training process. You can say a little more using something like k-fold cross validation, but unless your willing to do exhaustive cross-validation (which is not really feasible in many ML settings), you'll always have less data on the reliability of your training process. Take a pathological example, where you draw the model parameters at random, and you don't train them at all. You obtain some model instance f(x, w_a). Despite the absurdity of your (lack of) training process, your test set performance is still indicative of how that model instance will generalize to unseen data. Those N observations are still perfectly valid to use. Maybe you'll have gotten lucky and have landed on a pretty good w_a. However, if you combine the test and training set, then "retrain" the model to obtaining a w_b, you're in trouble. The results of your previous test performance amounts to basically a point estimate of how well your next random parameter draw will fare. There are statistical results that you can use to comment on the reliability of the entire training process. But they require some assumptions about your model class, loss function, and your ability to find the best f(x, w) from within that class for any given set of training observation. With all that, you can get some bounds on the probability that your performance on unseen data will deviate by more that a certain amount from what you measured on the training data. However, those results do not carry over (in a useful way) to overparameterized and non-convex models like modern neural networks. The pathological example above is a little over the top. But as an ML researcher and consultant, I have seen neural network training pipelines that occasionally latch on to terrible local minima, but otherwise perform great. Without a final test split, you'd have no way of being sure that hadn't happened on your final retraining. More generally, in a modern machine learning context, you cannot treat the models coming out of your training process as interchangeable. Even if they do perform similarly on a validation set. In fact, you may see considerable variation from one model to the next when using the full bag of stochastic optimization tricks. (For more details on that, check out this work on underspecification.)
Is it legitimate to refit my best model with my test data as a final step in the model building proc It depends on the model you're using. Unless you're limiting yourself to a simple class of convex models/loss functions, you're considerably better off keeping a final test split. Here's why: Let's sa
36,627
Truncated power basis function and continuity in b-splines
Truncated power basis functions can be used to construct splines, the purpose of which is to interpolate or smooth data. B-splines are an alternative system to construct splines. They are different algorithms - 2 separate systems for achieving the same goal. B-splines are more commonly used because, while the truncated power basis is conceptually simple, rounding problems can occur at powers of large numbers. Nevertheless, I will address your question about truncated power basis functions, specifically. As a low-level explanation for where the "continuity" in the spline comes from, continuity means that there are no gaps in the values of a function $f(x)$. This can be achieved by joining together multiple functions together at knots (like $\xi_1, \xi_2$ in the below diagram). But continuity is not just limited to the value of the function, it should also apply to its first derivative $f'(x)$, second derivative $f''(x)$ and potentially even higher orders. Typically, continuity at $\{ f(x), \ f'(x), \ f''(x) \}$ is enough to make functions look smooth to the human eye, but the application may demand higher orders as well. Using high-enough powers in truncated power functions allows you to "match up" not only the function values $f(x)$, but also their derivatives $f'(x), \ f''(x), \ \ldots$, at the knots. This is done by constraining these quantities to be equal at the knots during the process of fitting the spline. This example of increasing orders of continuity at knots $\xi_1, \xi_2$ from ESL Chapter 5 should be helpful with the intuition:
Truncated power basis function and continuity in b-splines
Truncated power basis functions can be used to construct splines, the purpose of which is to interpolate or smooth data. B-splines are an alternative system to construct splines. They are different al
Truncated power basis function and continuity in b-splines Truncated power basis functions can be used to construct splines, the purpose of which is to interpolate or smooth data. B-splines are an alternative system to construct splines. They are different algorithms - 2 separate systems for achieving the same goal. B-splines are more commonly used because, while the truncated power basis is conceptually simple, rounding problems can occur at powers of large numbers. Nevertheless, I will address your question about truncated power basis functions, specifically. As a low-level explanation for where the "continuity" in the spline comes from, continuity means that there are no gaps in the values of a function $f(x)$. This can be achieved by joining together multiple functions together at knots (like $\xi_1, \xi_2$ in the below diagram). But continuity is not just limited to the value of the function, it should also apply to its first derivative $f'(x)$, second derivative $f''(x)$ and potentially even higher orders. Typically, continuity at $\{ f(x), \ f'(x), \ f''(x) \}$ is enough to make functions look smooth to the human eye, but the application may demand higher orders as well. Using high-enough powers in truncated power functions allows you to "match up" not only the function values $f(x)$, but also their derivatives $f'(x), \ f''(x), \ \ldots$, at the knots. This is done by constraining these quantities to be equal at the knots during the process of fitting the spline. This example of increasing orders of continuity at knots $\xi_1, \xi_2$ from ESL Chapter 5 should be helpful with the intuition:
Truncated power basis function and continuity in b-splines Truncated power basis functions can be used to construct splines, the purpose of which is to interpolate or smooth data. B-splines are an alternative system to construct splines. They are different al
36,628
Truncated power basis function and continuity in b-splines
I don't think that the truncating power basis function is added for continuity. The main advantage of the truncated power function basis is the simplicity of its construction and the ease of interpreting the parameters in a model that corresponds to these basis functions. But it can definitely be proved that adding truncating basis function ((x − ξ)^n) to a 'n' degree polynomial leads to discontinuity only in third order derivatives. The first and second order derivative will still be continuous and hence the spline function will be smooth and continuous.
Truncated power basis function and continuity in b-splines
I don't think that the truncating power basis function is added for continuity. The main advantage of the truncated power function basis is the simplicity of its construction and the ease of interpret
Truncated power basis function and continuity in b-splines I don't think that the truncating power basis function is added for continuity. The main advantage of the truncated power function basis is the simplicity of its construction and the ease of interpreting the parameters in a model that corresponds to these basis functions. But it can definitely be proved that adding truncating basis function ((x − ξ)^n) to a 'n' degree polynomial leads to discontinuity only in third order derivatives. The first and second order derivative will still be continuous and hence the spline function will be smooth and continuous.
Truncated power basis function and continuity in b-splines I don't think that the truncating power basis function is added for continuity. The main advantage of the truncated power function basis is the simplicity of its construction and the ease of interpret
36,629
Q-Learning stuck on a nearly toy problem
Exploration might be an issue. Are you sure the algorithm tries all legal actions during the training? Setting a very high initial estimate for all the Q-values will encourage exploration at the start of the training. You could also try "soft selection" where you randomly select an action other than the one with highest Q-value some of the time.
Q-Learning stuck on a nearly toy problem
Exploration might be an issue. Are you sure the algorithm tries all legal actions during the training? Setting a very high initial estimate for all the Q-values will encourage exploration at the start
Q-Learning stuck on a nearly toy problem Exploration might be an issue. Are you sure the algorithm tries all legal actions during the training? Setting a very high initial estimate for all the Q-values will encourage exploration at the start of the training. You could also try "soft selection" where you randomly select an action other than the one with highest Q-value some of the time.
Q-Learning stuck on a nearly toy problem Exploration might be an issue. Are you sure the algorithm tries all legal actions during the training? Setting a very high initial estimate for all the Q-values will encourage exploration at the start
36,630
Handling case weight in the Random Forest packages in R
Do not duplicate to up-weight samples. That would make the out-of-bag cross validation very over optimistic. Both stratification and class weighting are implemented in randomForest and here's some other threads on that. random-forest-with-classes-that-are-very-unbalanced R package for Weighted Random Forest? classwt option? Weighting more recent data in Random Forest model
Handling case weight in the Random Forest packages in R
Do not duplicate to up-weight samples. That would make the out-of-bag cross validation very over optimistic. Both stratification and class weighting are implemented in randomForest and here's some oth
Handling case weight in the Random Forest packages in R Do not duplicate to up-weight samples. That would make the out-of-bag cross validation very over optimistic. Both stratification and class weighting are implemented in randomForest and here's some other threads on that. random-forest-with-classes-that-are-very-unbalanced R package for Weighted Random Forest? classwt option? Weighting more recent data in Random Forest model
Handling case weight in the Random Forest packages in R Do not duplicate to up-weight samples. That would make the out-of-bag cross validation very over optimistic. Both stratification and class weighting are implemented in randomForest and here's some oth
36,631
Handling case weight in the Random Forest packages in R
Replicating your observations might be a good idea. I know that WEKA allows different weights for each instance. From WEKA's wiki: This feature exists in versions of Weka >= 3.5.8. A weight can be associated with an instance in a standard ARFF file by appending it to the end of the line for that instance and enclosing the value in curly braces. E.g: @data 0, X, 0, Y, "class A", {5} For a sparse instance, this example would look like: @data {1 X, 3 Y, 4 "class A"}, {5} If you still want to use R you might try the package RWeka.
Handling case weight in the Random Forest packages in R
Replicating your observations might be a good idea. I know that WEKA allows different weights for each instance. From WEKA's wiki: This feature exists in versions of Weka >= 3.5.8. A weight can be as
Handling case weight in the Random Forest packages in R Replicating your observations might be a good idea. I know that WEKA allows different weights for each instance. From WEKA's wiki: This feature exists in versions of Weka >= 3.5.8. A weight can be associated with an instance in a standard ARFF file by appending it to the end of the line for that instance and enclosing the value in curly braces. E.g: @data 0, X, 0, Y, "class A", {5} For a sparse instance, this example would look like: @data {1 X, 3 Y, 4 "class A"}, {5} If you still want to use R you might try the package RWeka.
Handling case weight in the Random Forest packages in R Replicating your observations might be a good idea. I know that WEKA allows different weights for each instance. From WEKA's wiki: This feature exists in versions of Weka >= 3.5.8. A weight can be as
36,632
variational inference with KL
The KL divergences can be seen as a product of a weighting function $w(x)$ and a penalty function $g(x)$, i.e. $KL(q||p) = \sum_x w(x)g(x)$ with $w(x) = q(x)$ and $g(x) = \log\frac{q(x)}{p(x)}$ in the case of the reverse KL divergence. Whenever the weighting function is close to zero, i.e. $w(x) \approx 0$, the product of $w(x)g(x)$ is also close to zero and the value of the penalty function $g(x)$ does not contribute to the KL divergence no matter how large it is. Consider first the case of reverse KL divergence. When $q(x)$ is close to zero, the penalty term $g(x) = \log\frac{q(x)}{p(x)}$ is ignored and therefore the reverse KL divergence ''ignores'' the portion of $p(x)$, which is not covered by $q(x)$. On the other hand, when $q(x)$ has significant mass and $p(x)$ is close to zero the penalty term $g(x)$ will be large. Therefore the reverse KL divergence discourages situations where $q(x)$ is high and $p(x)$ is small leading to the ''zero-forcing''-effect. We can now make a similar analysis of the ''forward'' KL divergence. Now the weighting function corresponds to the target distribution $p$, i.e. $w(x) = p(x)$. Thus, when $p(x) \approx 0$ the value of the penalty $g(x) = \log\frac{p(x)}{q(x)}$ is largely ignored. Thus, there is almost no cost of having large $q(x)$ when $p(x)$ is small. On the other hand we see that when $p(x)$ has significant mass and $q(x)$ is small the contribution to the KL divergence is large. Combining these two properties leads to the ''zero-avoiding'' property.
variational inference with KL
The KL divergences can be seen as a product of a weighting function $w(x)$ and a penalty function $g(x)$, i.e. $KL(q||p) = \sum_x w(x)g(x)$ with $w(x) = q(x)$ and $g(x) = \log\frac{q(x)}{p(x)}$ in the
variational inference with KL The KL divergences can be seen as a product of a weighting function $w(x)$ and a penalty function $g(x)$, i.e. $KL(q||p) = \sum_x w(x)g(x)$ with $w(x) = q(x)$ and $g(x) = \log\frac{q(x)}{p(x)}$ in the case of the reverse KL divergence. Whenever the weighting function is close to zero, i.e. $w(x) \approx 0$, the product of $w(x)g(x)$ is also close to zero and the value of the penalty function $g(x)$ does not contribute to the KL divergence no matter how large it is. Consider first the case of reverse KL divergence. When $q(x)$ is close to zero, the penalty term $g(x) = \log\frac{q(x)}{p(x)}$ is ignored and therefore the reverse KL divergence ''ignores'' the portion of $p(x)$, which is not covered by $q(x)$. On the other hand, when $q(x)$ has significant mass and $p(x)$ is close to zero the penalty term $g(x)$ will be large. Therefore the reverse KL divergence discourages situations where $q(x)$ is high and $p(x)$ is small leading to the ''zero-forcing''-effect. We can now make a similar analysis of the ''forward'' KL divergence. Now the weighting function corresponds to the target distribution $p$, i.e. $w(x) = p(x)$. Thus, when $p(x) \approx 0$ the value of the penalty $g(x) = \log\frac{p(x)}{q(x)}$ is largely ignored. Thus, there is almost no cost of having large $q(x)$ when $p(x)$ is small. On the other hand we see that when $p(x)$ has significant mass and $q(x)$ is small the contribution to the KL divergence is large. Combining these two properties leads to the ''zero-avoiding'' property.
variational inference with KL The KL divergences can be seen as a product of a weighting function $w(x)$ and a penalty function $g(x)$, i.e. $KL(q||p) = \sum_x w(x)g(x)$ with $w(x) = q(x)$ and $g(x) = \log\frac{q(x)}{p(x)}$ in the
36,633
Why use precision instead of variance in a prior?
I guess that you ask about parametrization of Normal distribution, as some statistical software such as BUGS, or JAGS use precision rather than variance. First, notice that it is not true for every statistical package, e.g. R or Stan use "traditional" standard deviation (square root of variance), so this is not always true. Why precision is used? It is mostly for some historical, obsolete, reasons. The general rationale, as I heard about it, was that we are rather interested in how "precise", i.e. focused around the mean, is our variable, rather then how "unprecise" or diffuse it is, since we often think of it in terms of mean. There is also another reason given by Kruschke (Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan, p. 454): Because of its role in conjugate priors for normal likelihood function, the gamma distribution is routinely used as a prior for precision. But there is no logical necessity to do so, and modern MCMC methods permit more flexible specification of priors. Indeed, because precision is less intuitive than standard deviation, it can be more useful to give standard deviation a uniform prior that spans a wide range. The problem with precision is also that in most cases people are interested in knowing the variance, so you end up with inverting precision.
Why use precision instead of variance in a prior?
I guess that you ask about parametrization of Normal distribution, as some statistical software such as BUGS, or JAGS use precision rather than variance. First, notice that it is not true for every st
Why use precision instead of variance in a prior? I guess that you ask about parametrization of Normal distribution, as some statistical software such as BUGS, or JAGS use precision rather than variance. First, notice that it is not true for every statistical package, e.g. R or Stan use "traditional" standard deviation (square root of variance), so this is not always true. Why precision is used? It is mostly for some historical, obsolete, reasons. The general rationale, as I heard about it, was that we are rather interested in how "precise", i.e. focused around the mean, is our variable, rather then how "unprecise" or diffuse it is, since we often think of it in terms of mean. There is also another reason given by Kruschke (Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan, p. 454): Because of its role in conjugate priors for normal likelihood function, the gamma distribution is routinely used as a prior for precision. But there is no logical necessity to do so, and modern MCMC methods permit more flexible specification of priors. Indeed, because precision is less intuitive than standard deviation, it can be more useful to give standard deviation a uniform prior that spans a wide range. The problem with precision is also that in most cases people are interested in knowing the variance, so you end up with inverting precision.
Why use precision instead of variance in a prior? I guess that you ask about parametrization of Normal distribution, as some statistical software such as BUGS, or JAGS use precision rather than variance. First, notice that it is not true for every st
36,634
Statistical test for increasing incidence of a rare event
You can use the non-parametric Mann-Kendall test. For this sample data, cases and the one-sided null hypothesis that there is no increasing trend, you can implement as follows in r. > n<-length(cases) > d<-outer(cases,cases,"-") > s<-sum(sign(d[lower.tri(d)])) > ties<-table(cases) > v<-1/18*(n*(n-1)*(2*n+5)-sum(ties*(ties-1)*(2*ties+5))) > t<-sign(s)*(abs(s)-1)/sqrt(v) > 1-pnorm(t) [1] 0.04319868 And reject at the 5% level in favor of an increasing trend.
Statistical test for increasing incidence of a rare event
You can use the non-parametric Mann-Kendall test. For this sample data, cases and the one-sided null hypothesis that there is no increasing trend, you can implement as follows in r. > n<-length(cases)
Statistical test for increasing incidence of a rare event You can use the non-parametric Mann-Kendall test. For this sample data, cases and the one-sided null hypothesis that there is no increasing trend, you can implement as follows in r. > n<-length(cases) > d<-outer(cases,cases,"-") > s<-sum(sign(d[lower.tri(d)])) > ties<-table(cases) > v<-1/18*(n*(n-1)*(2*n+5)-sum(ties*(ties-1)*(2*ties+5))) > t<-sign(s)*(abs(s)-1)/sqrt(v) > 1-pnorm(t) [1] 0.04319868 And reject at the 5% level in favor of an increasing trend.
Statistical test for increasing incidence of a rare event You can use the non-parametric Mann-Kendall test. For this sample data, cases and the one-sided null hypothesis that there is no increasing trend, you can implement as follows in r. > n<-length(cases)
36,635
Statistical test for increasing incidence of a rare event
You could fit a very simple regression model consisting only of an intercept and time component and test the "significance" of the time component. For instance, you might model $Y_t \sim$ Poisson$(\lambda_t)$ where $Y_t$ is the number of occurences in year $t$ and $\log(\lambda_t) = \alpha + \beta t$ and check if $\beta > 0$.
Statistical test for increasing incidence of a rare event
You could fit a very simple regression model consisting only of an intercept and time component and test the "significance" of the time component. For instance, you might model $Y_t \sim$ Poisson$(\l
Statistical test for increasing incidence of a rare event You could fit a very simple regression model consisting only of an intercept and time component and test the "significance" of the time component. For instance, you might model $Y_t \sim$ Poisson$(\lambda_t)$ where $Y_t$ is the number of occurences in year $t$ and $\log(\lambda_t) = \alpha + \beta t$ and check if $\beta > 0$.
Statistical test for increasing incidence of a rare event You could fit a very simple regression model consisting only of an intercept and time component and test the "significance" of the time component. For instance, you might model $Y_t \sim$ Poisson$(\l
36,636
Statistical test for increasing incidence of a rare event
Just check whether your number of new cases (i.e., number_affected) is significantly correlated with time (i.e., year). As any possible linear dependence of the event rate is at least distorted to the observational discretisation, you want to use a rank-based correlation coefficient, e.g., Kendall’s τ or Spearman’s ρ.
Statistical test for increasing incidence of a rare event
Just check whether your number of new cases (i.e., number_affected) is significantly correlated with time (i.e., year). As any possible linear dependence of the event rate is at least distorted to the
Statistical test for increasing incidence of a rare event Just check whether your number of new cases (i.e., number_affected) is significantly correlated with time (i.e., year). As any possible linear dependence of the event rate is at least distorted to the observational discretisation, you want to use a rank-based correlation coefficient, e.g., Kendall’s τ or Spearman’s ρ.
Statistical test for increasing incidence of a rare event Just check whether your number of new cases (i.e., number_affected) is significantly correlated with time (i.e., year). As any possible linear dependence of the event rate is at least distorted to the
36,637
Should I bother that t-test power is relatively small when H0 is already rejected?
In a narrow sense, you are correct. Power is the chance to correctly reject a false null hypothesis, so you had a small chance but were able to do it anyway. However, from a bayesian belief updating perspective, "reducing power implies reducing the belief shift that is warranted from observing a statistically significant result (McClelland et al. 2015)." Think of it this way: if I told you I surveyed 30,000 people from the general public and found that, contrary to sales figures, people tend to like Pepsi more than Coke, that would be very compelling. I found a result after studying 1% of a population (i.e. the US general public). It is likely to generalize to the larger population. If I surveyed 7 people and found the same thing, even if it was statistically significant, I wouldn't convince anyone. You can argue a lot of reasons for that (you can't get a representative sample, ANOVA/regression assumptions may not be met etc.), but what's important is that high power means highly persuasive (and you should be as critical or more of your results as those you are trying to convince). For the Bayesian mathematics as well as further explanation, you can check out any of the following. Abelson, R. P. (2012). Statistics as principled argument. Psychology Press. Brinberg, D., Lynch Jr, J. G., & Sawyer, A. G. (1992). Hypothesized and confounded explanations in theory tests: A Bayesian analysis. Journal of Consumer Research, 139-154. McClelland, G., Lynch, J. G., Irwin, J. R., Spiller, S. A., & Fitzsimons, G. J. (2015). Median Splits, Type II Errors, and False Positive Consumer Psychology: Don't Fight the Power. Type II Errors, and False Positive Consumer Psychology: Don't Fight the Power (March 10, 2015). Also, Ioannidis (2005) provides some compelling arguments to low power results reflecting type I errors even in the absence of p-hacking and other biases that often result from low power (and the paper is open access in case you don't work for a university or something similar!).
Should I bother that t-test power is relatively small when H0 is already rejected?
In a narrow sense, you are correct. Power is the chance to correctly reject a false null hypothesis, so you had a small chance but were able to do it anyway. However, from a bayesian belief updating p
Should I bother that t-test power is relatively small when H0 is already rejected? In a narrow sense, you are correct. Power is the chance to correctly reject a false null hypothesis, so you had a small chance but were able to do it anyway. However, from a bayesian belief updating perspective, "reducing power implies reducing the belief shift that is warranted from observing a statistically significant result (McClelland et al. 2015)." Think of it this way: if I told you I surveyed 30,000 people from the general public and found that, contrary to sales figures, people tend to like Pepsi more than Coke, that would be very compelling. I found a result after studying 1% of a population (i.e. the US general public). It is likely to generalize to the larger population. If I surveyed 7 people and found the same thing, even if it was statistically significant, I wouldn't convince anyone. You can argue a lot of reasons for that (you can't get a representative sample, ANOVA/regression assumptions may not be met etc.), but what's important is that high power means highly persuasive (and you should be as critical or more of your results as those you are trying to convince). For the Bayesian mathematics as well as further explanation, you can check out any of the following. Abelson, R. P. (2012). Statistics as principled argument. Psychology Press. Brinberg, D., Lynch Jr, J. G., & Sawyer, A. G. (1992). Hypothesized and confounded explanations in theory tests: A Bayesian analysis. Journal of Consumer Research, 139-154. McClelland, G., Lynch, J. G., Irwin, J. R., Spiller, S. A., & Fitzsimons, G. J. (2015). Median Splits, Type II Errors, and False Positive Consumer Psychology: Don't Fight the Power. Type II Errors, and False Positive Consumer Psychology: Don't Fight the Power (March 10, 2015). Also, Ioannidis (2005) provides some compelling arguments to low power results reflecting type I errors even in the absence of p-hacking and other biases that often result from low power (and the paper is open access in case you don't work for a university or something similar!).
Should I bother that t-test power is relatively small when H0 is already rejected? In a narrow sense, you are correct. Power is the chance to correctly reject a false null hypothesis, so you had a small chance but were able to do it anyway. However, from a bayesian belief updating p
36,638
Should I bother that t-test power is relatively small when H0 is already rejected?
It depends on how the power analysis was conducted. Generally speaking, there is a relationship between four variables (alpha, power, the effect size, and $N$) such that if you stipulate any three you can solve for the fourth. Typically, when people run a power analysis after analyzing their data, they do a post-hoc power analysis (hence the name), which means they plug in their value for alpha, their observed effect size, and their $N$, to solve for power. You certainly don't have to do it that way (you could do it beforehand with a theoretically suggested effect size and the $N$ you know will be available to you), but if you do, the results are largely foregone. Specifically, if your result was significant, the power will be $>50\%$, and if your result was not significant, the power will be $<50\%$. That doesn't seem to be quite what you found. One possibility is that there is a subtle discrepancy between the methods used in your test and those in the power analysis. This is suggested by the fact that your observed $p$-value is close to $.05$ and your computed power is close to $50\%$, even though they are on different sides of the line. Another possibility is that you used a slightly different effect size from what you found. So, "should [it] bother [you] that the power is small?" Yes and no. If you did a traditional (invalid) post-hoc power analysis, you were necessarily going to get values like that—the exercise was completely uninformative. On the other hand, if we take the power analysis seriously, a significant effect with a low powered setup basically means that your observed effect has to be biased to be larger than it really is, so you should be less trusting of the results.
Should I bother that t-test power is relatively small when H0 is already rejected?
It depends on how the power analysis was conducted. Generally speaking, there is a relationship between four variables (alpha, power, the effect size, and $N$) such that if you stipulate any three yo
Should I bother that t-test power is relatively small when H0 is already rejected? It depends on how the power analysis was conducted. Generally speaking, there is a relationship between four variables (alpha, power, the effect size, and $N$) such that if you stipulate any three you can solve for the fourth. Typically, when people run a power analysis after analyzing their data, they do a post-hoc power analysis (hence the name), which means they plug in their value for alpha, their observed effect size, and their $N$, to solve for power. You certainly don't have to do it that way (you could do it beforehand with a theoretically suggested effect size and the $N$ you know will be available to you), but if you do, the results are largely foregone. Specifically, if your result was significant, the power will be $>50\%$, and if your result was not significant, the power will be $<50\%$. That doesn't seem to be quite what you found. One possibility is that there is a subtle discrepancy between the methods used in your test and those in the power analysis. This is suggested by the fact that your observed $p$-value is close to $.05$ and your computed power is close to $50\%$, even though they are on different sides of the line. Another possibility is that you used a slightly different effect size from what you found. So, "should [it] bother [you] that the power is small?" Yes and no. If you did a traditional (invalid) post-hoc power analysis, you were necessarily going to get values like that—the exercise was completely uninformative. On the other hand, if we take the power analysis seriously, a significant effect with a low powered setup basically means that your observed effect has to be biased to be larger than it really is, so you should be less trusting of the results.
Should I bother that t-test power is relatively small when H0 is already rejected? It depends on how the power analysis was conducted. Generally speaking, there is a relationship between four variables (alpha, power, the effect size, and $N$) such that if you stipulate any three yo
36,639
Should I bother that t-test power is relatively small when H0 is already rejected?
Denote $p$ the $p$-value of your test (as a random variable) and fix some $\alpha$. Call a test result significant or positive when $p \leq \alpha$. We have $P(p \leq \alpha \,|\, H_0) \leq \alpha$. Moreover, let $\beta$ be such that $P(p > \alpha \,|\, H_1) \leq \beta$. Then $1-\beta$ is the power of the test. Treating $H_0$ and $H_1$ as (complementary) events, Bayes' theorem gives: $$\frac{P(H_1 \, | \, p\leq\alpha)}{P(H_0 \,|\, p\leq\alpha)} = \frac{P(p\leq\alpha \,|\, H_1)}{P(p\leq\alpha \,|\, H_0)} \cdot \frac{P(H_1)}{P(H_0)} \geq \frac{1-\beta}{\alpha} \cdot \frac{P(H_1)}{P(H_0)}$$ This shows that the post odds for $H_1$ are a scaled version of the prior odds, with the strength of the scaling in favor for $H_1$ increasing with $1-\beta$. This means we learn more from a positive test when $1-\beta$ is large. For further illustration, look at confidence intervals (CI). One may argue that larger sample size will make the CI more narrow and thus, if the test was significant for a smaller sample, it will also be significant for the larger sample. However, also the location of the CI can shift when we include more data in our sample, potentially making the result non-significant. It is also conceivable that the larger sample will have a much larger standard error and thus the CI will become wider in fact. One could say that a larger sample size gives the facts more opportunity to prove themselves. There has been some interesting discussion lately about the interpretation of $p$-values, see, e.g.: [1] Colquhoun, "An investigation of the false discovery rate and the misinterpretation of p-values", Royal Society Open Science, 2014 [2] Colquhoun, "The Reproducibility Of Research And The Misinterpretation Of P Values", 2017, http://www.biorxiv.org/content/early/2017/08/07/144337 [3] "What would Cohen say? A comment on $p < .005$", https://replicationindex.wordpress.com/2017/08/02/what-would-cohen-say-a-comment-on-p-005/ Concerning your particular result, I am not qualified to judge it. Using only your $p$-value and the classification from [2], it is between "weak evidence: worth another look" and "moderate evidence for a real effect".
Should I bother that t-test power is relatively small when H0 is already rejected?
Denote $p$ the $p$-value of your test (as a random variable) and fix some $\alpha$. Call a test result significant or positive when $p \leq \alpha$. We have $P(p \leq \alpha \,|\, H_0) \leq \alpha$. M
Should I bother that t-test power is relatively small when H0 is already rejected? Denote $p$ the $p$-value of your test (as a random variable) and fix some $\alpha$. Call a test result significant or positive when $p \leq \alpha$. We have $P(p \leq \alpha \,|\, H_0) \leq \alpha$. Moreover, let $\beta$ be such that $P(p > \alpha \,|\, H_1) \leq \beta$. Then $1-\beta$ is the power of the test. Treating $H_0$ and $H_1$ as (complementary) events, Bayes' theorem gives: $$\frac{P(H_1 \, | \, p\leq\alpha)}{P(H_0 \,|\, p\leq\alpha)} = \frac{P(p\leq\alpha \,|\, H_1)}{P(p\leq\alpha \,|\, H_0)} \cdot \frac{P(H_1)}{P(H_0)} \geq \frac{1-\beta}{\alpha} \cdot \frac{P(H_1)}{P(H_0)}$$ This shows that the post odds for $H_1$ are a scaled version of the prior odds, with the strength of the scaling in favor for $H_1$ increasing with $1-\beta$. This means we learn more from a positive test when $1-\beta$ is large. For further illustration, look at confidence intervals (CI). One may argue that larger sample size will make the CI more narrow and thus, if the test was significant for a smaller sample, it will also be significant for the larger sample. However, also the location of the CI can shift when we include more data in our sample, potentially making the result non-significant. It is also conceivable that the larger sample will have a much larger standard error and thus the CI will become wider in fact. One could say that a larger sample size gives the facts more opportunity to prove themselves. There has been some interesting discussion lately about the interpretation of $p$-values, see, e.g.: [1] Colquhoun, "An investigation of the false discovery rate and the misinterpretation of p-values", Royal Society Open Science, 2014 [2] Colquhoun, "The Reproducibility Of Research And The Misinterpretation Of P Values", 2017, http://www.biorxiv.org/content/early/2017/08/07/144337 [3] "What would Cohen say? A comment on $p < .005$", https://replicationindex.wordpress.com/2017/08/02/what-would-cohen-say-a-comment-on-p-005/ Concerning your particular result, I am not qualified to judge it. Using only your $p$-value and the classification from [2], it is between "weak evidence: worth another look" and "moderate evidence for a real effect".
Should I bother that t-test power is relatively small when H0 is already rejected? Denote $p$ the $p$-value of your test (as a random variable) and fix some $\alpha$. Call a test result significant or positive when $p \leq \alpha$. We have $P(p \leq \alpha \,|\, H_0) \leq \alpha$. M
36,640
Elements of Statistical Learning alternatives
I agree that An Intro to Statistical Learning has a very accommodating tone. You may want to look at Learning From Data, A Short Course by Yaser Abu-Mostafa et al. I found this book and the accompanying youtube videos to be great. Lastly, spdrnl's comment about Applied Predictive Modeling by Kuhn is a good suggestion. I have not read it yet, but I have perused it and it seems like a great resource as well.
Elements of Statistical Learning alternatives
I agree that An Intro to Statistical Learning has a very accommodating tone. You may want to look at Learning From Data, A Short Course by Yaser Abu-Mostafa et al. I found this book and the accompanyi
Elements of Statistical Learning alternatives I agree that An Intro to Statistical Learning has a very accommodating tone. You may want to look at Learning From Data, A Short Course by Yaser Abu-Mostafa et al. I found this book and the accompanying youtube videos to be great. Lastly, spdrnl's comment about Applied Predictive Modeling by Kuhn is a good suggestion. I have not read it yet, but I have perused it and it seems like a great resource as well.
Elements of Statistical Learning alternatives I agree that An Intro to Statistical Learning has a very accommodating tone. You may want to look at Learning From Data, A Short Course by Yaser Abu-Mostafa et al. I found this book and the accompanyi
36,641
Elements of Statistical Learning alternatives
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. Possible alternatives: Pattern Recognition and Machine Learning by Christopher Bishop: I don't like the book's notation systems, but I heard the graphical model chapter is good Machine Learning: A Probabilistic Perspective by Kevin P. Murphy: like a dictionary, describe various of pre-deep-learning-era machine learning methods Deep Learning Book: Newer, covering more about deep learning part Dive into Deep Learning: Possibly newest deep learning book so far Also, try some course notes: CS229T: Statistical Learning Theory CS 228: Probabilistic Graphical Models CS 236: Deep Generative Models
Elements of Statistical Learning alternatives
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Elements of Statistical Learning alternatives Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted. Possible alternatives: Pattern Recognition and Machine Learning by Christopher Bishop: I don't like the book's notation systems, but I heard the graphical model chapter is good Machine Learning: A Probabilistic Perspective by Kevin P. Murphy: like a dictionary, describe various of pre-deep-learning-era machine learning methods Deep Learning Book: Newer, covering more about deep learning part Dive into Deep Learning: Possibly newest deep learning book so far Also, try some course notes: CS229T: Statistical Learning Theory CS 228: Probabilistic Graphical Models CS 236: Deep Generative Models
Elements of Statistical Learning alternatives Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
36,642
What is the best algorithm to find similar text documents?
To find similar documents in very large document sets is locality sensitive hashing (LSH). An indication of the gist is: "One general approach to LSH is to “hash” items several times, in such a way that similar items are more likely to be hashed to the same bucket than dissimilar items are." For in-depth information see: http://infolab.stanford.edu/~ullman/mmds/ch3a.pdf
What is the best algorithm to find similar text documents?
To find similar documents in very large document sets is locality sensitive hashing (LSH). An indication of the gist is: "One general approach to LSH is to “hash” items several times, in such a way th
What is the best algorithm to find similar text documents? To find similar documents in very large document sets is locality sensitive hashing (LSH). An indication of the gist is: "One general approach to LSH is to “hash” items several times, in such a way that similar items are more likely to be hashed to the same bucket than dissimilar items are." For in-depth information see: http://infolab.stanford.edu/~ullman/mmds/ch3a.pdf
What is the best algorithm to find similar text documents? To find similar documents in very large document sets is locality sensitive hashing (LSH). An indication of the gist is: "One general approach to LSH is to “hash” items several times, in such a way th
36,643
What is the best algorithm to find similar text documents?
Why cluster? Why LDA?Much too expensive, complicated, and unreliable. Let me present you an incredible novel technique to find similar documents: text search There is a wonderful tool called Apache Lucene, that makes text search fast and easy to integrate, too.
What is the best algorithm to find similar text documents?
Why cluster? Why LDA?Much too expensive, complicated, and unreliable. Let me present you an incredible novel technique to find similar documents: text search There is a wonderful tool called Apache Lu
What is the best algorithm to find similar text documents? Why cluster? Why LDA?Much too expensive, complicated, and unreliable. Let me present you an incredible novel technique to find similar documents: text search There is a wonderful tool called Apache Lucene, that makes text search fast and easy to integrate, too.
What is the best algorithm to find similar text documents? Why cluster? Why LDA?Much too expensive, complicated, and unreliable. Let me present you an incredible novel technique to find similar documents: text search There is a wonderful tool called Apache Lu
36,644
What is the best algorithm to find similar text documents?
One good technique that I've seen used in the past for information retrieval applications is to shingle your target documents and query document, and then take the Jaccard similarity over sets of shingles. Shingling is a procedure that takes a sliding window over characters in your document, representing a string as the set of character $k$-grams that occur in the strong. Now that we have a set representation of documents, we can compare them using their Jaccard similarity. As an example, the 2-shingles of the string "racecar" would be the set {ra, ac, ce, ec, ca, ar}. Below is some simple Python code that would do this to illustrate the point: def shingle(doc, k=3): return { doc[i:i+k] for i in range(0, len(doc) - k + 1) } def jaccard(a, b): return 1.0 * len(a.intersection(b)) / len(a.union(b)) documents = [...] # List of strings query = "this week on twitter..." query_shingles = shingle(query) best_doc = -1 best_score = float("-inf") for i, doc in enumerate(documents): doc_shingles = shingle(doc) similarity = jaccard(doc_shingles, query_shingles) if similarity > best_score: best_score = similarity best_doc = i The idea is that documents with similar $k$-shingles have similar contents for a well-chosen value of $k$. For most applications $k$ is almost always between 2 and 4 (3 is the most popular choice that I've seen). There are alternative formulations such as $w$-shingling which use word $n$-grams instead of character $n$-grams, but the idea is still the same.
What is the best algorithm to find similar text documents?
One good technique that I've seen used in the past for information retrieval applications is to shingle your target documents and query document, and then take the Jaccard similarity over sets of shin
What is the best algorithm to find similar text documents? One good technique that I've seen used in the past for information retrieval applications is to shingle your target documents and query document, and then take the Jaccard similarity over sets of shingles. Shingling is a procedure that takes a sliding window over characters in your document, representing a string as the set of character $k$-grams that occur in the strong. Now that we have a set representation of documents, we can compare them using their Jaccard similarity. As an example, the 2-shingles of the string "racecar" would be the set {ra, ac, ce, ec, ca, ar}. Below is some simple Python code that would do this to illustrate the point: def shingle(doc, k=3): return { doc[i:i+k] for i in range(0, len(doc) - k + 1) } def jaccard(a, b): return 1.0 * len(a.intersection(b)) / len(a.union(b)) documents = [...] # List of strings query = "this week on twitter..." query_shingles = shingle(query) best_doc = -1 best_score = float("-inf") for i, doc in enumerate(documents): doc_shingles = shingle(doc) similarity = jaccard(doc_shingles, query_shingles) if similarity > best_score: best_score = similarity best_doc = i The idea is that documents with similar $k$-shingles have similar contents for a well-chosen value of $k$. For most applications $k$ is almost always between 2 and 4 (3 is the most popular choice that I've seen). There are alternative formulations such as $w$-shingling which use word $n$-grams instead of character $n$-grams, but the idea is still the same.
What is the best algorithm to find similar text documents? One good technique that I've seen used in the past for information retrieval applications is to shingle your target documents and query document, and then take the Jaccard similarity over sets of shin
36,645
What is the best algorithm to find similar text documents?
This program uses word frequency analysis ("bag of words") and sorts the repository texts by Euclidian distance to the vector of frequencies of the sample text. Given a sample text, this program lists the repository texts sorted by similarity: simple implementation of bag of words in C++. The algorithm is linear in the total length of the sample text and the repository texts. Plus the program is multi-threaded to process repository texts in parallel. Here is the core algorithm: class Statistics { std::unordered_map<std::string, int64_t> _counts; int64_t _totWords; void process(std::string& token); public: explicit Statistics(const std::string& text); double Dist(const Statistics& fellow) const; bool IsEmpty() const { return _totWords == 0; } }; namespace { const std::string gPunctStr = ".,;:!?"; const std::unordered_set<char> gPunctSet(gPunctStr.begin(), gPunctStr.end()); } Statistics::Statistics(const std::string& text) { std::string lastToken; for (size_t i = 0; i < text.size(); i++) { int ch = static_cast<uint8_t>(text[i]); if (!isspace(ch)) { lastToken.push_back(tolower(ch)); continue; } process(lastToken); } process(lastToken); } void Statistics::process(std::string& token) { do { if (token.size() == 0) { break; } if (gPunctSet.find(token.back()) != gPunctSet.end()) { token.pop_back(); } } while (false); if (token.size() != 0) { auto it = _counts.find(token); if (it == _counts.end()) { _counts.emplace(token, 1); } else { it->second++; } _totWords++; token.clear(); } } double Statistics::Dist(const Statistics& fellow) const { double sum = 0; for (const auto& wordInfo : _counts) { const std::string wordText = wordInfo.first; const double freq = double(wordInfo.second) / _totWords; auto it = fellow._counts.find(wordText); double fellowFreq; if (it == fellow._counts.end()) { fellowFreq = 0; } else { fellowFreq = double(it->second) / fellow._totWords; } const double d = freq - fellowFreq; sum += d * d; } return std::sqrt(sum); } It's tested on Project Gutenberg books, as you can see in the example on GitHub.
What is the best algorithm to find similar text documents?
This program uses word frequency analysis ("bag of words") and sorts the repository texts by Euclidian distance to the vector of frequencies of the sample text. Given a sample text, this program lists
What is the best algorithm to find similar text documents? This program uses word frequency analysis ("bag of words") and sorts the repository texts by Euclidian distance to the vector of frequencies of the sample text. Given a sample text, this program lists the repository texts sorted by similarity: simple implementation of bag of words in C++. The algorithm is linear in the total length of the sample text and the repository texts. Plus the program is multi-threaded to process repository texts in parallel. Here is the core algorithm: class Statistics { std::unordered_map<std::string, int64_t> _counts; int64_t _totWords; void process(std::string& token); public: explicit Statistics(const std::string& text); double Dist(const Statistics& fellow) const; bool IsEmpty() const { return _totWords == 0; } }; namespace { const std::string gPunctStr = ".,;:!?"; const std::unordered_set<char> gPunctSet(gPunctStr.begin(), gPunctStr.end()); } Statistics::Statistics(const std::string& text) { std::string lastToken; for (size_t i = 0; i < text.size(); i++) { int ch = static_cast<uint8_t>(text[i]); if (!isspace(ch)) { lastToken.push_back(tolower(ch)); continue; } process(lastToken); } process(lastToken); } void Statistics::process(std::string& token) { do { if (token.size() == 0) { break; } if (gPunctSet.find(token.back()) != gPunctSet.end()) { token.pop_back(); } } while (false); if (token.size() != 0) { auto it = _counts.find(token); if (it == _counts.end()) { _counts.emplace(token, 1); } else { it->second++; } _totWords++; token.clear(); } } double Statistics::Dist(const Statistics& fellow) const { double sum = 0; for (const auto& wordInfo : _counts) { const std::string wordText = wordInfo.first; const double freq = double(wordInfo.second) / _totWords; auto it = fellow._counts.find(wordText); double fellowFreq; if (it == fellow._counts.end()) { fellowFreq = 0; } else { fellowFreq = double(it->second) / fellow._totWords; } const double d = freq - fellowFreq; sum += d * d; } return std::sqrt(sum); } It's tested on Project Gutenberg books, as you can see in the example on GitHub.
What is the best algorithm to find similar text documents? This program uses word frequency analysis ("bag of words") and sorts the repository texts by Euclidian distance to the vector of frequencies of the sample text. Given a sample text, this program lists
36,646
Why (and when) does one have to learn the reward function from samples in reinforcement learning?
In his notes, when you must "estimate them from data", he does not mean the reward function. You rarely estimate the reward function. You typically learn the value function, which estimates the immediate reward plus the temporally-discounted future reward (if the temporal discount is zero, then you are estimating the rewards). Or, you can learn Q values, which are values associated with state-action pairs. In summary, the reward function and the true transition function is defined by the environment. The agent learns things like the transition function, Q values, and the value function.
Why (and when) does one have to learn the reward function from samples in reinforcement learning?
In his notes, when you must "estimate them from data", he does not mean the reward function. You rarely estimate the reward function. You typically learn the value function, which estimates the imme
Why (and when) does one have to learn the reward function from samples in reinforcement learning? In his notes, when you must "estimate them from data", he does not mean the reward function. You rarely estimate the reward function. You typically learn the value function, which estimates the immediate reward plus the temporally-discounted future reward (if the temporal discount is zero, then you are estimating the rewards). Or, you can learn Q values, which are values associated with state-action pairs. In summary, the reward function and the true transition function is defined by the environment. The agent learns things like the transition function, Q values, and the value function.
Why (and when) does one have to learn the reward function from samples in reinforcement learning? In his notes, when you must "estimate them from data", he does not mean the reward function. You rarely estimate the reward function. You typically learn the value function, which estimates the imme
36,647
Why (and when) does one have to learn the reward function from samples in reinforcement learning?
I agree with the other answers that usually, the reward function is not learned directly. The transition probabilities also don't have to be learned. The agent can learn directly the action values, or even directly the policy, with policy gradien method for instance. There are, however techniques for which the reward and the transition probabilities have to be learned. For example, the dyna-Q algorithm (described in Sutton & Barto) maintains a model of the environment. At each time step, the agent uses the reward and state information received from the environment to update the action-values, just like in Q-learning for instance. But it also update its own model of the environment, and then performs N other action-values updates based on that model. The supposition is that the acting->sensing loop takes some non-null time, time that we can put to good use by improving the action-values with simulated samples.
Why (and when) does one have to learn the reward function from samples in reinforcement learning?
I agree with the other answers that usually, the reward function is not learned directly. The transition probabilities also don't have to be learned. The agent can learn directly the action values, or
Why (and when) does one have to learn the reward function from samples in reinforcement learning? I agree with the other answers that usually, the reward function is not learned directly. The transition probabilities also don't have to be learned. The agent can learn directly the action values, or even directly the policy, with policy gradien method for instance. There are, however techniques for which the reward and the transition probabilities have to be learned. For example, the dyna-Q algorithm (described in Sutton & Barto) maintains a model of the environment. At each time step, the agent uses the reward and state information received from the environment to update the action-values, just like in Q-learning for instance. But it also update its own model of the environment, and then performs N other action-values updates based on that model. The supposition is that the acting->sensing loop takes some non-null time, time that we can put to good use by improving the action-values with simulated samples.
Why (and when) does one have to learn the reward function from samples in reinforcement learning? I agree with the other answers that usually, the reward function is not learned directly. The transition probabilities also don't have to be learned. The agent can learn directly the action values, or
36,648
Why (and when) does one have to learn the reward function from samples in reinforcement learning?
This is a good question which is deeper than any imprecise wording in Andrew's notes. It is true that in RL you generally do not need to learn a reward function R(S,A,S'); you need to specify it as part of the problem setup. BUT, there are algorithms (in my experience associated with the afterstate or post-decision state value function) which require the expected reward r(S,A) = E[R(S,A,S')|S,A]. Generally the texts I've seen make little comment on this and assume that r(s,a) is known just as R(S,A,S') is known. But in some cases the reward is dependent on the future state so, without a model, you need to learn this expectation. I am currently working on such a problem where the expected reward function as well as the value function need to be learned. Note that most RL algorithms do NOT require the expected reward function, but some do. See for example the discussion on pg 58 in Algorithms for Reinforcement Learning by Szepesvari. In summary you do not need to learn the reward function, but when working with post-decision state variables, you may need to learn the expected reward function. This is the only case that I am aware of where you need to learn an expected reward function, but I'd be interested to hear of other cases.
Why (and when) does one have to learn the reward function from samples in reinforcement learning?
This is a good question which is deeper than any imprecise wording in Andrew's notes. It is true that in RL you generally do not need to learn a reward function R(S,A,S'); you need to specify it as pa
Why (and when) does one have to learn the reward function from samples in reinforcement learning? This is a good question which is deeper than any imprecise wording in Andrew's notes. It is true that in RL you generally do not need to learn a reward function R(S,A,S'); you need to specify it as part of the problem setup. BUT, there are algorithms (in my experience associated with the afterstate or post-decision state value function) which require the expected reward r(S,A) = E[R(S,A,S')|S,A]. Generally the texts I've seen make little comment on this and assume that r(s,a) is known just as R(S,A,S') is known. But in some cases the reward is dependent on the future state so, without a model, you need to learn this expectation. I am currently working on such a problem where the expected reward function as well as the value function need to be learned. Note that most RL algorithms do NOT require the expected reward function, but some do. See for example the discussion on pg 58 in Algorithms for Reinforcement Learning by Szepesvari. In summary you do not need to learn the reward function, but when working with post-decision state variables, you may need to learn the expected reward function. This is the only case that I am aware of where you need to learn an expected reward function, but I'd be interested to hear of other cases.
Why (and when) does one have to learn the reward function from samples in reinforcement learning? This is a good question which is deeper than any imprecise wording in Andrew's notes. It is true that in RL you generally do not need to learn a reward function R(S,A,S'); you need to specify it as pa
36,649
Why (and when) does one have to learn the reward function from samples in reinforcement learning?
In reinforcement learning, the agent learns the value function, not the reward function. The value of an action is it's overall utility; for example, an action may bring a high reward, but lead to low-value states, making it low-value. What the quote says is that sometimes the world is complicated: some problems have state-action spaces that are too large to enumerate, so we don't have explicit transition probability and reward functions. In such a case the agent would have to learn some generalization of the true value function.
Why (and when) does one have to learn the reward function from samples in reinforcement learning?
In reinforcement learning, the agent learns the value function, not the reward function. The value of an action is it's overall utility; for example, an action may bring a high reward, but lead to low
Why (and when) does one have to learn the reward function from samples in reinforcement learning? In reinforcement learning, the agent learns the value function, not the reward function. The value of an action is it's overall utility; for example, an action may bring a high reward, but lead to low-value states, making it low-value. What the quote says is that sometimes the world is complicated: some problems have state-action spaces that are too large to enumerate, so we don't have explicit transition probability and reward functions. In such a case the agent would have to learn some generalization of the true value function.
Why (and when) does one have to learn the reward function from samples in reinforcement learning? In reinforcement learning, the agent learns the value function, not the reward function. The value of an action is it's overall utility; for example, an action may bring a high reward, but lead to low
36,650
Why (and when) does one have to learn the reward function from samples in reinforcement learning?
I think those notes are slightly confusing. The rewards should be designed by you to encourage your RL agent to optimise the behaviour you want to see. The transitions between states are given by the enviroment and will often be estimated from data. I think what Andrew is refering to is a situation where from state A you could transition to state B which you give reward x or state C which you give reward y. If states B and C are identical except for the differences in reward, you would often eliminate states B and C and give state A a reward estimated from data which shows how often you transition to B or C from A.
Why (and when) does one have to learn the reward function from samples in reinforcement learning?
I think those notes are slightly confusing. The rewards should be designed by you to encourage your RL agent to optimise the behaviour you want to see. The transitions between states are given by the
Why (and when) does one have to learn the reward function from samples in reinforcement learning? I think those notes are slightly confusing. The rewards should be designed by you to encourage your RL agent to optimise the behaviour you want to see. The transitions between states are given by the enviroment and will often be estimated from data. I think what Andrew is refering to is a situation where from state A you could transition to state B which you give reward x or state C which you give reward y. If states B and C are identical except for the differences in reward, you would often eliminate states B and C and give state A a reward estimated from data which shows how often you transition to B or C from A.
Why (and when) does one have to learn the reward function from samples in reinforcement learning? I think those notes are slightly confusing. The rewards should be designed by you to encourage your RL agent to optimise the behaviour you want to see. The transitions between states are given by the
36,651
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant?
The idea that only non-orthogonal comparisons require adjustment is a myth. See section 6.1 of Frane (2015): http://jrp.icaap.org/index.php/jrp/article/view/514/417 In general, computing several alternate statistics and picking the one that gives you the answer you like best is a bad policy and can cause error inflation (as it's a form of multiple comparisons in itself). It's best to have a statistical plan before you look at your data. Bonferroni is less powerful than Holm. Holm is less powerful than some other procedures that require more assumptions. Sidak is only a tiny bit more powerful than Bonferroni and requires the assumption of non-negative dependence. If you just want to compare each treatment to control, and not compare the different treatments to each other, you can use Dunnett's procedure (which is designed for that purpose). Not sure what you mean by "post hoc." Unfortunately, different people use that term in different ways. Multiplicity applies any time you conduct more than one comparison. See 5. If you're not interested in the omnibus result, there's no reason to perform the omnibus test. As you observed, you can just go straight to the individual tests, adjusted for multiplicity (though it may be advisable to use the omnibus error term for those tests, which can provide more power in some cases). Some people perform the omnibus test and then use Fisher's LSD method (i.e. do the individual comparisons without adjustment), but that doesn't generally control the familywise error rate and may thus be hard to justify. I don't see why the significance of a main effect should inherently affect whether you adjust the other tests. Response to @Sophocole's reply from Aug 5, 2016 to @Bonferroni's answer from Aug 3, 2016. I don't know who you talked to at IBM, but SPSS has several ways to control the familywise error rate, including Bonferroni, Tukey, and Dunnett tests (just google "multiple comparisons in SPSS" and you'll see). The same goes for any other reputable statistical package, including SAS and R. And if you're using a simple method like Bonferroni, you can probably do the adjustment in your head. Regarding doing multiple tests of a single comparison and choosing the one that gives you the answer you like best, it's pretty straightforward to see what the problem with that is. If you try one method that produces error at a rate of 5%, but then you get a second, third, and fourth chance with alternative methods, obviously the error rate is going to be bigger than 5%. That's like playing darts and setting up a second, third, and fourth bull's eye in slightly different positions on the dart board--obviously, you're increasing your chances of getting lucky. If you're in a very early stage of your research where you're just exploring around and error rates aren't a big concern, then by all means, test your heart out and don't bother with adjustments--you could even just look at the plots and mean differences and not do any formal testing at all if that suits your needs. But if you're trying to publish a claim or sell a treatment based on your results, you likely need statistical rigor. And if you're trying to get a drug approved by the FDA, you can forget about playing loose with error control! By the way, you may want to read that Nakagawa article again. It seems he is not arguing against "getting rid of multiplicity adjustments altogether." He apparently thinks Bonferroni and Holm are generally too conservative for behavioral ecology research, but he does endorse false discovery rate control.
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant?
The idea that only non-orthogonal comparisons require adjustment is a myth. See section 6.1 of Frane (2015): http://jrp.icaap.org/index.php/jrp/article/view/514/417 In general, computing several alter
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant? The idea that only non-orthogonal comparisons require adjustment is a myth. See section 6.1 of Frane (2015): http://jrp.icaap.org/index.php/jrp/article/view/514/417 In general, computing several alternate statistics and picking the one that gives you the answer you like best is a bad policy and can cause error inflation (as it's a form of multiple comparisons in itself). It's best to have a statistical plan before you look at your data. Bonferroni is less powerful than Holm. Holm is less powerful than some other procedures that require more assumptions. Sidak is only a tiny bit more powerful than Bonferroni and requires the assumption of non-negative dependence. If you just want to compare each treatment to control, and not compare the different treatments to each other, you can use Dunnett's procedure (which is designed for that purpose). Not sure what you mean by "post hoc." Unfortunately, different people use that term in different ways. Multiplicity applies any time you conduct more than one comparison. See 5. If you're not interested in the omnibus result, there's no reason to perform the omnibus test. As you observed, you can just go straight to the individual tests, adjusted for multiplicity (though it may be advisable to use the omnibus error term for those tests, which can provide more power in some cases). Some people perform the omnibus test and then use Fisher's LSD method (i.e. do the individual comparisons without adjustment), but that doesn't generally control the familywise error rate and may thus be hard to justify. I don't see why the significance of a main effect should inherently affect whether you adjust the other tests. Response to @Sophocole's reply from Aug 5, 2016 to @Bonferroni's answer from Aug 3, 2016. I don't know who you talked to at IBM, but SPSS has several ways to control the familywise error rate, including Bonferroni, Tukey, and Dunnett tests (just google "multiple comparisons in SPSS" and you'll see). The same goes for any other reputable statistical package, including SAS and R. And if you're using a simple method like Bonferroni, you can probably do the adjustment in your head. Regarding doing multiple tests of a single comparison and choosing the one that gives you the answer you like best, it's pretty straightforward to see what the problem with that is. If you try one method that produces error at a rate of 5%, but then you get a second, third, and fourth chance with alternative methods, obviously the error rate is going to be bigger than 5%. That's like playing darts and setting up a second, third, and fourth bull's eye in slightly different positions on the dart board--obviously, you're increasing your chances of getting lucky. If you're in a very early stage of your research where you're just exploring around and error rates aren't a big concern, then by all means, test your heart out and don't bother with adjustments--you could even just look at the plots and mean differences and not do any formal testing at all if that suits your needs. But if you're trying to publish a claim or sell a treatment based on your results, you likely need statistical rigor. And if you're trying to get a drug approved by the FDA, you can forget about playing loose with error control! By the way, you may want to read that Nakagawa article again. It seems he is not arguing against "getting rid of multiplicity adjustments altogether." He apparently thinks Bonferroni and Holm are generally too conservative for behavioral ecology research, but he does endorse false discovery rate control.
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant? The idea that only non-orthogonal comparisons require adjustment is a myth. See section 6.1 of Frane (2015): http://jrp.icaap.org/index.php/jrp/article/view/514/417 In general, computing several alter
36,652
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant?
For whatever it’s worth I offer the following comments: I say there shouldn’t be or can’t be any consensus (or at least a single way to do it) because there are multiple ways to characterize such adjustments and the severity of consequences of any adjustment for multiplicity depends on the subject matter, politics, economics, time of year, history, time sensitivity, etc. The sufficient information for choosing a method is not intrinsic to the field of statistics. However, I don’t see that if one agrees that there is no consensus, that an end-user can then do whatever suits their needs. This is in part because all of us can be pretty good at rationalizing all sorts of things. Multiplicity is not just characterized by the probability of making at least one Type I error. One might be appropriately satisfied to keep the probability of making at least four Type I errors no larger than a specified value. For large numbers of comparisons it probably makes more sense to specify and use a false discovery rate. Why should a choice of method depend on whether main effects are significant or not? I’d argue that a decision about what to do needs to be made prior to the data collection (or at least prior to looking at the results) and shouldn’t be influenced by any one set of results. If a comparison of interest stands on it's own, then it needs no multiple comparison adjustment. And I don't see orthogonal contrasts automatically getting a free pass. Two orthogonal contrasts constitute a set of multiple comparisons. In short, the important issues to understand are (1) what you’re getting (and not getting) with any particular multiple comparison adjustment, (2) that there can be many characterizations of adjustments, and (3) subject matter information is essential to make a decision.
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant?
For whatever it’s worth I offer the following comments: I say there shouldn’t be or can’t be any consensus (or at least a single way to do it) because there are multiple ways to characterize such adj
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant? For whatever it’s worth I offer the following comments: I say there shouldn’t be or can’t be any consensus (or at least a single way to do it) because there are multiple ways to characterize such adjustments and the severity of consequences of any adjustment for multiplicity depends on the subject matter, politics, economics, time of year, history, time sensitivity, etc. The sufficient information for choosing a method is not intrinsic to the field of statistics. However, I don’t see that if one agrees that there is no consensus, that an end-user can then do whatever suits their needs. This is in part because all of us can be pretty good at rationalizing all sorts of things. Multiplicity is not just characterized by the probability of making at least one Type I error. One might be appropriately satisfied to keep the probability of making at least four Type I errors no larger than a specified value. For large numbers of comparisons it probably makes more sense to specify and use a false discovery rate. Why should a choice of method depend on whether main effects are significant or not? I’d argue that a decision about what to do needs to be made prior to the data collection (or at least prior to looking at the results) and shouldn’t be influenced by any one set of results. If a comparison of interest stands on it's own, then it needs no multiple comparison adjustment. And I don't see orthogonal contrasts automatically getting a free pass. Two orthogonal contrasts constitute a set of multiple comparisons. In short, the important issues to understand are (1) what you’re getting (and not getting) with any particular multiple comparison adjustment, (2) that there can be many characterizations of adjustments, and (3) subject matter information is essential to make a decision.
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant? For whatever it’s worth I offer the following comments: I say there shouldn’t be or can’t be any consensus (or at least a single way to do it) because there are multiple ways to characterize such adj
36,653
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant?
TL;DR With respect to the example in your question, you mention three tests: $H_0^{(1)}: \mu_1=\mu_2$ versus $H_1^{(1)}: \mu_1 \ne \mu_2$ $H_0^{(2)}: \mu_1=\mu_3$ versus $H_1^{(2)}: \mu_1 \ne \mu_3$ $H_0^{(3)}: \mu_1=\mu_4$ versus $H_1^{(3)}: \mu_1 \ne \mu_4$ Let us take one individual test, e.g. the first one. As explained in What follows if we fail to reject the null hypothesis?, the goal is to find statistical evidence for $H_1$, using one value for a test-statistic observed from a sample. Based on the value of that test statistic in your sample you may conclude that $H_1$ is valid but you make type I errors. Such a type I error occurs whenever you are ''unlucky'' with the sample; it could be because of randomness the sample yields a value that rejects $H_0$ because of ''bad luck''. The probability that such a type I error occurs, or the probability that you have bad luck with the sample, is equal (for continuous rv) to the significance level $\alpha$. If I now use one and the same sample and I perform three tests on it, then the probability that I have bad luck with the sample for at least one of the three tests will be at least $\alpha$, so the type I erro increases. If the three tests are independent the probability of a type I error in at least one of the three tests is $1-(1-\alpha)^3$ see also Family-wise error boundary: Does re-using data sets on different studies of independent questions lead to multiple testing problems?
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant?
TL;DR With respect to the example in your question, you mention three tests: $H_0^{(1)}: \mu_1=\mu_2$ versus $H_1^{(1)}: \mu_1 \ne \mu_2$ $H_0^{(2)}: \mu_1=\mu_3$ versus $H_1^{(2)}: \mu_1 \ne \mu_3$
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant? TL;DR With respect to the example in your question, you mention three tests: $H_0^{(1)}: \mu_1=\mu_2$ versus $H_1^{(1)}: \mu_1 \ne \mu_2$ $H_0^{(2)}: \mu_1=\mu_3$ versus $H_1^{(2)}: \mu_1 \ne \mu_3$ $H_0^{(3)}: \mu_1=\mu_4$ versus $H_1^{(3)}: \mu_1 \ne \mu_4$ Let us take one individual test, e.g. the first one. As explained in What follows if we fail to reject the null hypothesis?, the goal is to find statistical evidence for $H_1$, using one value for a test-statistic observed from a sample. Based on the value of that test statistic in your sample you may conclude that $H_1$ is valid but you make type I errors. Such a type I error occurs whenever you are ''unlucky'' with the sample; it could be because of randomness the sample yields a value that rejects $H_0$ because of ''bad luck''. The probability that such a type I error occurs, or the probability that you have bad luck with the sample, is equal (for continuous rv) to the significance level $\alpha$. If I now use one and the same sample and I perform three tests on it, then the probability that I have bad luck with the sample for at least one of the three tests will be at least $\alpha$, so the type I erro increases. If the three tests are independent the probability of a type I error in at least one of the three tests is $1-(1-\alpha)^3$ see also Family-wise error boundary: Does re-using data sets on different studies of independent questions lead to multiple testing problems?
Is there a consensus on adjusting alpha for multiple contrasts if the main effect is significant? TL;DR With respect to the example in your question, you mention three tests: $H_0^{(1)}: \mu_1=\mu_2$ versus $H_1^{(1)}: \mu_1 \ne \mu_2$ $H_0^{(2)}: \mu_1=\mu_3$ versus $H_1^{(2)}: \mu_1 \ne \mu_3$
36,654
What is the difference between buckets and bins?
A very good question, and a question that I myself had because I have heard these called buckets, groups, groupings, categories, categorical variables, discrete variables, and bins as I have changed disciplines. In general, use the language that the end-users of your analysis are most comfortable using - in a sense, speak their language (or force them to use yours! ha). There is no wrong answer here, other than a countless number of statisticians that would say that you shouldn't be grouping your variables into bins/buckets without a very good reason (or ever!) as you are spending degrees of freedom, making arbitrary cutoffs to create your buckets/bins, and losing information that was provided by your once valuable, continuous variables.
What is the difference between buckets and bins?
A very good question, and a question that I myself had because I have heard these called buckets, groups, groupings, categories, categorical variables, discrete variables, and bins as I have changed d
What is the difference between buckets and bins? A very good question, and a question that I myself had because I have heard these called buckets, groups, groupings, categories, categorical variables, discrete variables, and bins as I have changed disciplines. In general, use the language that the end-users of your analysis are most comfortable using - in a sense, speak their language (or force them to use yours! ha). There is no wrong answer here, other than a countless number of statisticians that would say that you shouldn't be grouping your variables into bins/buckets without a very good reason (or ever!) as you are spending degrees of freedom, making arbitrary cutoffs to create your buckets/bins, and losing information that was provided by your once valuable, continuous variables.
What is the difference between buckets and bins? A very good question, and a question that I myself had because I have heard these called buckets, groups, groupings, categories, categorical variables, discrete variables, and bins as I have changed d
36,655
Which econometric models can be used to forecast security returns + ARIMA/GARCH questions
My goal is simply to ... find statistically significant predictive results. Also, is there a particular market you would look at (energy, rates, equities)? Most if not all the established and liquid financial markets will be very hard to predict whatever model you will use. If markets were relatively easy to predict, market participant would try to exploit that to make money. By doing that they would eliminate the predictability. This brings a contradiction, and thus the markets are not easy to predict. Lastly, is GARCH only used for forecasting volatility? The professor I mentioned seemed to suggest I should turn toward GARCH or ARIMA-GARCH models to model stock returns. I read some papers that seemed to imply it could also be used for actual returns... GARCH model is used for modelling the conditional variance of the disturbance term of the conditional mean model for a dependent variable $y_t$. E.g. if you have a conditional mean model $y_t=\alpha+\epsilon_t$, the GARCH model will describe the conditional variance of $\epsilon_t$. Sometimes the conditional mean model is "empty" ($y_t=\epsilon_t$), then GARCH model is used to model the conditional variance of $y_t$ itself. Even if you are primarily interested in the conditional mean model (e.g. you want to predict stock returns using an ARMA model), a GARCH model combined with a model for the conditional mean can be useful. If the conditional variance of the dependent variable is time-varying, that should be accounted for, and a GARCH model does exactly that. If a time-varying conditional variance is neglected, the conditional mean model may (and likely will) be invalid. Would the AR and MA components in an ARIMA-GARCH model differ from those in an ARMA model? Yes. That also illustrates my last remark above. From what I vaguely understood, ARIMA and GARCH are two completely separate things (with the former being used to predict the actual time series and the other to predict its volatility). This is true. But as I have already explained, the two models can work together nicely.
Which econometric models can be used to forecast security returns + ARIMA/GARCH questions
My goal is simply to ... find statistically significant predictive results. Also, is there a particular market you would look at (energy, rates, equities)? Most if not all the established and liquid
Which econometric models can be used to forecast security returns + ARIMA/GARCH questions My goal is simply to ... find statistically significant predictive results. Also, is there a particular market you would look at (energy, rates, equities)? Most if not all the established and liquid financial markets will be very hard to predict whatever model you will use. If markets were relatively easy to predict, market participant would try to exploit that to make money. By doing that they would eliminate the predictability. This brings a contradiction, and thus the markets are not easy to predict. Lastly, is GARCH only used for forecasting volatility? The professor I mentioned seemed to suggest I should turn toward GARCH or ARIMA-GARCH models to model stock returns. I read some papers that seemed to imply it could also be used for actual returns... GARCH model is used for modelling the conditional variance of the disturbance term of the conditional mean model for a dependent variable $y_t$. E.g. if you have a conditional mean model $y_t=\alpha+\epsilon_t$, the GARCH model will describe the conditional variance of $\epsilon_t$. Sometimes the conditional mean model is "empty" ($y_t=\epsilon_t$), then GARCH model is used to model the conditional variance of $y_t$ itself. Even if you are primarily interested in the conditional mean model (e.g. you want to predict stock returns using an ARMA model), a GARCH model combined with a model for the conditional mean can be useful. If the conditional variance of the dependent variable is time-varying, that should be accounted for, and a GARCH model does exactly that. If a time-varying conditional variance is neglected, the conditional mean model may (and likely will) be invalid. Would the AR and MA components in an ARIMA-GARCH model differ from those in an ARMA model? Yes. That also illustrates my last remark above. From what I vaguely understood, ARIMA and GARCH are two completely separate things (with the former being used to predict the actual time series and the other to predict its volatility). This is true. But as I have already explained, the two models can work together nicely.
Which econometric models can be used to forecast security returns + ARIMA/GARCH questions My goal is simply to ... find statistically significant predictive results. Also, is there a particular market you would look at (energy, rates, equities)? Most if not all the established and liquid
36,656
Which econometric models can be used to forecast security returns + ARIMA/GARCH questions
I applaud your enthusiasm for the subject. There is a lot of applications and methods to help with prediction but it is clear that there is no silver bullet. Just like there is no one weather model that predict all weather in all locations with equal accuracy, there is not model that can predict financial time series. I would encourage you to look at a single sub-behavior of markets to see if you can understand it. Some quick examples are Month end price action Price movements around earnings-releases / economic data influences of winter storms on US natural gas markets futures contract rolls As for techniques, one new-classic method is Cointegration: http://en.wikipedia.org/wiki/Cointegration http://gekkoquant.com/2013/01/21/statistical-arbitrage-trading-a-cointegrated-pair/ http://www.eforenergy.org/docpublicaciones/documentos-de-trabajo/WPFA05-2013.pdf I am in no way endorsing the analysis and results in the above links. They are simply some top google results to get you on the path to learn more about co-integration.
Which econometric models can be used to forecast security returns + ARIMA/GARCH questions
I applaud your enthusiasm for the subject. There is a lot of applications and methods to help with prediction but it is clear that there is no silver bullet. Just like there is no one weather model
Which econometric models can be used to forecast security returns + ARIMA/GARCH questions I applaud your enthusiasm for the subject. There is a lot of applications and methods to help with prediction but it is clear that there is no silver bullet. Just like there is no one weather model that predict all weather in all locations with equal accuracy, there is not model that can predict financial time series. I would encourage you to look at a single sub-behavior of markets to see if you can understand it. Some quick examples are Month end price action Price movements around earnings-releases / economic data influences of winter storms on US natural gas markets futures contract rolls As for techniques, one new-classic method is Cointegration: http://en.wikipedia.org/wiki/Cointegration http://gekkoquant.com/2013/01/21/statistical-arbitrage-trading-a-cointegrated-pair/ http://www.eforenergy.org/docpublicaciones/documentos-de-trabajo/WPFA05-2013.pdf I am in no way endorsing the analysis and results in the above links. They are simply some top google results to get you on the path to learn more about co-integration.
Which econometric models can be used to forecast security returns + ARIMA/GARCH questions I applaud your enthusiasm for the subject. There is a lot of applications and methods to help with prediction but it is clear that there is no silver bullet. Just like there is no one weather model
36,657
Effect of categorical interaction terms with random forest machine learning algorithm
I think your questions are very interesting, I spend some of my time looking at the effective mapping curvature of random forest(RF) model fits. RF can capture some orders of interactions depending on the situation. x1 * x2 is a two-way interaction and so on... You did not write how many levels your categorical predictors had. It matters a lot. For continous variables(many levels) often no more than multiple local two-way interactions can be captured. The problem is, that the RF model itself only splits and do not transform data. Therefore RF is stuck with local uni-variate splits which is not optimal for captivating interactions. Therefore RF is fairly shallow compared to deep-lerning. In the complete other end of the spectre are binary features. I did not know how deep RF can go, so I ran a grid-search simulation. RF seems to capture up to some 4-8 orders of interactions for binary features. I use 12 binary variables and 100 to 15000 observations. E.g. for the 4th order interaction, the prediction vector y is: orderOfInteraction = 4 y = factor(apply(X[,1:orderOfInteraction],1,prod)) where any element of X either is -1 or 1 and the product of the first four variable columns of X is the prediction. All four variables are completely complimentary. Therefore, no main-effects, 2nd or 3rd order effects. The OOB prediction error will therefore reflect only how well RF can captivate an interaction of the Nth order. Things which makes RF captivate higher order of interactions: plenty of observation, few levels in variables, few variables Limiting factors for RF captivating higher orders: the opposite of above, limited sampsize, limited maxnodes and redundant/sufficient lower order information. The last one means that if RF can find the same information in low-order interactions, there is, so to say, no need to go deeper. Information may not even be redundant. It just have to be sufficient for RF to make correct binary predictions. Depth of random forest: OOB err.rate vs. observations vs. order of interaction rm(list=ls()) library(randomForest) library(parallel) library(rgl) simulate.a.forest = function(std.pars,ite.pars) { #Merge standard parameters with iterated parameters run.pars = c(std.pars,ite.pars) #simulate data of a given order X = replicate(run.pars$vars,sample(c(-1,1),run.pars$obs,replace=T)) y = factor(apply(X[,1:run.pars$intOrder],1,prod)) #run forest with run.pars, pars with wrong name is ignored rfo = do.call(randomForest, run.pars) #Fetch OOB error.rate and return out = rev(rfo$err.rate[,1])[1] #fetch error rate from object names(out) = paste(ite.pars,collapse="-")[1] return(out) } ## Lets try some situations (you can also pass arguments to randomForest here) intOrders = c(2,3,4,5,6,12) #hidden signal is a N-way interaction of Nth order obss = c(100,500,1000,3500,7000,15000) #available observations ## Produce list of all possible combinations of parameters ite.pars.matrix = expand.grid(intOrder=intOrders,obs=obss) n.runs = dim(ite.pars.matrix)[1] ite.pars.list = lapply(1:n.runs, function(i) ite.pars.matrix[i,]) i=1 ##for test-purposes out = mclapply(1:n.runs, function(i){ #line below can be run alone without mclapply to check for errors before going multicore out = simulate.a.forest(std.pars=alist(x=X,y=y, ntree=250, vars=12), #sampsize=min(run.pars$obs,2000)), ite.pars=ite.pars.list[[i]]) return(out) }) ##view grid results persp3d(x = intOrders,xlab="Nth order interaction", y = log(obss,base=10),ylab="10log(observations)", z = matrix(unlist(out),nrow=length(intOrders)),zlab="OOB prediction error, binary target", col=c("grey","black"),alpha=.2) rgl.snapshot(filename = "aweSomePlot.png", fmt = "png", top = TRUE)
Effect of categorical interaction terms with random forest machine learning algorithm
I think your questions are very interesting, I spend some of my time looking at the effective mapping curvature of random forest(RF) model fits. RF can capture some orders of interactions depending on
Effect of categorical interaction terms with random forest machine learning algorithm I think your questions are very interesting, I spend some of my time looking at the effective mapping curvature of random forest(RF) model fits. RF can capture some orders of interactions depending on the situation. x1 * x2 is a two-way interaction and so on... You did not write how many levels your categorical predictors had. It matters a lot. For continous variables(many levels) often no more than multiple local two-way interactions can be captured. The problem is, that the RF model itself only splits and do not transform data. Therefore RF is stuck with local uni-variate splits which is not optimal for captivating interactions. Therefore RF is fairly shallow compared to deep-lerning. In the complete other end of the spectre are binary features. I did not know how deep RF can go, so I ran a grid-search simulation. RF seems to capture up to some 4-8 orders of interactions for binary features. I use 12 binary variables and 100 to 15000 observations. E.g. for the 4th order interaction, the prediction vector y is: orderOfInteraction = 4 y = factor(apply(X[,1:orderOfInteraction],1,prod)) where any element of X either is -1 or 1 and the product of the first four variable columns of X is the prediction. All four variables are completely complimentary. Therefore, no main-effects, 2nd or 3rd order effects. The OOB prediction error will therefore reflect only how well RF can captivate an interaction of the Nth order. Things which makes RF captivate higher order of interactions: plenty of observation, few levels in variables, few variables Limiting factors for RF captivating higher orders: the opposite of above, limited sampsize, limited maxnodes and redundant/sufficient lower order information. The last one means that if RF can find the same information in low-order interactions, there is, so to say, no need to go deeper. Information may not even be redundant. It just have to be sufficient for RF to make correct binary predictions. Depth of random forest: OOB err.rate vs. observations vs. order of interaction rm(list=ls()) library(randomForest) library(parallel) library(rgl) simulate.a.forest = function(std.pars,ite.pars) { #Merge standard parameters with iterated parameters run.pars = c(std.pars,ite.pars) #simulate data of a given order X = replicate(run.pars$vars,sample(c(-1,1),run.pars$obs,replace=T)) y = factor(apply(X[,1:run.pars$intOrder],1,prod)) #run forest with run.pars, pars with wrong name is ignored rfo = do.call(randomForest, run.pars) #Fetch OOB error.rate and return out = rev(rfo$err.rate[,1])[1] #fetch error rate from object names(out) = paste(ite.pars,collapse="-")[1] return(out) } ## Lets try some situations (you can also pass arguments to randomForest here) intOrders = c(2,3,4,5,6,12) #hidden signal is a N-way interaction of Nth order obss = c(100,500,1000,3500,7000,15000) #available observations ## Produce list of all possible combinations of parameters ite.pars.matrix = expand.grid(intOrder=intOrders,obs=obss) n.runs = dim(ite.pars.matrix)[1] ite.pars.list = lapply(1:n.runs, function(i) ite.pars.matrix[i,]) i=1 ##for test-purposes out = mclapply(1:n.runs, function(i){ #line below can be run alone without mclapply to check for errors before going multicore out = simulate.a.forest(std.pars=alist(x=X,y=y, ntree=250, vars=12), #sampsize=min(run.pars$obs,2000)), ite.pars=ite.pars.list[[i]]) return(out) }) ##view grid results persp3d(x = intOrders,xlab="Nth order interaction", y = log(obss,base=10),ylab="10log(observations)", z = matrix(unlist(out),nrow=length(intOrders)),zlab="OOB prediction error, binary target", col=c("grey","black"),alpha=.2) rgl.snapshot(filename = "aweSomePlot.png", fmt = "png", top = TRUE)
Effect of categorical interaction terms with random forest machine learning algorithm I think your questions are very interesting, I spend some of my time looking at the effective mapping curvature of random forest(RF) model fits. RF can capture some orders of interactions depending on
36,658
Proper cross validation for stacking models
Question 1: local prediction & cross validation Looking for closeby cases and upweighting them for prediction is referred to as local models or local prediction. For the proper way to do cross validation, remember that for each fold, you only use training cases, and then do with the test cases exactly what you do for prediciton of a new unkown case. I'd recommend to see the calculation of $X_1$ as part of the prediction. E.g. in a two level model consisting of a $n$ nearest neighbours + a second level model: For each of the training cases, find the $n$ nearest neighbours and calculate $X_{11}$ Calculate the "2nd level" model based on $X_1, ..., X_{11}$. So for prediction of a case $X_{new}$, you find the $n$ nearest neighbours and calculate the $X_{11}$ for the new case then calculate the prediction of the 2nd level model. You use exactly this prediction procedure to predict the test cases in the cross validation. Question 2: combining predictions random forest tends to overfit on training data set Usually random forest will overfit only in situations where you have a hierarchical/clustered data structer that creates a dependence between (some) rows of your data. Boosting is more prone to overfitting because of the iteratively weighted average (as opposed to the simple average of the random forest). I did not yet completely understand your question (see comment). But here's my guess: I assume you want to find out the optimal weight you should use for random forest and boosted prediction, which is a linear model of those two models. (I don't see how you could use the individual trees within those ensemble models because the trees will totally change between the splits). This again amounts to a 2 level model (or 3 levels if combined with the approach of question 1). The general answer here is that whenever you do a data-driven model or hyperparameter optimization (e.g. optimize the weights for random forest prediction and gradient boosted prediction by test/cross validation results), you need to do an independent validation to assess the real performance of the resulting model. Thus you need either yet another independent test set, or a so-called nested or double cross validation. So the 1st approach would not work unless you derive the weights from the training data. As you point out for the 2nd approach, having more and more levels of cross validation needs huge sample sizes to start with. I'd recommend a different approach here: try to cut down as far as possible the number of splits you need by doing as few data-driven hyperparameter calculations or optimizations as possible. There cannot be any discussion about the need of a validation of the final model. But you may be able to show that no inner splitting is needed if you can show that the models you try to stack are not overfit. In addition this would remove the need to stack at all: Ensemble models only help if the underlying individual models suffer from variance, i.e. are unstable. (Or if they are biased in opposing directions, so the ensembe would roughly cancel the individual biases. I suspect that this is not the case here, assuming that your GBM uses trees like the RF.) As for the instability, you can measure this easily by repeated aka iterated cross validation (see e.g. this answer). If this does not point to substantial variance in the prediction of the same case by models built on slightly varying training data (i.e. if your RF and GBM are stable), producing an ensemble of the ensemble models is not going to help.
Proper cross validation for stacking models
Question 1: local prediction & cross validation Looking for closeby cases and upweighting them for prediction is referred to as local models or local prediction. For the proper way to do cross valida
Proper cross validation for stacking models Question 1: local prediction & cross validation Looking for closeby cases and upweighting them for prediction is referred to as local models or local prediction. For the proper way to do cross validation, remember that for each fold, you only use training cases, and then do with the test cases exactly what you do for prediciton of a new unkown case. I'd recommend to see the calculation of $X_1$ as part of the prediction. E.g. in a two level model consisting of a $n$ nearest neighbours + a second level model: For each of the training cases, find the $n$ nearest neighbours and calculate $X_{11}$ Calculate the "2nd level" model based on $X_1, ..., X_{11}$. So for prediction of a case $X_{new}$, you find the $n$ nearest neighbours and calculate the $X_{11}$ for the new case then calculate the prediction of the 2nd level model. You use exactly this prediction procedure to predict the test cases in the cross validation. Question 2: combining predictions random forest tends to overfit on training data set Usually random forest will overfit only in situations where you have a hierarchical/clustered data structer that creates a dependence between (some) rows of your data. Boosting is more prone to overfitting because of the iteratively weighted average (as opposed to the simple average of the random forest). I did not yet completely understand your question (see comment). But here's my guess: I assume you want to find out the optimal weight you should use for random forest and boosted prediction, which is a linear model of those two models. (I don't see how you could use the individual trees within those ensemble models because the trees will totally change between the splits). This again amounts to a 2 level model (or 3 levels if combined with the approach of question 1). The general answer here is that whenever you do a data-driven model or hyperparameter optimization (e.g. optimize the weights for random forest prediction and gradient boosted prediction by test/cross validation results), you need to do an independent validation to assess the real performance of the resulting model. Thus you need either yet another independent test set, or a so-called nested or double cross validation. So the 1st approach would not work unless you derive the weights from the training data. As you point out for the 2nd approach, having more and more levels of cross validation needs huge sample sizes to start with. I'd recommend a different approach here: try to cut down as far as possible the number of splits you need by doing as few data-driven hyperparameter calculations or optimizations as possible. There cannot be any discussion about the need of a validation of the final model. But you may be able to show that no inner splitting is needed if you can show that the models you try to stack are not overfit. In addition this would remove the need to stack at all: Ensemble models only help if the underlying individual models suffer from variance, i.e. are unstable. (Or if they are biased in opposing directions, so the ensembe would roughly cancel the individual biases. I suspect that this is not the case here, assuming that your GBM uses trees like the RF.) As for the instability, you can measure this easily by repeated aka iterated cross validation (see e.g. this answer). If this does not point to substantial variance in the prediction of the same case by models built on slightly varying training data (i.e. if your RF and GBM are stable), producing an ensemble of the ensemble models is not going to help.
Proper cross validation for stacking models Question 1: local prediction & cross validation Looking for closeby cases and upweighting them for prediction is referred to as local models or local prediction. For the proper way to do cross valida
36,659
Proper cross validation for stacking models
Question 1: This is really similar to what is called KFold Target Encoding, and a correct way to do it is explained here: https://medium.com/@pouryaayria/k-fold-target-encoding-dfe9a594874b Your encoding is slightly different than what is describe in the article above, but you can apply the same design.
Proper cross validation for stacking models
Question 1: This is really similar to what is called KFold Target Encoding, and a correct way to do it is explained here: https://medium.com/@pouryaayria/k-fold-target-encoding-dfe9a594874b Your encod
Proper cross validation for stacking models Question 1: This is really similar to what is called KFold Target Encoding, and a correct way to do it is explained here: https://medium.com/@pouryaayria/k-fold-target-encoding-dfe9a594874b Your encoding is slightly different than what is describe in the article above, but you can apply the same design.
Proper cross validation for stacking models Question 1: This is really similar to what is called KFold Target Encoding, and a correct way to do it is explained here: https://medium.com/@pouryaayria/k-fold-target-encoding-dfe9a594874b Your encod
36,660
Does the uniform distribution have the greatest variance among all concave distributions on a bounded interval?
Yes, this is true. First, note that any concave PDF must be unimodal. (This is an elementary consequence of the concavity.) The answer to a related question shows that on the interval $[0,1]$, the variance of a distribution with mean $\mu$ cannot exceed $\mu(2-3\mu)/3$ (when $0 \le \mu \le 1/2$) or $(1-\mu)(3\mu-1)/3$ (when $1/2\le \mu \le 1$). Neither of these expressions exceeds $1/12$ (which is achieved solely when $\mu=1/2$. By shifting and rescaling the interval $[0,1]$ to $[a,b]$, it immediately follows that $\sigma^2$ cannot exceed $(b-a)^2/12$, QED. Evidently a stronger statement can be made when the mean $\mu$ is known: a tight upper bound is then $$\sigma^2 \le \frac{(\mu-a)(2b+a-3\mu)}{3}$$ when $\mu \le (a+b)/2$. For $\mu \gt (a+b)/2$, switch $a$ and $b$ and replace $\mu$ by $b-\mu$.
Does the uniform distribution have the greatest variance among all concave distributions on a bounde
Yes, this is true. First, note that any concave PDF must be unimodal. (This is an elementary consequence of the concavity.) The answer to a related question shows that on the interval $[0,1]$, the va
Does the uniform distribution have the greatest variance among all concave distributions on a bounded interval? Yes, this is true. First, note that any concave PDF must be unimodal. (This is an elementary consequence of the concavity.) The answer to a related question shows that on the interval $[0,1]$, the variance of a distribution with mean $\mu$ cannot exceed $\mu(2-3\mu)/3$ (when $0 \le \mu \le 1/2$) or $(1-\mu)(3\mu-1)/3$ (when $1/2\le \mu \le 1$). Neither of these expressions exceeds $1/12$ (which is achieved solely when $\mu=1/2$. By shifting and rescaling the interval $[0,1]$ to $[a,b]$, it immediately follows that $\sigma^2$ cannot exceed $(b-a)^2/12$, QED. Evidently a stronger statement can be made when the mean $\mu$ is known: a tight upper bound is then $$\sigma^2 \le \frac{(\mu-a)(2b+a-3\mu)}{3}$$ when $\mu \le (a+b)/2$. For $\mu \gt (a+b)/2$, switch $a$ and $b$ and replace $\mu$ by $b-\mu$.
Does the uniform distribution have the greatest variance among all concave distributions on a bounde Yes, this is true. First, note that any concave PDF must be unimodal. (This is an elementary consequence of the concavity.) The answer to a related question shows that on the interval $[0,1]$, the va
36,661
Testing Whether a Binomial Distribution Fits Data
Steps in carrying out a chi-square goodness of fit for a binomial: Compute an efficient estimate of $p$. The usual estimator will do nicely. Calculate the probability of getting Type $i$ for each $i$, given that Type is drawn from a $\text{binomial}(n\hat{p})$. Hence calculate the expected number of observations at each Type. Compute the chi-square goodness of fit statistic $\sum_i\frac{(O_i-E_i)^2}{E_i}$. The d.f. for the test will be the number of categories minus 1 for the equality of $\sum_iO_i=\sum_iE_i$ and minus another 1 for the estimation of $p$. You could look up chi-square tables to find the critical value or use a package to find the p-value from the CDF of the chi-square.
Testing Whether a Binomial Distribution Fits Data
Steps in carrying out a chi-square goodness of fit for a binomial: Compute an efficient estimate of $p$. The usual estimator will do nicely. Calculate the probability of getting Type $i$ for each $i$
Testing Whether a Binomial Distribution Fits Data Steps in carrying out a chi-square goodness of fit for a binomial: Compute an efficient estimate of $p$. The usual estimator will do nicely. Calculate the probability of getting Type $i$ for each $i$, given that Type is drawn from a $\text{binomial}(n\hat{p})$. Hence calculate the expected number of observations at each Type. Compute the chi-square goodness of fit statistic $\sum_i\frac{(O_i-E_i)^2}{E_i}$. The d.f. for the test will be the number of categories minus 1 for the equality of $\sum_iO_i=\sum_iE_i$ and minus another 1 for the estimation of $p$. You could look up chi-square tables to find the critical value or use a package to find the p-value from the CDF of the chi-square.
Testing Whether a Binomial Distribution Fits Data Steps in carrying out a chi-square goodness of fit for a binomial: Compute an efficient estimate of $p$. The usual estimator will do nicely. Calculate the probability of getting Type $i$ for each $i$
36,662
Upper Bound on $E[\frac{1}{1-X}]$ where $E[X]=a$ and $0<a<1$
There is no upper bound. Intuitively, if $X$ has substantial support along a sequence approaching $1$, then $1/(1-X)$ could have a divergent (arbitrarily large) expectation. To show there is no upper bound, all we have to do is find a combination of support and probabilities that achieves the desired expectation of $a$. The following explicitly constructs such an $X$. Assume $0 \lt \lambda \lt 1$ (to be chosen later) and $s \gt 1$ (also to be chosen later). Let $X$ take on the values $$a_n = 1 - \lambda n^{-s}$$ with probabilities $$p_n = \frac{n^{-s}}{\zeta(s)},$$ $n = 1, 2, \ldots $. Then $$a = \mathbb{E}(X) = \sum_{n=1}^\infty p_n a_n = \frac{1}{\zeta(s)}\sum_{n=1}^\infty n^{-s}\left(1 - \lambda n^{-s}\right) = 1 - \lambda \frac{\zeta(2s)}{\zeta(s)}.$$ The range of $f(s) = \zeta(2s)/\zeta(s)$ is the interval $(0,1)$, as this partial graph indicates: Selecting $\lambda$ such that $1-a \lt \lambda \lt 1$, pick $s \gt 1$ for which $f(s) = (1-a)/\lambda$; that is, $a = 1 - \lambda f(s)$. This constructs an $X$ with all the stated properties. Consider $$\mathbb{E}\left(\frac{1}{1-X}\right) = \sum_{n=1}^\infty p_n \frac{n^s}{\lambda} = \frac{1}{\lambda\zeta(s)}\sum_{n=1}^\infty 1.$$ The sum diverges. Consequently no upper bound is consistent with the stated conditions.
Upper Bound on $E[\frac{1}{1-X}]$ where $E[X]=a$ and $0<a<1$
There is no upper bound. Intuitively, if $X$ has substantial support along a sequence approaching $1$, then $1/(1-X)$ could have a divergent (arbitrarily large) expectation. To show there is no upper
Upper Bound on $E[\frac{1}{1-X}]$ where $E[X]=a$ and $0<a<1$ There is no upper bound. Intuitively, if $X$ has substantial support along a sequence approaching $1$, then $1/(1-X)$ could have a divergent (arbitrarily large) expectation. To show there is no upper bound, all we have to do is find a combination of support and probabilities that achieves the desired expectation of $a$. The following explicitly constructs such an $X$. Assume $0 \lt \lambda \lt 1$ (to be chosen later) and $s \gt 1$ (also to be chosen later). Let $X$ take on the values $$a_n = 1 - \lambda n^{-s}$$ with probabilities $$p_n = \frac{n^{-s}}{\zeta(s)},$$ $n = 1, 2, \ldots $. Then $$a = \mathbb{E}(X) = \sum_{n=1}^\infty p_n a_n = \frac{1}{\zeta(s)}\sum_{n=1}^\infty n^{-s}\left(1 - \lambda n^{-s}\right) = 1 - \lambda \frac{\zeta(2s)}{\zeta(s)}.$$ The range of $f(s) = \zeta(2s)/\zeta(s)$ is the interval $(0,1)$, as this partial graph indicates: Selecting $\lambda$ such that $1-a \lt \lambda \lt 1$, pick $s \gt 1$ for which $f(s) = (1-a)/\lambda$; that is, $a = 1 - \lambda f(s)$. This constructs an $X$ with all the stated properties. Consider $$\mathbb{E}\left(\frac{1}{1-X}\right) = \sum_{n=1}^\infty p_n \frac{n^s}{\lambda} = \frac{1}{\lambda\zeta(s)}\sum_{n=1}^\infty 1.$$ The sum diverges. Consequently no upper bound is consistent with the stated conditions.
Upper Bound on $E[\frac{1}{1-X}]$ where $E[X]=a$ and $0<a<1$ There is no upper bound. Intuitively, if $X$ has substantial support along a sequence approaching $1$, then $1/(1-X)$ could have a divergent (arbitrarily large) expectation. To show there is no upper
36,663
How is data generated in the Bayesian framework and what is the nature on the parameter that generates the data?
It is pretty straightforward: there are no differences between Bayesians and frequentists regarding the idea of the data-generating model. To understand this, consider first that the data-generating model is mathematically encoded in the likelihood, which is the basis for the inference of Bayesians and frequentists alike. And there is zero difference between a Bayesian and frequentist likelihood. Now, you could say: that doesn't mean that Bayesians think that the parameters of the data-generating process are fixed. Sure, but really, it makes very little sense to think otherwise - what would be the point of estimating a quantity that is not fixed? What would that even mean mathematically? Of course, it could be that you have a quantity that is not a value, but a distribution. But then you estimate the distribution, so it is fixed again. The real difference, as @Xi'an says, is not in the assumption about how our data is generated, but in the inference. So, when you say However, in the Bayesian setting, we model the parameter as a random variable. I would disagree - we model our knowledge / uncertainty about the true parameter as a random variable - that is the subtle, but important difference - we treat the parameter as random variables to explore our uncertainty about their "true" value.
How is data generated in the Bayesian framework and what is the nature on the parameter that generat
It is pretty straightforward: there are no differences between Bayesians and frequentists regarding the idea of the data-generating model. To understand this, consider first that the data-generating
How is data generated in the Bayesian framework and what is the nature on the parameter that generates the data? It is pretty straightforward: there are no differences between Bayesians and frequentists regarding the idea of the data-generating model. To understand this, consider first that the data-generating model is mathematically encoded in the likelihood, which is the basis for the inference of Bayesians and frequentists alike. And there is zero difference between a Bayesian and frequentist likelihood. Now, you could say: that doesn't mean that Bayesians think that the parameters of the data-generating process are fixed. Sure, but really, it makes very little sense to think otherwise - what would be the point of estimating a quantity that is not fixed? What would that even mean mathematically? Of course, it could be that you have a quantity that is not a value, but a distribution. But then you estimate the distribution, so it is fixed again. The real difference, as @Xi'an says, is not in the assumption about how our data is generated, but in the inference. So, when you say However, in the Bayesian setting, we model the parameter as a random variable. I would disagree - we model our knowledge / uncertainty about the true parameter as a random variable - that is the subtle, but important difference - we treat the parameter as random variables to explore our uncertainty about their "true" value.
How is data generated in the Bayesian framework and what is the nature on the parameter that generat It is pretty straightforward: there are no differences between Bayesians and frequentists regarding the idea of the data-generating model. To understand this, consider first that the data-generating
36,664
How is data generated in the Bayesian framework and what is the nature on the parameter that generates the data?
Pages 3 and 4 of BDA by Gelman et al., 3rd ed., are illuminating. Bayesian statistics aims to make inference from data using probability models for observables and unobservable quantities. We refer to the unobservable quantities as parameters, even if the distinction is not always clear-cut. In Bayesian statistics all uncertainty about the variables involved in the model is represented using probability. Thus we need to setup a full probability model, i.e., a joint probability among all variables involved in our problem, both observable and unobservable, i.e., parameters. This means that we use random variables to represent both. It doesn't mean that we believe the parameter to be random: it means simply that our knowledge of the real value of the parameters is limited, and we represent whatever limited knowledge we have before observing data through the prior probability distribution. We then observe data and condition on the observed data using a model for the data generating process (which gives rise to a certain likelihood function) and Bayes' rule, to obtain a posterior probability distribution, which quantifies the remaining uncertainty in our knowledge about the unobservable quantities. In other words we use random variables for parameters not because we believe that there are no true parameters, but because we have a limited knowledge of them, which improves after observing data for the measurable variables, but it doesn't disappear completely. As a matter of fact, there are technical conditions under which the posterior distribution tends to a Dirac delta (thus the random variable used to represent the parameter becomes degenerate) in the limit for the number of observations which goes to 0. If there was no "true" value for the parameter, this wouldn't make a lot of sense. Now, surely these conditions are not always valid, but in many standard Bayesian analyses (even if not all) we do not doubt the existence of a true model, and of true or fixed values for the unobservables.
How is data generated in the Bayesian framework and what is the nature on the parameter that generat
Pages 3 and 4 of BDA by Gelman et al., 3rd ed., are illuminating. Bayesian statistics aims to make inference from data using probability models for observables and unobservable quantities. We refer to
How is data generated in the Bayesian framework and what is the nature on the parameter that generates the data? Pages 3 and 4 of BDA by Gelman et al., 3rd ed., are illuminating. Bayesian statistics aims to make inference from data using probability models for observables and unobservable quantities. We refer to the unobservable quantities as parameters, even if the distinction is not always clear-cut. In Bayesian statistics all uncertainty about the variables involved in the model is represented using probability. Thus we need to setup a full probability model, i.e., a joint probability among all variables involved in our problem, both observable and unobservable, i.e., parameters. This means that we use random variables to represent both. It doesn't mean that we believe the parameter to be random: it means simply that our knowledge of the real value of the parameters is limited, and we represent whatever limited knowledge we have before observing data through the prior probability distribution. We then observe data and condition on the observed data using a model for the data generating process (which gives rise to a certain likelihood function) and Bayes' rule, to obtain a posterior probability distribution, which quantifies the remaining uncertainty in our knowledge about the unobservable quantities. In other words we use random variables for parameters not because we believe that there are no true parameters, but because we have a limited knowledge of them, which improves after observing data for the measurable variables, but it doesn't disappear completely. As a matter of fact, there are technical conditions under which the posterior distribution tends to a Dirac delta (thus the random variable used to represent the parameter becomes degenerate) in the limit for the number of observations which goes to 0. If there was no "true" value for the parameter, this wouldn't make a lot of sense. Now, surely these conditions are not always valid, but in many standard Bayesian analyses (even if not all) we do not doubt the existence of a true model, and of true or fixed values for the unobservables.
How is data generated in the Bayesian framework and what is the nature on the parameter that generat Pages 3 and 4 of BDA by Gelman et al., 3rd ed., are illuminating. Bayesian statistics aims to make inference from data using probability models for observables and unobservable quantities. We refer to
36,665
How is data generated in the Bayesian framework and what is the nature on the parameter that generates the data?
Is this the standard way to interpret the data generation process for in the Bayesian framework? No, this is not the standard interpretation. In fact, you have already recognised in your question the "subjective" interpretation of probability, which is the standard basis of Bayesian statistics. Under the "subjectivist" interpretation (more properly called the "epistemic" interpretation), the prior and posterior probability distributions for the parameters are used to represent the user's uncertainty about the unknown parameters in the model. Under this account there is no assumption of any corresponding metaphysical process occurring in nature, or any randomness in nature. Indeed, under this view the Bayesian paradigm does not provide any theory at all on the "data generation process" of nature; it merely gives us a mathematical way to model our uncertainty about things in nature, and hence form an inferential and predictive theory. Your latter description is an example of the propensity theory of probability, which posits that there is a metaphysical process that occurs in nature that is analogous to the probability calculus. This interpretation of probability assumes that there is some inbuilt metaphysical "propensity" in nature for outcomes to occur at random according to the laws of probability. As with most Bayesians, I have always found the propensity accounts to be a bit silly. It is really an example of human beings' propensity to project our own modes of thinking onto nature, and assume that there are analogues in nature to our epistemological methods and constructs. (As such, the "propensity interpretation" is more properly a propensity theory of human beings than one of probability!) Now, you might decide to adopt the subjectivist interpretation of probability, or you might disagree with me and decide to adopt the propensity interpretation. Regardless, you are going to get yourself into an awful mess if you equivocate between these two different interpretations. That is probably what is giving you difficulties at the moment.
How is data generated in the Bayesian framework and what is the nature on the parameter that generat
Is this the standard way to interpret the data generation process for in the Bayesian framework? No, this is not the standard interpretation. In fact, you have already recognised in your question th
How is data generated in the Bayesian framework and what is the nature on the parameter that generates the data? Is this the standard way to interpret the data generation process for in the Bayesian framework? No, this is not the standard interpretation. In fact, you have already recognised in your question the "subjective" interpretation of probability, which is the standard basis of Bayesian statistics. Under the "subjectivist" interpretation (more properly called the "epistemic" interpretation), the prior and posterior probability distributions for the parameters are used to represent the user's uncertainty about the unknown parameters in the model. Under this account there is no assumption of any corresponding metaphysical process occurring in nature, or any randomness in nature. Indeed, under this view the Bayesian paradigm does not provide any theory at all on the "data generation process" of nature; it merely gives us a mathematical way to model our uncertainty about things in nature, and hence form an inferential and predictive theory. Your latter description is an example of the propensity theory of probability, which posits that there is a metaphysical process that occurs in nature that is analogous to the probability calculus. This interpretation of probability assumes that there is some inbuilt metaphysical "propensity" in nature for outcomes to occur at random according to the laws of probability. As with most Bayesians, I have always found the propensity accounts to be a bit silly. It is really an example of human beings' propensity to project our own modes of thinking onto nature, and assume that there are analogues in nature to our epistemological methods and constructs. (As such, the "propensity interpretation" is more properly a propensity theory of human beings than one of probability!) Now, you might decide to adopt the subjectivist interpretation of probability, or you might disagree with me and decide to adopt the propensity interpretation. Regardless, you are going to get yourself into an awful mess if you equivocate between these two different interpretations. That is probably what is giving you difficulties at the moment.
How is data generated in the Bayesian framework and what is the nature on the parameter that generat Is this the standard way to interpret the data generation process for in the Bayesian framework? No, this is not the standard interpretation. In fact, you have already recognised in your question th
36,666
How is data generated in the Bayesian framework and what is the nature on the parameter that generates the data?
The parameter $\theta$ can only be regarded as fixed but unknown if you assume that the underlying model that you are working with is a perfect representation of the true system. However, since nature is usually much more complex than any mathematical model that we use, this assumption cannot be made. Therefore, there is no 'one true fixed' parameter of your model. Mathematically, as you add more and more data, you will converge to a certain parameter $\theta$. However, this is due to the insufficiency of your assumptions in the modeling process. You should be careful to call it the true fixed parameter of the underlying system. Even if a parameter in your model has a physical meaning - it is only an assumption that the posterior parameter retains this interpretation completely. The data in a Bayesian view is generated by the 'true system' - which you will never be able to model correctly. Therefore, an underlying true parameter of your assumed model cannot exist.
How is data generated in the Bayesian framework and what is the nature on the parameter that generat
The parameter $\theta$ can only be regarded as fixed but unknown if you assume that the underlying model that you are working with is a perfect representation of the true system. However, since nature
How is data generated in the Bayesian framework and what is the nature on the parameter that generates the data? The parameter $\theta$ can only be regarded as fixed but unknown if you assume that the underlying model that you are working with is a perfect representation of the true system. However, since nature is usually much more complex than any mathematical model that we use, this assumption cannot be made. Therefore, there is no 'one true fixed' parameter of your model. Mathematically, as you add more and more data, you will converge to a certain parameter $\theta$. However, this is due to the insufficiency of your assumptions in the modeling process. You should be careful to call it the true fixed parameter of the underlying system. Even if a parameter in your model has a physical meaning - it is only an assumption that the posterior parameter retains this interpretation completely. The data in a Bayesian view is generated by the 'true system' - which you will never be able to model correctly. Therefore, an underlying true parameter of your assumed model cannot exist.
How is data generated in the Bayesian framework and what is the nature on the parameter that generat The parameter $\theta$ can only be regarded as fixed but unknown if you assume that the underlying model that you are working with is a perfect representation of the true system. However, since nature
36,667
Outlier detection with data (which has categorical and numeric variables) with R
Let's look at a standard definition for outliers in fraud detection first (paraphrased from Han et al. Data Mining, 2012): A customer generates transactions, which follow roughly a Gaussian distribution, consider e.g. buying a bigger lunch one day, a smaller the other and so on. An outlier is a data object, which deviates significantly from the rest of the objects, as if following a different distribution. I.e. when plotting a numeric variable, those points that deviate from your Gaussian distribution are your outliers (could use e.g. a Q-Q plot, standard scores, or other methods). Proceeding. Using unsupervised learning, e.g. clustering, forms, indeed as mkemp6 noticed, a valid subgroup of distinctly different data points. However there is no reason not to declare these as a groups of outliers. You are, however, rather facing 3 problems when working with mixed type variables: If you intend to use non-hierarchical clustering, which I'd suggest, then you will need to determine how many clusters (denoted by $k$) your data should be grouped into You will end up with a combination of numeric and non-numeric distributions, for the latter you will need to define what an outlier is With regards to the definition of outliers, outliers might follow very different distributions, hence clustering them might be tricky Problem #3 is the text book problem of applying unsupervised learning methods to outlier detection, but this is what you will have to live with. Depending on the number of expressions per categorical variable, your problem is more or less computationally intensive. Without being an expert and without having thought all of these through, here are some ideas. Option 1 Semi-fast and easy This option is a special case of clustering, for which you will not need a formal algorithm. You could find all unique combinations of categorical variables (unique(data[,your_categorical_variables])), which gives you the maximum number of possible unique clusters if you consider. From the observation of the distribution of the numeric variables associated with, you can proceed to identify those data points, which do not fit an underlying (probably Gaussian) distribution. However, considering the size of your data set, there will probably not be much repetition, i.e. per unique combination of categorical variable I suspect there will only be few data points, which would make this approach obsolete. Option 2 Not so fast, not so easy This actually uses clustering. You pick a hierarchical k-prototypes algorithm. As you can hardly make a graphical observation you can either use your judgement from Option 1 to "guess" clusters, though for outlier detection this might be unsuitable. Rather, you can use an F-test as your stopping criterion. The F-test tells you essentially, whether or not, based on the sum of squared deviations in your clusters, a division in to $k+1$ is statistically significantly better than a division into $k$ clusters. After your clustering is finished, you go on similar to Option 1 to identify rare categorical variable combination, and look at their numeric distributions to detect your outliers. Option 3 Semi-fast, easy You select only your numeric variables. You plot the distributions. By graphical inspection you note down possible cluster centers per variable. You use a standard k-means algorithm from the package cluster. You pass the anticipated cluster centers as expected starting points to the clustering algorithm. You use the output index list on your complete data set (incl. categorical data) and determine the rare combinations of categorical variables per cluster. I would particularly investigate very small clusters in your case. You will have to make some assumptions when declaring any cluster as a cluster of outliers. Notes on k-prototypes The k-prototypes algorithm defines cluster centers as mixtures of numeric and categorical data points. It follows the standard procedure for hierarchical clustering: Pick $k$ amount of random cluster centers from your data Compute distance for one point to each cluster center. The distance function typically contains a Euclidean part for numeric and a 0-1 matching for categorical variables (read linked paper). More elaborate distance functions for the categorical variables might be needed. Adjust cluster centers according to the mean and mode of all points currently assigned to them Repeat 2-3 for every data point Iterate 2-4 until cluster centers do not change anymore Depending on the level of sophistication of your result, you may also want to look into genetic algorithms to not fall into local optima here; I believe this is a case, for which this might make particular sense. Notes on the F-Test This is taken from Cluster Analysis, Everitt et al., 2011. To compare if a clustering into $k+1$ clusters is better than a clustering into $k$ clusters, you calculate the F-statistic in the following manner: $$ F_(g1,g2)=\frac{\frac{(S_{g1}^2-S_{g2}^2)}{S_{g2}^2}}{\frac{n-g_1}{n-g_2}*(\frac{g_2}{g_1})^{2/p}-1} $$ where $g1$ = $k$ number of clusters $g2$ = $k+1$ number of clusters $n$ = number of data objects $p$ = number of variables $S^1$ = the sum of the sum of squared deviations from the cluster centers in your division into $k$ clusters $S^2$ = the sum of the sum of squared deviations from the cluster centers in your division into $k+1$ clusters Your division of the $n$ objects into $g2$ clusters is significantly better, if the F-statistics exceeds the critical value of an F-distribution with $p(g2-g1)$ and $p(n-g2)$ degrees of freedom.
Outlier detection with data (which has categorical and numeric variables) with R
Let's look at a standard definition for outliers in fraud detection first (paraphrased from Han et al. Data Mining, 2012): A customer generates transactions, which follow roughly a Gaussian distribut
Outlier detection with data (which has categorical and numeric variables) with R Let's look at a standard definition for outliers in fraud detection first (paraphrased from Han et al. Data Mining, 2012): A customer generates transactions, which follow roughly a Gaussian distribution, consider e.g. buying a bigger lunch one day, a smaller the other and so on. An outlier is a data object, which deviates significantly from the rest of the objects, as if following a different distribution. I.e. when plotting a numeric variable, those points that deviate from your Gaussian distribution are your outliers (could use e.g. a Q-Q plot, standard scores, or other methods). Proceeding. Using unsupervised learning, e.g. clustering, forms, indeed as mkemp6 noticed, a valid subgroup of distinctly different data points. However there is no reason not to declare these as a groups of outliers. You are, however, rather facing 3 problems when working with mixed type variables: If you intend to use non-hierarchical clustering, which I'd suggest, then you will need to determine how many clusters (denoted by $k$) your data should be grouped into You will end up with a combination of numeric and non-numeric distributions, for the latter you will need to define what an outlier is With regards to the definition of outliers, outliers might follow very different distributions, hence clustering them might be tricky Problem #3 is the text book problem of applying unsupervised learning methods to outlier detection, but this is what you will have to live with. Depending on the number of expressions per categorical variable, your problem is more or less computationally intensive. Without being an expert and without having thought all of these through, here are some ideas. Option 1 Semi-fast and easy This option is a special case of clustering, for which you will not need a formal algorithm. You could find all unique combinations of categorical variables (unique(data[,your_categorical_variables])), which gives you the maximum number of possible unique clusters if you consider. From the observation of the distribution of the numeric variables associated with, you can proceed to identify those data points, which do not fit an underlying (probably Gaussian) distribution. However, considering the size of your data set, there will probably not be much repetition, i.e. per unique combination of categorical variable I suspect there will only be few data points, which would make this approach obsolete. Option 2 Not so fast, not so easy This actually uses clustering. You pick a hierarchical k-prototypes algorithm. As you can hardly make a graphical observation you can either use your judgement from Option 1 to "guess" clusters, though for outlier detection this might be unsuitable. Rather, you can use an F-test as your stopping criterion. The F-test tells you essentially, whether or not, based on the sum of squared deviations in your clusters, a division in to $k+1$ is statistically significantly better than a division into $k$ clusters. After your clustering is finished, you go on similar to Option 1 to identify rare categorical variable combination, and look at their numeric distributions to detect your outliers. Option 3 Semi-fast, easy You select only your numeric variables. You plot the distributions. By graphical inspection you note down possible cluster centers per variable. You use a standard k-means algorithm from the package cluster. You pass the anticipated cluster centers as expected starting points to the clustering algorithm. You use the output index list on your complete data set (incl. categorical data) and determine the rare combinations of categorical variables per cluster. I would particularly investigate very small clusters in your case. You will have to make some assumptions when declaring any cluster as a cluster of outliers. Notes on k-prototypes The k-prototypes algorithm defines cluster centers as mixtures of numeric and categorical data points. It follows the standard procedure for hierarchical clustering: Pick $k$ amount of random cluster centers from your data Compute distance for one point to each cluster center. The distance function typically contains a Euclidean part for numeric and a 0-1 matching for categorical variables (read linked paper). More elaborate distance functions for the categorical variables might be needed. Adjust cluster centers according to the mean and mode of all points currently assigned to them Repeat 2-3 for every data point Iterate 2-4 until cluster centers do not change anymore Depending on the level of sophistication of your result, you may also want to look into genetic algorithms to not fall into local optima here; I believe this is a case, for which this might make particular sense. Notes on the F-Test This is taken from Cluster Analysis, Everitt et al., 2011. To compare if a clustering into $k+1$ clusters is better than a clustering into $k$ clusters, you calculate the F-statistic in the following manner: $$ F_(g1,g2)=\frac{\frac{(S_{g1}^2-S_{g2}^2)}{S_{g2}^2}}{\frac{n-g_1}{n-g_2}*(\frac{g_2}{g_1})^{2/p}-1} $$ where $g1$ = $k$ number of clusters $g2$ = $k+1$ number of clusters $n$ = number of data objects $p$ = number of variables $S^1$ = the sum of the sum of squared deviations from the cluster centers in your division into $k$ clusters $S^2$ = the sum of the sum of squared deviations from the cluster centers in your division into $k+1$ clusters Your division of the $n$ objects into $g2$ clusters is significantly better, if the F-statistics exceeds the critical value of an F-distribution with $p(g2-g1)$ and $p(n-g2)$ degrees of freedom.
Outlier detection with data (which has categorical and numeric variables) with R Let's look at a standard definition for outliers in fraud detection first (paraphrased from Han et al. Data Mining, 2012): A customer generates transactions, which follow roughly a Gaussian distribut
36,668
characteristic functions and symmetry
Yes. When the characteristic function $\phi_X$ of a random variable $X$ is real-valued, that means $$\overline{\phi_X}(t) = \phi_X(t)$$ for all $t$. But for any characteristic function $$\phi_{-X}(t) = \phi_X(-t) = \overline{\phi_X}(t),$$ showing that $X$ and $-X$ have identical distributions (since the cf determines the distribution), implying $X$ is symmetric about zero. (The converse is equally clear.) These facts are given in the Wikipedia article, which also mentions this result.
characteristic functions and symmetry
Yes. When the characteristic function $\phi_X$ of a random variable $X$ is real-valued, that means $$\overline{\phi_X}(t) = \phi_X(t)$$ for all $t$. But for any characteristic function $$\phi_{-X}(t
characteristic functions and symmetry Yes. When the characteristic function $\phi_X$ of a random variable $X$ is real-valued, that means $$\overline{\phi_X}(t) = \phi_X(t)$$ for all $t$. But for any characteristic function $$\phi_{-X}(t) = \phi_X(-t) = \overline{\phi_X}(t),$$ showing that $X$ and $-X$ have identical distributions (since the cf determines the distribution), implying $X$ is symmetric about zero. (The converse is equally clear.) These facts are given in the Wikipedia article, which also mentions this result.
characteristic functions and symmetry Yes. When the characteristic function $\phi_X$ of a random variable $X$ is real-valued, that means $$\overline{\phi_X}(t) = \phi_X(t)$$ for all $t$. But for any characteristic function $$\phi_{-X}(t
36,669
Is stratified meta-analysis more or less objective than meta-regression?
Here are some suggestions for how you could respond: Given that your predictors are continuous (and artificially categorizing predictors is usually frowned upon), meta-regression seems like the right approach (and in fact, meta-regression can also deal with categorical predictors just as well as stratifying on them, so why bother?). If I understand you correctly, you entered those 4 predictors simultaneously into the model. Stratifying would either imply examining one (artificially categorized) predictor at a time (which does not consider heterogeneity that may be better accounted for by other predictors or potential confounding between the predictors) or if one were to start stratifying on combinations of predictors, the subgroups will start to get quite small. That doesn't seem like a good idea (see also the next point). How well the amount of heterogeneity in a random-effects model (or the amount of residual heterogeneity in a mixed-effects meta-regression model) is estimated depends to a great extent on the number of studies. Stratifying will lead to smaller subsets with poorer estimates of the amount of heterogeneity. I actually discuss these issues in this article: Viechtbauer, W. (2007). Accounting for heterogeneity via random-effects models and moderator analyses in meta-analysis. Zeitschrift für Psychologie / Journal of Psychology, 215(2), 104-121. If you are interested and cannot get hold of a copy of the article (it's in a German journal; but the article is in English), feel free to send me an e-mail (you'll find my website linked to from my profile; e-mail address can be found there).
Is stratified meta-analysis more or less objective than meta-regression?
Here are some suggestions for how you could respond: Given that your predictors are continuous (and artificially categorizing predictors is usually frowned upon), meta-regression seems like the right
Is stratified meta-analysis more or less objective than meta-regression? Here are some suggestions for how you could respond: Given that your predictors are continuous (and artificially categorizing predictors is usually frowned upon), meta-regression seems like the right approach (and in fact, meta-regression can also deal with categorical predictors just as well as stratifying on them, so why bother?). If I understand you correctly, you entered those 4 predictors simultaneously into the model. Stratifying would either imply examining one (artificially categorized) predictor at a time (which does not consider heterogeneity that may be better accounted for by other predictors or potential confounding between the predictors) or if one were to start stratifying on combinations of predictors, the subgroups will start to get quite small. That doesn't seem like a good idea (see also the next point). How well the amount of heterogeneity in a random-effects model (or the amount of residual heterogeneity in a mixed-effects meta-regression model) is estimated depends to a great extent on the number of studies. Stratifying will lead to smaller subsets with poorer estimates of the amount of heterogeneity. I actually discuss these issues in this article: Viechtbauer, W. (2007). Accounting for heterogeneity via random-effects models and moderator analyses in meta-analysis. Zeitschrift für Psychologie / Journal of Psychology, 215(2), 104-121. If you are interested and cannot get hold of a copy of the article (it's in a German journal; but the article is in English), feel free to send me an e-mail (you'll find my website linked to from my profile; e-mail address can be found there).
Is stratified meta-analysis more or less objective than meta-regression? Here are some suggestions for how you could respond: Given that your predictors are continuous (and artificially categorizing predictors is usually frowned upon), meta-regression seems like the right
36,670
Deep learning algorithm
Deep convex network is relatively new architecture of deep neural networks, which has been developed in order to overcome the scalability limitations of deep belief networks (DBN). You can read more on technical details of the architecture and its performance in research papers, for example, in this paper as well as a relevant later paper, both from Microsoft Research. It might be beneficial to read more about DBN on this fascinating peer-reviewed open-access site, as it's more comprehensive than Wikipedia on the topic. In my opinion, even more comprehensive and interesting overview of deep learning architectures in AI can be found in this technical report.
Deep learning algorithm
Deep convex network is relatively new architecture of deep neural networks, which has been developed in order to overcome the scalability limitations of deep belief networks (DBN). You can read more o
Deep learning algorithm Deep convex network is relatively new architecture of deep neural networks, which has been developed in order to overcome the scalability limitations of deep belief networks (DBN). You can read more on technical details of the architecture and its performance in research papers, for example, in this paper as well as a relevant later paper, both from Microsoft Research. It might be beneficial to read more about DBN on this fascinating peer-reviewed open-access site, as it's more comprehensive than Wikipedia on the topic. In my opinion, even more comprehensive and interesting overview of deep learning architectures in AI can be found in this technical report.
Deep learning algorithm Deep convex network is relatively new architecture of deep neural networks, which has been developed in order to overcome the scalability limitations of deep belief networks (DBN). You can read more o
36,671
Analysing the residuals themselves
This has been referred to as residual index, although not consistently. I guess the type of analyses you subject it to would depend on your question of interest (as most result in some level of 'deeper understanding'), and so would pros and cons. Garcia-Berthou discusses cons of one example of such application as "an ad hoc sequential procedure with no statistical justification" here http://onlinelibrary.wiley.com/doi/10.1046/j.1365-2656.2001.00524.x/full In other words, if you suspect other factors are affecting the response, why not start with a model that would account for these multiple factors and their interactions. Yet, in other cases it is possible to justify, and there are valid examples of its use in spatial analyses.
Analysing the residuals themselves
This has been referred to as residual index, although not consistently. I guess the type of analyses you subject it to would depend on your question of interest (as most result in some level of 'deepe
Analysing the residuals themselves This has been referred to as residual index, although not consistently. I guess the type of analyses you subject it to would depend on your question of interest (as most result in some level of 'deeper understanding'), and so would pros and cons. Garcia-Berthou discusses cons of one example of such application as "an ad hoc sequential procedure with no statistical justification" here http://onlinelibrary.wiley.com/doi/10.1046/j.1365-2656.2001.00524.x/full In other words, if you suspect other factors are affecting the response, why not start with a model that would account for these multiple factors and their interactions. Yet, in other cases it is possible to justify, and there are valid examples of its use in spatial analyses.
Analysing the residuals themselves This has been referred to as residual index, although not consistently. I guess the type of analyses you subject it to would depend on your question of interest (as most result in some level of 'deepe
36,672
Analysing the residuals themselves
As a partial answer to your question, you can build a residual model (also known as a variance model) to model the residuals for the original model as a function of the predicted response (for example) as follows (in R notation): residual.model <- lm(abs(residuals(original.model)) ~ predict(original.model), ...) You can then examine the residual model to get a deeper understanding of the data. From the residual model you can estimate prediction intervals, for example. The residuals are usually much more noisy than the original data used to build the model, and so there will be more uncertainty about the residual model than the original model. The above residual model uses lm and thus assumes (at most) a linear relationship between the absolute residuals and the predicted response, which is often a good enough approximation to the (unknown) underlying reality---or maybe I should say, a linear residual model is often about the most complicated residual model you would want to use given the noise in the residuals. My earth R package builds variance models essentially using the above idea (but the ideas are fairly universal and apply not just to earth/MARS models). Some of the background theory can be found in the package vignette Variance models in earth. When reading the vignette, mentally substitute the name of your model instead of "earth" e.g. substitute "lm" for "earth". Additional references can be found in the above vignette. Especially helpful is Carroll and Ruppert Transformation and Weighting in Regression.
Analysing the residuals themselves
As a partial answer to your question, you can build a residual model (also known as a variance model) to model the residuals for the original model as a function of the predicted response (for exampl
Analysing the residuals themselves As a partial answer to your question, you can build a residual model (also known as a variance model) to model the residuals for the original model as a function of the predicted response (for example) as follows (in R notation): residual.model <- lm(abs(residuals(original.model)) ~ predict(original.model), ...) You can then examine the residual model to get a deeper understanding of the data. From the residual model you can estimate prediction intervals, for example. The residuals are usually much more noisy than the original data used to build the model, and so there will be more uncertainty about the residual model than the original model. The above residual model uses lm and thus assumes (at most) a linear relationship between the absolute residuals and the predicted response, which is often a good enough approximation to the (unknown) underlying reality---or maybe I should say, a linear residual model is often about the most complicated residual model you would want to use given the noise in the residuals. My earth R package builds variance models essentially using the above idea (but the ideas are fairly universal and apply not just to earth/MARS models). Some of the background theory can be found in the package vignette Variance models in earth. When reading the vignette, mentally substitute the name of your model instead of "earth" e.g. substitute "lm" for "earth". Additional references can be found in the above vignette. Especially helpful is Carroll and Ruppert Transformation and Weighting in Regression.
Analysing the residuals themselves As a partial answer to your question, you can build a residual model (also known as a variance model) to model the residuals for the original model as a function of the predicted response (for exampl
36,673
What's the difference between estimating equations and method of moments estimators?
The most common justification of the method of moments is simply the law of large numbers, which would seem to make your suggestion of estimating $\mu_3$ by $\hat{\mu}_3$ "method of moments" (and I'd be inclined to call it MoM in any case). However, a number of books and documents, such as this for example (and to some extent the wikipedia page on method of moments) imply that you take the lowest $k$ moments* and estimate the required quantities for given the probability model from that, as you imply by estimating $\mu_3$ from the first two moments. *(where you need to estimate $k$ parameters to obtain the required quantity) -- Ultimately, I guess it comes down to "who defines what counts as method of moments?" Do we look to Pearson? Do we look to the most common conventions? Do we accept any convenient definition? --- Any of those choices has problems, and benefits. The interesting bit, to me, is whether one can always or almost always reparameterize a parametric family to characterize an estimation problem in EE as the solution to the moments of a (possibly bizarre) distribution function? Clearly there are large classes of distribution for which method of moments would be useless. For an obvious example, the mean of the Cauchy distribution is undefined. Even when moments exist and are finite, there could be a large number of situations where the set of equations $f(\mathbf{\theta},\mathbf{y})=0$ has 0 solutions (think of some curve that never crosses the x-axis) or multiple solutions (one that crosses the axis repeatedly -- though multiple solutions aren't necessarily an insurmountable problem if you have a way to choose between them). Of course, we also commonly see situations where a solution exists but doesn't lie in the parameter space (there may even be cases where there's never a solution in the parameter space, but I don't know of any -- it would be an interesting question to discover if some such cases exist). I imagine there can be more complicated situations still, though I don't have any in mind at the moment.
What's the difference between estimating equations and method of moments estimators?
The most common justification of the method of moments is simply the law of large numbers, which would seem to make your suggestion of estimating $\mu_3$ by $\hat{\mu}_3$ "method of moments" (and I'd
What's the difference between estimating equations and method of moments estimators? The most common justification of the method of moments is simply the law of large numbers, which would seem to make your suggestion of estimating $\mu_3$ by $\hat{\mu}_3$ "method of moments" (and I'd be inclined to call it MoM in any case). However, a number of books and documents, such as this for example (and to some extent the wikipedia page on method of moments) imply that you take the lowest $k$ moments* and estimate the required quantities for given the probability model from that, as you imply by estimating $\mu_3$ from the first two moments. *(where you need to estimate $k$ parameters to obtain the required quantity) -- Ultimately, I guess it comes down to "who defines what counts as method of moments?" Do we look to Pearson? Do we look to the most common conventions? Do we accept any convenient definition? --- Any of those choices has problems, and benefits. The interesting bit, to me, is whether one can always or almost always reparameterize a parametric family to characterize an estimation problem in EE as the solution to the moments of a (possibly bizarre) distribution function? Clearly there are large classes of distribution for which method of moments would be useless. For an obvious example, the mean of the Cauchy distribution is undefined. Even when moments exist and are finite, there could be a large number of situations where the set of equations $f(\mathbf{\theta},\mathbf{y})=0$ has 0 solutions (think of some curve that never crosses the x-axis) or multiple solutions (one that crosses the axis repeatedly -- though multiple solutions aren't necessarily an insurmountable problem if you have a way to choose between them). Of course, we also commonly see situations where a solution exists but doesn't lie in the parameter space (there may even be cases where there's never a solution in the parameter space, but I don't know of any -- it would be an interesting question to discover if some such cases exist). I imagine there can be more complicated situations still, though I don't have any in mind at the moment.
What's the difference between estimating equations and method of moments estimators? The most common justification of the method of moments is simply the law of large numbers, which would seem to make your suggestion of estimating $\mu_3$ by $\hat{\mu}_3$ "method of moments" (and I'd
36,674
What's the difference between estimating equations and method of moments estimators?
Estimating equations is a more general method, it doesnt specify from where you get the estimating equation. Maximum likelihood is also an example of estimating equations, as it leads to the score equation. Various forms of quasi (or pseudo)-likelihood are other examples! as are method of moments.
What's the difference between estimating equations and method of moments estimators?
Estimating equations is a more general method, it doesnt specify from where you get the estimating equation. Maximum likelihood is also an example of estimating equations, as it leads to the score equ
What's the difference between estimating equations and method of moments estimators? Estimating equations is a more general method, it doesnt specify from where you get the estimating equation. Maximum likelihood is also an example of estimating equations, as it leads to the score equation. Various forms of quasi (or pseudo)-likelihood are other examples! as are method of moments.
What's the difference between estimating equations and method of moments estimators? Estimating equations is a more general method, it doesnt specify from where you get the estimating equation. Maximum likelihood is also an example of estimating equations, as it leads to the score equ
36,675
When does an unpaired test result in higher p-value than a paired test?
As @whuber says in the comment above, when the measures are negatively correlated, the p-value can be lower in the unpaired test than in the paired test. Here's an example where there is a difference: library(MASS) s <- matrix(c(1, -0.8, -0.8, 1), 2) df <- mvrnorm(n=100, mu=c(0, 0.3), Sigma=s, empirical=TRUE) t.test(df[,1], df[, 2], paired=FALSE) t.test(df[,1], df[, 2], paired=TRUE) The first test (unpaired) gives p=0.035, the second gives p=0.117. Yes, this is a design issue. This book chapter discusses it: Keren, G. (2014). Between-or within-subjects design: A methodological dilemma. A Handbook for Data Analysis in the Behaviorial Sciences: Volume 1: Methodological Issues Volume 2: Statistical Issues, 257, which you can read some of on Google books. Hmmm... I'm not sure. I'd do a simulation to find out the effect on the type I error rate. How this affects your power is a separate issue that I haven't looked into here. Slight adaptation of my previous code: paired <- rep(NA, 1000) unpaired <- rep(NA, 1000) for(i in 1:1000){ df <- mvrnorm(n=100, mu=c(0, 0), Sigma=s, empirical=FALSE) unpaired[i] <- t.test(df[,1], df[, 2], paired=FALSE)$p.value paired[i] <- t.test(df[,1], df[, 2], paired=TRUE )$p.value } sum(paired < 0.05) sum(unpaired < 0.05) Result: > sum(paired < 0.05) [1] 46 > sum(unpaired < 0.05) [1] 137 Well look at that. If you treat them as unpaired, your type I error rate rockets. You need to treat them as paired to get the right answer. I believe (it's a long time since I've read it) that this is one of the issues Keren talks about in that chapter. If you're going to have data that might be negative correlated (e.g. amount of soup and amount of burgers someone eats) you'll have more power with an unpaired design.
When does an unpaired test result in higher p-value than a paired test?
As @whuber says in the comment above, when the measures are negatively correlated, the p-value can be lower in the unpaired test than in the paired test. Here's an example where there is a difference:
When does an unpaired test result in higher p-value than a paired test? As @whuber says in the comment above, when the measures are negatively correlated, the p-value can be lower in the unpaired test than in the paired test. Here's an example where there is a difference: library(MASS) s <- matrix(c(1, -0.8, -0.8, 1), 2) df <- mvrnorm(n=100, mu=c(0, 0.3), Sigma=s, empirical=TRUE) t.test(df[,1], df[, 2], paired=FALSE) t.test(df[,1], df[, 2], paired=TRUE) The first test (unpaired) gives p=0.035, the second gives p=0.117. Yes, this is a design issue. This book chapter discusses it: Keren, G. (2014). Between-or within-subjects design: A methodological dilemma. A Handbook for Data Analysis in the Behaviorial Sciences: Volume 1: Methodological Issues Volume 2: Statistical Issues, 257, which you can read some of on Google books. Hmmm... I'm not sure. I'd do a simulation to find out the effect on the type I error rate. How this affects your power is a separate issue that I haven't looked into here. Slight adaptation of my previous code: paired <- rep(NA, 1000) unpaired <- rep(NA, 1000) for(i in 1:1000){ df <- mvrnorm(n=100, mu=c(0, 0), Sigma=s, empirical=FALSE) unpaired[i] <- t.test(df[,1], df[, 2], paired=FALSE)$p.value paired[i] <- t.test(df[,1], df[, 2], paired=TRUE )$p.value } sum(paired < 0.05) sum(unpaired < 0.05) Result: > sum(paired < 0.05) [1] 46 > sum(unpaired < 0.05) [1] 137 Well look at that. If you treat them as unpaired, your type I error rate rockets. You need to treat them as paired to get the right answer. I believe (it's a long time since I've read it) that this is one of the issues Keren talks about in that chapter. If you're going to have data that might be negative correlated (e.g. amount of soup and amount of burgers someone eats) you'll have more power with an unpaired design.
When does an unpaired test result in higher p-value than a paired test? As @whuber says in the comment above, when the measures are negatively correlated, the p-value can be lower in the unpaired test than in the paired test. Here's an example where there is a difference:
36,676
Which post-hoc is more valid for multiple comparison of an unbalanced lmer-model: lsm or mcp?
Are you sure that the results really differ at all? I see only one change in the 4th decimal place (of the p-value of the difference between groups 2 and 3), a relative difference of 0.3%, which could be a numerical difference due to doing equivalent computations in a different sequence. ?lsm says: It works similarly to ‘mcp’ except with ‘specs’ (and optionally ‘by’ and ‘contr’ arguments) provided as in a call to ‘lsmeans’. which suggests strongly to me (since lsmeans is generally well-documented) that this is only a different interface to the same functionality: if there were important statistical differences I think they would be mentioned ... It would be helpful to tell us that lsm comes from the lsmeans package (and glht is from multcomp).
Which post-hoc is more valid for multiple comparison of an unbalanced lmer-model: lsm or mcp?
Are you sure that the results really differ at all? I see only one change in the 4th decimal place (of the p-value of the difference between groups 2 and 3), a relative difference of 0.3%, which coul
Which post-hoc is more valid for multiple comparison of an unbalanced lmer-model: lsm or mcp? Are you sure that the results really differ at all? I see only one change in the 4th decimal place (of the p-value of the difference between groups 2 and 3), a relative difference of 0.3%, which could be a numerical difference due to doing equivalent computations in a different sequence. ?lsm says: It works similarly to ‘mcp’ except with ‘specs’ (and optionally ‘by’ and ‘contr’ arguments) provided as in a call to ‘lsmeans’. which suggests strongly to me (since lsmeans is generally well-documented) that this is only a different interface to the same functionality: if there were important statistical differences I think they would be mentioned ... It would be helpful to tell us that lsm comes from the lsmeans package (and glht is from multcomp).
Which post-hoc is more valid for multiple comparison of an unbalanced lmer-model: lsm or mcp? Are you sure that the results really differ at all? I see only one change in the 4th decimal place (of the p-value of the difference between groups 2 and 3), a relative difference of 0.3%, which coul
36,677
Cross correlation for very sparse binary data
You are right to think of correlation as the mean of the product of the standardized variables: this has great conceptual advantages over other definitions. It also leads to minimal loss of floating point precision. However, it is not necessarily the best approach for all computation, especially when speed is important. Our goal is to make algebraic manipulations that lead to calculations involving, if possible, dot products of the original variables, for then the inherent sparse matrix operations ought to make short work indeed of those computations. Let, then, $\mathbf u$ and $\mathbf v$ be two of the columns of the original sparse binary matrix $\mathbb Y$ (so that the $n$ entries in each of $\mathbf u$ and $\mathbf v$ are only zeros and ones). Let $\mathbf 1 = (1,1,\ldots, 1)$ be an $n$-vector and write $$\bar u = (u_1 + u_2 + \cdots + u_n)/n = \frac{1}{n}\mathbf u \cdot \mathbf 1$$ (and likewise $\bar v = \frac{1}{n}\mathbf v \cdot \mathbf 1$) for their means and $$\mathbf u_0 = (u_1 - \bar u, u_2 - \bar u, \ldots, u_n - \bar u)$$ (and similarly for $\mathbf v_0$) for the centered vectors of their residuals. Then $$||\mathbf u_0||^2 = \mathbf u_0 \cdot \mathbf u_0$$ shows how to find the lengths of the residual vectors which are used to standardize them to $$\mathbf \upsilon = \mathbf u_0 / \sqrt{||\mathbf u_0||/n};\quad\mathbf \phi= \mathbf v_0 / \sqrt{||\mathbf v_0||/n}$$ whence, by definition, $$\rho_{\mathbf u, \mathbf v} = \mathbf \upsilon \cdot \mathbf \phi.$$ (Apart from choices of when to divide by $n$, this appears to be what the code in the question is doing.) Working backwards (by plugging the foregoing into this formula) easily yields $$\eqalign{ \rho_{\mathbf u, \mathbf v} &=\mathbf u_0 / \sqrt{||\mathbf u_0||/n} \cdot \mathbf v_0 / \sqrt{||\mathbf v_0||/n} \\ &=n\frac{\left(\mathbf u - \bar u \mathbf 1\right)\cdot\left(\mathbf v - \bar v \mathbf 1\right)}{\sqrt{\left(\mathbf u - \bar u \mathbf 1\right)\cdot\left(\mathbf u - \bar u \mathbf 1\right)\,\left(\mathbf v - \bar v \mathbf 1\right)\cdot\left(\mathbf v - \bar v \mathbf 1\right)}}. }$$ Using the distributive law to expand the dot products shows that $$\eqalign{ \left(\mathbf u - \bar u \mathbf 1\right)\cdot\left(\mathbf v - \bar v \mathbf 1\right) &= \mathbf u \cdot \mathbf v - \frac{2}{n}(\mathbf u \cdot \mathbf 1) (\mathbf 1 \cdot \mathbf v) + \frac{1}{n^2}(\mathbf u \cdot \mathbf 1)(\mathbf v \cdot \mathbf 1)\mathbf 1 \cdot \mathbf 1 \\ &= \mathbf u \cdot \mathbf v -\frac{1}{n}(\mathbf u \cdot \mathbf 1)(\mathbf v \cdot \mathbf 1) }$$ because $\mathbf 1 \cdot \mathbf 1 = n$. Similar formulas hold for the expressions in the denominator. This shows how the correlation coefficient can be computed in terms of dot products of the original (raw, sparse) vectors. Note in particular that the terms in the denominator can be written $$\mathbf u \cdot \mathbf u -\frac{1}{n}(\mathbf u \cdot \mathbf 1)(\mathbf u \cdot \mathbf 1)=n \bar u - \frac{1}{n}(n \bar u)^2 = n(\bar u - \bar u^2)$$ An efficient implementation will compute column sums (from which their means $\bar u$ are immediately derived) and obtain all the dot products of all pairs of columns at once by means of a single matrix operation $\mathbb Y^\prime \mathbb Y$. Using these it is simple and fast to obtain the correlation coefficients with the preceding formula. To obtain lagged correlations at lag $k$, remove the first $k$ rows of $\mathbb Y$ (call this $\mathbb Y_{(k)}$ and separately remove the last $k$ rows (call this $\mathbb Y_{(-k)}$). The essential material for the computation can be found in the non-diagonal entries of $\mathbb Y_{(k)}^\prime \mathbb Y_{(-k)}$. The new denominators will scarcely differ from the old ones and so, to a high degree of accuracy, need not be recomputed at all; but for perfect accuracy note that the column sums in $\mathbb Y_{(k)}$ are of the form $$\sum_{i=k+1}^n u_i = \left(\sum_{i=1}^n u_i\right) - u_k - u_{k-1} - \cdots - u_2 - u_1$$ which are easily obtained from the original column sums by means of just $k$ subtractions (and similarly for the column sums of $\mathbb Y_{(-k)}$. Thus, computing the entire $21\times 60\times 60$ array comes down to performing $21$ multiplications of sparse binary matrices and adjusting the results. The total number of numeric operations involved (with each dot product requiring about $2n$ multiplications and $2n$ additions) will be approximately $$2 \times 5271159 \times 60^2 \times 21 \approx 800 \times 10^9.$$ Unparallelized, but running as native code on a modern PC, this would take two minutes without any sparse matrix speed improvements. Tests in R (without using sparse arithmetic) with a $5271159 \times 6$ matrix took $1.3$ seconds; the quadratic scaling indicates R would thereby require $130$ seconds, confirming the two minute estimate. Given a random binary array of dimensions $5271159\times 60$ and mean of $1/40$, Mathematica 9 took one second to compute $\mathbb Y^\prime \mathbb Y$, suggesting the total computation for all $21$ lags should be around $20$ seconds.
Cross correlation for very sparse binary data
You are right to think of correlation as the mean of the product of the standardized variables: this has great conceptual advantages over other definitions. It also leads to minimal loss of floating
Cross correlation for very sparse binary data You are right to think of correlation as the mean of the product of the standardized variables: this has great conceptual advantages over other definitions. It also leads to minimal loss of floating point precision. However, it is not necessarily the best approach for all computation, especially when speed is important. Our goal is to make algebraic manipulations that lead to calculations involving, if possible, dot products of the original variables, for then the inherent sparse matrix operations ought to make short work indeed of those computations. Let, then, $\mathbf u$ and $\mathbf v$ be two of the columns of the original sparse binary matrix $\mathbb Y$ (so that the $n$ entries in each of $\mathbf u$ and $\mathbf v$ are only zeros and ones). Let $\mathbf 1 = (1,1,\ldots, 1)$ be an $n$-vector and write $$\bar u = (u_1 + u_2 + \cdots + u_n)/n = \frac{1}{n}\mathbf u \cdot \mathbf 1$$ (and likewise $\bar v = \frac{1}{n}\mathbf v \cdot \mathbf 1$) for their means and $$\mathbf u_0 = (u_1 - \bar u, u_2 - \bar u, \ldots, u_n - \bar u)$$ (and similarly for $\mathbf v_0$) for the centered vectors of their residuals. Then $$||\mathbf u_0||^2 = \mathbf u_0 \cdot \mathbf u_0$$ shows how to find the lengths of the residual vectors which are used to standardize them to $$\mathbf \upsilon = \mathbf u_0 / \sqrt{||\mathbf u_0||/n};\quad\mathbf \phi= \mathbf v_0 / \sqrt{||\mathbf v_0||/n}$$ whence, by definition, $$\rho_{\mathbf u, \mathbf v} = \mathbf \upsilon \cdot \mathbf \phi.$$ (Apart from choices of when to divide by $n$, this appears to be what the code in the question is doing.) Working backwards (by plugging the foregoing into this formula) easily yields $$\eqalign{ \rho_{\mathbf u, \mathbf v} &=\mathbf u_0 / \sqrt{||\mathbf u_0||/n} \cdot \mathbf v_0 / \sqrt{||\mathbf v_0||/n} \\ &=n\frac{\left(\mathbf u - \bar u \mathbf 1\right)\cdot\left(\mathbf v - \bar v \mathbf 1\right)}{\sqrt{\left(\mathbf u - \bar u \mathbf 1\right)\cdot\left(\mathbf u - \bar u \mathbf 1\right)\,\left(\mathbf v - \bar v \mathbf 1\right)\cdot\left(\mathbf v - \bar v \mathbf 1\right)}}. }$$ Using the distributive law to expand the dot products shows that $$\eqalign{ \left(\mathbf u - \bar u \mathbf 1\right)\cdot\left(\mathbf v - \bar v \mathbf 1\right) &= \mathbf u \cdot \mathbf v - \frac{2}{n}(\mathbf u \cdot \mathbf 1) (\mathbf 1 \cdot \mathbf v) + \frac{1}{n^2}(\mathbf u \cdot \mathbf 1)(\mathbf v \cdot \mathbf 1)\mathbf 1 \cdot \mathbf 1 \\ &= \mathbf u \cdot \mathbf v -\frac{1}{n}(\mathbf u \cdot \mathbf 1)(\mathbf v \cdot \mathbf 1) }$$ because $\mathbf 1 \cdot \mathbf 1 = n$. Similar formulas hold for the expressions in the denominator. This shows how the correlation coefficient can be computed in terms of dot products of the original (raw, sparse) vectors. Note in particular that the terms in the denominator can be written $$\mathbf u \cdot \mathbf u -\frac{1}{n}(\mathbf u \cdot \mathbf 1)(\mathbf u \cdot \mathbf 1)=n \bar u - \frac{1}{n}(n \bar u)^2 = n(\bar u - \bar u^2)$$ An efficient implementation will compute column sums (from which their means $\bar u$ are immediately derived) and obtain all the dot products of all pairs of columns at once by means of a single matrix operation $\mathbb Y^\prime \mathbb Y$. Using these it is simple and fast to obtain the correlation coefficients with the preceding formula. To obtain lagged correlations at lag $k$, remove the first $k$ rows of $\mathbb Y$ (call this $\mathbb Y_{(k)}$ and separately remove the last $k$ rows (call this $\mathbb Y_{(-k)}$). The essential material for the computation can be found in the non-diagonal entries of $\mathbb Y_{(k)}^\prime \mathbb Y_{(-k)}$. The new denominators will scarcely differ from the old ones and so, to a high degree of accuracy, need not be recomputed at all; but for perfect accuracy note that the column sums in $\mathbb Y_{(k)}$ are of the form $$\sum_{i=k+1}^n u_i = \left(\sum_{i=1}^n u_i\right) - u_k - u_{k-1} - \cdots - u_2 - u_1$$ which are easily obtained from the original column sums by means of just $k$ subtractions (and similarly for the column sums of $\mathbb Y_{(-k)}$. Thus, computing the entire $21\times 60\times 60$ array comes down to performing $21$ multiplications of sparse binary matrices and adjusting the results. The total number of numeric operations involved (with each dot product requiring about $2n$ multiplications and $2n$ additions) will be approximately $$2 \times 5271159 \times 60^2 \times 21 \approx 800 \times 10^9.$$ Unparallelized, but running as native code on a modern PC, this would take two minutes without any sparse matrix speed improvements. Tests in R (without using sparse arithmetic) with a $5271159 \times 6$ matrix took $1.3$ seconds; the quadratic scaling indicates R would thereby require $130$ seconds, confirming the two minute estimate. Given a random binary array of dimensions $5271159\times 60$ and mean of $1/40$, Mathematica 9 took one second to compute $\mathbb Y^\prime \mathbb Y$, suggesting the total computation for all $21$ lags should be around $20$ seconds.
Cross correlation for very sparse binary data You are right to think of correlation as the mean of the product of the standardized variables: this has great conceptual advantages over other definitions. It also leads to minimal loss of floating
36,678
Using proper scoring rule to determine class membership from logistic regression
What you need to do is "put the model into production", that is, as you say, to actually predict which cases will be "yes", what you need is a loss function. You have two possible errors, saying "yes" when no, saying "no" when yes. Do these errors have economical consequences, costs associated? Do these costs depend on other things too, such as some specific covariate value? Then you build these information into a cost function, and you can determine cutoffs by minimizing expected cost. That is the principled solution.
Using proper scoring rule to determine class membership from logistic regression
What you need to do is "put the model into production", that is, as you say, to actually predict which cases will be "yes", what you need is a loss function. You have two possible errors, saying "yes
Using proper scoring rule to determine class membership from logistic regression What you need to do is "put the model into production", that is, as you say, to actually predict which cases will be "yes", what you need is a loss function. You have two possible errors, saying "yes" when no, saying "no" when yes. Do these errors have economical consequences, costs associated? Do these costs depend on other things too, such as some specific covariate value? Then you build these information into a cost function, and you can determine cutoffs by minimizing expected cost. That is the principled solution.
Using proper scoring rule to determine class membership from logistic regression What you need to do is "put the model into production", that is, as you say, to actually predict which cases will be "yes", what you need is a loss function. You have two possible errors, saying "yes
36,679
What is the difference between ex ante and a priori, if any?
Ex Ante means before the event. Ex Post means after the event. In this example, I think this means before and after the event that gives the statistical difference you're testing, respectively. On the other hand, a priori and a posteriori are terms from philosophy, respectively denoting knowledge that is logically derived, and knowledge that requires empirical evidence. (Wikipedia)
What is the difference between ex ante and a priori, if any?
Ex Ante means before the event. Ex Post means after the event. In this example, I think this means before and after the event that gives the statistical difference you're testing, respectively. On the
What is the difference between ex ante and a priori, if any? Ex Ante means before the event. Ex Post means after the event. In this example, I think this means before and after the event that gives the statistical difference you're testing, respectively. On the other hand, a priori and a posteriori are terms from philosophy, respectively denoting knowledge that is logically derived, and knowledge that requires empirical evidence. (Wikipedia)
What is the difference between ex ante and a priori, if any? Ex Ante means before the event. Ex Post means after the event. In this example, I think this means before and after the event that gives the statistical difference you're testing, respectively. On the
36,680
What is the difference between ex ante and a priori, if any?
"Ex ante" & "ex post" are used in forecasting: An ex ante forecast uses only the information available at a given time to predict what'll happen after that time. An ex post forecast also uses information available after the given time. So while an ex post sales forecast based on GDP growth in a region may be informative, the ex ante sales forecast for practical application will need to be based on forecasts of future GDP growth.
What is the difference between ex ante and a priori, if any?
"Ex ante" & "ex post" are used in forecasting: An ex ante forecast uses only the information available at a given time to predict what'll happen after that time. An ex post forecast also uses informat
What is the difference between ex ante and a priori, if any? "Ex ante" & "ex post" are used in forecasting: An ex ante forecast uses only the information available at a given time to predict what'll happen after that time. An ex post forecast also uses information available after the given time. So while an ex post sales forecast based on GDP growth in a region may be informative, the ex ante sales forecast for practical application will need to be based on forecasts of future GDP growth.
What is the difference between ex ante and a priori, if any? "Ex ante" & "ex post" are used in forecasting: An ex ante forecast uses only the information available at a given time to predict what'll happen after that time. An ex post forecast also uses informat
36,681
What is the difference between ex ante and a priori, if any?
To me, there is a meaning of process in the term a priori: a priori, I think so, but my mind might change through the process of understanding of the new ideas. However, ex ante refers to a moment that is right before an event: ex ante Wall Street fell down, I sold my assets.
What is the difference between ex ante and a priori, if any?
To me, there is a meaning of process in the term a priori: a priori, I think so, but my mind might change through the process of understanding of the new ideas. However, ex ante refers to a moment tha
What is the difference between ex ante and a priori, if any? To me, there is a meaning of process in the term a priori: a priori, I think so, but my mind might change through the process of understanding of the new ideas. However, ex ante refers to a moment that is right before an event: ex ante Wall Street fell down, I sold my assets.
What is the difference between ex ante and a priori, if any? To me, there is a meaning of process in the term a priori: a priori, I think so, but my mind might change through the process of understanding of the new ideas. However, ex ante refers to a moment tha
36,682
Prediction of continuous variable using "bnlearn" package in R
Why are you using table to compare the output? Using cbind to put the actual and predicted values side by side shows that the predictions are not the same as the actual, and you can compute standard accuracy metrics to quantify the degree to which they diverge. library(bnlearn) # Load the package in R library(forecast) data(gaussian.test) training.set = gaussian.test[1:4000, ] # This is training set to learn the parameters test.set = gaussian.test[4001:4010, ] # This is test set to give as evidence res = hc(training.set) # learn BN structure on training set data fitted = bn.fit(res, training.set) # learning of parameters pred = predict(fitted, "C", test.set) # predicts the value of node C given test set cbind(pred, test.set[, "C"]) # compare the actual and predicted accuracy(f = pred, x = test.set[, "C"]) Comparing the actual and predicted: > cbind(predicted = pred, actual = test.set[, "C"]) predicted actual [1,] 3.5749952 3.952410 [2,] 0.7434548 1.443177 [3,] 5.1731669 5.924198 [4,] 10.0840800 10.296560 [5,] 12.3966908 12.268170 [6,] 9.1834888 9.725431 [7,] 6.8067145 5.625797 [8,] 9.9246630 9.597326 [9,] 5.9426798 6.503896 [10,] 16.0056136 16.037176 Measuring accuracy of prediction: > accuracy(f = pred, x = test.set[, "C"]) ME RMSE MAE MPE MAPE Test set 0.1538594 0.5804431 0.4812143 6.172352 11.26223
Prediction of continuous variable using "bnlearn" package in R
Why are you using table to compare the output? Using cbind to put the actual and predicted values side by side shows that the predictions are not the same as the actual, and you can compute standard a
Prediction of continuous variable using "bnlearn" package in R Why are you using table to compare the output? Using cbind to put the actual and predicted values side by side shows that the predictions are not the same as the actual, and you can compute standard accuracy metrics to quantify the degree to which they diverge. library(bnlearn) # Load the package in R library(forecast) data(gaussian.test) training.set = gaussian.test[1:4000, ] # This is training set to learn the parameters test.set = gaussian.test[4001:4010, ] # This is test set to give as evidence res = hc(training.set) # learn BN structure on training set data fitted = bn.fit(res, training.set) # learning of parameters pred = predict(fitted, "C", test.set) # predicts the value of node C given test set cbind(pred, test.set[, "C"]) # compare the actual and predicted accuracy(f = pred, x = test.set[, "C"]) Comparing the actual and predicted: > cbind(predicted = pred, actual = test.set[, "C"]) predicted actual [1,] 3.5749952 3.952410 [2,] 0.7434548 1.443177 [3,] 5.1731669 5.924198 [4,] 10.0840800 10.296560 [5,] 12.3966908 12.268170 [6,] 9.1834888 9.725431 [7,] 6.8067145 5.625797 [8,] 9.9246630 9.597326 [9,] 5.9426798 6.503896 [10,] 16.0056136 16.037176 Measuring accuracy of prediction: > accuracy(f = pred, x = test.set[, "C"]) ME RMSE MAE MPE MAPE Test set 0.1538594 0.5804431 0.4812143 6.172352 11.26223
Prediction of continuous variable using "bnlearn" package in R Why are you using table to compare the output? Using cbind to put the actual and predicted values side by side shows that the predictions are not the same as the actual, and you can compute standard a
36,683
Prediction of continuous variable using "bnlearn" package in R
For both the predicted sets you proposed (with both the Original values and zeros) I found the same output in R. [1] 3.5749952 0.7434548 5.1731669 10.0840800 12.3966908 9.1834888 6.8067145 [8] 9.9246630 5.9426798 16.0056136 This shows that the values of C are irrelevant. Furthermore, test.set$c provides you with: [1] 3.952410 1.443177 5.924198 10.296560 12.268170 9.725431 5.625797 9.597326 [9] 6.503896 16.037176 which is inherently different from the predicted output. This leads me to believe that your code is in fact correct.
Prediction of continuous variable using "bnlearn" package in R
For both the predicted sets you proposed (with both the Original values and zeros) I found the same output in R. [1] 3.5749952 0.7434548 5.1731669 10.0840800 12.3966908 9.1834888 6.8067145 [8]
Prediction of continuous variable using "bnlearn" package in R For both the predicted sets you proposed (with both the Original values and zeros) I found the same output in R. [1] 3.5749952 0.7434548 5.1731669 10.0840800 12.3966908 9.1834888 6.8067145 [8] 9.9246630 5.9426798 16.0056136 This shows that the values of C are irrelevant. Furthermore, test.set$c provides you with: [1] 3.952410 1.443177 5.924198 10.296560 12.268170 9.725431 5.625797 9.597326 [9] 6.503896 16.037176 which is inherently different from the predicted output. This leads me to believe that your code is in fact correct.
Prediction of continuous variable using "bnlearn" package in R For both the predicted sets you proposed (with both the Original values and zeros) I found the same output in R. [1] 3.5749952 0.7434548 5.1731669 10.0840800 12.3966908 9.1834888 6.8067145 [8]
36,684
Prediction of continuous variable using "bnlearn" package in R
The equivalent for the discrete case occurs (inability to set the target variable to zero). In this case do the following: test.set\$TARGET<-as.factor(0) levels(test.set\$TARGET) <- c(level1,level2,level3...)
Prediction of continuous variable using "bnlearn" package in R
The equivalent for the discrete case occurs (inability to set the target variable to zero). In this case do the following: test.set\$TARGET<-as.factor(0) levels(test.set\$TARGET) <- c(level1,level2,
Prediction of continuous variable using "bnlearn" package in R The equivalent for the discrete case occurs (inability to set the target variable to zero). In this case do the following: test.set\$TARGET<-as.factor(0) levels(test.set\$TARGET) <- c(level1,level2,level3...)
Prediction of continuous variable using "bnlearn" package in R The equivalent for the discrete case occurs (inability to set the target variable to zero). In this case do the following: test.set\$TARGET<-as.factor(0) levels(test.set\$TARGET) <- c(level1,level2,
36,685
Covariance term in simple linear regression
I was trying to prove the same and struggled a bit but finally got to a solution. I know this was asked long back but there might be other people interested. $$Cov (\bar{Y}, \hat{\beta_1}) = E[(\bar{Y} - E(\bar{Y}))(\hat{\beta}_1 - \beta_1)]\\ = E[(\beta_0 + \bar{X}\beta_1 + \bar{\epsilon} - \beta_0 - \bar{X} \beta_1) (\hat{\beta}_1 - \beta_1)]\\ = E(\bar{\epsilon} (\hat{\beta}_1 - \beta_1)]\\ = E(\bar{\epsilon} \hat{\beta}_1) - \beta_1 E(\bar{\epsilon})\\ = E(\bar{\epsilon} \hat{\beta}_1) $$ Now we know that $$ \hat{\beta}_1 = \sum_{i=1}^n \dfrac{(X_i - \bar{X})Y_i}{\sum(X_i - \bar{X})^2}$$ which we can write as $$ \hat{\beta}_1 = \sum_{i=1}^n c_i Y_i$$ for convenience. Now consider, $$ Cov(\bar{\epsilon}, \hat{\beta}_1) = E(\bar{\epsilon} \hat{\beta}_1)\\ = Cov(\sum c_i \epsilon_i , \bar{\epsilon})\\ = \sum_{i=1}^n \sum_{j=1}^n c_i\times \dfrac{1}{n} Cov(\epsilon_i, \epsilon_j) \\ \text{by independence we get,}\\ = \sum_{i=1}^n \dfrac{c_i}{n} \sigma^2\\ = \dfrac{\sigma^2}{n}\sum_i c_i = 0$$ This is because $$ c_i = \dfrac{(X_i - \bar{X})}{\sum_{j=1}^n (X_j - \bar{X})^2}\\ \sum_{i=1}^n c_i = \dfrac{1}{\sum_{j=1}^n (X_j - \bar{X})^2} \sum_{i=1}^n (X_i - \bar{X})\\ =\dfrac{1}{\sum_{j=1}^n (X_j - \bar{X})^2} (n\bar{X} - n\bar{X}) = 0 $$
Covariance term in simple linear regression
I was trying to prove the same and struggled a bit but finally got to a solution. I know this was asked long back but there might be other people interested. $$Cov (\bar{Y}, \hat{\beta_1}) = E[(\bar{
Covariance term in simple linear regression I was trying to prove the same and struggled a bit but finally got to a solution. I know this was asked long back but there might be other people interested. $$Cov (\bar{Y}, \hat{\beta_1}) = E[(\bar{Y} - E(\bar{Y}))(\hat{\beta}_1 - \beta_1)]\\ = E[(\beta_0 + \bar{X}\beta_1 + \bar{\epsilon} - \beta_0 - \bar{X} \beta_1) (\hat{\beta}_1 - \beta_1)]\\ = E(\bar{\epsilon} (\hat{\beta}_1 - \beta_1)]\\ = E(\bar{\epsilon} \hat{\beta}_1) - \beta_1 E(\bar{\epsilon})\\ = E(\bar{\epsilon} \hat{\beta}_1) $$ Now we know that $$ \hat{\beta}_1 = \sum_{i=1}^n \dfrac{(X_i - \bar{X})Y_i}{\sum(X_i - \bar{X})^2}$$ which we can write as $$ \hat{\beta}_1 = \sum_{i=1}^n c_i Y_i$$ for convenience. Now consider, $$ Cov(\bar{\epsilon}, \hat{\beta}_1) = E(\bar{\epsilon} \hat{\beta}_1)\\ = Cov(\sum c_i \epsilon_i , \bar{\epsilon})\\ = \sum_{i=1}^n \sum_{j=1}^n c_i\times \dfrac{1}{n} Cov(\epsilon_i, \epsilon_j) \\ \text{by independence we get,}\\ = \sum_{i=1}^n \dfrac{c_i}{n} \sigma^2\\ = \dfrac{\sigma^2}{n}\sum_i c_i = 0$$ This is because $$ c_i = \dfrac{(X_i - \bar{X})}{\sum_{j=1}^n (X_j - \bar{X})^2}\\ \sum_{i=1}^n c_i = \dfrac{1}{\sum_{j=1}^n (X_j - \bar{X})^2} \sum_{i=1}^n (X_i - \bar{X})\\ =\dfrac{1}{\sum_{j=1}^n (X_j - \bar{X})^2} (n\bar{X} - n\bar{X}) = 0 $$
Covariance term in simple linear regression I was trying to prove the same and struggled a bit but finally got to a solution. I know this was asked long back but there might be other people interested. $$Cov (\bar{Y}, \hat{\beta_1}) = E[(\bar{
36,686
Covariance term in simple linear regression
$$ {\rm Cov}\bigg[\frac 1 n \sum y_i,\ \frac{\sum(x_i - \bar x)y_i}{\sum(x_i-\bar x)^2}\bigg] = \frac 1 n \times \frac{\sum(x_i-\bar x)\sigma^2}{\sum(x_i - \bar x)^2} = 1$$ it does not equal zero this way I believe
Covariance term in simple linear regression
$$ {\rm Cov}\bigg[\frac 1 n \sum y_i,\ \frac{\sum(x_i - \bar x)y_i}{\sum(x_i-\bar x)^2}\bigg] = \frac 1 n \times \frac{\sum(x_i-\bar x)\sigma^2}{\sum(x_i - \bar x)^2} = 1$$ it does not equal zero this
Covariance term in simple linear regression $$ {\rm Cov}\bigg[\frac 1 n \sum y_i,\ \frac{\sum(x_i - \bar x)y_i}{\sum(x_i-\bar x)^2}\bigg] = \frac 1 n \times \frac{\sum(x_i-\bar x)\sigma^2}{\sum(x_i - \bar x)^2} = 1$$ it does not equal zero this way I believe
Covariance term in simple linear regression $$ {\rm Cov}\bigg[\frac 1 n \sum y_i,\ \frac{\sum(x_i - \bar x)y_i}{\sum(x_i-\bar x)^2}\bigg] = \frac 1 n \times \frac{\sum(x_i-\bar x)\sigma^2}{\sum(x_i - \bar x)^2} = 1$$ it does not equal zero this
36,687
How to gently introduce epidemiologists/public health coworkers to advanced predictive modeling?
I'm going to weigh in as an Epidemiologist. I can see inertia setting in as researchers & professionals in the health care field move into middle management and beyond and are out of touch with new developments in statistics. First, I would strongly advise you not to assume this is simply inertia, either in the form of the discipline not wanting to adopt new techniques, or your coworkers falling out of touch with new developments in statistics. You can go to academic epidemiology conferences where new and very methodologically sophisticated work is being done, and still not necessarily find much on predictive modeling. The hint is in the name. Predictive modeling. Epidemiology, as a field, is not particularly interested in prediction for it's own sake. Instead, it's focus is on developing etiological explanations for observed disease patterns in a population. The two are related, but distinct, and this often leads to something of a philosophical distrust of more modern classification and prediction techniques that purely attempt to maximize the predictive impact of a model. At the extreme end of this is the people who are of the opinion that variable selection should be performed primarily with the use of something like a directed acyclic graph, which could be considered the opposite of where predictive modeling is heading. This is largely why the methodological developments in epidemiology have been concentrated in causal inference and systems models in the recent past - both are built off etiological and causal arguments, rather than prediction. This results in it not being part of their background, not being something they encounter much in the literature, and to be perfectly frank, a high likelihood that their exposure to it has been via people who don't actually understand the problems they are trying to solve. This, in the comments, is a perfect example: That throws some people - the fact we're purposefully introducing bias into penalized regression to improve predictive accuracy Very nearly every epidemiologist I know, if you made them pick, would pick a reduction in bias over an increase in accuracy. That is not to say that it never gets brought up. There are times when predictive models do get used - often in clinical cases where the prediction of this particular patient's outcome is of considerable interest, or outbreak detection, where these techniques are useful because we don't know what's coming and can't make etiological arguments. Or when prediction really is the goal - for example, in many exposure estimation models. They're just somewhat niche in the field.
How to gently introduce epidemiologists/public health coworkers to advanced predictive modeling?
I'm going to weigh in as an Epidemiologist. I can see inertia setting in as researchers & professionals in the health care field move into middle management and beyond and are out of touch with new d
How to gently introduce epidemiologists/public health coworkers to advanced predictive modeling? I'm going to weigh in as an Epidemiologist. I can see inertia setting in as researchers & professionals in the health care field move into middle management and beyond and are out of touch with new developments in statistics. First, I would strongly advise you not to assume this is simply inertia, either in the form of the discipline not wanting to adopt new techniques, or your coworkers falling out of touch with new developments in statistics. You can go to academic epidemiology conferences where new and very methodologically sophisticated work is being done, and still not necessarily find much on predictive modeling. The hint is in the name. Predictive modeling. Epidemiology, as a field, is not particularly interested in prediction for it's own sake. Instead, it's focus is on developing etiological explanations for observed disease patterns in a population. The two are related, but distinct, and this often leads to something of a philosophical distrust of more modern classification and prediction techniques that purely attempt to maximize the predictive impact of a model. At the extreme end of this is the people who are of the opinion that variable selection should be performed primarily with the use of something like a directed acyclic graph, which could be considered the opposite of where predictive modeling is heading. This is largely why the methodological developments in epidemiology have been concentrated in causal inference and systems models in the recent past - both are built off etiological and causal arguments, rather than prediction. This results in it not being part of their background, not being something they encounter much in the literature, and to be perfectly frank, a high likelihood that their exposure to it has been via people who don't actually understand the problems they are trying to solve. This, in the comments, is a perfect example: That throws some people - the fact we're purposefully introducing bias into penalized regression to improve predictive accuracy Very nearly every epidemiologist I know, if you made them pick, would pick a reduction in bias over an increase in accuracy. That is not to say that it never gets brought up. There are times when predictive models do get used - often in clinical cases where the prediction of this particular patient's outcome is of considerable interest, or outbreak detection, where these techniques are useful because we don't know what's coming and can't make etiological arguments. Or when prediction really is the goal - for example, in many exposure estimation models. They're just somewhat niche in the field.
How to gently introduce epidemiologists/public health coworkers to advanced predictive modeling? I'm going to weigh in as an Epidemiologist. I can see inertia setting in as researchers & professionals in the health care field move into middle management and beyond and are out of touch with new d
36,688
Polynomial term in logistic regression
Logistic regression models the log odds of a "1" or "success" response as a linear function of the regression coefficients (i.e. the parameters), but there's no need to insist that the log odds be a linear function of predictors. [This model is linear in parameters & the predictor: $$\operatorname{logit}\pi_i = \beta_0 + \beta_1 x_i$$ This one is linear in only the parameters: $$\operatorname{logit}\pi_i = \beta_0 + \beta_1 x_i + \beta_2 x_i^2$$ ] Just as with ordinary least-squares regression, polynomial predictor terms can be used if required by theory or simply to allow for curvature in empirical models.
Polynomial term in logistic regression
Logistic regression models the log odds of a "1" or "success" response as a linear function of the regression coefficients (i.e. the parameters), but there's no need to insist that the log odds be a l
Polynomial term in logistic regression Logistic regression models the log odds of a "1" or "success" response as a linear function of the regression coefficients (i.e. the parameters), but there's no need to insist that the log odds be a linear function of predictors. [This model is linear in parameters & the predictor: $$\operatorname{logit}\pi_i = \beta_0 + \beta_1 x_i$$ This one is linear in only the parameters: $$\operatorname{logit}\pi_i = \beta_0 + \beta_1 x_i + \beta_2 x_i^2$$ ] Just as with ordinary least-squares regression, polynomial predictor terms can be used if required by theory or simply to allow for curvature in empirical models.
Polynomial term in logistic regression Logistic regression models the log odds of a "1" or "success" response as a linear function of the regression coefficients (i.e. the parameters), but there's no need to insist that the log odds be a l
36,689
Advice on sensitivity analysis for priors in Bayesian statistics
Try as I might, I'm unable to find an open source that fully explains that process, so for a fuller treatment than the below, I'm left to direct your to Bayesian Data Analysis. In particular, Ch. 6 should prove very helpful. In broadest strokes, following the analysis one should ponder whether model inferences make realistic sense. For instance, consider this paper detailing prior considerations in a pharmacological study. In brief, liver size was a variable relevant to the model, about which much is known in medical literature: For example, parameter 8 represents the mass of the liver as a fraction of lean body mass; from previous medical studies, the liver is known to be about 3.3% of lean body mass for young adult males, with little variation. A non-informative prior would have suffered a few pitfalls: If noninformative prior distributions were assigned to all the individual parameters, then the model would fit the data very closely but with scientifically unreasonable parameters – for example, a person with a liver weighing 10 k. This sort of difficulty is what motivates a researcher to specify a prior distribution using external information. This is a simple test of realism: If your model suggests a human liver the size of a Thanksgiving turkey, there's a flaw of some sort. While not well-applied to your problem, this example makes clear how much these considerations depend on context. To examine whether the posterior is overly dependent on the prior, one can consider multiple priors and see whether the posterior changes, in a practical sense, as different priors will necessarily always yield different posteriors. For example, say you're polling a constituency about support for a proposed law. In particular, no one has ever gathered data about this population's support for this law: Your data exist in a knowledge vacuum. You construct a model in which each person you randomly poll is a Bernoulli random variable with parameter $\theta \le 1$. You select the beta distribution as a convenience prior for $\theta$, because it's conjugate to the Bernoulli. You've polled 98 randomly selected persons, 45 of which support the measure. But you wonder whether the Jeffrey's prior, $B(\frac{1}{2}, \frac{1}{2})$ or a uniform density over $[0,1]$, given by $B(1,1)$. Leaving the formal math aside, the respective posteriors are $B(45.5, 53.5)$ and $B(46, 54)$, and it's difficult to see this difference could be of practical consequence: (Note that the blue and green lines are nearly indistinguishable.) Now, you can imagine that if one had previous, extensive polling data on this proposal, then perhaps this data could signal an change in opinion, a status quo result, or random noise. In that case, one would be wise to compare these inferences with ones derived from more informed priors. Now, to your specific questions above: Parameters of interest must always have a specified distribution and prior, lest one couldn't make inferences on them at all. To the question of correct priors, that again depends on the state of knowledge of the problem, and perhaps what priors your skeptical audience will find agreeable. If knowledge is scant, you may wish to consider non-informative priors. But any choice of prior, or the choice to fix a parameter, must be justified either from existing knowledge or uncertainty. Simply derive posteriors from any priors you would like to consider, then compare them to examine whether the difference is of consequence to the problem at hand. That's the tough one, as it depends entirely on context. If any prior produces a turkey-liver type inference, it's probably safe to dismiss. But for subtler distinctions, I'm aware of no substitute for subject matter expertise, careful analysis, and more data. Bayes factors are often used in model comparison, but typically when comparing models of distinct forms. (I've honestly never considered Bayes factors to compare priors, but my sense is that a Bayes factor analysis would favor the vaguer prior, i.e. the one that gave more weight to the data.)
Advice on sensitivity analysis for priors in Bayesian statistics
Try as I might, I'm unable to find an open source that fully explains that process, so for a fuller treatment than the below, I'm left to direct your to Bayesian Data Analysis. In particular, Ch. 6 sh
Advice on sensitivity analysis for priors in Bayesian statistics Try as I might, I'm unable to find an open source that fully explains that process, so for a fuller treatment than the below, I'm left to direct your to Bayesian Data Analysis. In particular, Ch. 6 should prove very helpful. In broadest strokes, following the analysis one should ponder whether model inferences make realistic sense. For instance, consider this paper detailing prior considerations in a pharmacological study. In brief, liver size was a variable relevant to the model, about which much is known in medical literature: For example, parameter 8 represents the mass of the liver as a fraction of lean body mass; from previous medical studies, the liver is known to be about 3.3% of lean body mass for young adult males, with little variation. A non-informative prior would have suffered a few pitfalls: If noninformative prior distributions were assigned to all the individual parameters, then the model would fit the data very closely but with scientifically unreasonable parameters – for example, a person with a liver weighing 10 k. This sort of difficulty is what motivates a researcher to specify a prior distribution using external information. This is a simple test of realism: If your model suggests a human liver the size of a Thanksgiving turkey, there's a flaw of some sort. While not well-applied to your problem, this example makes clear how much these considerations depend on context. To examine whether the posterior is overly dependent on the prior, one can consider multiple priors and see whether the posterior changes, in a practical sense, as different priors will necessarily always yield different posteriors. For example, say you're polling a constituency about support for a proposed law. In particular, no one has ever gathered data about this population's support for this law: Your data exist in a knowledge vacuum. You construct a model in which each person you randomly poll is a Bernoulli random variable with parameter $\theta \le 1$. You select the beta distribution as a convenience prior for $\theta$, because it's conjugate to the Bernoulli. You've polled 98 randomly selected persons, 45 of which support the measure. But you wonder whether the Jeffrey's prior, $B(\frac{1}{2}, \frac{1}{2})$ or a uniform density over $[0,1]$, given by $B(1,1)$. Leaving the formal math aside, the respective posteriors are $B(45.5, 53.5)$ and $B(46, 54)$, and it's difficult to see this difference could be of practical consequence: (Note that the blue and green lines are nearly indistinguishable.) Now, you can imagine that if one had previous, extensive polling data on this proposal, then perhaps this data could signal an change in opinion, a status quo result, or random noise. In that case, one would be wise to compare these inferences with ones derived from more informed priors. Now, to your specific questions above: Parameters of interest must always have a specified distribution and prior, lest one couldn't make inferences on them at all. To the question of correct priors, that again depends on the state of knowledge of the problem, and perhaps what priors your skeptical audience will find agreeable. If knowledge is scant, you may wish to consider non-informative priors. But any choice of prior, or the choice to fix a parameter, must be justified either from existing knowledge or uncertainty. Simply derive posteriors from any priors you would like to consider, then compare them to examine whether the difference is of consequence to the problem at hand. That's the tough one, as it depends entirely on context. If any prior produces a turkey-liver type inference, it's probably safe to dismiss. But for subtler distinctions, I'm aware of no substitute for subject matter expertise, careful analysis, and more data. Bayes factors are often used in model comparison, but typically when comparing models of distinct forms. (I've honestly never considered Bayes factors to compare priors, but my sense is that a Bayes factor analysis would favor the vaguer prior, i.e. the one that gave more weight to the data.)
Advice on sensitivity analysis for priors in Bayesian statistics Try as I might, I'm unable to find an open source that fully explains that process, so for a fuller treatment than the below, I'm left to direct your to Bayesian Data Analysis. In particular, Ch. 6 sh
36,690
Linearity Assumption in OLS with Dummy Variables
It's time this question had an answer. I have a continuous response variable and a regression model with multiple predictors. Most of my predictors are continuous The continuity or otherwise of a predictor makes no no difference; a relationship only need be linear over the domain where it's defined, for it to be linear. How do I determine whether the ols assumption of linearity is met or violated? With a 0/1 predictor ($d$ say) there are only two possibilities: $E(Y|d=0,\underline{x})=E(Y|d=1,\underline{x})$ or $E(Y|d=0,\underline{x})\neq E(Y|d=1,\underline{x})$ (where $\underline{x}$ is all the other predictors) In either case, linearity is satisfied, since the population coefficient is the difference in expected values in either case. It is, however, possible that the size of the coefficient depends on the values of the other parameters (i.e. interactions between other predictors and $d$ may exist). And if the linearity assumption is violated, how would I go about transforming the dummy variable? The (conditional) linearity of $y$ in terms of $d$ is automatically satisfied - fortunately, because we can't gain anything substantive here by attempting to transform a dummy.
Linearity Assumption in OLS with Dummy Variables
It's time this question had an answer. I have a continuous response variable and a regression model with multiple predictors. Most of my predictors are continuous The continuity or otherwise of a
Linearity Assumption in OLS with Dummy Variables It's time this question had an answer. I have a continuous response variable and a regression model with multiple predictors. Most of my predictors are continuous The continuity or otherwise of a predictor makes no no difference; a relationship only need be linear over the domain where it's defined, for it to be linear. How do I determine whether the ols assumption of linearity is met or violated? With a 0/1 predictor ($d$ say) there are only two possibilities: $E(Y|d=0,\underline{x})=E(Y|d=1,\underline{x})$ or $E(Y|d=0,\underline{x})\neq E(Y|d=1,\underline{x})$ (where $\underline{x}$ is all the other predictors) In either case, linearity is satisfied, since the population coefficient is the difference in expected values in either case. It is, however, possible that the size of the coefficient depends on the values of the other parameters (i.e. interactions between other predictors and $d$ may exist). And if the linearity assumption is violated, how would I go about transforming the dummy variable? The (conditional) linearity of $y$ in terms of $d$ is automatically satisfied - fortunately, because we can't gain anything substantive here by attempting to transform a dummy.
Linearity Assumption in OLS with Dummy Variables It's time this question had an answer. I have a continuous response variable and a regression model with multiple predictors. Most of my predictors are continuous The continuity or otherwise of a
36,691
Linearity Assumption in OLS with Dummy Variables
Adding to the excellent answer by Glen_b, it is worth noting that adding a categorical variable into a regression cannot cause problems with the linearity assumption in and of itself. If there is an issue of non-linearity in the model it will be due to some underlying relationship that is not captured by the specified model form, but the inclusion of a categorical variable cannot cause this problem. To see this more clearly, consider a regression with an arbitrary categorical variable $h = 1,...,k$ with $k \geqslant 2$ possible outcomes, and one or more other terms encapsulated by $\mathbf{x}.$ The categorical variable is represented in a regression by $k-1$ indicator variables for the categories (with one base category). So the relevant terms in the model will look like this: $$\mathbb{E}(Y_i|\mathbf{x},\mathbf{h}) = \beta_0 + \sum_{\ell=1}^{k-1} \beta_\ell \cdot \mathbb{I}(h_i = \ell) + \text{Other terms for } x_i.$$ The linearity assumption in regression requires that the regression equation be linear with respect to the coefficient parameters. The presence of the categorical variable $h$ in the regression adds the parameters $\beta_1,...\beta_{k-1}$ which apply across categories. Each individual indicator term simply adds a term for the difference in conditional expectation based on whether the categorical variable is in that category or not. The addition of such terms cannot constitute non-linearity.
Linearity Assumption in OLS with Dummy Variables
Adding to the excellent answer by Glen_b, it is worth noting that adding a categorical variable into a regression cannot cause problems with the linearity assumption in and of itself. If there is an
Linearity Assumption in OLS with Dummy Variables Adding to the excellent answer by Glen_b, it is worth noting that adding a categorical variable into a regression cannot cause problems with the linearity assumption in and of itself. If there is an issue of non-linearity in the model it will be due to some underlying relationship that is not captured by the specified model form, but the inclusion of a categorical variable cannot cause this problem. To see this more clearly, consider a regression with an arbitrary categorical variable $h = 1,...,k$ with $k \geqslant 2$ possible outcomes, and one or more other terms encapsulated by $\mathbf{x}.$ The categorical variable is represented in a regression by $k-1$ indicator variables for the categories (with one base category). So the relevant terms in the model will look like this: $$\mathbb{E}(Y_i|\mathbf{x},\mathbf{h}) = \beta_0 + \sum_{\ell=1}^{k-1} \beta_\ell \cdot \mathbb{I}(h_i = \ell) + \text{Other terms for } x_i.$$ The linearity assumption in regression requires that the regression equation be linear with respect to the coefficient parameters. The presence of the categorical variable $h$ in the regression adds the parameters $\beta_1,...\beta_{k-1}$ which apply across categories. Each individual indicator term simply adds a term for the difference in conditional expectation based on whether the categorical variable is in that category or not. The addition of such terms cannot constitute non-linearity.
Linearity Assumption in OLS with Dummy Variables Adding to the excellent answer by Glen_b, it is worth noting that adding a categorical variable into a regression cannot cause problems with the linearity assumption in and of itself. If there is an
36,692
How to derive the $\alpha$ for the Pareto rule
The basic result is: $\alpha=\log_4 5=1.160964...$ The calculation comes from the Lorenz curve; specifically you're asking for the $\alpha$ for which $L(0.8)=0.2$. $L$ is defined as $$L(F)=\frac{\int_{x_\mathrm{m}}^{x(F)}xf(x)\,dx}{\int_{x_\mathrm{m}}^\infty xf(x)\,dx} =\frac{\int_0^F x(F')\,dF'}{\int_0^1 x(F')\,dF'}$$ where $x(F)$ is the inverse of the cdf. The denominator is the mean of the distribution. For the Pareto distribution, the Lorenz curve is $L(F) = 1-(1-F)^{1-\frac{1}{\alpha}}$, from which we obtain the equation we need to solve: $$0.2 = 1-(1-0.8)^{1-\frac{1}{\alpha}}.\,$$ Hence $$1-\frac{1}{\alpha} = \log(0.8)/\log(0.2)$$ $$\alpha=\frac{1}{1-\log(0.8)/\log(0.2)}=1.160964\ldots$$ This is mentioned on the Wikipedia page for the Pareto principle, and on the page on the Pareto distribution The details are given here.
How to derive the $\alpha$ for the Pareto rule
The basic result is: $\alpha=\log_4 5=1.160964...$ The calculation comes from the Lorenz curve; specifically you're asking for the $\alpha$ for which $L(0.8)=0.2$. $L$ is defined as $$L(F)=\frac{\int_
How to derive the $\alpha$ for the Pareto rule The basic result is: $\alpha=\log_4 5=1.160964...$ The calculation comes from the Lorenz curve; specifically you're asking for the $\alpha$ for which $L(0.8)=0.2$. $L$ is defined as $$L(F)=\frac{\int_{x_\mathrm{m}}^{x(F)}xf(x)\,dx}{\int_{x_\mathrm{m}}^\infty xf(x)\,dx} =\frac{\int_0^F x(F')\,dF'}{\int_0^1 x(F')\,dF'}$$ where $x(F)$ is the inverse of the cdf. The denominator is the mean of the distribution. For the Pareto distribution, the Lorenz curve is $L(F) = 1-(1-F)^{1-\frac{1}{\alpha}}$, from which we obtain the equation we need to solve: $$0.2 = 1-(1-0.8)^{1-\frac{1}{\alpha}}.\,$$ Hence $$1-\frac{1}{\alpha} = \log(0.8)/\log(0.2)$$ $$\alpha=\frac{1}{1-\log(0.8)/\log(0.2)}=1.160964\ldots$$ This is mentioned on the Wikipedia page for the Pareto principle, and on the page on the Pareto distribution The details are given here.
How to derive the $\alpha$ for the Pareto rule The basic result is: $\alpha=\log_4 5=1.160964...$ The calculation comes from the Lorenz curve; specifically you're asking for the $\alpha$ for which $L(0.8)=0.2$. $L$ is defined as $$L(F)=\frac{\int_
36,693
Back Transformation
Your model and its estimates posit that $$\sqrt{Y} = 2.1014 D - 3.0147 + \varepsilon$$ where $D$ is Dose.Back (or its logarithm) and $\varepsilon$ is a random variable of zero expectation whose standard deviation is approximately $16.28.$ Squaring both sides gives $$Y = (2.1014 D - 3.0147 + \varepsilon)^2.$$ Adding $0.01$ to $D$ yields the value $$(2.1014 (D + 0.01) - 3.0147 + \varepsilon')^2.$$ The difference is $$2(2.1014 D - 3.0147 + \varepsilon)(\varepsilon' - \varepsilon + (0.01)(2.1014)) + (\varepsilon' - \varepsilon + (0.01)(2.1014))^2.$$ This expression, as well as its expectation, are complicated. Let us therefore focus on the simpler question of how the expectation of $Y$ varies with $D$. Note that $$\eqalign{ \mathbb{E}(Y) &= \mathbb{E}\left(2.1014 D - 3.0147 + \varepsilon\right)^2 \\ &= (2.1014D - 3.0147)^2 + 2(2.1014D - 3.0147) \mathbb{E}(\varepsilon) + \mathbb{E}(\varepsilon^2) \\ &=(2.1014D - 3.0147)^2 + 0 + (16.28)^2. }$$ (This result is of considerable interest in its own right because it reveals the role played by the mean squared error in interpreting the relationship between $D$ and $Y$.) When $0.01$ is added to $D$ the value of $\mathbb{E}(Y)$ increases by $$2(2.1014)(2.1014D - 3.0147)(0.01) + 2.1014(0.01)^2.$$ The last term $2.1014(0.01)^2 \approx 0.0002$ is so small compared to the squared errors (with their typical value of $16.28$) that we may neglect it. In this case, to a good approximation, this fitted model associates an (additive) increase in $D$ of $0.01$ with an increase in $Y$ of $$2(2.1014)(2.1014D - 3.0147)(0.01) = 0.0883176 D - 0.126.$$ When $D$ is the natural logarithm of some quantity $d$, a 1% multiplicative increase in $d$ causes a value of approximately $0.01$ to be added to $D$, because $$\log(1.01 d) = \log(1.01) + \log(d) = \left(0.01 - (0.01)^2/2 + \cdots\right) + D \approx 0.01 + D.$$ If you used a logarithm to another base $b$, entailing $D = \log_b(d) = \log(d)/\log(b),$ then a 1% multiplicative increase in $d$ causes a value of approximately $(0.01)/\log(b)$ to be added to $D$, so everywhere "$0.01$" occurs in the preceding formulas you must use $(0.01/\log(b))$ instead.
Back Transformation
Your model and its estimates posit that $$\sqrt{Y} = 2.1014 D - 3.0147 + \varepsilon$$ where $D$ is Dose.Back (or its logarithm) and $\varepsilon$ is a random variable of zero expectation whose stan
Back Transformation Your model and its estimates posit that $$\sqrt{Y} = 2.1014 D - 3.0147 + \varepsilon$$ where $D$ is Dose.Back (or its logarithm) and $\varepsilon$ is a random variable of zero expectation whose standard deviation is approximately $16.28.$ Squaring both sides gives $$Y = (2.1014 D - 3.0147 + \varepsilon)^2.$$ Adding $0.01$ to $D$ yields the value $$(2.1014 (D + 0.01) - 3.0147 + \varepsilon')^2.$$ The difference is $$2(2.1014 D - 3.0147 + \varepsilon)(\varepsilon' - \varepsilon + (0.01)(2.1014)) + (\varepsilon' - \varepsilon + (0.01)(2.1014))^2.$$ This expression, as well as its expectation, are complicated. Let us therefore focus on the simpler question of how the expectation of $Y$ varies with $D$. Note that $$\eqalign{ \mathbb{E}(Y) &= \mathbb{E}\left(2.1014 D - 3.0147 + \varepsilon\right)^2 \\ &= (2.1014D - 3.0147)^2 + 2(2.1014D - 3.0147) \mathbb{E}(\varepsilon) + \mathbb{E}(\varepsilon^2) \\ &=(2.1014D - 3.0147)^2 + 0 + (16.28)^2. }$$ (This result is of considerable interest in its own right because it reveals the role played by the mean squared error in interpreting the relationship between $D$ and $Y$.) When $0.01$ is added to $D$ the value of $\mathbb{E}(Y)$ increases by $$2(2.1014)(2.1014D - 3.0147)(0.01) + 2.1014(0.01)^2.$$ The last term $2.1014(0.01)^2 \approx 0.0002$ is so small compared to the squared errors (with their typical value of $16.28$) that we may neglect it. In this case, to a good approximation, this fitted model associates an (additive) increase in $D$ of $0.01$ with an increase in $Y$ of $$2(2.1014)(2.1014D - 3.0147)(0.01) = 0.0883176 D - 0.126.$$ When $D$ is the natural logarithm of some quantity $d$, a 1% multiplicative increase in $d$ causes a value of approximately $0.01$ to be added to $D$, because $$\log(1.01 d) = \log(1.01) + \log(d) = \left(0.01 - (0.01)^2/2 + \cdots\right) + D \approx 0.01 + D.$$ If you used a logarithm to another base $b$, entailing $D = \log_b(d) = \log(d)/\log(b),$ then a 1% multiplicative increase in $d$ causes a value of approximately $(0.01)/\log(b)$ to be added to $D$, so everywhere "$0.01$" occurs in the preceding formulas you must use $(0.01/\log(b))$ instead.
Back Transformation Your model and its estimates posit that $$\sqrt{Y} = 2.1014 D - 3.0147 + \varepsilon$$ where $D$ is Dose.Back (or its logarithm) and $\varepsilon$ is a random variable of zero expectation whose stan
36,694
Optimization of the regularized least squares with gradient descent
Instead of using a constant learning rate, set your learning rate to a reasonably large value (try $\alpha=1$) and then use "backoff" to shrink your learning rate as appropriate using the following algorithm: while $f(w^{(k)} - \alpha d) \gt f(w^{(k)}) $: $\alpha := \alpha/2$ $w^{(k+1)} := w^{(k)} - \alpha d$ where $f$ is your objective function, $d$ is your descent direction, and $\alpha$ is the learning rate. I don't think you've correctly implemented the gradient in your code. In particular, I believe the way you have it coded the s term evaluates to $s=\sum_{i=1}^N ( x_i \omega - y_i x_i )$ when you really want $s=\sum\limits_{i=1}^N ((\sum\limits_{j=1}^d x_{ij}\omega_j)x_{ik} - x_{ik} y_i)$. Gradient Descent probably isn't the best solution here. Gradient descent is slow: you shouldn't be surprised that it's taking a long time to converge, because gradient descent usually does. It gets the job done, but it's generally a slow option. Try playing with other optimization alogorithms and see what happens. Try using newton-raphson, for instance. I'm sure if you poke around the literature you'll be able to determine the "state-of-the-art" algorithm choice for optimizing the ridge regression loss function. I'd put money on it not being simple gradient descent.
Optimization of the regularized least squares with gradient descent
Instead of using a constant learning rate, set your learning rate to a reasonably large value (try $\alpha=1$) and then use "backoff" to shrink your learning rate as appropriate using the following al
Optimization of the regularized least squares with gradient descent Instead of using a constant learning rate, set your learning rate to a reasonably large value (try $\alpha=1$) and then use "backoff" to shrink your learning rate as appropriate using the following algorithm: while $f(w^{(k)} - \alpha d) \gt f(w^{(k)}) $: $\alpha := \alpha/2$ $w^{(k+1)} := w^{(k)} - \alpha d$ where $f$ is your objective function, $d$ is your descent direction, and $\alpha$ is the learning rate. I don't think you've correctly implemented the gradient in your code. In particular, I believe the way you have it coded the s term evaluates to $s=\sum_{i=1}^N ( x_i \omega - y_i x_i )$ when you really want $s=\sum\limits_{i=1}^N ((\sum\limits_{j=1}^d x_{ij}\omega_j)x_{ik} - x_{ik} y_i)$. Gradient Descent probably isn't the best solution here. Gradient descent is slow: you shouldn't be surprised that it's taking a long time to converge, because gradient descent usually does. It gets the job done, but it's generally a slow option. Try playing with other optimization alogorithms and see what happens. Try using newton-raphson, for instance. I'm sure if you poke around the literature you'll be able to determine the "state-of-the-art" algorithm choice for optimizing the ridge regression loss function. I'd put money on it not being simple gradient descent.
Optimization of the regularized least squares with gradient descent Instead of using a constant learning rate, set your learning rate to a reasonably large value (try $\alpha=1$) and then use "backoff" to shrink your learning rate as appropriate using the following al
36,695
Optimization of the regularized least squares with gradient descent
As whuber commented, there is no need to bother with optimization algorithms. Gradient in matrix notation is $$ 2X'(Xw-y)+2\lambda w $$ Equating it to zero in Matlab is a one-liner: w_star = (X'*X+lambda*eye(d)) \ X'*y;
Optimization of the regularized least squares with gradient descent
As whuber commented, there is no need to bother with optimization algorithms. Gradient in matrix notation is $$ 2X'(Xw-y)+2\lambda w $$ Equating it to zero in Matlab is a one-liner: w_star = (X'*X+lam
Optimization of the regularized least squares with gradient descent As whuber commented, there is no need to bother with optimization algorithms. Gradient in matrix notation is $$ 2X'(Xw-y)+2\lambda w $$ Equating it to zero in Matlab is a one-liner: w_star = (X'*X+lambda*eye(d)) \ X'*y;
Optimization of the regularized least squares with gradient descent As whuber commented, there is no need to bother with optimization algorithms. Gradient in matrix notation is $$ 2X'(Xw-y)+2\lambda w $$ Equating it to zero in Matlab is a one-liner: w_star = (X'*X+lam
36,696
Errors in optim when fitting arima model in R
Edited: if you down-vote this can you please explain why? I'm new here. I'm had the same problem. I looked around online and found a solution suggested elsewhere on Cross Validated. I figured I'd share here in case anyone wanted it. I just added a "method="CSS"" to my model and it worked. For example: model = Arima(x, order=c(1,1,1), seasonal=list(order=c(1,1,1), period=12), xreg=xreg, method="CSS") Here's the reference: auto.arima and Arima (forecast package)
Errors in optim when fitting arima model in R
Edited: if you down-vote this can you please explain why? I'm new here. I'm had the same problem. I looked around online and found a solution suggested elsewhere on Cross Validated. I figured I'd sha
Errors in optim when fitting arima model in R Edited: if you down-vote this can you please explain why? I'm new here. I'm had the same problem. I looked around online and found a solution suggested elsewhere on Cross Validated. I figured I'd share here in case anyone wanted it. I just added a "method="CSS"" to my model and it worked. For example: model = Arima(x, order=c(1,1,1), seasonal=list(order=c(1,1,1), period=12), xreg=xreg, method="CSS") Here's the reference: auto.arima and Arima (forecast package)
Errors in optim when fitting arima model in R Edited: if you down-vote this can you please explain why? I'm new here. I'm had the same problem. I looked around online and found a solution suggested elsewhere on Cross Validated. I figured I'd sha
36,697
Errors in optim when fitting arima model in R
Fitting the ARIMA model with Maximum Likelihood (method = "ML") requires optimising (minimising) the ARIMA model negative log-likelihood over the parameters. This turns out to be a constrained optimisation problem as the parameters must result in a stationary model. This nonlinear constraint is accounted for with the negative log-likelihood returning Inf (infinity) if the the constraint is not satisfied. If the MLE is near the boundary of the constraint evaluation of the negative log-likelihood near the MLE could return infinity. As the hessian is obtained with numerical differentiation by evaluating the negative log-likelihood near the MLE this can result in the non-finite finite difference error you obtained. So if the hessian is not required put hessian = FALSE. Otherwise, this error depends on the MLE solution so an alternative optimisation algorithm (Nelder-Mead) might return an MLE sufficiently far from the boundary of the constrain that the error is avoided.
Errors in optim when fitting arima model in R
Fitting the ARIMA model with Maximum Likelihood (method = "ML") requires optimising (minimising) the ARIMA model negative log-likelihood over the parameters. This turns out to be a constrained optimis
Errors in optim when fitting arima model in R Fitting the ARIMA model with Maximum Likelihood (method = "ML") requires optimising (minimising) the ARIMA model negative log-likelihood over the parameters. This turns out to be a constrained optimisation problem as the parameters must result in a stationary model. This nonlinear constraint is accounted for with the negative log-likelihood returning Inf (infinity) if the the constraint is not satisfied. If the MLE is near the boundary of the constraint evaluation of the negative log-likelihood near the MLE could return infinity. As the hessian is obtained with numerical differentiation by evaluating the negative log-likelihood near the MLE this can result in the non-finite finite difference error you obtained. So if the hessian is not required put hessian = FALSE. Otherwise, this error depends on the MLE solution so an alternative optimisation algorithm (Nelder-Mead) might return an MLE sufficiently far from the boundary of the constrain that the error is avoided.
Errors in optim when fitting arima model in R Fitting the ARIMA model with Maximum Likelihood (method = "ML") requires optimising (minimising) the ARIMA model negative log-likelihood over the parameters. This turns out to be a constrained optimis
36,698
Errors in optim when fitting arima model in R
You seem to have problem with algorithms convergence. This happens sometimes with numerical optimization. Here is link to wikipedia article on this particular optimization method: http://en.wikipedia.org/wiki/Broyden%E2%80%93Fletcher%E2%80%93Goldfarb%E2%80%93Shanno_algorithm
Errors in optim when fitting arima model in R
You seem to have problem with algorithms convergence. This happens sometimes with numerical optimization. Here is link to wikipedia article on this particular optimization method: http://en.wikipedia.
Errors in optim when fitting arima model in R You seem to have problem with algorithms convergence. This happens sometimes with numerical optimization. Here is link to wikipedia article on this particular optimization method: http://en.wikipedia.org/wiki/Broyden%E2%80%93Fletcher%E2%80%93Goldfarb%E2%80%93Shanno_algorithm
Errors in optim when fitting arima model in R You seem to have problem with algorithms convergence. This happens sometimes with numerical optimization. Here is link to wikipedia article on this particular optimization method: http://en.wikipedia.
36,699
QR factorization and linear regression
First, rewriting the $QR$ decomposition in a (hopefully) clearer way by showing the partitioning of $Q$ and explicitly giving the dimensions of the $0$ matrix: $$ X=QR=[Q_f,Q_g]\left[\begin{array}{c}R_1\\0_{(n-p)\times p}\end{array}\right]=Q_fR_1 $$ So I think part of the confusion here is that in the book you are referring to, $R$ is not the $R$ of the $QR$ decomposition but actually only the first $p$ rows, what I have denoted $R_1$. In your example, $X$ should be $4 \times 2$, not $2 \times 4$ as you've stated. So $n=4$, $p=2$. Then, yes, $y$ is $4 \times 1$, but $Q$ is $n\times n$ and so $4 \times 4$ as is $Q^{t}$. Then $Q^{t}y$ is $4 \times 1$ which is consistent with $f$ and $r$.
QR factorization and linear regression
First, rewriting the $QR$ decomposition in a (hopefully) clearer way by showing the partitioning of $Q$ and explicitly giving the dimensions of the $0$ matrix: $$ X=QR=[Q_f,Q_g]\left[\begin{array}{c}R
QR factorization and linear regression First, rewriting the $QR$ decomposition in a (hopefully) clearer way by showing the partitioning of $Q$ and explicitly giving the dimensions of the $0$ matrix: $$ X=QR=[Q_f,Q_g]\left[\begin{array}{c}R_1\\0_{(n-p)\times p}\end{array}\right]=Q_fR_1 $$ So I think part of the confusion here is that in the book you are referring to, $R$ is not the $R$ of the $QR$ decomposition but actually only the first $p$ rows, what I have denoted $R_1$. In your example, $X$ should be $4 \times 2$, not $2 \times 4$ as you've stated. So $n=4$, $p=2$. Then, yes, $y$ is $4 \times 1$, but $Q$ is $n\times n$ and so $4 \times 4$ as is $Q^{t}$. Then $Q^{t}y$ is $4 \times 1$ which is consistent with $f$ and $r$.
QR factorization and linear regression First, rewriting the $QR$ decomposition in a (hopefully) clearer way by showing the partitioning of $Q$ and explicitly giving the dimensions of the $0$ matrix: $$ X=QR=[Q_f,Q_g]\left[\begin{array}{c}R
36,700
p-values different for binomial test vs. proportions test. Which to report?
If you are testing whether 44 occurrences out of 63 can be a sample from the binomial population with probability 80% of a success in individual independent trial, then the first test is certainly correct.
p-values different for binomial test vs. proportions test. Which to report?
If you are testing whether 44 occurrences out of 63 can be a sample from the binomial population with probability 80% of a success in individual independent trial, then the first test is certainly cor
p-values different for binomial test vs. proportions test. Which to report? If you are testing whether 44 occurrences out of 63 can be a sample from the binomial population with probability 80% of a success in individual independent trial, then the first test is certainly correct.
p-values different for binomial test vs. proportions test. Which to report? If you are testing whether 44 occurrences out of 63 can be a sample from the binomial population with probability 80% of a success in individual independent trial, then the first test is certainly cor