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 |
|---|---|---|---|---|---|---|
30,501 | How to group-center / standardize variables in R? | Here is a data.table solution. It is definitely faster than plyr (relevant only for large data sets). Maybe later I'll do up a dplyr example.
# generate example data
raw.data <- data.frame( outcome = c(rnorm(500, 100, 15), rnorm(500, 110, 12)),
group = c(rep("a", 500), rep("b", 500)))
library(data.table)
# convert dataframe to data.table
raw.data <- data.table(raw.data, key = "group")
# create group standardized outcome variable
raw.data[ , group_std_outcome := (outcome - mean(outcome, na.rm = TRUE)) /
sd(outcome, na.rm = TRUE), "group"]
(Yes, I rediscovered a question I asked years ago when I was an R noob ;) | How to group-center / standardize variables in R? | Here is a data.table solution. It is definitely faster than plyr (relevant only for large data sets). Maybe later I'll do up a dplyr example.
# generate example data
raw.data <- data.frame( outcome | How to group-center / standardize variables in R?
Here is a data.table solution. It is definitely faster than plyr (relevant only for large data sets). Maybe later I'll do up a dplyr example.
# generate example data
raw.data <- data.frame( outcome = c(rnorm(500, 100, 15), rnorm(500, 110, 12)),
group = c(rep("a", 500), rep("b", 500)))
library(data.table)
# convert dataframe to data.table
raw.data <- data.table(raw.data, key = "group")
# create group standardized outcome variable
raw.data[ , group_std_outcome := (outcome - mean(outcome, na.rm = TRUE)) /
sd(outcome, na.rm = TRUE), "group"]
(Yes, I rediscovered a question I asked years ago when I was an R noob ;) | How to group-center / standardize variables in R?
Here is a data.table solution. It is definitely faster than plyr (relevant only for large data sets). Maybe later I'll do up a dplyr example.
# generate example data
raw.data <- data.frame( outcome |
30,502 | How to group-center / standardize variables in R? | You can use (among others) tapply for this (the plyr package contains lots of other options that may be better suited for your specific situation):
tapply(variabletoscale, list(groupvar1, groupvar2), scale) | How to group-center / standardize variables in R? | You can use (among others) tapply for this (the plyr package contains lots of other options that may be better suited for your specific situation):
tapply(variabletoscale, list(groupvar1, groupvar2), | How to group-center / standardize variables in R?
You can use (among others) tapply for this (the plyr package contains lots of other options that may be better suited for your specific situation):
tapply(variabletoscale, list(groupvar1, groupvar2), scale) | How to group-center / standardize variables in R?
You can use (among others) tapply for this (the plyr package contains lots of other options that may be better suited for your specific situation):
tapply(variabletoscale, list(groupvar1, groupvar2), |
30,503 | How to group-center / standardize variables in R? | This answer is from a white paper by Mahmood Arai. It has the convenient side effect of labeling the centered results with the prefix "C.":
gcenter <- function(df1,group) {
variables <- paste(
rep("C", ncol(df1)), colnames(df1), sep=".")
copydf <- df1
for (i in 1:ncol(df1)) {
copydf[,i] <- df1[,i] - ave(df1[,i], group, FUN=mean)}
colnames(copydf) <- variables
return(cbind(df1,copydf))} | How to group-center / standardize variables in R? | This answer is from a white paper by Mahmood Arai. It has the convenient side effect of labeling the centered results with the prefix "C.":
gcenter <- function(df1,group) {
variables <- paste( | How to group-center / standardize variables in R?
This answer is from a white paper by Mahmood Arai. It has the convenient side effect of labeling the centered results with the prefix "C.":
gcenter <- function(df1,group) {
variables <- paste(
rep("C", ncol(df1)), colnames(df1), sep=".")
copydf <- df1
for (i in 1:ncol(df1)) {
copydf[,i] <- df1[,i] - ave(df1[,i], group, FUN=mean)}
colnames(copydf) <- variables
return(cbind(df1,copydf))} | How to group-center / standardize variables in R?
This answer is from a white paper by Mahmood Arai. It has the convenient side effect of labeling the centered results with the prefix "C.":
gcenter <- function(df1,group) {
variables <- paste( |
30,504 | How to group-center / standardize variables in R? | Here is an updated implementation using dplyr from tidyverse.
library(tidyverse)
my.df <- data.frame(x=rnorm(100, mean=10), sex=sample(c("M","F"), 100, rep=T))
my.df <- group_by(my.df, sex) %>% mutate(x.sd = as.numeric(scale(x))) | How to group-center / standardize variables in R? | Here is an updated implementation using dplyr from tidyverse.
library(tidyverse)
my.df <- data.frame(x=rnorm(100, mean=10), sex=sample(c("M","F"), 100, rep=T))
my.df <- group_by(my.df, sex) %>% mutat | How to group-center / standardize variables in R?
Here is an updated implementation using dplyr from tidyverse.
library(tidyverse)
my.df <- data.frame(x=rnorm(100, mean=10), sex=sample(c("M","F"), 100, rep=T))
my.df <- group_by(my.df, sex) %>% mutate(x.sd = as.numeric(scale(x))) | How to group-center / standardize variables in R?
Here is an updated implementation using dplyr from tidyverse.
library(tidyverse)
my.df <- data.frame(x=rnorm(100, mean=10), sex=sample(c("M","F"), 100, rep=T))
my.df <- group_by(my.df, sex) %>% mutat |
30,505 | How to calculate centrality measures in a 4 million edge network using R? | What you have is an edge list, which can be converted to a network object using the network library. Here is an example using fictitious data.
library(network)
src <- c("A", "B", "C", "D", "E", "B", "A", "F")
dst <- c("B", "E", "A", "B", "B", "A", "F", "A")
edges <- cbind(src, dst)
Net <- as.network(edges, matrix.type = "edgelist")
summary(Net)
plot(Net)
However, a warning is in order: you have a very large network and I am not sure a plot will be all that informative. It will probably look like a big ball of yarn. I am also not sure how well these libraries deal with such large datasets. I suggest you take a look at the documentation for the network, statnet, and ergm libraries. The Journal of Statistical Software (v24/3) offers several articles covering these libraries. The issue can be found here:
http://www.jstatsoft.org/v24 | How to calculate centrality measures in a 4 million edge network using R? | What you have is an edge list, which can be converted to a network object using the network library. Here is an example using fictitious data.
library(network)
src <- c("A", "B", "C", "D", "E", "B", | How to calculate centrality measures in a 4 million edge network using R?
What you have is an edge list, which can be converted to a network object using the network library. Here is an example using fictitious data.
library(network)
src <- c("A", "B", "C", "D", "E", "B", "A", "F")
dst <- c("B", "E", "A", "B", "B", "A", "F", "A")
edges <- cbind(src, dst)
Net <- as.network(edges, matrix.type = "edgelist")
summary(Net)
plot(Net)
However, a warning is in order: you have a very large network and I am not sure a plot will be all that informative. It will probably look like a big ball of yarn. I am also not sure how well these libraries deal with such large datasets. I suggest you take a look at the documentation for the network, statnet, and ergm libraries. The Journal of Statistical Software (v24/3) offers several articles covering these libraries. The issue can be found here:
http://www.jstatsoft.org/v24 | How to calculate centrality measures in a 4 million edge network using R?
What you have is an edge list, which can be converted to a network object using the network library. Here is an example using fictitious data.
library(network)
src <- c("A", "B", "C", "D", "E", "B", |
30,506 | How to calculate centrality measures in a 4 million edge network using R? | I don't think that R is a first choice here (maybe I'm wrong). You will need huge arrays here to index and prepare your networks files in the appropriate data format. First of all, I will try to use Jure's (Rob mention him in the post above) SNAP library; it's written in C++ and works very well on large networks. | How to calculate centrality measures in a 4 million edge network using R? | I don't think that R is a first choice here (maybe I'm wrong). You will need huge arrays here to index and prepare your networks files in the appropriate data format. First of all, I will try to use J | How to calculate centrality measures in a 4 million edge network using R?
I don't think that R is a first choice here (maybe I'm wrong). You will need huge arrays here to index and prepare your networks files in the appropriate data format. First of all, I will try to use Jure's (Rob mention him in the post above) SNAP library; it's written in C++ and works very well on large networks. | How to calculate centrality measures in a 4 million edge network using R?
I don't think that R is a first choice here (maybe I'm wrong). You will need huge arrays here to index and prepare your networks files in the appropriate data format. First of all, I will try to use J |
30,507 | How to calculate centrality measures in a 4 million edge network using R? | Gephi ( http://gephi.org/ ) might be an easy way to explore the data. You can almost certainly visualize it, and perform some calculations (though I have not used it for some time so I can't remember all the functions). | How to calculate centrality measures in a 4 million edge network using R? | Gephi ( http://gephi.org/ ) might be an easy way to explore the data. You can almost certainly visualize it, and perform some calculations (though I have not used it for some time so I can't remember | How to calculate centrality measures in a 4 million edge network using R?
Gephi ( http://gephi.org/ ) might be an easy way to explore the data. You can almost certainly visualize it, and perform some calculations (though I have not used it for some time so I can't remember all the functions). | How to calculate centrality measures in a 4 million edge network using R?
Gephi ( http://gephi.org/ ) might be an easy way to explore the data. You can almost certainly visualize it, and perform some calculations (though I have not used it for some time so I can't remember |
30,508 | How to calculate centrality measures in a 4 million edge network using R? | From past experience with a network of 7 million nodes, I think visualizing your complete network will give you an uninterpretable image. I might suggest different visualizations using subsets of your data such as just using the top 10 nodes with the most inbound or outbound links. I second celenius's suggestion on using gephi. | How to calculate centrality measures in a 4 million edge network using R? | From past experience with a network of 7 million nodes, I think visualizing your complete network will give you an uninterpretable image. I might suggest different visualizations using subsets of your | How to calculate centrality measures in a 4 million edge network using R?
From past experience with a network of 7 million nodes, I think visualizing your complete network will give you an uninterpretable image. I might suggest different visualizations using subsets of your data such as just using the top 10 nodes with the most inbound or outbound links. I second celenius's suggestion on using gephi. | How to calculate centrality measures in a 4 million edge network using R?
From past experience with a network of 7 million nodes, I think visualizing your complete network will give you an uninterpretable image. I might suggest different visualizations using subsets of your |
30,509 | How to calculate centrality measures in a 4 million edge network using R? | If you're concerned with the size of the network, you could try the igraph package in R. And if that performs poorly inside R, it might do better as Python module.
Or even the networkx package for Python | How to calculate centrality measures in a 4 million edge network using R? | If you're concerned with the size of the network, you could try the igraph package in R. And if that performs poorly inside R, it might do better as Python module.
Or even the networkx package for Pyt | How to calculate centrality measures in a 4 million edge network using R?
If you're concerned with the size of the network, you could try the igraph package in R. And if that performs poorly inside R, it might do better as Python module.
Or even the networkx package for Python | How to calculate centrality measures in a 4 million edge network using R?
If you're concerned with the size of the network, you could try the igraph package in R. And if that performs poorly inside R, it might do better as Python module.
Or even the networkx package for Pyt |
30,510 | How to calculate centrality measures in a 4 million edge network using R? | Do you suspect that the network has a small number of very large connected components? If not, you can decompose it into distinct components which will make it much easier to compute measures of centrality. | How to calculate centrality measures in a 4 million edge network using R? | Do you suspect that the network has a small number of very large connected components? If not, you can decompose it into distinct components which will make it much easier to compute measures of cent | How to calculate centrality measures in a 4 million edge network using R?
Do you suspect that the network has a small number of very large connected components? If not, you can decompose it into distinct components which will make it much easier to compute measures of centrality. | How to calculate centrality measures in a 4 million edge network using R?
Do you suspect that the network has a small number of very large connected components? If not, you can decompose it into distinct components which will make it much easier to compute measures of cent |
30,511 | How to calculate centrality measures in a 4 million edge network using R? | There are several R software packages one could use, including "sna" and "network". One thing I wouldn't necessarily rely on if you're having performance issues with sna is NetworkX. I love NetworkX to death, and use it for most of my analysis, but NetworkX is quite proud of being a mostly purely Pythonic implementation. It doesn't particularly exploit speedy pre-compiled code well, and sna often outpaces NetworkX by a considerable margin. | How to calculate centrality measures in a 4 million edge network using R? | There are several R software packages one could use, including "sna" and "network". One thing I wouldn't necessarily rely on if you're having performance issues with sna is NetworkX. I love NetworkX t | How to calculate centrality measures in a 4 million edge network using R?
There are several R software packages one could use, including "sna" and "network". One thing I wouldn't necessarily rely on if you're having performance issues with sna is NetworkX. I love NetworkX to death, and use it for most of my analysis, but NetworkX is quite proud of being a mostly purely Pythonic implementation. It doesn't particularly exploit speedy pre-compiled code well, and sna often outpaces NetworkX by a considerable margin. | How to calculate centrality measures in a 4 million edge network using R?
There are several R software packages one could use, including "sna" and "network". One thing I wouldn't necessarily rely on if you're having performance issues with sna is NetworkX. I love NetworkX t |
30,512 | p-vector and K-vector | It's merely some generic notation for a vector of $p$ attributes or variables observed on $i=1,\dots, N$ individuals, so that you can define $X^T = (X_1,X_2,\dots,X_p)$ as a vector of inputs, in the feature (or input) space (and each individual will have one such vector of observed inputs).
The $K$ notation seems to be reserved to the output space: in a classical linear regression model where $Y=X\beta$, Y is a scalar ($K=1$), whereas in a multivariate setting (say, you record weight, height, and color) it could be a $K$-vector (i.e., 3-vector with my example). | p-vector and K-vector | It's merely some generic notation for a vector of $p$ attributes or variables observed on $i=1,\dots, N$ individuals, so that you can define $X^T = (X_1,X_2,\dots,X_p)$ as a vector of inputs, in the f | p-vector and K-vector
It's merely some generic notation for a vector of $p$ attributes or variables observed on $i=1,\dots, N$ individuals, so that you can define $X^T = (X_1,X_2,\dots,X_p)$ as a vector of inputs, in the feature (or input) space (and each individual will have one such vector of observed inputs).
The $K$ notation seems to be reserved to the output space: in a classical linear regression model where $Y=X\beta$, Y is a scalar ($K=1$), whereas in a multivariate setting (say, you record weight, height, and color) it could be a $K$-vector (i.e., 3-vector with my example). | p-vector and K-vector
It's merely some generic notation for a vector of $p$ attributes or variables observed on $i=1,\dots, N$ individuals, so that you can define $X^T = (X_1,X_2,\dots,X_p)$ as a vector of inputs, in the f |
30,513 | p-vector and K-vector | In mathematics and physics, the "x" in "x-vector" stands for the dimension of the vector. The meanings of $K$ and $p$ were previously established. Typically a "p-vector" is written as a column vector and a "p-covector" would be written as a row vector. | p-vector and K-vector | In mathematics and physics, the "x" in "x-vector" stands for the dimension of the vector. The meanings of $K$ and $p$ were previously established. Typically a "p-vector" is written as a column vecto | p-vector and K-vector
In mathematics and physics, the "x" in "x-vector" stands for the dimension of the vector. The meanings of $K$ and $p$ were previously established. Typically a "p-vector" is written as a column vector and a "p-covector" would be written as a row vector. | p-vector and K-vector
In mathematics and physics, the "x" in "x-vector" stands for the dimension of the vector. The meanings of $K$ and $p$ were previously established. Typically a "p-vector" is written as a column vecto |
30,514 | p-vector and K-vector | So there is a confusion if one is coming from the domain of machine learning.
In the beginning of the book it said that: features = inputs = a set of variables (X1,.... Xp). "inputs" is not related to the number of input samples. Input samples (training samples) are called "observations" (1 .. i .. N).
xi - the ith observation as a column vector of X1,X2 ... Xp
X is N x p matrix where each row is an observation and contains one input vector, so each row is xti
xti = (X1,X2 .... j ... Xp) | p-vector and K-vector | So there is a confusion if one is coming from the domain of machine learning.
In the beginning of the book it said that: features = inputs = a set of variables (X1,.... Xp). "inputs" is not related t | p-vector and K-vector
So there is a confusion if one is coming from the domain of machine learning.
In the beginning of the book it said that: features = inputs = a set of variables (X1,.... Xp). "inputs" is not related to the number of input samples. Input samples (training samples) are called "observations" (1 .. i .. N).
xi - the ith observation as a column vector of X1,X2 ... Xp
X is N x p matrix where each row is an observation and contains one input vector, so each row is xti
xti = (X1,X2 .... j ... Xp) | p-vector and K-vector
So there is a confusion if one is coming from the domain of machine learning.
In the beginning of the book it said that: features = inputs = a set of variables (X1,.... Xp). "inputs" is not related t |
30,515 | Eigenvalues/Eigenvectors of Correlation and Covariance matrices | If $\Sigma$ is diagonal (with arbitrary eigenvalues) then $P$ is just the unit matrix (all eigenvalues equal to one), so there cannot be any general relation between the eigenvalues of $\Sigma$ (alone) to those of $P$.
Also notice that if $\Sigma$ is 2-dimensional then $P$ has the form
$$ P = \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix} $$ whose eigenvectors are always $(1,1)$ and $(1,-1)$ regardless of $\rho$:
$$ \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix} \begin{pmatrix} 1 \\ 1 \end{pmatrix} = (1+\rho) \begin{pmatrix} 1 \\ 1 \end{pmatrix}$$
$$ \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix} \begin{pmatrix} 1 \\ -1 \end{pmatrix} = (1-\rho) \begin{pmatrix} 1 \\ -1 \end{pmatrix}$$
so clearly the eigenvectors of $\Sigma$ cannot be related to those of $P$ either. (Of course given both the eigenvalues and eigenvectors of $\Sigma$, one can determine $\Sigma$, and therefore $P$, and therefore the eigenvalues and eigenvectors of $P$). | Eigenvalues/Eigenvectors of Correlation and Covariance matrices | If $\Sigma$ is diagonal (with arbitrary eigenvalues) then $P$ is just the unit matrix (all eigenvalues equal to one), so there cannot be any general relation between the eigenvalues of $\Sigma$ (alone | Eigenvalues/Eigenvectors of Correlation and Covariance matrices
If $\Sigma$ is diagonal (with arbitrary eigenvalues) then $P$ is just the unit matrix (all eigenvalues equal to one), so there cannot be any general relation between the eigenvalues of $\Sigma$ (alone) to those of $P$.
Also notice that if $\Sigma$ is 2-dimensional then $P$ has the form
$$ P = \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix} $$ whose eigenvectors are always $(1,1)$ and $(1,-1)$ regardless of $\rho$:
$$ \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix} \begin{pmatrix} 1 \\ 1 \end{pmatrix} = (1+\rho) \begin{pmatrix} 1 \\ 1 \end{pmatrix}$$
$$ \begin{pmatrix} 1 & \rho \\ \rho & 1 \end{pmatrix} \begin{pmatrix} 1 \\ -1 \end{pmatrix} = (1-\rho) \begin{pmatrix} 1 \\ -1 \end{pmatrix}$$
so clearly the eigenvectors of $\Sigma$ cannot be related to those of $P$ either. (Of course given both the eigenvalues and eigenvectors of $\Sigma$, one can determine $\Sigma$, and therefore $P$, and therefore the eigenvalues and eigenvectors of $P$). | Eigenvalues/Eigenvectors of Correlation and Covariance matrices
If $\Sigma$ is diagonal (with arbitrary eigenvalues) then $P$ is just the unit matrix (all eigenvalues equal to one), so there cannot be any general relation between the eigenvalues of $\Sigma$ (alone |
30,516 | Eigenvalues/Eigenvectors of Correlation and Covariance matrices | Expanding on my comment:
Since $P = \text{diag}(\Sigma)^{-1/2} \Sigma \text{diag}(\Sigma)^{-1/2}$, where $\text{diag}(\Sigma)$ is the diagonal matrix obtained by considering only the diagonal entries of $\Sigma$, then $P$ and $\Sigma$ are congruent. Then, according to Sylvester's law of intertia, $P$ and $\Sigma$ have the same number of positive, negative, and zero eigenvalues. because both $P$ and $\Sigma$ have the same rank, then they have the same number of zero eigenvalues. Moreover, because they are both positive semi-definite, they will also have the same number of positive eigenvalues (thanks to @whuber for pointing this out).
One more thing: if we let $P = Q_P\Lambda_PQ_P^T$ and $\Sigma = Q_\Sigma\Lambda_\Sigma Q_\Sigma^T$ be the eigendecompositions of $P$ and $\Sigma$ respectively, we can relate their eigenvalues as follows:
\begin{align}
P &= \text{diag}(\Sigma)^{-1/2} \Sigma \text{diag}(\Sigma)^{-1/2} \\
Q_P\Lambda_PQ_P^T &= \text{diag}(\Sigma)^{-1/2} Q_\Sigma\Lambda_\Sigma Q_\Sigma^T \text{diag}(\Sigma)^{-1/2} \\
\Lambda_P &= Q_P^T \text{diag}(\Sigma)^{-1/2} Q_\Sigma\Lambda_\Sigma Q_\Sigma^T \text{diag}(\Sigma)^{-1/2} Q_P \\
\Lambda_P &= B\Lambda_\Sigma B^T
\end{align}
where $$B = Q_P^T \text{diag}(\Sigma)^{-1/2} Q_\Sigma$$ | Eigenvalues/Eigenvectors of Correlation and Covariance matrices | Expanding on my comment:
Since $P = \text{diag}(\Sigma)^{-1/2} \Sigma \text{diag}(\Sigma)^{-1/2}$, where $\text{diag}(\Sigma)$ is the diagonal matrix obtained by considering only the diagonal entries | Eigenvalues/Eigenvectors of Correlation and Covariance matrices
Expanding on my comment:
Since $P = \text{diag}(\Sigma)^{-1/2} \Sigma \text{diag}(\Sigma)^{-1/2}$, where $\text{diag}(\Sigma)$ is the diagonal matrix obtained by considering only the diagonal entries of $\Sigma$, then $P$ and $\Sigma$ are congruent. Then, according to Sylvester's law of intertia, $P$ and $\Sigma$ have the same number of positive, negative, and zero eigenvalues. because both $P$ and $\Sigma$ have the same rank, then they have the same number of zero eigenvalues. Moreover, because they are both positive semi-definite, they will also have the same number of positive eigenvalues (thanks to @whuber for pointing this out).
One more thing: if we let $P = Q_P\Lambda_PQ_P^T$ and $\Sigma = Q_\Sigma\Lambda_\Sigma Q_\Sigma^T$ be the eigendecompositions of $P$ and $\Sigma$ respectively, we can relate their eigenvalues as follows:
\begin{align}
P &= \text{diag}(\Sigma)^{-1/2} \Sigma \text{diag}(\Sigma)^{-1/2} \\
Q_P\Lambda_PQ_P^T &= \text{diag}(\Sigma)^{-1/2} Q_\Sigma\Lambda_\Sigma Q_\Sigma^T \text{diag}(\Sigma)^{-1/2} \\
\Lambda_P &= Q_P^T \text{diag}(\Sigma)^{-1/2} Q_\Sigma\Lambda_\Sigma Q_\Sigma^T \text{diag}(\Sigma)^{-1/2} Q_P \\
\Lambda_P &= B\Lambda_\Sigma B^T
\end{align}
where $$B = Q_P^T \text{diag}(\Sigma)^{-1/2} Q_\Sigma$$ | Eigenvalues/Eigenvectors of Correlation and Covariance matrices
Expanding on my comment:
Since $P = \text{diag}(\Sigma)^{-1/2} \Sigma \text{diag}(\Sigma)^{-1/2}$, where $\text{diag}(\Sigma)$ is the diagonal matrix obtained by considering only the diagonal entries |
30,517 | Eigenvalues/Eigenvectors of Correlation and Covariance matrices | First question: given a vector $\lambda = (\lambda_1,\ldots,\lambda_n)$ of eigenvalues of a variance matrix $\Sigma,$ what are the possible eigenvalues $(\tau_1, \ldots, \tau_n)$ of a covariance matrix $P$ having correlation matrix $\Sigma$?
Writing the diagonal elements of $\Sigma$ as $\Sigma_{ii} = \sigma_i^2$ (for nonnegative square roots $\sigma_i$), we need to know that the relationship between the matrices is
$$\operatorname{Diag}(\sigma)P\operatorname{Diag}(\sigma) = \Sigma.\tag{*}$$
To interpret this question, I suppose you know the eigenvalues but you don't know $\Sigma.$ Thus, it's possible $\Sigma$ is diagonal, $\Sigma = \operatorname{Diag}(\lambda).$ Then all the matrices in $(*)$ are diagonal and it reduces to $n$ simultaneous equations
$$\sigma_i \tau_i \sigma_i = \lambda_i,$$
for which we find the unique solution
$$\sigma_i = \sqrt{\frac{\lambda_i}{\tau_i}}$$
when all the $\tau_i\gt 0.$ When $\tau_i=0,$ necessarily $\lambda_i=0,$ too, and $\sigma_i$ can be any positive number.
Consequently, the zeros of $\tau$ must match the zeros of $\lambda$ and otherwise the components of $\tau$ can be anything.
Second question: given an orthonormal frame $\mathbf e_1, \ldots, \mathbf e_n$ of eigenvectors of a covariance matrix $\Sigma,$ what are the possible frames of eigenvectors of its correlation matrix $P$?
Again, to interpret this reasonably we must suppose the frame is known but $\Sigma$ is not known.
A dimension-counting argument provides insight. There are only $n$ unknown parameters $\sigma_i$ connecting $\Sigma$ and $P.$ Consequently, the dimension of the manifold of frames of eigenvectors associated with $P$ can be at most $n.$ Because the dimension of the manifold of all orthonormal frames, $\mathbb F_n,$ is $(n-1)+(n-2)+\cdots+1=n(n-1)/2,$ when $n\gt 3$ the possible frames of $\Sigma$ cannot be all possible frames: there is a definite restriction.
There appears to be no simple way of characterizing that restriction, because the map
$$\phi_\Sigma : \mathbb R_+^n \to \mathbb F_n$$
that sends $\sigma$ to the frame of eigenvectors of $P(\sigma,\Sigma) = \operatorname{Diag}(\sigma^{-1})\Sigma \operatorname{Diag}(\sigma^{-1})$ depends on $\Sigma.$ | Eigenvalues/Eigenvectors of Correlation and Covariance matrices | First question: given a vector $\lambda = (\lambda_1,\ldots,\lambda_n)$ of eigenvalues of a variance matrix $\Sigma,$ what are the possible eigenvalues $(\tau_1, \ldots, \tau_n)$ of a covariance matri | Eigenvalues/Eigenvectors of Correlation and Covariance matrices
First question: given a vector $\lambda = (\lambda_1,\ldots,\lambda_n)$ of eigenvalues of a variance matrix $\Sigma,$ what are the possible eigenvalues $(\tau_1, \ldots, \tau_n)$ of a covariance matrix $P$ having correlation matrix $\Sigma$?
Writing the diagonal elements of $\Sigma$ as $\Sigma_{ii} = \sigma_i^2$ (for nonnegative square roots $\sigma_i$), we need to know that the relationship between the matrices is
$$\operatorname{Diag}(\sigma)P\operatorname{Diag}(\sigma) = \Sigma.\tag{*}$$
To interpret this question, I suppose you know the eigenvalues but you don't know $\Sigma.$ Thus, it's possible $\Sigma$ is diagonal, $\Sigma = \operatorname{Diag}(\lambda).$ Then all the matrices in $(*)$ are diagonal and it reduces to $n$ simultaneous equations
$$\sigma_i \tau_i \sigma_i = \lambda_i,$$
for which we find the unique solution
$$\sigma_i = \sqrt{\frac{\lambda_i}{\tau_i}}$$
when all the $\tau_i\gt 0.$ When $\tau_i=0,$ necessarily $\lambda_i=0,$ too, and $\sigma_i$ can be any positive number.
Consequently, the zeros of $\tau$ must match the zeros of $\lambda$ and otherwise the components of $\tau$ can be anything.
Second question: given an orthonormal frame $\mathbf e_1, \ldots, \mathbf e_n$ of eigenvectors of a covariance matrix $\Sigma,$ what are the possible frames of eigenvectors of its correlation matrix $P$?
Again, to interpret this reasonably we must suppose the frame is known but $\Sigma$ is not known.
A dimension-counting argument provides insight. There are only $n$ unknown parameters $\sigma_i$ connecting $\Sigma$ and $P.$ Consequently, the dimension of the manifold of frames of eigenvectors associated with $P$ can be at most $n.$ Because the dimension of the manifold of all orthonormal frames, $\mathbb F_n,$ is $(n-1)+(n-2)+\cdots+1=n(n-1)/2,$ when $n\gt 3$ the possible frames of $\Sigma$ cannot be all possible frames: there is a definite restriction.
There appears to be no simple way of characterizing that restriction, because the map
$$\phi_\Sigma : \mathbb R_+^n \to \mathbb F_n$$
that sends $\sigma$ to the frame of eigenvectors of $P(\sigma,\Sigma) = \operatorname{Diag}(\sigma^{-1})\Sigma \operatorname{Diag}(\sigma^{-1})$ depends on $\Sigma.$ | Eigenvalues/Eigenvectors of Correlation and Covariance matrices
First question: given a vector $\lambda = (\lambda_1,\ldots,\lambda_n)$ of eigenvalues of a variance matrix $\Sigma,$ what are the possible eigenvalues $(\tau_1, \ldots, \tau_n)$ of a covariance matri |
30,518 | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$ | It's surprising but correct. The exponential distribution is memoryless, meaning that the distribution of time until a decay is the same whenever you start. It's easy to show it's the same if you pick any fixed time to start, and you've shown it's also the same if you pick a random time to start. In particular, if you pick the time nucleus 1 decayed as the start and nucleus 2 hasn't decayed yet it's the same, and if you pick the time nucleus 2 decayed as the start and nucleus 1 hasn't decayed yet it's the same. | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$ | It's surprising but correct. The exponential distribution is memoryless, meaning that the distribution of time until a decay is the same whenever you start. It's easy to show it's the same if you pi | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$
It's surprising but correct. The exponential distribution is memoryless, meaning that the distribution of time until a decay is the same whenever you start. It's easy to show it's the same if you pick any fixed time to start, and you've shown it's also the same if you pick a random time to start. In particular, if you pick the time nucleus 1 decayed as the start and nucleus 2 hasn't decayed yet it's the same, and if you pick the time nucleus 2 decayed as the start and nucleus 1 hasn't decayed yet it's the same. | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$
It's surprising but correct. The exponential distribution is memoryless, meaning that the distribution of time until a decay is the same whenever you start. It's easy to show it's the same if you pi |
30,519 | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$ | I would handle with a different approach which, imo, is more insightful:
Consider $T_i\overset{\textrm{iid}}{\sim}\mathrm{Exp}(\alpha), ~i\in\{1, 2\}; Z:=|T_1-T_2|.$ Now
\begin{align}\mathbb P(Z\leq z) &= \mathbb P(|T_1-T_2|\leq z) \\&= \mathbb P(T_1\leq T_2+z)-\mathbb P(T_1\leq T_2-z)\\&=\int_0^\infty \mathbb P(T_1\leq t_2+z) \alpha\exp(-\alpha t_2)~\mathrm dt_2-\int_z^\infty\mathbb P(T_1\leq t_2-z)\alpha\exp(-\alpha t_2)~\mathrm dt_2\\&= \int_0^\infty\alpha(1-\exp(-\alpha(t_2+z)))\exp(-\alpha t_2)~\mathrm dt_2-\int_z^\infty \alpha (1-\exp(-\alpha(t_2-z)))\exp(-\alpha t_2)~\mathrm dt_2\\&= 1-\exp(-\alpha z) \int_0^\infty\alpha\exp(-2\alpha t_2)~\mathrm dt_2-\alpha\left[\int_z^\infty\exp(-\alpha t_2)~\mathrm dt_2-\exp(\alpha z) \int_z^\infty \exp(-2\alpha t_2)~\mathrm dt_2\right]\\&= 1-\frac{\exp(-\alpha z) }2-\alpha\left[\frac{\exp(-\alpha z) }{\alpha}+\frac{\exp(\alpha z-2\alpha z) }{2\alpha}\right]\\&= 1-\exp(-\alpha z),\tag 1\end{align}
which is the cdf of $\mathrm{Exp}(\alpha). $ | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$ | I would handle with a different approach which, imo, is more insightful:
Consider $T_i\overset{\textrm{iid}}{\sim}\mathrm{Exp}(\alpha), ~i\in\{1, 2\}; Z:=|T_1-T_2|.$ Now
\begin{align}\mathbb P(Z\leq z | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$
I would handle with a different approach which, imo, is more insightful:
Consider $T_i\overset{\textrm{iid}}{\sim}\mathrm{Exp}(\alpha), ~i\in\{1, 2\}; Z:=|T_1-T_2|.$ Now
\begin{align}\mathbb P(Z\leq z) &= \mathbb P(|T_1-T_2|\leq z) \\&= \mathbb P(T_1\leq T_2+z)-\mathbb P(T_1\leq T_2-z)\\&=\int_0^\infty \mathbb P(T_1\leq t_2+z) \alpha\exp(-\alpha t_2)~\mathrm dt_2-\int_z^\infty\mathbb P(T_1\leq t_2-z)\alpha\exp(-\alpha t_2)~\mathrm dt_2\\&= \int_0^\infty\alpha(1-\exp(-\alpha(t_2+z)))\exp(-\alpha t_2)~\mathrm dt_2-\int_z^\infty \alpha (1-\exp(-\alpha(t_2-z)))\exp(-\alpha t_2)~\mathrm dt_2\\&= 1-\exp(-\alpha z) \int_0^\infty\alpha\exp(-2\alpha t_2)~\mathrm dt_2-\alpha\left[\int_z^\infty\exp(-\alpha t_2)~\mathrm dt_2-\exp(\alpha z) \int_z^\infty \exp(-2\alpha t_2)~\mathrm dt_2\right]\\&= 1-\frac{\exp(-\alpha z) }2-\alpha\left[\frac{\exp(-\alpha z) }{\alpha}+\frac{\exp(\alpha z-2\alpha z) }{2\alpha}\right]\\&= 1-\exp(-\alpha z),\tag 1\end{align}
which is the cdf of $\mathrm{Exp}(\alpha). $ | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$
I would handle with a different approach which, imo, is more insightful:
Consider $T_i\overset{\textrm{iid}}{\sim}\mathrm{Exp}(\alpha), ~i\in\{1, 2\}; Z:=|T_1-T_2|.$ Now
\begin{align}\mathbb P(Z\leq z |
30,520 | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$ | For exponential distribution family, operating its survival function $S(t) = e^{-\alpha t}$ is usually slightly more convenient than treating the distribution function $F(t) = 1 - e^{-\alpha t}$. Except it, my answer below is almost the same as User1865345's.
For any $t > 0$, by the independence of $T_1$ and $T_2$:
\begin{align}
& P[|T_1 - T_2| > t] = P[T_1 > T_2 + t] + P[T_2 > T_1 + t] \\
=& \int_0^{\infty}P[T_1 > s + t]f_{T_2}(s)ds + \int_0^\infty P[T_2 > s + t]f_{T_1}(s)ds \\
=& 2\int_0^{\infty}e^{-\alpha(s + t)}\alpha e^{-\alpha s}ds \\
=& e^{-\alpha t} \int_0^\infty 2\alpha e^{-2\alpha s}ds \\
=& e^{-\alpha t},
\end{align}
which is the survival function of an $\exp(\alpha)$ r.v., hence the result. | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$ | For exponential distribution family, operating its survival function $S(t) = e^{-\alpha t}$ is usually slightly more convenient than treating the distribution function $F(t) = 1 - e^{-\alpha t}$. Exc | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$
For exponential distribution family, operating its survival function $S(t) = e^{-\alpha t}$ is usually slightly more convenient than treating the distribution function $F(t) = 1 - e^{-\alpha t}$. Except it, my answer below is almost the same as User1865345's.
For any $t > 0$, by the independence of $T_1$ and $T_2$:
\begin{align}
& P[|T_1 - T_2| > t] = P[T_1 > T_2 + t] + P[T_2 > T_1 + t] \\
=& \int_0^{\infty}P[T_1 > s + t]f_{T_2}(s)ds + \int_0^\infty P[T_2 > s + t]f_{T_1}(s)ds \\
=& 2\int_0^{\infty}e^{-\alpha(s + t)}\alpha e^{-\alpha s}ds \\
=& e^{-\alpha t} \int_0^\infty 2\alpha e^{-2\alpha s}ds \\
=& e^{-\alpha t},
\end{align}
which is the survival function of an $\exp(\alpha)$ r.v., hence the result. | Density of $|t_1 - t_2|$ where $t_1$ and $t_2$ are iid with $P(t) = \alpha e^{-t\alpha}$
For exponential distribution family, operating its survival function $S(t) = e^{-\alpha t}$ is usually slightly more convenient than treating the distribution function $F(t) = 1 - e^{-\alpha t}$. Exc |
30,521 | How to motivate undergrads to take an Intro to Math Stats course | This is not an answer, it's a story -
My experience matriculating from an agricultural-based community college to a large urban liberal arts college was culture shock on every front. I knew I was hungry for mathematics and, especially, statistics. In 3rd year mathematics, students are exposed to proofs, like Rudin's Analysis. It doesn't feel "gentle" - but imagine being dropped into Functional Analysis or Measure Theory without a proofs background!
In stats, I often find there's no 3rd year statistics book or course that establishes fundamental statistics. I wrote a cotaught undergraduate (4th level)/graduate level probability and statistics course from Hogg and Craig as a 3rd year student.
Hogg and Craig's book perfectly reflects the awkwardness of this discipline to establish itself as an insular and self-sufficing degree of study. The introduction, for instance, discusses the probability space as a non-negative measure on a collection of Borel sets. I remember needing wikipedia to read the first pages. Not only is that definition highly sophisticated (and I think there are more general probability spaces than are described), that result is not used anywhere else in the book except that very general results about integration are used with reckless abandon. The rest of the book is multivariable calculus. Hogg and Craig provide different treatments for continuous and discrete DFs as a result. Hogg and Craig is not a good 3rd year book at all.
I think Casella Berger is a better book for this reason. It's very focused on problems and concepts. I also think students would benefit having prior or concurrent exposure to Sheldon Ross' Probability Models which goes over probability in great detail, skipping the statistical results - the difference between these fields is as underappreciated by students as it is by us practicing professionals. Lastly, I haven't found any textbook to be of adequate quality dealing with the topic of regression, definitely the most widespread and discussed area of statistics and inference- Nachtsheim et al. is perhaps accessible at the undergraduate level, but something like a capstone project would be a better way to expose students to using the software, doing analyses, and presenting the results.
How do you motivate students to study these areas? Well, the students have to motivate themselves. You could try the "carrot" method about all the opportunities they have, and you can say that it fosters "critical and quantitative thinking", although I find training in probability theory to be more useful than statistics in this regard. You can go farther to point out that virtually every scientific discipline requires its practitioners to be critical producers of and consumers of information that is presented using statistical summaries. For students going into mathematics and statistics, you can point out that there are many exciting results just waiting for them in a 4th year course, or graduate theory - a special topics day could go over the Cantor distribution function, or you could present the Hodges' Superefficient Estimator and explain why it "breaks" the Cramer-Rao bound. | How to motivate undergrads to take an Intro to Math Stats course | This is not an answer, it's a story -
My experience matriculating from an agricultural-based community college to a large urban liberal arts college was culture shock on every front. I knew I was hung | How to motivate undergrads to take an Intro to Math Stats course
This is not an answer, it's a story -
My experience matriculating from an agricultural-based community college to a large urban liberal arts college was culture shock on every front. I knew I was hungry for mathematics and, especially, statistics. In 3rd year mathematics, students are exposed to proofs, like Rudin's Analysis. It doesn't feel "gentle" - but imagine being dropped into Functional Analysis or Measure Theory without a proofs background!
In stats, I often find there's no 3rd year statistics book or course that establishes fundamental statistics. I wrote a cotaught undergraduate (4th level)/graduate level probability and statistics course from Hogg and Craig as a 3rd year student.
Hogg and Craig's book perfectly reflects the awkwardness of this discipline to establish itself as an insular and self-sufficing degree of study. The introduction, for instance, discusses the probability space as a non-negative measure on a collection of Borel sets. I remember needing wikipedia to read the first pages. Not only is that definition highly sophisticated (and I think there are more general probability spaces than are described), that result is not used anywhere else in the book except that very general results about integration are used with reckless abandon. The rest of the book is multivariable calculus. Hogg and Craig provide different treatments for continuous and discrete DFs as a result. Hogg and Craig is not a good 3rd year book at all.
I think Casella Berger is a better book for this reason. It's very focused on problems and concepts. I also think students would benefit having prior or concurrent exposure to Sheldon Ross' Probability Models which goes over probability in great detail, skipping the statistical results - the difference between these fields is as underappreciated by students as it is by us practicing professionals. Lastly, I haven't found any textbook to be of adequate quality dealing with the topic of regression, definitely the most widespread and discussed area of statistics and inference- Nachtsheim et al. is perhaps accessible at the undergraduate level, but something like a capstone project would be a better way to expose students to using the software, doing analyses, and presenting the results.
How do you motivate students to study these areas? Well, the students have to motivate themselves. You could try the "carrot" method about all the opportunities they have, and you can say that it fosters "critical and quantitative thinking", although I find training in probability theory to be more useful than statistics in this regard. You can go farther to point out that virtually every scientific discipline requires its practitioners to be critical producers of and consumers of information that is presented using statistical summaries. For students going into mathematics and statistics, you can point out that there are many exciting results just waiting for them in a 4th year course, or graduate theory - a special topics day could go over the Cantor distribution function, or you could present the Hodges' Superefficient Estimator and explain why it "breaks" the Cramer-Rao bound. | How to motivate undergrads to take an Intro to Math Stats course
This is not an answer, it's a story -
My experience matriculating from an agricultural-based community college to a large urban liberal arts college was culture shock on every front. I knew I was hung |
30,522 | How to motivate undergrads to take an Intro to Math Stats course | Do you hope to do research on statistical or machine-learning methods? Even if this class just proves conclusions that you've already seen, the mathematical techniques and frameworks behind these proofs are the same ones used by research statisticians to develop new cutting-edge results. This class is the first step towards making your own contributions to statistical methodology. It will also help you sanity-check a colleague's work when they say they've developed a "better" statistical method for some scenario. (How is it better: more efficient? more robust? etc. Does it actually work the way they think it does?)
Do you appreciate beauty in math? I find that some of the math techniques or results themselves are beautiful. For instance, you can approach several common situations from totally different angles (MLE, MOM, Bayesian posterior mode, minimizing MSE...) and they all give the same answer (sample mean)! How cool is that?
Do you only care about applications, not the "pure" math itself? Even so, a Math Stats course will give you a much deeper understanding of what these methods are doing. Personally, I had seen p-values and confidence intervals many times, but they did not really click for me until I took Math Stats. It will also help you learn to watch out for situations when the standard methods won't work and possibly develop your own solutions or workarounds.
Do you want to work with data-minded colleagues but not analyze data yourself? Even so, you'll be better prepared to follow other people's new developments in statistics, AI, and machine learning, so you can sensibly decide whether they're useful to your work. For instance, differential privacy has been a recent hot topic in my areas of work, but it's not trivial to understand what it's even trying to solve or how it proposes to do so; some Math Stat background definitely helps. | How to motivate undergrads to take an Intro to Math Stats course | Do you hope to do research on statistical or machine-learning methods? Even if this class just proves conclusions that you've already seen, the mathematical techniques and frameworks behind these proo | How to motivate undergrads to take an Intro to Math Stats course
Do you hope to do research on statistical or machine-learning methods? Even if this class just proves conclusions that you've already seen, the mathematical techniques and frameworks behind these proofs are the same ones used by research statisticians to develop new cutting-edge results. This class is the first step towards making your own contributions to statistical methodology. It will also help you sanity-check a colleague's work when they say they've developed a "better" statistical method for some scenario. (How is it better: more efficient? more robust? etc. Does it actually work the way they think it does?)
Do you appreciate beauty in math? I find that some of the math techniques or results themselves are beautiful. For instance, you can approach several common situations from totally different angles (MLE, MOM, Bayesian posterior mode, minimizing MSE...) and they all give the same answer (sample mean)! How cool is that?
Do you only care about applications, not the "pure" math itself? Even so, a Math Stats course will give you a much deeper understanding of what these methods are doing. Personally, I had seen p-values and confidence intervals many times, but they did not really click for me until I took Math Stats. It will also help you learn to watch out for situations when the standard methods won't work and possibly develop your own solutions or workarounds.
Do you want to work with data-minded colleagues but not analyze data yourself? Even so, you'll be better prepared to follow other people's new developments in statistics, AI, and machine learning, so you can sensibly decide whether they're useful to your work. For instance, differential privacy has been a recent hot topic in my areas of work, but it's not trivial to understand what it's even trying to solve or how it proposes to do so; some Math Stat background definitely helps. | How to motivate undergrads to take an Intro to Math Stats course
Do you hope to do research on statistical or machine-learning methods? Even if this class just proves conclusions that you've already seen, the mathematical techniques and frameworks behind these proo |
30,523 | How to motivate undergrads to take an Intro to Math Stats course | If the undergraduates have just taken a course in Introduction to Applied Statistics, well, frankly I can't blame them for not taking the Introduction to Mathematical Statistics course. For interested students, I would think that the "theory" behind applied statistics would be at least minimally presented in the applied statistics course; enough for them to understand it in principle. And these things take a while, and some experience, to intuitively understand and be cogitated upon. Unless perhaps there was some deficiency in the first course in explaining basic concepts and they got stuck on that.
I would suggest that perhaps other courses might fit students' progression up the statistical ladder, such as regression (logistic, Poisson and others); sampling methods; a software-oriented epidemiology course, or even an applied course in genetics. These would help them to intuit statistical logic. It seems your college might be forcibly dividing intro statistics in to an "applied" camp where the basic how-to is performed, and a "mathematical" camp where more mathematical, probability-based and inter-related statistics are looked at under the hood. You could always change the name of the course to make it a more logical follow-on to the first course. My guess is that those who took the first course are actually hungry for more applications of statistics, and this second course might be better to have some real-world examples, making it "semi-applied."
With that said, I appreciate trying to teach the undergraduates more about the logic of inference and probability and so forth, beyond what they learned in the nuts-and-bolts course. But it might be (or sound) overwhelming for them. In my own personal journey I've come to appreciate statistical theory on things well after I've had multiple statistical courses on everything from design of experiments to logistic regression and probability, and a lot of real-world research. And I've found the theory to usually be much simpler than it sounds; again, partly because a certain amount of applied statistics has been put under my belt. | How to motivate undergrads to take an Intro to Math Stats course | If the undergraduates have just taken a course in Introduction to Applied Statistics, well, frankly I can't blame them for not taking the Introduction to Mathematical Statistics course. For interested | How to motivate undergrads to take an Intro to Math Stats course
If the undergraduates have just taken a course in Introduction to Applied Statistics, well, frankly I can't blame them for not taking the Introduction to Mathematical Statistics course. For interested students, I would think that the "theory" behind applied statistics would be at least minimally presented in the applied statistics course; enough for them to understand it in principle. And these things take a while, and some experience, to intuitively understand and be cogitated upon. Unless perhaps there was some deficiency in the first course in explaining basic concepts and they got stuck on that.
I would suggest that perhaps other courses might fit students' progression up the statistical ladder, such as regression (logistic, Poisson and others); sampling methods; a software-oriented epidemiology course, or even an applied course in genetics. These would help them to intuit statistical logic. It seems your college might be forcibly dividing intro statistics in to an "applied" camp where the basic how-to is performed, and a "mathematical" camp where more mathematical, probability-based and inter-related statistics are looked at under the hood. You could always change the name of the course to make it a more logical follow-on to the first course. My guess is that those who took the first course are actually hungry for more applications of statistics, and this second course might be better to have some real-world examples, making it "semi-applied."
With that said, I appreciate trying to teach the undergraduates more about the logic of inference and probability and so forth, beyond what they learned in the nuts-and-bolts course. But it might be (or sound) overwhelming for them. In my own personal journey I've come to appreciate statistical theory on things well after I've had multiple statistical courses on everything from design of experiments to logistic regression and probability, and a lot of real-world research. And I've found the theory to usually be much simpler than it sounds; again, partly because a certain amount of applied statistics has been put under my belt. | How to motivate undergrads to take an Intro to Math Stats course
If the undergraduates have just taken a course in Introduction to Applied Statistics, well, frankly I can't blame them for not taking the Introduction to Mathematical Statistics course. For interested |
30,524 | Discovering groupings of descriptive tags from media | You can use the market basket analysis, a simple and popular data mining technique that does exactly what you described: groups co-occurring items together.
For a more sophisticated solution, you can use cluster analysis. For binary data, there is a rich family of models called latent class analysis that are designed for this purpose. I'm not sure though if it would scale to a large dataset with many columns and rows like yours.
You could transform the binary data into embeddings that would reduce its dimensionality and convert it into continuous features that later could be clustered, which makes it a simpler problem. For creating the embeddings, you could use a neural network or take one of the latent matrices created by matrix factorization (an algorithm used usually for recommender systems), where both scale very well to large data. They will create continuous features, so you can cluster them with any algorithm, e.g. $k$-means. | Discovering groupings of descriptive tags from media | You can use the market basket analysis, a simple and popular data mining technique that does exactly what you described: groups co-occurring items together.
For a more sophisticated solution, you can | Discovering groupings of descriptive tags from media
You can use the market basket analysis, a simple and popular data mining technique that does exactly what you described: groups co-occurring items together.
For a more sophisticated solution, you can use cluster analysis. For binary data, there is a rich family of models called latent class analysis that are designed for this purpose. I'm not sure though if it would scale to a large dataset with many columns and rows like yours.
You could transform the binary data into embeddings that would reduce its dimensionality and convert it into continuous features that later could be clustered, which makes it a simpler problem. For creating the embeddings, you could use a neural network or take one of the latent matrices created by matrix factorization (an algorithm used usually for recommender systems), where both scale very well to large data. They will create continuous features, so you can cluster them with any algorithm, e.g. $k$-means. | Discovering groupings of descriptive tags from media
You can use the market basket analysis, a simple and popular data mining technique that does exactly what you described: groups co-occurring items together.
For a more sophisticated solution, you can |
30,525 | Discovering groupings of descriptive tags from media | If you are after visualizing the relationships, then you might use some network visualization algorithms.
I did this once with the tags of cross validated (Disclaimer: I am not an expert at this). I made a matrix that keeps track of the number of times of times that the different tags are appearing together. Then I used that matrix as
a matrix describing the edges in a network graph
a correlation matrix in PCA and
3 after some arbitrary trial and error with transformations, as a dissimilarity matrix in an hierarchical clustering method | Discovering groupings of descriptive tags from media | If you are after visualizing the relationships, then you might use some network visualization algorithms.
I did this once with the tags of cross validated (Disclaimer: I am not an expert at this). I m | Discovering groupings of descriptive tags from media
If you are after visualizing the relationships, then you might use some network visualization algorithms.
I did this once with the tags of cross validated (Disclaimer: I am not an expert at this). I made a matrix that keeps track of the number of times of times that the different tags are appearing together. Then I used that matrix as
a matrix describing the edges in a network graph
a correlation matrix in PCA and
3 after some arbitrary trial and error with transformations, as a dissimilarity matrix in an hierarchical clustering method | Discovering groupings of descriptive tags from media
If you are after visualizing the relationships, then you might use some network visualization algorithms.
I did this once with the tags of cross validated (Disclaimer: I am not an expert at this). I m |
30,526 | Is it required to train the model in entire data after cross validation? | The argument refit is for this purpose, which is by default True.
See the documentation:
refit: bool, str, or callable, default=True
Refit an estimator using the best found parameters on the whole dataset.
About putting it into the production, I'd suggest you separate some part of your dataset as a test set and do a final check with the refitted model. Although CV is there to select best HPs, it doesn't have the ability to prevent overfitting, and it's for your good to detect if you have it and choose to go with it. Nobody should go to production blindfold. | Is it required to train the model in entire data after cross validation? | The argument refit is for this purpose, which is by default True.
See the documentation:
refit: bool, str, or callable, default=True
Refit an estimator using the best found parameters on the whole da | Is it required to train the model in entire data after cross validation?
The argument refit is for this purpose, which is by default True.
See the documentation:
refit: bool, str, or callable, default=True
Refit an estimator using the best found parameters on the whole dataset.
About putting it into the production, I'd suggest you separate some part of your dataset as a test set and do a final check with the refitted model. Although CV is there to select best HPs, it doesn't have the ability to prevent overfitting, and it's for your good to detect if you have it and choose to go with it. Nobody should go to production blindfold. | Is it required to train the model in entire data after cross validation?
The argument refit is for this purpose, which is by default True.
See the documentation:
refit: bool, str, or callable, default=True
Refit an estimator using the best found parameters on the whole da |
30,527 | Is it required to train the model in entire data after cross validation? | It is not required. In many cases, it might be a good idea, for example when you have a rather small dataset. On the other hand, if you have a lot of good data, so the set used for tuning was already decent, it might not be necessary. It not always will be possible as well, for example, if training your model cost as much as a new car (some large deep learning models) you might not have enough resources to repeat it, same if the training takes very long and you don't have the time. If you decide to re-train, it is a good idea to keep the held-out test set to make sure that the re-trained model performs as well as the one found during cross-validation, as there's always a risk that something goes wrong (e.g. bug in the code, for a trivial example). | Is it required to train the model in entire data after cross validation? | It is not required. In many cases, it might be a good idea, for example when you have a rather small dataset. On the other hand, if you have a lot of good data, so the set used for tuning was already | Is it required to train the model in entire data after cross validation?
It is not required. In many cases, it might be a good idea, for example when you have a rather small dataset. On the other hand, if you have a lot of good data, so the set used for tuning was already decent, it might not be necessary. It not always will be possible as well, for example, if training your model cost as much as a new car (some large deep learning models) you might not have enough resources to repeat it, same if the training takes very long and you don't have the time. If you decide to re-train, it is a good idea to keep the held-out test set to make sure that the re-trained model performs as well as the one found during cross-validation, as there's always a risk that something goes wrong (e.g. bug in the code, for a trivial example). | Is it required to train the model in entire data after cross validation?
It is not required. In many cases, it might be a good idea, for example when you have a rather small dataset. On the other hand, if you have a lot of good data, so the set used for tuning was already |
30,528 | Is it required to train the model in entire data after cross validation? | If you do cross-validation (CV), you have one model per fold. E.g. if you did 2-times-repeated 7-fold CV, you have 14 models. Sometimes it is acceptable to have that many models and to just average their results.
However, you reduce runtime (just one model), make it easier to use model interpretability tools and may also get better performance, if you refit on all the data. Whether you will is not always totally clear, you on the one hand have more data (ought to improve things), but by training multiple times on different data, you are getting some (potentially useful) variety and are to some extent doing seed averaging (you can of course train "a final time" on all data multiple times with different random number seeds to get that same effect). From what I've heard from top-Kagglers it's more likely that retraining on all data is the best choice.
What are reasons not to? Training cost is probably not the main issue, since you could afford to do CV, so just one more fit presumably does not matter so much. However, sometimes you do early stopping based on CV. Generally, you'd want to define when you stop based on CV (e.g. identify a fixed number of epochs/trees/whatever that seems to work across folds), but if your training approach is so fragile that this is not possible and you need a validation set to decide when to stop (arguably, you ought to stabilize things to prevent this situation), that could be an argument for avoiding re-training. | Is it required to train the model in entire data after cross validation? | If you do cross-validation (CV), you have one model per fold. E.g. if you did 2-times-repeated 7-fold CV, you have 14 models. Sometimes it is acceptable to have that many models and to just average th | Is it required to train the model in entire data after cross validation?
If you do cross-validation (CV), you have one model per fold. E.g. if you did 2-times-repeated 7-fold CV, you have 14 models. Sometimes it is acceptable to have that many models and to just average their results.
However, you reduce runtime (just one model), make it easier to use model interpretability tools and may also get better performance, if you refit on all the data. Whether you will is not always totally clear, you on the one hand have more data (ought to improve things), but by training multiple times on different data, you are getting some (potentially useful) variety and are to some extent doing seed averaging (you can of course train "a final time" on all data multiple times with different random number seeds to get that same effect). From what I've heard from top-Kagglers it's more likely that retraining on all data is the best choice.
What are reasons not to? Training cost is probably not the main issue, since you could afford to do CV, so just one more fit presumably does not matter so much. However, sometimes you do early stopping based on CV. Generally, you'd want to define when you stop based on CV (e.g. identify a fixed number of epochs/trees/whatever that seems to work across folds), but if your training approach is so fragile that this is not possible and you need a validation set to decide when to stop (arguably, you ought to stabilize things to prevent this situation), that could be an argument for avoiding re-training. | Is it required to train the model in entire data after cross validation?
If you do cross-validation (CV), you have one model per fold. E.g. if you did 2-times-repeated 7-fold CV, you have 14 models. Sometimes it is acceptable to have that many models and to just average th |
30,529 | Is it required to train the model in entire data after cross validation? | It slightly depends on what you mean by "entire data".
In the "train, cross-validate, test" paradigm, where the cross-validation folds are taken from the training set, once you have selected your model and hyper-parameters you should then train that model on the full training set and finally (and only once) test it against the test set you set aside at the beginning to see how good this final model is on unseen data.
Whether you then
(a) use that tested model in production, or
(b) retrain it (with the same model and hyper-parameters) on the combined training and test set
is your choice. If you have sufficient data and your test data was similar to your training set, then it should not make much difference. You would not have a test of the accuracy of an option (b) model on out-of-sample data until you have new previously unseen data, but that may not be an issue and you may want the small theoretical benefit of training on slightly more data. | Is it required to train the model in entire data after cross validation? | It slightly depends on what you mean by "entire data".
In the "train, cross-validate, test" paradigm, where the cross-validation folds are taken from the training set, once you have selected your mode | Is it required to train the model in entire data after cross validation?
It slightly depends on what you mean by "entire data".
In the "train, cross-validate, test" paradigm, where the cross-validation folds are taken from the training set, once you have selected your model and hyper-parameters you should then train that model on the full training set and finally (and only once) test it against the test set you set aside at the beginning to see how good this final model is on unseen data.
Whether you then
(a) use that tested model in production, or
(b) retrain it (with the same model and hyper-parameters) on the combined training and test set
is your choice. If you have sufficient data and your test data was similar to your training set, then it should not make much difference. You would not have a test of the accuracy of an option (b) model on out-of-sample data until you have new previously unseen data, but that may not be an issue and you may want the small theoretical benefit of training on slightly more data. | Is it required to train the model in entire data after cross validation?
It slightly depends on what you mean by "entire data".
In the "train, cross-validate, test" paradigm, where the cross-validation folds are taken from the training set, once you have selected your mode |
30,530 | How to simulate the St. Petersburg paradox | This is more a story of instability than of infinity.
You can spot the inexistence of a mean of a random variable $X$ by examining how the empirical mean changes over time. When the mean exists, eventually the mean of a long series of independent draws will settle down to the mean of $X:$ that is what various Laws of Large Numbers assert.
Now, although no finite simulation can definitively establish whether a mean exists or not, simulations can be suggestive.
As Wikipedia describes it,
A casino offers a game of chance for a single player in which a fair coin is tossed at each stage. The initial stake begins at 2 dollars and is doubled every time heads appears. The first time tails appears, the game ends and the player wins whatever is in the pot.
This game is certain to terminate, because the chance that it lasts longer than $n$ tosses is only $2^{-n},$ which can be made smaller than any positive number, showing that the chance the game does not terminate is less than all positive numbers: it must be zero.
The number of tosses follows a Geometric distribution, allowing for efficient simulation of this game, as in this R implementation of a million independent iterations.
X <- 1 + rgeom(1e6, 1/2)
A histogram of these results -- which are the binary logarithms of the winnings -- gives us a picture of their relative frequences. The steady decrease from $1/2$ for surviving just one roll, to $1/4,$ to $1/8,$ and so on, is apparent, indicating this simulation is doing the right thing.
The second panel plots mean winnings after each iteration. They don't appear to be settling down. The infinite expectation is manifest in the occasional large jumps.
Think about what a jump must mean. The leap from near 20 to almost 25 around iteration 400,000, for instance, indicates the total winnings must suddenly have increased by about $(25 - 20)\times 4\times 10^5 \approx 2^{11}.$ It took a sequence of 11 tails in a row to do that. Every once in a while, going on as long as the game could ever be played, there will be such jumps.
Others have used simulations in the same way to analyze other situations with undefined or infinite means, such as a Cauchy random variable. | How to simulate the St. Petersburg paradox | This is more a story of instability than of infinity.
You can spot the inexistence of a mean of a random variable $X$ by examining how the empirical mean changes over time. When the mean exists, even | How to simulate the St. Petersburg paradox
This is more a story of instability than of infinity.
You can spot the inexistence of a mean of a random variable $X$ by examining how the empirical mean changes over time. When the mean exists, eventually the mean of a long series of independent draws will settle down to the mean of $X:$ that is what various Laws of Large Numbers assert.
Now, although no finite simulation can definitively establish whether a mean exists or not, simulations can be suggestive.
As Wikipedia describes it,
A casino offers a game of chance for a single player in which a fair coin is tossed at each stage. The initial stake begins at 2 dollars and is doubled every time heads appears. The first time tails appears, the game ends and the player wins whatever is in the pot.
This game is certain to terminate, because the chance that it lasts longer than $n$ tosses is only $2^{-n},$ which can be made smaller than any positive number, showing that the chance the game does not terminate is less than all positive numbers: it must be zero.
The number of tosses follows a Geometric distribution, allowing for efficient simulation of this game, as in this R implementation of a million independent iterations.
X <- 1 + rgeom(1e6, 1/2)
A histogram of these results -- which are the binary logarithms of the winnings -- gives us a picture of their relative frequences. The steady decrease from $1/2$ for surviving just one roll, to $1/4,$ to $1/8,$ and so on, is apparent, indicating this simulation is doing the right thing.
The second panel plots mean winnings after each iteration. They don't appear to be settling down. The infinite expectation is manifest in the occasional large jumps.
Think about what a jump must mean. The leap from near 20 to almost 25 around iteration 400,000, for instance, indicates the total winnings must suddenly have increased by about $(25 - 20)\times 4\times 10^5 \approx 2^{11}.$ It took a sequence of 11 tails in a row to do that. Every once in a while, going on as long as the game could ever be played, there will be such jumps.
Others have used simulations in the same way to analyze other situations with undefined or infinite means, such as a Cauchy random variable. | How to simulate the St. Petersburg paradox
This is more a story of instability than of infinity.
You can spot the inexistence of a mean of a random variable $X$ by examining how the empirical mean changes over time. When the mean exists, even |
30,531 | How to simulate the St. Petersburg paradox | I'm not sure you can numerically simulate a process involving infinity. Every individual instance of the game terminates with a finite value, so any finite number of plays will result in the mean value also being finite. No matter how many times you simulate the game in practice, your simulation mean will never reach the expected value of the game, which is infinite.
The underlying issue is that a numerical simulation cannot converge to infinity - numerical models produce numerical results, but infinity isn't a number. At best, your simulation can return a very large number, but that does not itself imply that the process actually converges to an infinite expected value. | How to simulate the St. Petersburg paradox | I'm not sure you can numerically simulate a process involving infinity. Every individual instance of the game terminates with a finite value, so any finite number of plays will result in the mean valu | How to simulate the St. Petersburg paradox
I'm not sure you can numerically simulate a process involving infinity. Every individual instance of the game terminates with a finite value, so any finite number of plays will result in the mean value also being finite. No matter how many times you simulate the game in practice, your simulation mean will never reach the expected value of the game, which is infinite.
The underlying issue is that a numerical simulation cannot converge to infinity - numerical models produce numerical results, but infinity isn't a number. At best, your simulation can return a very large number, but that does not itself imply that the process actually converges to an infinite expected value. | How to simulate the St. Petersburg paradox
I'm not sure you can numerically simulate a process involving infinity. Every individual instance of the game terminates with a finite value, so any finite number of plays will result in the mean valu |
30,532 | Ideal Use Cases for Splines | You have to define what you mean by "ideal" or "best" in this question, but I will give you my two cents none the less.
Are there any ideal use cases for splines?
My (very radical) opinion is that when data are plentiful, a spline makes the most sense to use in the absence of any other information. Frank Harrell provides an excellent rationale for this perspective, which I will repeat now.
There are 2 possibilities (use splines, or don't) and 2 latent truths (the effect of the variable truly is non-linear, or it is linear). There are then 4 outcomes to consider:
We don’t use splines and the effect is linear. In this case, a simple model will suffice and we benefit from lower variance fits.
We use splines and the effect is linear. In this case, we spend extra degrees of freedom unnecessarily, increasing the variance of our fits, but the effect of the variable is appropriately estimated.
We don’t use splines and the effect is non-linear. This has the potential to be catastrophic! Imagine that a variable has an effect on y that looks like $y = x^2$. If $x$ is mean centered, then the linear fit could estimate the effect to be 0 or too small, depending on the distribution of $x$.
We use splines and the effect is non-linear. This would be the best case scenario where we appropriately spend our degrees of freedom.
From this scenario analysis it seems that it is always best to fit a spline to data (again, I will concede to the weaker position that this really depends on the availability of data). Best of all, if we initially fit a spline we can always perform an F test to determine if the spline model explains more variance than a linear effect, thereby informing future models fit to similar data.
That's my opinion, generally. Now, let me offer an example in which splines are really clearly the better choice. Suppose you are modelling some function over the course a day (maybe it is traffic to a website or something). The effect has a strong chance of being non-linear since our lives are largely effected by time (we sleep during some periods thereby leading to lower activity on the website, and are active in other periods). Not only is the effect non-linear, it is cyclic (the activity at 1 minute prior to midnight is approximately the same as the activity 1 minute post midnight). We could potentially model this with a trig function, but a better option is to use a cyclic spline which can a) accommodate the cyclic nature of the phenomenon, and b) avoid model bias in having to specify a function form of the phenomena a priori. | Ideal Use Cases for Splines | You have to define what you mean by "ideal" or "best" in this question, but I will give you my two cents none the less.
Are there any ideal use cases for splines?
My (very radical) opinion is that w | Ideal Use Cases for Splines
You have to define what you mean by "ideal" or "best" in this question, but I will give you my two cents none the less.
Are there any ideal use cases for splines?
My (very radical) opinion is that when data are plentiful, a spline makes the most sense to use in the absence of any other information. Frank Harrell provides an excellent rationale for this perspective, which I will repeat now.
There are 2 possibilities (use splines, or don't) and 2 latent truths (the effect of the variable truly is non-linear, or it is linear). There are then 4 outcomes to consider:
We don’t use splines and the effect is linear. In this case, a simple model will suffice and we benefit from lower variance fits.
We use splines and the effect is linear. In this case, we spend extra degrees of freedom unnecessarily, increasing the variance of our fits, but the effect of the variable is appropriately estimated.
We don’t use splines and the effect is non-linear. This has the potential to be catastrophic! Imagine that a variable has an effect on y that looks like $y = x^2$. If $x$ is mean centered, then the linear fit could estimate the effect to be 0 or too small, depending on the distribution of $x$.
We use splines and the effect is non-linear. This would be the best case scenario where we appropriately spend our degrees of freedom.
From this scenario analysis it seems that it is always best to fit a spline to data (again, I will concede to the weaker position that this really depends on the availability of data). Best of all, if we initially fit a spline we can always perform an F test to determine if the spline model explains more variance than a linear effect, thereby informing future models fit to similar data.
That's my opinion, generally. Now, let me offer an example in which splines are really clearly the better choice. Suppose you are modelling some function over the course a day (maybe it is traffic to a website or something). The effect has a strong chance of being non-linear since our lives are largely effected by time (we sleep during some periods thereby leading to lower activity on the website, and are active in other periods). Not only is the effect non-linear, it is cyclic (the activity at 1 minute prior to midnight is approximately the same as the activity 1 minute post midnight). We could potentially model this with a trig function, but a better option is to use a cyclic spline which can a) accommodate the cyclic nature of the phenomenon, and b) avoid model bias in having to specify a function form of the phenomena a priori. | Ideal Use Cases for Splines
You have to define what you mean by "ideal" or "best" in this question, but I will give you my two cents none the less.
Are there any ideal use cases for splines?
My (very radical) opinion is that w |
30,533 | Ideal Use Cases for Splines | Splines can be seen as non-parametric interpolation or fitting tools. So, the ideal application would be a case where you don't have a model to describe the variable but need to either interpolate it or produce a smooth version of the data.
Splines are often used in conjunction with other methods. For instance, take a look at linear splines: they model a function as a piece-wise linear function. If you think that your response has a nonlinear relationship to a variable, you could model the variable as a linear spline and enter into your OLS equation. See, mkspline function in State, for instance. You can think of GAM (generalized additive model) as an application of a similar approach, where you can apply a (non-smoothing) spline to a variable before throwing it into a regression.
Cubic (non-smoothing) splines are used to upsample variables, e.g. convert quarterly GDP variable into monthly for a model where the response is monthly.
You seem to describe the smoothing splines in your question, that's a different approach to interpolation altogether. It models the response variable as a low order polynomial piece-wise plus introduces the roughness penalty to make the output smooth.
Summarizing, there are many different spline applications used in the industry, some of them are stand-alone (like interpolation) and the others are integrated in other techniques such as regressions. | Ideal Use Cases for Splines | Splines can be seen as non-parametric interpolation or fitting tools. So, the ideal application would be a case where you don't have a model to describe the variable but need to either interpolate it | Ideal Use Cases for Splines
Splines can be seen as non-parametric interpolation or fitting tools. So, the ideal application would be a case where you don't have a model to describe the variable but need to either interpolate it or produce a smooth version of the data.
Splines are often used in conjunction with other methods. For instance, take a look at linear splines: they model a function as a piece-wise linear function. If you think that your response has a nonlinear relationship to a variable, you could model the variable as a linear spline and enter into your OLS equation. See, mkspline function in State, for instance. You can think of GAM (generalized additive model) as an application of a similar approach, where you can apply a (non-smoothing) spline to a variable before throwing it into a regression.
Cubic (non-smoothing) splines are used to upsample variables, e.g. convert quarterly GDP variable into monthly for a model where the response is monthly.
You seem to describe the smoothing splines in your question, that's a different approach to interpolation altogether. It models the response variable as a low order polynomial piece-wise plus introduces the roughness penalty to make the output smooth.
Summarizing, there are many different spline applications used in the industry, some of them are stand-alone (like interpolation) and the others are integrated in other techniques such as regressions. | Ideal Use Cases for Splines
Splines can be seen as non-parametric interpolation or fitting tools. So, the ideal application would be a case where you don't have a model to describe the variable but need to either interpolate it |
30,534 | Are Random Forests good at detecting interaction terms? | Yes, tree based methods are good at detecting interactions, but not always. For example, using $x_1\lessgtr0$ and $x_2\lessgtr0$ in subsequent levels of the tree would be equivalent to using $x_1x_2\lessgtr0$ on one level. That said, since you set a max depth hyperparameter in random forests, adding promising interactions will decrease your overall depth and paves the way for more performance via leaving the remaining levels for other features. | Are Random Forests good at detecting interaction terms? | Yes, tree based methods are good at detecting interactions, but not always. For example, using $x_1\lessgtr0$ and $x_2\lessgtr0$ in subsequent levels of the tree would be equivalent to using $x_1x_2\l | Are Random Forests good at detecting interaction terms?
Yes, tree based methods are good at detecting interactions, but not always. For example, using $x_1\lessgtr0$ and $x_2\lessgtr0$ in subsequent levels of the tree would be equivalent to using $x_1x_2\lessgtr0$ on one level. That said, since you set a max depth hyperparameter in random forests, adding promising interactions will decrease your overall depth and paves the way for more performance via leaving the remaining levels for other features. | Are Random Forests good at detecting interaction terms?
Yes, tree based methods are good at detecting interactions, but not always. For example, using $x_1\lessgtr0$ and $x_2\lessgtr0$ in subsequent levels of the tree would be equivalent to using $x_1x_2\l |
30,535 | Are Random Forests good at detecting interaction terms? | @gunes has already given the answer, that random forests do work well with interactions. It may help to give a practical example, though. For that, we will need some toy data
set.seed(2021)
n = 5000
x1 <- rnorm(2*n)
x2 <- runif(2*n)
interaction <- x1 * x2
pseudointeraction <- sample(interaction)
x3 <- rbeta(2*n, 2, 10)
epsilon <- rt(2*n, df = 1)
y <- 1*x1 + 2*x2 + 3*x3 + 10*interaction
example <- data.frame(x1 = x1, x2 = x2, x3 = x3, x4 = rbeta(2*n, 5, 5), x5 = runif(2*n,-10, 10),
interaction = interaction, pseudointeraction = pseudointeraction,
y = y)
Basically we have a y that is a linear function of x1, x2, x3 and the interaction x1*x2. In the dataset there is also a permutation of the interaction term and two more random variables, all of which bear no real information. We split this into a training and an equally sized testing dataset like so:
train <- example[1:n,]
test <- example[(n+1):(2*n),]
As the toy data have been modelled in a linear model, linear regression should be able to solve that puzzle easily:
> linear1 <- lm(y ~ . - pseudointeraction , data = example)
> summary(linear1)
Call:
lm(formula = y ~ . - pseudointeraction, data = example)
Residuals:
Min 1Q Median 3Q Max
-1.071e-12 -3.400e-16 5.000e-17 4.700e-16 1.524e-12
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -1.641e-14 9.004e-16 -1.823e+01 < 2e-16 ***
x1 1.000e+00 4.293e-16 2.329e+15 < 2e-16 ***
x2 2.000e+00 7.480e-16 2.674e+15 < 2e-16 ***
x3 3.000e+00 2.076e-15 1.445e+15 < 2e-16 ***
x4 3.798e-15 1.423e-15 2.669e+00 0.00762 **
x5 2.698e-18 3.725e-17 7.200e-02 0.94225
interaction 1.000e+01 7.415e-16 1.349e+16 < 2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.145e-14 on 9993 degrees of freedom
Multiple R-squared: 1, Adjusted R-squared: 1
F-statistic: 1.647e+32 on 6 and 9993 DF, p-value: < 2.2e-16
The linear modell is wrong in declaring x4 a significant predictor but as it was to be expected, $R^2$ is about 100%.
If we take the interaction term away or exchange it for the permuted interaction term, things get far worse as was to be expected:
> linear2 <- lm(y ~ . - interaction, data = example)
> summary(linear2)
Call:
lm(formula = y ~ . - interaction, data = example)
Residuals:
Min 1Q Median 3Q Max
-17.4533 -1.2764 0.0621 1.2977 14.8616
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.1791910 0.1214622 -1.475 0.140
x1 6.0262464 0.0287402 209.680 <2e-16 ***
x2 2.0022413 0.1009082 19.842 <2e-16 ***
x3 3.0676424 0.2800356 10.954 <2e-16 ***
x4 0.1791824 0.1919885 0.933 0.351
x5 0.0005224 0.0050245 0.104 0.917
pseudointeraction 0.0121493 0.0496305 0.245 0.807
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.894 on 9993 degrees of freedom
Multiple R-squared: 0.816, Adjusted R-squared: 0.8159
F-statistic: 7385 on 6 and 9993 DF, p-value: < 2.2e-16
$R^2$ dropped to 82%. So the interaction term is important in this model.
Let's grow a randomForest with the interaction term and one without it:
library(randomForest)
rf1 <- randomForest(y ~ . - interaction, data = example, mtry = 3)
rf2 <- randomForest(y ~ . - pseudointeraction, data = example, mtry = 3)
print(rf1)
print(rf2)
This will take some time to compute and the print results will claim that the random forest with an interaction term given explained 99.67% of the variance while the random forest with the interaction term explained 99.93% of the variance.
It is hard to compare within-sample $R^2$ to Out-of-bag-performance, so we predict our test data set with all four of our models we have so far:
linear1.on.test <- predict(linear1, data = test)
linear2.on.test <- predict(linear2, data = test)
rf1.on.test <- predict(rf1, data = test)
rf2.on.test <- predict(rf2, data = test)
In a next step we compute the absolute residuals and plot them as boxplots:
boxplot(linear1.on.test - test$y, linear2.on.test - test$y, rf1.on.test - test$y, rf2.on.test - test$y,
ylim=c(-7, 7), xaxt="n", ylab = "residuals")
axis(1, at = 1:4, labels = c("linear with I", "linear w/o I", "rf w/o I", "rf with I"))
So the linear model with interaction term fits best to how the data was constructed and thus predicts best. The linear model without interaction term has no flexibility to adapt and has the worst predictive value of all models.
For the random forests we see quite similar results with and without the interaction term. Stating the interaction term explicitely appears to be helpfull but the model without it is flexible enough to give good predictions without that.
Real world interactions will rarely follow the rules of exact multiplication so the small advantage of computing the interaction term for the model may be even smaller for real world interactions.
All of this will be influenced by sample size, number of features, tuning parameters and so on but the short take away message is that whilst feature building is a good thing, random forest can detect and make use of interactions even if they are not stated in the call to randomForest.
Feel free to run this code with different set.seed values, compute RMSEs etc. | Are Random Forests good at detecting interaction terms? | @gunes has already given the answer, that random forests do work well with interactions. It may help to give a practical example, though. For that, we will need some toy data
set.seed(2021)
n = 5000
x | Are Random Forests good at detecting interaction terms?
@gunes has already given the answer, that random forests do work well with interactions. It may help to give a practical example, though. For that, we will need some toy data
set.seed(2021)
n = 5000
x1 <- rnorm(2*n)
x2 <- runif(2*n)
interaction <- x1 * x2
pseudointeraction <- sample(interaction)
x3 <- rbeta(2*n, 2, 10)
epsilon <- rt(2*n, df = 1)
y <- 1*x1 + 2*x2 + 3*x3 + 10*interaction
example <- data.frame(x1 = x1, x2 = x2, x3 = x3, x4 = rbeta(2*n, 5, 5), x5 = runif(2*n,-10, 10),
interaction = interaction, pseudointeraction = pseudointeraction,
y = y)
Basically we have a y that is a linear function of x1, x2, x3 and the interaction x1*x2. In the dataset there is also a permutation of the interaction term and two more random variables, all of which bear no real information. We split this into a training and an equally sized testing dataset like so:
train <- example[1:n,]
test <- example[(n+1):(2*n),]
As the toy data have been modelled in a linear model, linear regression should be able to solve that puzzle easily:
> linear1 <- lm(y ~ . - pseudointeraction , data = example)
> summary(linear1)
Call:
lm(formula = y ~ . - pseudointeraction, data = example)
Residuals:
Min 1Q Median 3Q Max
-1.071e-12 -3.400e-16 5.000e-17 4.700e-16 1.524e-12
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -1.641e-14 9.004e-16 -1.823e+01 < 2e-16 ***
x1 1.000e+00 4.293e-16 2.329e+15 < 2e-16 ***
x2 2.000e+00 7.480e-16 2.674e+15 < 2e-16 ***
x3 3.000e+00 2.076e-15 1.445e+15 < 2e-16 ***
x4 3.798e-15 1.423e-15 2.669e+00 0.00762 **
x5 2.698e-18 3.725e-17 7.200e-02 0.94225
interaction 1.000e+01 7.415e-16 1.349e+16 < 2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.145e-14 on 9993 degrees of freedom
Multiple R-squared: 1, Adjusted R-squared: 1
F-statistic: 1.647e+32 on 6 and 9993 DF, p-value: < 2.2e-16
The linear modell is wrong in declaring x4 a significant predictor but as it was to be expected, $R^2$ is about 100%.
If we take the interaction term away or exchange it for the permuted interaction term, things get far worse as was to be expected:
> linear2 <- lm(y ~ . - interaction, data = example)
> summary(linear2)
Call:
lm(formula = y ~ . - interaction, data = example)
Residuals:
Min 1Q Median 3Q Max
-17.4533 -1.2764 0.0621 1.2977 14.8616
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.1791910 0.1214622 -1.475 0.140
x1 6.0262464 0.0287402 209.680 <2e-16 ***
x2 2.0022413 0.1009082 19.842 <2e-16 ***
x3 3.0676424 0.2800356 10.954 <2e-16 ***
x4 0.1791824 0.1919885 0.933 0.351
x5 0.0005224 0.0050245 0.104 0.917
pseudointeraction 0.0121493 0.0496305 0.245 0.807
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.894 on 9993 degrees of freedom
Multiple R-squared: 0.816, Adjusted R-squared: 0.8159
F-statistic: 7385 on 6 and 9993 DF, p-value: < 2.2e-16
$R^2$ dropped to 82%. So the interaction term is important in this model.
Let's grow a randomForest with the interaction term and one without it:
library(randomForest)
rf1 <- randomForest(y ~ . - interaction, data = example, mtry = 3)
rf2 <- randomForest(y ~ . - pseudointeraction, data = example, mtry = 3)
print(rf1)
print(rf2)
This will take some time to compute and the print results will claim that the random forest with an interaction term given explained 99.67% of the variance while the random forest with the interaction term explained 99.93% of the variance.
It is hard to compare within-sample $R^2$ to Out-of-bag-performance, so we predict our test data set with all four of our models we have so far:
linear1.on.test <- predict(linear1, data = test)
linear2.on.test <- predict(linear2, data = test)
rf1.on.test <- predict(rf1, data = test)
rf2.on.test <- predict(rf2, data = test)
In a next step we compute the absolute residuals and plot them as boxplots:
boxplot(linear1.on.test - test$y, linear2.on.test - test$y, rf1.on.test - test$y, rf2.on.test - test$y,
ylim=c(-7, 7), xaxt="n", ylab = "residuals")
axis(1, at = 1:4, labels = c("linear with I", "linear w/o I", "rf w/o I", "rf with I"))
So the linear model with interaction term fits best to how the data was constructed and thus predicts best. The linear model without interaction term has no flexibility to adapt and has the worst predictive value of all models.
For the random forests we see quite similar results with and without the interaction term. Stating the interaction term explicitely appears to be helpfull but the model without it is flexible enough to give good predictions without that.
Real world interactions will rarely follow the rules of exact multiplication so the small advantage of computing the interaction term for the model may be even smaller for real world interactions.
All of this will be influenced by sample size, number of features, tuning parameters and so on but the short take away message is that whilst feature building is a good thing, random forest can detect and make use of interactions even if they are not stated in the call to randomForest.
Feel free to run this code with different set.seed values, compute RMSEs etc. | Are Random Forests good at detecting interaction terms?
@gunes has already given the answer, that random forests do work well with interactions. It may help to give a practical example, though. For that, we will need some toy data
set.seed(2021)
n = 5000
x |
30,536 | Can time series models be applied to synthetic data | Applying time series techniques to simulated data is quite common, and it can be very enlightening indeed.
For example: pick an ARIMA model of reasonable order with well-behaved parameters, simulate it and apply some kind of automatic ARIMA fitter to the simulated series (like forecast::auto.arima() in R). How often will the original model be recovered? Answer: surprisingly rarely. It's simulations like these, where you know the ground truth, that can teach you a lot of humility.
Then again, to be honest, if a paper only applies its new method to simulated data, but not to real time series, I tend to lose interest. It's very easy to tweak a simulation in a way that supports your pet theory. With real data, not so much. (Yes, we can select datasets and overfit to the holdout data.)
So: applying methods to simulated data should be part of every time series analyst's toolbox. Among other tools.
Let us look at a little example. We will simulate $n=200$ data points from an ARIMA(1,1,1) process, with an AR(1) coefficient of $\phi_1=0.5$, an MA(1) coefficient of $\theta_1=-0.3$ and the default noise of $\epsilon\sim N(0,1)$. We then apply auto.arima() to the simulated series and ask whether auto.arima() at least gets the order (1,1,1) right. We do this whole process 1,000 times:
require(forecast)
n_sims <- 1e3
n_obs <- 200
model_true <- list(ar=0.5,ma=-0.3,order=c(1,1,1))
correct <- rep(FALSE,n_sims)
pb <- winProgressBar(max=n_sims)
for ( ii in 1:n_sims ) {
setWinProgressBar(pb,ii,paste(ii,"of",n_sims))
set.seed(ii) # for reproducibility
sim <- arima.sim(model=model_true,n=n_obs)
model <- auto.arima(sim)
correct[ii] <- isTRUE(all.equal(model$arma,c(1,1,0,0,1,1,0)))
# this corresponds to ARIMA(1,1,1), see ?arima
}
close(pb)
summary(correct)
It turns out that in just 105 cases did we even get the correct order. I think this teaches us something about the inherent difficulty in even identifying the correct ARIMA order.
Of course, if we increase the parameter values, reduce the noise or increase the length of the series, we would be right more often.
The next step would be not to pluck parameter values out of thin air, as I did here. Instead, we could take a time series that is "typical" for the application we have in mind. Fit an ARIMA model to it, and then use the fitted order, parameters and residual variance as inputs to this simulation, i.e., treat the fitted ARIMA model as if it were the true data generating process. You will still be surprised at how rarely such a ("realistic"!) DGP will actually be found by auto.arima(). (Which is the gold standard in ARIMA model fitting, I hasten to say.) And of course, you can do similar exercises with Exponential Smoothing and/or other time series methods.
And this is the reason why simulated series have their place in time series analysis. | Can time series models be applied to synthetic data | Applying time series techniques to simulated data is quite common, and it can be very enlightening indeed.
For example: pick an ARIMA model of reasonable order with well-behaved parameters, simulate i | Can time series models be applied to synthetic data
Applying time series techniques to simulated data is quite common, and it can be very enlightening indeed.
For example: pick an ARIMA model of reasonable order with well-behaved parameters, simulate it and apply some kind of automatic ARIMA fitter to the simulated series (like forecast::auto.arima() in R). How often will the original model be recovered? Answer: surprisingly rarely. It's simulations like these, where you know the ground truth, that can teach you a lot of humility.
Then again, to be honest, if a paper only applies its new method to simulated data, but not to real time series, I tend to lose interest. It's very easy to tweak a simulation in a way that supports your pet theory. With real data, not so much. (Yes, we can select datasets and overfit to the holdout data.)
So: applying methods to simulated data should be part of every time series analyst's toolbox. Among other tools.
Let us look at a little example. We will simulate $n=200$ data points from an ARIMA(1,1,1) process, with an AR(1) coefficient of $\phi_1=0.5$, an MA(1) coefficient of $\theta_1=-0.3$ and the default noise of $\epsilon\sim N(0,1)$. We then apply auto.arima() to the simulated series and ask whether auto.arima() at least gets the order (1,1,1) right. We do this whole process 1,000 times:
require(forecast)
n_sims <- 1e3
n_obs <- 200
model_true <- list(ar=0.5,ma=-0.3,order=c(1,1,1))
correct <- rep(FALSE,n_sims)
pb <- winProgressBar(max=n_sims)
for ( ii in 1:n_sims ) {
setWinProgressBar(pb,ii,paste(ii,"of",n_sims))
set.seed(ii) # for reproducibility
sim <- arima.sim(model=model_true,n=n_obs)
model <- auto.arima(sim)
correct[ii] <- isTRUE(all.equal(model$arma,c(1,1,0,0,1,1,0)))
# this corresponds to ARIMA(1,1,1), see ?arima
}
close(pb)
summary(correct)
It turns out that in just 105 cases did we even get the correct order. I think this teaches us something about the inherent difficulty in even identifying the correct ARIMA order.
Of course, if we increase the parameter values, reduce the noise or increase the length of the series, we would be right more often.
The next step would be not to pluck parameter values out of thin air, as I did here. Instead, we could take a time series that is "typical" for the application we have in mind. Fit an ARIMA model to it, and then use the fitted order, parameters and residual variance as inputs to this simulation, i.e., treat the fitted ARIMA model as if it were the true data generating process. You will still be surprised at how rarely such a ("realistic"!) DGP will actually be found by auto.arima(). (Which is the gold standard in ARIMA model fitting, I hasten to say.) And of course, you can do similar exercises with Exponential Smoothing and/or other time series methods.
And this is the reason why simulated series have their place in time series analysis. | Can time series models be applied to synthetic data
Applying time series techniques to simulated data is quite common, and it can be very enlightening indeed.
For example: pick an ARIMA model of reasonable order with well-behaved parameters, simulate i |
30,537 | Can time series models be applied to synthetic data | From my experience, it is common to test methods with synthetic data. I think doing so allows one to really focus on the strengths and weaknesses of a model. Then it is another question whether or not those tests and the synthetic data reflect real world scenarios well enough to make the method actually useful. But it has been certainly done.
As a reference, I can provide "A note on the Mean Absolute Scaled Error" by Philip Hans Franses (link), but I'm sure there are plenty of similar papers. | Can time series models be applied to synthetic data | From my experience, it is common to test methods with synthetic data. I think doing so allows one to really focus on the strengths and weaknesses of a model. Then it is another question whether or not | Can time series models be applied to synthetic data
From my experience, it is common to test methods with synthetic data. I think doing so allows one to really focus on the strengths and weaknesses of a model. Then it is another question whether or not those tests and the synthetic data reflect real world scenarios well enough to make the method actually useful. But it has been certainly done.
As a reference, I can provide "A note on the Mean Absolute Scaled Error" by Philip Hans Franses (link), but I'm sure there are plenty of similar papers. | Can time series models be applied to synthetic data
From my experience, it is common to test methods with synthetic data. I think doing so allows one to really focus on the strengths and weaknesses of a model. Then it is another question whether or not |
30,538 | Is there a difference between LASSO regularisation and LASSO penalisation? | In mathematics, statistics and physics, regularisation is the process of adding information in order to make an ill-posed problem soluble and well-behaved or to force a problem to exhibit some property known to be satisfied by suitable solutions; it particularly applies to objective functions in ill-posed optimisation problems.
With regard to the lasso, the added information pertains to the $\ell_1-$norm of some parameter vector and, due to convexity and the geometry of the extreme points of a polyhedron specified by a constraint of the form $$ \sum_{j=1}^{p} \lvert \beta_j \rvert \leq t,$$ with $t>0$ large enough, this comes down to specifying that some of the parameters $\beta_j$ vanish.
Whilst having the same meaning, the term penalisation is, to my knowledge, mostly used by statisticians and data scientists ; it has the merit of highlighting the fact that one regularises a problem by penalising solutions that stray from a certain desirable behaviour (e.g. sparsity). | Is there a difference between LASSO regularisation and LASSO penalisation? | In mathematics, statistics and physics, regularisation is the process of adding information in order to make an ill-posed problem soluble and well-behaved or to force a problem to exhibit some propert | Is there a difference between LASSO regularisation and LASSO penalisation?
In mathematics, statistics and physics, regularisation is the process of adding information in order to make an ill-posed problem soluble and well-behaved or to force a problem to exhibit some property known to be satisfied by suitable solutions; it particularly applies to objective functions in ill-posed optimisation problems.
With regard to the lasso, the added information pertains to the $\ell_1-$norm of some parameter vector and, due to convexity and the geometry of the extreme points of a polyhedron specified by a constraint of the form $$ \sum_{j=1}^{p} \lvert \beta_j \rvert \leq t,$$ with $t>0$ large enough, this comes down to specifying that some of the parameters $\beta_j$ vanish.
Whilst having the same meaning, the term penalisation is, to my knowledge, mostly used by statisticians and data scientists ; it has the merit of highlighting the fact that one regularises a problem by penalising solutions that stray from a certain desirable behaviour (e.g. sparsity). | Is there a difference between LASSO regularisation and LASSO penalisation?
In mathematics, statistics and physics, regularisation is the process of adding information in order to make an ill-posed problem soluble and well-behaved or to force a problem to exhibit some propert |
30,539 | Statsmodels Logistic Regression: Adding Intercept? | It is almost always necessary. I say almost always because it changes the interpretation of the other coefficients. Leaving out the column of 1s may be fine when you are regressing the outcome on categorical predictors, but often we include continuous predictors.
Let's compare a logistic regression with and without the intercept when we have a continuous predictor. Assume the data have been mean centered. Without the column of 1s, the model looks like
$$ \operatorname{logit}\left( \dfrac{p(x)}{1-p(x)} \right) = \beta x $$
When $x=0$ (i.e. when the covariate is equal to the sample mean), then the log odds of the outcome is 0, which corresponds to $p(x) = 0.5$. So what this says is that when $x$ is at the sample mean, then the probability of a success is 50% (which seems a bit restrictive).
If we do have the intercept, the model is then
$$ \operatorname{logit}\left( \dfrac{p(x)}{1-p(x)} \right) = \beta_0 + \beta x $$
Now, when $x=0$ the log odds is equal to $\beta_0$ which we can freely estimate from the data.
In short, unless you have good reason to do so, include the column of 1s. | Statsmodels Logistic Regression: Adding Intercept? | It is almost always necessary. I say almost always because it changes the interpretation of the other coefficients. Leaving out the column of 1s may be fine when you are regressing the outcome on cat | Statsmodels Logistic Regression: Adding Intercept?
It is almost always necessary. I say almost always because it changes the interpretation of the other coefficients. Leaving out the column of 1s may be fine when you are regressing the outcome on categorical predictors, but often we include continuous predictors.
Let's compare a logistic regression with and without the intercept when we have a continuous predictor. Assume the data have been mean centered. Without the column of 1s, the model looks like
$$ \operatorname{logit}\left( \dfrac{p(x)}{1-p(x)} \right) = \beta x $$
When $x=0$ (i.e. when the covariate is equal to the sample mean), then the log odds of the outcome is 0, which corresponds to $p(x) = 0.5$. So what this says is that when $x$ is at the sample mean, then the probability of a success is 50% (which seems a bit restrictive).
If we do have the intercept, the model is then
$$ \operatorname{logit}\left( \dfrac{p(x)}{1-p(x)} \right) = \beta_0 + \beta x $$
Now, when $x=0$ the log odds is equal to $\beta_0$ which we can freely estimate from the data.
In short, unless you have good reason to do so, include the column of 1s. | Statsmodels Logistic Regression: Adding Intercept?
It is almost always necessary. I say almost always because it changes the interpretation of the other coefficients. Leaving out the column of 1s may be fine when you are regressing the outcome on cat |
30,540 | Statsmodels Logistic Regression: Adding Intercept? | It appears that you may not have to manually include a constant for there to be an intercept in the model. From looking at the default parameters in the following class, there is a boolean parameter that is defaulted to True for intercept.
class sklearn.linear_model.LogisticRegression(penalty='l2', *, dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None, solver='lbfgs', max_iter=100, multi_class='auto', verbose=0, warm_start=False, n_jobs=None, l1_ratio=None)
The explanation given for that parameter is as follows:
fit_interceptbool, default=True: Specifies if a constant (a.k.a.
bias or intercept) should be added to the decision function.
Source: sklearn.linear_model.LogisticRegression | Statsmodels Logistic Regression: Adding Intercept? | It appears that you may not have to manually include a constant for there to be an intercept in the model. From looking at the default parameters in the following class, there is a boolean parameter t | Statsmodels Logistic Regression: Adding Intercept?
It appears that you may not have to manually include a constant for there to be an intercept in the model. From looking at the default parameters in the following class, there is a boolean parameter that is defaulted to True for intercept.
class sklearn.linear_model.LogisticRegression(penalty='l2', *, dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None, solver='lbfgs', max_iter=100, multi_class='auto', verbose=0, warm_start=False, n_jobs=None, l1_ratio=None)
The explanation given for that parameter is as follows:
fit_interceptbool, default=True: Specifies if a constant (a.k.a.
bias or intercept) should be added to the decision function.
Source: sklearn.linear_model.LogisticRegression | Statsmodels Logistic Regression: Adding Intercept?
It appears that you may not have to manually include a constant for there to be an intercept in the model. From looking at the default parameters in the following class, there is a boolean parameter t |
30,541 | Adjusting probability threshold for sklearn's logistic regression model | There is almost never a good reason to do this! As Kjetil said above, see here.
You should be able to get the probability outputs from ‘predict_proba’, then you can just write
decisions = (model.predict_proba() >= mythreshold).astype(int)
Note as stated that logistic regression itself does not have a threshold. However sklearn does have a “decision function” that implements the threshold directly in the “predict” function, unfortunately. Hence they consider logistic regression a classifier, unfortunately. | Adjusting probability threshold for sklearn's logistic regression model | There is almost never a good reason to do this! As Kjetil said above, see here.
You should be able to get the probability outputs from ‘predict_proba’, then you can just write
decisions = (model.pred | Adjusting probability threshold for sklearn's logistic regression model
There is almost never a good reason to do this! As Kjetil said above, see here.
You should be able to get the probability outputs from ‘predict_proba’, then you can just write
decisions = (model.predict_proba() >= mythreshold).astype(int)
Note as stated that logistic regression itself does not have a threshold. However sklearn does have a “decision function” that implements the threshold directly in the “predict” function, unfortunately. Hence they consider logistic regression a classifier, unfortunately. | Adjusting probability threshold for sklearn's logistic regression model
There is almost never a good reason to do this! As Kjetil said above, see here.
You should be able to get the probability outputs from ‘predict_proba’, then you can just write
decisions = (model.pred |
30,542 | Adjusting probability threshold for sklearn's logistic regression model | Let's say that your customized threshold is 0.6. It should be:
y_pred_new_threshold = (logreg.predict_proba(X_test)[:,1]>=0.6).astype(int) | Adjusting probability threshold for sklearn's logistic regression model | Let's say that your customized threshold is 0.6. It should be:
y_pred_new_threshold = (logreg.predict_proba(X_test)[:,1]>=0.6).astype(int) | Adjusting probability threshold for sklearn's logistic regression model
Let's say that your customized threshold is 0.6. It should be:
y_pred_new_threshold = (logreg.predict_proba(X_test)[:,1]>=0.6).astype(int) | Adjusting probability threshold for sklearn's logistic regression model
Let's say that your customized threshold is 0.6. It should be:
y_pred_new_threshold = (logreg.predict_proba(X_test)[:,1]>=0.6).astype(int) |
30,543 | Quantify the similarity of bags of words | Let me address this by describing the four maybe most common similarity metrics for bags of words and document (count) vectors in general, that is comparing collections of discrete variables.
Cosine similarity is used most frequently in general, but you should always measure first and make sure that no other similarity would produce better results for your problem, evaluating if you can use some of the more complex measures. Except for Jaccard's set similarity, you can (indeed, might want to) apply some form of TF-IDF reweighing (ff) to your document counts/vectors before using these measures. The TF weighting term might even be Okapi-BM25, and the IDF term replaced with corpus entropy, but in the end has little to do with the original question at hand (BoW similarity measures).
Note that the first measure, Jaccard similarity, suffers from a significant downside: It is the most heavily affected by length differences among documents, and does not take word frequencies into account, either. For Cosine similarity and the $\chi^2$-distance you can (or rather, should) adjust the vectors by normalizing your vectors to unit length (i.e., in addition to TF-IDF re-weighting). But even then, shorter documents will have more sparse counts (i.e., more zeros in their vectors) compared to longer documents, for obvious reasons. (One way around that sparsity difference could be to only include words above some minimum cutoff, using a dynamic cutoff value that increases with document length.)
Before we go over the measures, it should be mentioned that this discussion focuses only on symmetric measures, while asymmetric measure exist as well (particularly, the KL-divergence).
1. Jaccard similarity $J$
This is the most simplistic metric: Collect the set of all words in both documents (tweets, sentences, ...), ${A}$ and ${B}$, and measure the fraction of words the two sets have in common:
$$
J_{A,B} = \frac{|{A} \cap {B}|}{|{A} \cup {B}|}
$$
This measure also works for words (and documents) by collecting sets of character (or word) $n$-grams, where $n$ typically is 1, 2, and maybe 3.
Notice that Jaccard similarity has its limits, though; If the sequence of $A$ had been $(x, y, z, x, y, z, x, y, z)$ and that of $B$ were just $(x, y, z)$, their Jaccard similarity nonetheless is perfect (i.e., $1.0$), unless you use the n-gram "trick" just described.
Finally, it should be noted that the Dice coefficient $D$ is a slightly more involved version of the Jaccard similarity, but also does not take word counts into account, and it can easily be calculated from $J$ as: $D = \frac{2J}{1+J}$.
2. Cosine similarity $\alpha$
Cosine similarity is probably by far the most popular metric. Collect ordered sets of all word counts from both documents (tweets, sentences, ...), $A$ and $B$, that is, effectively, two "document vectors" $\vec{a}$ and $\vec{b}$, and measure the Cosine angle between the two vectors:
$$
\alpha_{A,B} = \frac{\vec{a} \cdot \vec{b}}{|\vec{a}||\vec{b}|} = \frac{\sum{a_i b_i}}{\sqrt{\sum{a_i^2}}\sqrt{\sum{b_i^2}}}
$$
Now, because you can normalize your vectors to unit vectors (i.e., the $|\vec{z}|$ parts) before doing this calculation, you actually only need to calculate the dot product between the two vectors to calculate the similarity - which is nothing more than the sum of the products of all pairs. The dot product can be calculated particularly efficient on modern CPUs.
3. Spearman's rank correlation coefficient $\rho$
Instead of using the counts of each word, you order the words of each document by their counts and thereby assign a rank to each word, for either document, $A$ and $B$. That therefor saves you from having to length-normalize the document vectors. Let's use the Wikipedia nomenclature and call the rank generating function (that finds the rank for a given word $i$ from a (word, count) tuple list $X$, or a document vector $\vec{x}$) $rg$. Second, lets define that distance $d$ between the same word $i$ among the two documents as $d_i = rg(A, i) - rg(B, i)$. That is, $d$ the difference among the two ranks, zero if equal, and non-zero otherwise. With this, the coefficient can be calculated from whole numbers as:
$$
\rho_{A,B} = 1 - \frac{6-\sum d_i^2}{n(n^2-1)}
$$
Note that this formulation has a strong requirement: All ranks must be distinct, so even for ties (if two words have the same count in the same document), you need to assign them distinct ranks; I suggest, you use alphanumeric ordering in those cases. And for words that only occur in one document, you place them in the last position(s) in the other document (again using the same alphanumeric ordering). It should be noted that by re-weighting your counts with TF-IDF before calculating this similarity, you can have far less ties among words with non-zero counts.
If you want to maintain ties (i.e., do not want to "artificially" make all ranks distinct) or if you are using cutoffs to remove some of the (word, count) tuples or selecting only the top $n$ most frequent words, however, you should be using the standard formula for $\rho$ (and define $rg$ as a function that generates the complete rank vector for all your document's alphanumerically ordered (word, count) tuples $X$ in the document vector $\vec{x}$):
$$
\rho_{A,B} = \frac{cov(rg(\vec{a}), rg(\vec{b}))}{\sigma_{rg_A} \sigma_{rg_B}}
$$
Where $cov$ is the covariance among the ranks of the the two documents, and $\sigma_{rg_X}$ is the standard deviation of the (possibly cut-off) ranks $rg$ (with ties) of document $X$.
In a nutshell, you could see this approach as half-way between the Jaccard similarity and the Cosine similarity. Particularly, it is (a bit more - see next measure) robust against distributional differences between word counts among documents, while still taking overall word frequency into account. However, in most works, Cosine similarity seems to out-perform Spearman's rank correction - but you should test this, and might get good results with TF-IDF and Spearman, while, as said, this approach does not require you to do length normalization of your document vectors.
4. (Pearson's $\chi^2$ test-based) $\chi^2$ distance
So far, all our similarity measures assume the homogeneity of word frequencies, that is assuming that the variances of our word counts are equal among all documents of a collection (a "corpus"), something that is (hopefully, kind of intuitively) not the case. That is, earlier, Kilgarriff (1997) had demonstrated that the $\chi^2$ is a better fit to compare word counts than our above measures. Note that if you are following current research, for corpus comparisons today (e.g., to do feature selection), however, you probably should be using the Bootstrap test instead of $\chi^2$.
Kilgarriff's $\chi^2$ comparison can be applied just as well to documents (by assuming that there are only two "classes", your two documents, and therefore, $d.f. = 1$), and due to its robustness it might be preferable over the similarity measures shown so far. Note that this approach gives you a distance so to convert this value to a similarity, you'd have to take its inverse (i.e., the larger this distance, the smaller the document similarity). Let us define the count of all words in a document $X$ as $n_X = \sum x_i$ and total of both documents $A$ and $B$ as $n = n_A + n_B$. Then, a $\chi^2$-statistic-based distance for two documents (document vectors) can be derived from Pearson's base formula $\sum \frac{(O_i-E_i)^2}{E_i}$ as:
$$
\chi^2_{A,B} = n \left[ \sum{ \frac{a_i^2}{n_A(a_i+b_i)} } + \sum{ \frac{b_i^2}{n_B(a_i+b_i)} } \right] - n
$$
However, this calculation is computationally far more costly to run, probably in itself explaining why most approaches stick to Cosine similarity, and even more so if you can verify that your classification/retrieval/clustering results don't gain from this latter distance measure. Also, as shown by the linked paper, this distance measure does not seem to out-compete Cosine similarity with TF-IDF reweighing. But note that the linked paper uses the "raw" term frequency counts to calculate this distance measure and compares that to TF-IDF re-weighted Cosine similarity. As discussed already, it usually is a good idea to first normalize the document vectors on their word counts (i.e., lengths) to get good results, i.e., transform $X / n_X$ first (and you might even try applying TF-IDF document vector re-weighting before that, too) in which case the above formula simplifies (a bit) to:
$$
\chi^2_{A,B} = 2 \left[ \sum{ \frac{a_i^2}{a_i+b_i} } + \sum{ \frac{b_i^2}{a_i+b_i} } \right] - 2
$$ | Quantify the similarity of bags of words | Let me address this by describing the four maybe most common similarity metrics for bags of words and document (count) vectors in general, that is comparing collections of discrete variables.
Cosine s | Quantify the similarity of bags of words
Let me address this by describing the four maybe most common similarity metrics for bags of words and document (count) vectors in general, that is comparing collections of discrete variables.
Cosine similarity is used most frequently in general, but you should always measure first and make sure that no other similarity would produce better results for your problem, evaluating if you can use some of the more complex measures. Except for Jaccard's set similarity, you can (indeed, might want to) apply some form of TF-IDF reweighing (ff) to your document counts/vectors before using these measures. The TF weighting term might even be Okapi-BM25, and the IDF term replaced with corpus entropy, but in the end has little to do with the original question at hand (BoW similarity measures).
Note that the first measure, Jaccard similarity, suffers from a significant downside: It is the most heavily affected by length differences among documents, and does not take word frequencies into account, either. For Cosine similarity and the $\chi^2$-distance you can (or rather, should) adjust the vectors by normalizing your vectors to unit length (i.e., in addition to TF-IDF re-weighting). But even then, shorter documents will have more sparse counts (i.e., more zeros in their vectors) compared to longer documents, for obvious reasons. (One way around that sparsity difference could be to only include words above some minimum cutoff, using a dynamic cutoff value that increases with document length.)
Before we go over the measures, it should be mentioned that this discussion focuses only on symmetric measures, while asymmetric measure exist as well (particularly, the KL-divergence).
1. Jaccard similarity $J$
This is the most simplistic metric: Collect the set of all words in both documents (tweets, sentences, ...), ${A}$ and ${B}$, and measure the fraction of words the two sets have in common:
$$
J_{A,B} = \frac{|{A} \cap {B}|}{|{A} \cup {B}|}
$$
This measure also works for words (and documents) by collecting sets of character (or word) $n$-grams, where $n$ typically is 1, 2, and maybe 3.
Notice that Jaccard similarity has its limits, though; If the sequence of $A$ had been $(x, y, z, x, y, z, x, y, z)$ and that of $B$ were just $(x, y, z)$, their Jaccard similarity nonetheless is perfect (i.e., $1.0$), unless you use the n-gram "trick" just described.
Finally, it should be noted that the Dice coefficient $D$ is a slightly more involved version of the Jaccard similarity, but also does not take word counts into account, and it can easily be calculated from $J$ as: $D = \frac{2J}{1+J}$.
2. Cosine similarity $\alpha$
Cosine similarity is probably by far the most popular metric. Collect ordered sets of all word counts from both documents (tweets, sentences, ...), $A$ and $B$, that is, effectively, two "document vectors" $\vec{a}$ and $\vec{b}$, and measure the Cosine angle between the two vectors:
$$
\alpha_{A,B} = \frac{\vec{a} \cdot \vec{b}}{|\vec{a}||\vec{b}|} = \frac{\sum{a_i b_i}}{\sqrt{\sum{a_i^2}}\sqrt{\sum{b_i^2}}}
$$
Now, because you can normalize your vectors to unit vectors (i.e., the $|\vec{z}|$ parts) before doing this calculation, you actually only need to calculate the dot product between the two vectors to calculate the similarity - which is nothing more than the sum of the products of all pairs. The dot product can be calculated particularly efficient on modern CPUs.
3. Spearman's rank correlation coefficient $\rho$
Instead of using the counts of each word, you order the words of each document by their counts and thereby assign a rank to each word, for either document, $A$ and $B$. That therefor saves you from having to length-normalize the document vectors. Let's use the Wikipedia nomenclature and call the rank generating function (that finds the rank for a given word $i$ from a (word, count) tuple list $X$, or a document vector $\vec{x}$) $rg$. Second, lets define that distance $d$ between the same word $i$ among the two documents as $d_i = rg(A, i) - rg(B, i)$. That is, $d$ the difference among the two ranks, zero if equal, and non-zero otherwise. With this, the coefficient can be calculated from whole numbers as:
$$
\rho_{A,B} = 1 - \frac{6-\sum d_i^2}{n(n^2-1)}
$$
Note that this formulation has a strong requirement: All ranks must be distinct, so even for ties (if two words have the same count in the same document), you need to assign them distinct ranks; I suggest, you use alphanumeric ordering in those cases. And for words that only occur in one document, you place them in the last position(s) in the other document (again using the same alphanumeric ordering). It should be noted that by re-weighting your counts with TF-IDF before calculating this similarity, you can have far less ties among words with non-zero counts.
If you want to maintain ties (i.e., do not want to "artificially" make all ranks distinct) or if you are using cutoffs to remove some of the (word, count) tuples or selecting only the top $n$ most frequent words, however, you should be using the standard formula for $\rho$ (and define $rg$ as a function that generates the complete rank vector for all your document's alphanumerically ordered (word, count) tuples $X$ in the document vector $\vec{x}$):
$$
\rho_{A,B} = \frac{cov(rg(\vec{a}), rg(\vec{b}))}{\sigma_{rg_A} \sigma_{rg_B}}
$$
Where $cov$ is the covariance among the ranks of the the two documents, and $\sigma_{rg_X}$ is the standard deviation of the (possibly cut-off) ranks $rg$ (with ties) of document $X$.
In a nutshell, you could see this approach as half-way between the Jaccard similarity and the Cosine similarity. Particularly, it is (a bit more - see next measure) robust against distributional differences between word counts among documents, while still taking overall word frequency into account. However, in most works, Cosine similarity seems to out-perform Spearman's rank correction - but you should test this, and might get good results with TF-IDF and Spearman, while, as said, this approach does not require you to do length normalization of your document vectors.
4. (Pearson's $\chi^2$ test-based) $\chi^2$ distance
So far, all our similarity measures assume the homogeneity of word frequencies, that is assuming that the variances of our word counts are equal among all documents of a collection (a "corpus"), something that is (hopefully, kind of intuitively) not the case. That is, earlier, Kilgarriff (1997) had demonstrated that the $\chi^2$ is a better fit to compare word counts than our above measures. Note that if you are following current research, for corpus comparisons today (e.g., to do feature selection), however, you probably should be using the Bootstrap test instead of $\chi^2$.
Kilgarriff's $\chi^2$ comparison can be applied just as well to documents (by assuming that there are only two "classes", your two documents, and therefore, $d.f. = 1$), and due to its robustness it might be preferable over the similarity measures shown so far. Note that this approach gives you a distance so to convert this value to a similarity, you'd have to take its inverse (i.e., the larger this distance, the smaller the document similarity). Let us define the count of all words in a document $X$ as $n_X = \sum x_i$ and total of both documents $A$ and $B$ as $n = n_A + n_B$. Then, a $\chi^2$-statistic-based distance for two documents (document vectors) can be derived from Pearson's base formula $\sum \frac{(O_i-E_i)^2}{E_i}$ as:
$$
\chi^2_{A,B} = n \left[ \sum{ \frac{a_i^2}{n_A(a_i+b_i)} } + \sum{ \frac{b_i^2}{n_B(a_i+b_i)} } \right] - n
$$
However, this calculation is computationally far more costly to run, probably in itself explaining why most approaches stick to Cosine similarity, and even more so if you can verify that your classification/retrieval/clustering results don't gain from this latter distance measure. Also, as shown by the linked paper, this distance measure does not seem to out-compete Cosine similarity with TF-IDF reweighing. But note that the linked paper uses the "raw" term frequency counts to calculate this distance measure and compares that to TF-IDF re-weighted Cosine similarity. As discussed already, it usually is a good idea to first normalize the document vectors on their word counts (i.e., lengths) to get good results, i.e., transform $X / n_X$ first (and you might even try applying TF-IDF document vector re-weighting before that, too) in which case the above formula simplifies (a bit) to:
$$
\chi^2_{A,B} = 2 \left[ \sum{ \frac{a_i^2}{a_i+b_i} } + \sum{ \frac{b_i^2}{a_i+b_i} } \right] - 2
$$ | Quantify the similarity of bags of words
Let me address this by describing the four maybe most common similarity metrics for bags of words and document (count) vectors in general, that is comparing collections of discrete variables.
Cosine s |
30,544 | MDS on large dataset (R or Python) | It would take more than a terabyte just to store a dense distance matrix of that size, using double precision floating point numbers. It's probably not feasible to attack such a large-scale problem head-on using a standard MDS algorithm. The runtime scales as $O(n^3)$, and you may not even be able to fit the distance matrix in memory on a single machine. Depending on your situation, you may be able to work around it. How to do this depends on your specific data and problem, but here are a few examples:
1) PCA is equivalent to classical MDS using the Euclidean distance metric. So, if this is the type of MDS you want to perform, you can use PCA instead. An additional requirement is that you have access to the original data points as vectors, rather than just the distance matrix. There are many algorithms for efficiently running PCA on enormous datasets.
2) Use an approximate form of MDS. This approach could work if you want to perform classical MDS. It doesn't require a Euclidean distance metric or a vector space representation of the data (access to the distances is all that's required). Landmark MDS is a good example. The first step is to choose a smaller set of 'landmark points' that represent the full data set. These can be obtained simply by sampling randomly from the data, or using a quick, greedy algorithm to optimize them a little more. Clustering could also be used in principle, but it's computationally expensive and not necessary. Classical MDS is performed on the landmark points to embed them in a vector space. The classical MDS results for the landmark points are then used to map the full dataset into the embedding space. Although not originally formulated as such, it turns out that Landmark MDS works by using the Nyström approximation, which is a way to approximate the eigenvalues/eigenvectors of a large matrix using a smaller submatrix.
3) If you want to perform nonclassical MDS, methods like Landmark MDS won't work. This is because nonclassical variants of MDS are solved iteratively using optimization algorithms, rather than by solving an eigenvalue problem. It might work to take the following approach instead: a) Select a representative subsample of the data. b) Use your chosen flavor of MDS to embed these points into a vector space. c) Using the subsampled data points as exemplars, learn a mapping into the embedding space using a nonlinear regression method. Proper care would be needed to learn a good mapping, not overfit, etc. d) Use the learned mapping to obtain an embedding for the entire data set. I recall seeing a couple papers describe this kind of approach as a way to perform out-of-sample generalization for nonlinear dimensionality reduction algorithms in general. But, it seems to me that it could also be used as a way to efficiently approximate nonclassical MDS. It's possible that more specialized solutions exist; if so I'd be glad to hear about them.
4) Parallelization could be used to solve the full problem if absolutely necessary. For example, for classical MDS, you could distribute blocks of the distance matrix across machines, then use parallel/distributed matrix operations and eigensolver to perform MDS. Some scheme could probably be imagined for nonclassical MDS. But, this could be a hefty undertaking, and it's quite possible that approximate MDS would work well enough. So, that's a better place to start.
References:
De Silva and Tenenbaum (2004). Sparse multidimensional scaling using landmark points.
Platt (2005). FastMap, MetricMap, and Landmark MDS are all Nystrom Algorithms. | MDS on large dataset (R or Python) | It would take more than a terabyte just to store a dense distance matrix of that size, using double precision floating point numbers. It's probably not feasible to attack such a large-scale problem he | MDS on large dataset (R or Python)
It would take more than a terabyte just to store a dense distance matrix of that size, using double precision floating point numbers. It's probably not feasible to attack such a large-scale problem head-on using a standard MDS algorithm. The runtime scales as $O(n^3)$, and you may not even be able to fit the distance matrix in memory on a single machine. Depending on your situation, you may be able to work around it. How to do this depends on your specific data and problem, but here are a few examples:
1) PCA is equivalent to classical MDS using the Euclidean distance metric. So, if this is the type of MDS you want to perform, you can use PCA instead. An additional requirement is that you have access to the original data points as vectors, rather than just the distance matrix. There are many algorithms for efficiently running PCA on enormous datasets.
2) Use an approximate form of MDS. This approach could work if you want to perform classical MDS. It doesn't require a Euclidean distance metric or a vector space representation of the data (access to the distances is all that's required). Landmark MDS is a good example. The first step is to choose a smaller set of 'landmark points' that represent the full data set. These can be obtained simply by sampling randomly from the data, or using a quick, greedy algorithm to optimize them a little more. Clustering could also be used in principle, but it's computationally expensive and not necessary. Classical MDS is performed on the landmark points to embed them in a vector space. The classical MDS results for the landmark points are then used to map the full dataset into the embedding space. Although not originally formulated as such, it turns out that Landmark MDS works by using the Nyström approximation, which is a way to approximate the eigenvalues/eigenvectors of a large matrix using a smaller submatrix.
3) If you want to perform nonclassical MDS, methods like Landmark MDS won't work. This is because nonclassical variants of MDS are solved iteratively using optimization algorithms, rather than by solving an eigenvalue problem. It might work to take the following approach instead: a) Select a representative subsample of the data. b) Use your chosen flavor of MDS to embed these points into a vector space. c) Using the subsampled data points as exemplars, learn a mapping into the embedding space using a nonlinear regression method. Proper care would be needed to learn a good mapping, not overfit, etc. d) Use the learned mapping to obtain an embedding for the entire data set. I recall seeing a couple papers describe this kind of approach as a way to perform out-of-sample generalization for nonlinear dimensionality reduction algorithms in general. But, it seems to me that it could also be used as a way to efficiently approximate nonclassical MDS. It's possible that more specialized solutions exist; if so I'd be glad to hear about them.
4) Parallelization could be used to solve the full problem if absolutely necessary. For example, for classical MDS, you could distribute blocks of the distance matrix across machines, then use parallel/distributed matrix operations and eigensolver to perform MDS. Some scheme could probably be imagined for nonclassical MDS. But, this could be a hefty undertaking, and it's quite possible that approximate MDS would work well enough. So, that's a better place to start.
References:
De Silva and Tenenbaum (2004). Sparse multidimensional scaling using landmark points.
Platt (2005). FastMap, MetricMap, and Landmark MDS are all Nystrom Algorithms. | MDS on large dataset (R or Python)
It would take more than a terabyte just to store a dense distance matrix of that size, using double precision floating point numbers. It's probably not feasible to attack such a large-scale problem he |
30,545 | MDS on large dataset (R or Python) | If you want to perform MDS on such large datasets you would need to use a parallel implementation of MDS. You can find a parallel implementation of MDS based on MPI at [1]. But in order to run a 400000 ×× 400000 dataset you would need a large cluster or a super computer. I have used this with a dataset with 200000 x 200000 data matrix ( i used a 24 node supercomputer to run it, could be done with less but will take more time). There is also a version that runs on spark which you can use [2]. But the spark implementation is much slower than the MPI based implementation
[1] https://github.com/DSC-SPIDAL/damds
[2] https://github.com/DSC-SPIDAL/damds.spark | MDS on large dataset (R or Python) | If you want to perform MDS on such large datasets you would need to use a parallel implementation of MDS. You can find a parallel implementation of MDS based on MPI at [1]. But in order to run a 40000 | MDS on large dataset (R or Python)
If you want to perform MDS on such large datasets you would need to use a parallel implementation of MDS. You can find a parallel implementation of MDS based on MPI at [1]. But in order to run a 400000 ×× 400000 dataset you would need a large cluster or a super computer. I have used this with a dataset with 200000 x 200000 data matrix ( i used a 24 node supercomputer to run it, could be done with less but will take more time). There is also a version that runs on spark which you can use [2]. But the spark implementation is much slower than the MPI based implementation
[1] https://github.com/DSC-SPIDAL/damds
[2] https://github.com/DSC-SPIDAL/damds.spark | MDS on large dataset (R or Python)
If you want to perform MDS on such large datasets you would need to use a parallel implementation of MDS. You can find a parallel implementation of MDS based on MPI at [1]. But in order to run a 40000 |
30,546 | MDS on large dataset (R or Python) | I was experiencing severe performance issues with cmdscale(). After some digging I managed to find a java library called mdsj (https://www.inf.uni-konstanz.de/exalgo/software/mdsj/) that can receive a matrix in textfile format and output a multidimensional scaled version to a textfile. This can all be done in bash which can be called using R's system() function. I'll share my code here just in case anybody finds it useful:
saveMDS = function(daisy.mat){
write.table(daisy.mat, file=paste("./MDS/data.txt",sep=""), row.names=FALSE, col.names=FALSE)
system('bash -c "cd MDS; > data-MDS.txt;java -jar mdsj.jar data.txt data-MDS.txt"')
}
loadMDS = function(){
return(as.matrix(read.table("./MDS/data-MDS.txt",header=FALSE,sep=" ")))
}
data <- data.frame(x=runif(10000),y=runif(10000),z=runif(10000))
daisy.mat <- as.matrix(daisy(data[,c(1:3)], metric="gower"))
saveMDS(daisy.mat)
mds.data = loadMDS()
In this isntance, I have a folder called MDS in my working directory which the data text files are stored to.
Hope this helps! | MDS on large dataset (R or Python) | I was experiencing severe performance issues with cmdscale(). After some digging I managed to find a java library called mdsj (https://www.inf.uni-konstanz.de/exalgo/software/mdsj/) that can receive a | MDS on large dataset (R or Python)
I was experiencing severe performance issues with cmdscale(). After some digging I managed to find a java library called mdsj (https://www.inf.uni-konstanz.de/exalgo/software/mdsj/) that can receive a matrix in textfile format and output a multidimensional scaled version to a textfile. This can all be done in bash which can be called using R's system() function. I'll share my code here just in case anybody finds it useful:
saveMDS = function(daisy.mat){
write.table(daisy.mat, file=paste("./MDS/data.txt",sep=""), row.names=FALSE, col.names=FALSE)
system('bash -c "cd MDS; > data-MDS.txt;java -jar mdsj.jar data.txt data-MDS.txt"')
}
loadMDS = function(){
return(as.matrix(read.table("./MDS/data-MDS.txt",header=FALSE,sep=" ")))
}
data <- data.frame(x=runif(10000),y=runif(10000),z=runif(10000))
daisy.mat <- as.matrix(daisy(data[,c(1:3)], metric="gower"))
saveMDS(daisy.mat)
mds.data = loadMDS()
In this isntance, I have a folder called MDS in my working directory which the data text files are stored to.
Hope this helps! | MDS on large dataset (R or Python)
I was experiencing severe performance issues with cmdscale(). After some digging I managed to find a java library called mdsj (https://www.inf.uni-konstanz.de/exalgo/software/mdsj/) that can receive a |
30,547 | Does a statistically significant correlation always give predictive power? | In regression, the p-value of a coeficient is the result of performing a hypothesis test about correlation, with the null hypothesis being that the correlation equals zero. Having a statistically significant correlation just means that we have a small p-value; and a very small p-value means that we can be very sure that the correlation is not zero. However, please notice that being sure the correlation is different from zero doesn't tell us anything about how large the correlation is - and it can be very small.
A very small p-value with a small correlation just tells us that we can be sure that our independent variable explains a small part of the variance of our response, and therefore it has very little predictive power.
In summary, it's possible to get a correlation that is both statistically significant and very small. In addition to possible, it's quite common when we have large samples.
Edit to make an addition: This is just an occurrence of the quite common phenomenon of getting a result with large statistical significance but tiny practical significance, that often happens when sample size is large.
For example, when doing a t-test to assess if a drug reduces probability of cancer, we might get a p-value of 0.00001 for a reduction larger than zero at the same time we estimate a reduction of probability of 0.000000001%. We could be very sure that there is a reduction of probability of cancer (based on our p-value) but for any practical purpose that reduction is so tiny that we can see the drug as having no effect.
With correlation it's the same: small p-value and small correlation makes us sure that correlation exists but it's small. However, sometimes correlation is big enough to have practical meaning (independent variable explains a sizeable part of the variance of the dependent variable) but not big enough to have predictive power. | Does a statistically significant correlation always give predictive power? | In regression, the p-value of a coeficient is the result of performing a hypothesis test about correlation, with the null hypothesis being that the correlation equals zero. Having a statistically sign | Does a statistically significant correlation always give predictive power?
In regression, the p-value of a coeficient is the result of performing a hypothesis test about correlation, with the null hypothesis being that the correlation equals zero. Having a statistically significant correlation just means that we have a small p-value; and a very small p-value means that we can be very sure that the correlation is not zero. However, please notice that being sure the correlation is different from zero doesn't tell us anything about how large the correlation is - and it can be very small.
A very small p-value with a small correlation just tells us that we can be sure that our independent variable explains a small part of the variance of our response, and therefore it has very little predictive power.
In summary, it's possible to get a correlation that is both statistically significant and very small. In addition to possible, it's quite common when we have large samples.
Edit to make an addition: This is just an occurrence of the quite common phenomenon of getting a result with large statistical significance but tiny practical significance, that often happens when sample size is large.
For example, when doing a t-test to assess if a drug reduces probability of cancer, we might get a p-value of 0.00001 for a reduction larger than zero at the same time we estimate a reduction of probability of 0.000000001%. We could be very sure that there is a reduction of probability of cancer (based on our p-value) but for any practical purpose that reduction is so tiny that we can see the drug as having no effect.
With correlation it's the same: small p-value and small correlation makes us sure that correlation exists but it's small. However, sometimes correlation is big enough to have practical meaning (independent variable explains a sizeable part of the variance of the dependent variable) but not big enough to have predictive power. | Does a statistically significant correlation always give predictive power?
In regression, the p-value of a coeficient is the result of performing a hypothesis test about correlation, with the null hypothesis being that the correlation equals zero. Having a statistically sign |
30,548 | Does a statistically significant correlation always give predictive power? | No. Correlation measures linear relationship between two variables, so if the relationship is not linear it becomes useless. You can easily produce examples where variables are strongly correlated ($r = 0.58; p < 0.001$) while the fit of the regression line to such data is far from "accurate". | Does a statistically significant correlation always give predictive power? | No. Correlation measures linear relationship between two variables, so if the relationship is not linear it becomes useless. You can easily produce examples where variables are strongly correlated ($r | Does a statistically significant correlation always give predictive power?
No. Correlation measures linear relationship between two variables, so if the relationship is not linear it becomes useless. You can easily produce examples where variables are strongly correlated ($r = 0.58; p < 0.001$) while the fit of the regression line to such data is far from "accurate". | Does a statistically significant correlation always give predictive power?
No. Correlation measures linear relationship between two variables, so if the relationship is not linear it becomes useless. You can easily produce examples where variables are strongly correlated ($r |
30,549 | Does a statistically significant correlation always give predictive power? | Late on the post, but to help future generations I will respond. In short, the answer is no. Statistical significance does not tell the researcher anything about a model's predictive ability.
The definition of p-values makes this clear. A p-value represents how likely it is that you the researcher observed a given data set under the assumption that the null hypothesis is true. So even if you reject the null, you really cannot say anything about which model is better at predicting, only that what you observed is more or less likely given the null. A super common mistake is that people assume rejecting the null implies that the alternative is a better model, which is simply not the case.
Perhaps a more complete answer would be this: p-values are not a valid metric for model comparison. To compare models effectively, you need methods like AIC or BIC. One could also ditch frequentism all together and use Bayesian estimation techniques to construct Bayes factors, which would allow you to compare models.
One last (and to some controversial) comment on p-values. Consider this, given enough data, you will obtain significance. This is due to the (silly) nature of the null-hypothesis, which states that an effect is exactly zero. In a vast majority of cases, this is almost certainly not true. There will be some non-zero effect, just a small one. So what p-value thresholds do in practice is set up straw-man requirement that can always be met with enough data. Thus, given that you can always achieve significance, it should be unsurprising that p-values do not really tell you anything about model performance. As far as I can tell, they really do not tell you much of anything. As scientists, we care about estimation and prediction and p-values do not help us do either... | Does a statistically significant correlation always give predictive power? | Late on the post, but to help future generations I will respond. In short, the answer is no. Statistical significance does not tell the researcher anything about a model's predictive ability.
The def | Does a statistically significant correlation always give predictive power?
Late on the post, but to help future generations I will respond. In short, the answer is no. Statistical significance does not tell the researcher anything about a model's predictive ability.
The definition of p-values makes this clear. A p-value represents how likely it is that you the researcher observed a given data set under the assumption that the null hypothesis is true. So even if you reject the null, you really cannot say anything about which model is better at predicting, only that what you observed is more or less likely given the null. A super common mistake is that people assume rejecting the null implies that the alternative is a better model, which is simply not the case.
Perhaps a more complete answer would be this: p-values are not a valid metric for model comparison. To compare models effectively, you need methods like AIC or BIC. One could also ditch frequentism all together and use Bayesian estimation techniques to construct Bayes factors, which would allow you to compare models.
One last (and to some controversial) comment on p-values. Consider this, given enough data, you will obtain significance. This is due to the (silly) nature of the null-hypothesis, which states that an effect is exactly zero. In a vast majority of cases, this is almost certainly not true. There will be some non-zero effect, just a small one. So what p-value thresholds do in practice is set up straw-man requirement that can always be met with enough data. Thus, given that you can always achieve significance, it should be unsurprising that p-values do not really tell you anything about model performance. As far as I can tell, they really do not tell you much of anything. As scientists, we care about estimation and prediction and p-values do not help us do either... | Does a statistically significant correlation always give predictive power?
Late on the post, but to help future generations I will respond. In short, the answer is no. Statistical significance does not tell the researcher anything about a model's predictive ability.
The def |
30,550 | For model selection/comparison, what kind of test should I use? | The algorithms should be compared on the exact same training/test sets, so a paired test makes sense.
The tricky issue with using a single data set to estimate generalization performance is that data has to be re-used across multiple runs, meaning there's overlap in the training sets (and sometimes test sets, depending on the procedure). This can produce erroneous results because it violates the independence assumption of common statistical tests, and can lead to underestimating the variance.
For comparing the generalization performance of two algorithms on a single dataset, paired t tests with 10-fold cross validation can give an inflated type 1 error (i.e. you'd incorrectly detect a significant difference more often than you should). See this paper:
Dietterich (1998). Approximate statistical tests for comparing supervised classification learning algorithms
Instead, he suggests using the '5x2cv t test' (a paired t test using 5 runs of 2-fold cross validation) or 'McNemar's test' (if computational resources are more limited). Unlike the t test w/ 10-fold cross validation, both of these methods have acceptable type 1 error. But, they have higher type 2 error (meaning a greater probability of failing to detect a true difference).
In this paper:
Nadeau and Bengio (2003). Inference for the generalization error
they propose the 'corrected resampled t test', which adjusts the variance based on overlap between the training/test sets. It has proper type 1 error, and greater statistical power (i.e. lower type 2 error) than the 5x2cv t test and McNemar's test.
In this paper:
Bouckaert and Frank (2004). Evaluating the Replicability of Significance Tests for Comparing Learning Algorithms
they argue that a test should have not only acceptable type 1 error and low type 2 error, but also high replicability (meaning the outcome of the test shouldn't depend strongly on a particular random partitioning of the data). They find that the 5x2cv t test has low replicability. The corrected resampled t test has higher replicability, and they propose a modification that further increases it.
This paper considers the case of comparing multiple algorithms on multiple data sets:
Demsar (2006). Statistical comparisons of classifiers over multiple data sets | For model selection/comparison, what kind of test should I use? | The algorithms should be compared on the exact same training/test sets, so a paired test makes sense.
The tricky issue with using a single data set to estimate generalization performance is that data | For model selection/comparison, what kind of test should I use?
The algorithms should be compared on the exact same training/test sets, so a paired test makes sense.
The tricky issue with using a single data set to estimate generalization performance is that data has to be re-used across multiple runs, meaning there's overlap in the training sets (and sometimes test sets, depending on the procedure). This can produce erroneous results because it violates the independence assumption of common statistical tests, and can lead to underestimating the variance.
For comparing the generalization performance of two algorithms on a single dataset, paired t tests with 10-fold cross validation can give an inflated type 1 error (i.e. you'd incorrectly detect a significant difference more often than you should). See this paper:
Dietterich (1998). Approximate statistical tests for comparing supervised classification learning algorithms
Instead, he suggests using the '5x2cv t test' (a paired t test using 5 runs of 2-fold cross validation) or 'McNemar's test' (if computational resources are more limited). Unlike the t test w/ 10-fold cross validation, both of these methods have acceptable type 1 error. But, they have higher type 2 error (meaning a greater probability of failing to detect a true difference).
In this paper:
Nadeau and Bengio (2003). Inference for the generalization error
they propose the 'corrected resampled t test', which adjusts the variance based on overlap between the training/test sets. It has proper type 1 error, and greater statistical power (i.e. lower type 2 error) than the 5x2cv t test and McNemar's test.
In this paper:
Bouckaert and Frank (2004). Evaluating the Replicability of Significance Tests for Comparing Learning Algorithms
they argue that a test should have not only acceptable type 1 error and low type 2 error, but also high replicability (meaning the outcome of the test shouldn't depend strongly on a particular random partitioning of the data). They find that the 5x2cv t test has low replicability. The corrected resampled t test has higher replicability, and they propose a modification that further increases it.
This paper considers the case of comparing multiple algorithms on multiple data sets:
Demsar (2006). Statistical comparisons of classifiers over multiple data sets | For model selection/comparison, what kind of test should I use?
The algorithms should be compared on the exact same training/test sets, so a paired test makes sense.
The tricky issue with using a single data set to estimate generalization performance is that data |
30,551 | For model selection/comparison, what kind of test should I use? | A follow up on @user20160 comment, and based on Bouckaert and Frank (2004), you can use 10 times repeated 10 fold cross validation while taking into account two points:
Reduce Type 1 error by multiplying the variance with a constant coefficient based onNadeau and Bengi correction.
Tackle the interdependence issue between the fold by reducing the degrees of freedom from 99 to 10.
I think this is one of the compromised solutions I found out there! | For model selection/comparison, what kind of test should I use? | A follow up on @user20160 comment, and based on Bouckaert and Frank (2004), you can use 10 times repeated 10 fold cross validation while taking into account two points:
Reduce Type 1 error by multipl | For model selection/comparison, what kind of test should I use?
A follow up on @user20160 comment, and based on Bouckaert and Frank (2004), you can use 10 times repeated 10 fold cross validation while taking into account two points:
Reduce Type 1 error by multiplying the variance with a constant coefficient based onNadeau and Bengi correction.
Tackle the interdependence issue between the fold by reducing the degrees of freedom from 99 to 10.
I think this is one of the compromised solutions I found out there! | For model selection/comparison, what kind of test should I use?
A follow up on @user20160 comment, and based on Bouckaert and Frank (2004), you can use 10 times repeated 10 fold cross validation while taking into account two points:
Reduce Type 1 error by multipl |
30,552 | Gaussian process prediction interval | I will answer your question inside the Bayesian framework. If you specifically need a frequentist solution, you can get one by slightly modifying my answer, but I think it will underestimate the actual uncertainty: you would need a fully frequentist approach, but I don't know how to do that in this specific case.
To briefly recap the Bayesian GPR (Gaussian Process Regression) framework, you assume the model
$$y=f(x|\boldsymbol{\theta})+\epsilon$$
where $f(x|\boldsymbol{\theta})\sim \mathcal{GP}(\mu(x|\boldsymbol{\theta}),k(x,x'|\boldsymbol{\theta}))$, i.e., the latent variables or function values are distributed as a Gaussian Process, conditionally on the hyperparameters $\boldsymbol{\theta}$, and $\epsilon\sim\mathcal{N}(0,\sigma^2)$ is the usual iid Gaussian noise.
Actually, $\sigma^2$ is an hyperparameter too, so it really belongs in $\boldsymbol{\theta}$, but I wanted to underscore that GPR usually assumes a trivial covariance structure for the noise.
The posterior predictive distribution of $y_*$ at a new point $x_*$, conditionally on data $\{(x_1,y_1,)\dots,(x_d,y_d)\}=(\mathbf{x},\mathbf{y})$ and on hyperparameters $\boldsymbol{\theta}$, is $p(y_*|\boldsymbol{\theta},\mathbf{y})$. Now, assume that the mean function of the Gaussian Process is zero: the general case can also be dealt with, but let's try and keep things simple. Then, using the usual GPR machinery, we get
$$p(f_*|\boldsymbol{\theta},\mathbf{y}) = \mathcal{N}(\mathbf{k}_*^T(K+\sigma^2I)^{-1}\mathbf{y},k(x_*,x_*)-\mathbf{k}_*^T(K+\sigma^2I)^{-1}\mathbf{k}_*)$$
where
$$K=\pmatrix{k(x_{1},x_{1};\boldsymbol{\theta})& & k(x_{1},x_{d};\boldsymbol{\theta}) \\ & \ddots & \\k(x_{1},x_{d};\boldsymbol{\theta})& & k(x_{d},x_{d};\boldsymbol{\theta}) }$$
$$\mathbf{k}_*=\pmatrix{k(x_*,x_{1};\boldsymbol{\theta}) \\ \vdots \\k(x_*,x_{d};\boldsymbol{\theta})}$$
i.e., conditional on observed data and hyperparameters, the distribution of the latent variable at a new point is still Gaussian, with the mean and standard deviation shown above.
However, we are interested in the distribution of a new observation $y_*$, not a new latent variable. This is easy because in our model the noise is additive, independent of all other variables and is normally distributed with zero mean and variance $\sigma^2$, thus we only need to add the noise variance:
$$p(y_*|\boldsymbol{\theta},\mathbf{y}) = \mathcal{N}(\mathbf{k}_*^T(K+\sigma^2I)^{-1}\mathbf{y},k(x_*,x_*)-\mathbf{k}_*^T(K+\sigma^2I)^{-1}\mathbf{k}_*+\sigma^2)$$
Note that I'm considering a single new observation $y_*$, so the distribution $p(y_*|\boldsymbol{\theta},\mathbf{y})$ is just a univariate Gaussian, and the variance is actually a variance and not a variance-covariance matrix.
To actually use this expression, you need values for the hyperparameters, which are not known. There are 2 ways out of this:
(the most common solution) the hyperparameters are estimated by MLE, or MAP, and the above expression is used. This approach completely neglects the
uncertainty in the estimation of the hyperparameters, thus it doesn't seem very safe.
in a fully Bayesian approach, you are not really interested in $p(y_*|\boldsymbol{\theta},\mathbf{y})$, but in the predictive distribution of $y_*$ given $\mathbf{y}$, which is obtained by $p(y_*|\boldsymbol{\theta},\mathbf{y})$ after integrating out the hyperparameters:
$$p(y_*|\mathbf{y})=\int{p(y_*,\boldsymbol{\theta}|\mathbf{y})}d\boldsymbol{\theta}=\int{p(y_*|\boldsymbol{\theta},\mathbf{y})p(\boldsymbol{\theta}|\mathbf{y})}d\boldsymbol{\theta}$$
There are two problems here: given a prior distribution for the hyperparameters $p(\boldsymbol{\theta})$, then the posterior distribution $p(\boldsymbol{\theta}|\mathbf{y})$, which appears in the integral, is not known but must be derived using the Bayes' theorem, which for most hyperpriors means having to run a MCMC. Thus we don't have an explicit expression for $p(\boldsymbol{\theta}|\mathbf{y})$, but only samples from the MCMC. And even if we had an expression for $p(\boldsymbol{\theta}|\mathbf{y})$, then the integral giving $p(y_*|\mathbf{y})$ would still be impossible to evaluate in a closed form in most cases. The solution is an hierarchical Bayes simulation: for each sample $\hat{\boldsymbol{\theta}}_i$ obtained from $p(\boldsymbol{\theta}|\mathbf{y})$ with the MCMC, you draw a sample $y^*_i$ from $p(y_*|\hat{\boldsymbol{\theta}}_i,\mathbf{y})$. Use these $m$ samples $y^*_i$ to estimate an HPD interval for $y_*$, and there you are.
From an intuitive point of view, the second solution draws samples from a distribution where the hyperparameters are "not fixed", but allowed to vary randomly according to their posterior distribution $p(\boldsymbol{\theta}|\mathbf{y})$. Thus the prediction interval obtained in the second case takes into account the uncertainty due to our lack of knowledge about the hyperparameters. | Gaussian process prediction interval | I will answer your question inside the Bayesian framework. If you specifically need a frequentist solution, you can get one by slightly modifying my answer, but I think it will underestimate the actua | Gaussian process prediction interval
I will answer your question inside the Bayesian framework. If you specifically need a frequentist solution, you can get one by slightly modifying my answer, but I think it will underestimate the actual uncertainty: you would need a fully frequentist approach, but I don't know how to do that in this specific case.
To briefly recap the Bayesian GPR (Gaussian Process Regression) framework, you assume the model
$$y=f(x|\boldsymbol{\theta})+\epsilon$$
where $f(x|\boldsymbol{\theta})\sim \mathcal{GP}(\mu(x|\boldsymbol{\theta}),k(x,x'|\boldsymbol{\theta}))$, i.e., the latent variables or function values are distributed as a Gaussian Process, conditionally on the hyperparameters $\boldsymbol{\theta}$, and $\epsilon\sim\mathcal{N}(0,\sigma^2)$ is the usual iid Gaussian noise.
Actually, $\sigma^2$ is an hyperparameter too, so it really belongs in $\boldsymbol{\theta}$, but I wanted to underscore that GPR usually assumes a trivial covariance structure for the noise.
The posterior predictive distribution of $y_*$ at a new point $x_*$, conditionally on data $\{(x_1,y_1,)\dots,(x_d,y_d)\}=(\mathbf{x},\mathbf{y})$ and on hyperparameters $\boldsymbol{\theta}$, is $p(y_*|\boldsymbol{\theta},\mathbf{y})$. Now, assume that the mean function of the Gaussian Process is zero: the general case can also be dealt with, but let's try and keep things simple. Then, using the usual GPR machinery, we get
$$p(f_*|\boldsymbol{\theta},\mathbf{y}) = \mathcal{N}(\mathbf{k}_*^T(K+\sigma^2I)^{-1}\mathbf{y},k(x_*,x_*)-\mathbf{k}_*^T(K+\sigma^2I)^{-1}\mathbf{k}_*)$$
where
$$K=\pmatrix{k(x_{1},x_{1};\boldsymbol{\theta})& & k(x_{1},x_{d};\boldsymbol{\theta}) \\ & \ddots & \\k(x_{1},x_{d};\boldsymbol{\theta})& & k(x_{d},x_{d};\boldsymbol{\theta}) }$$
$$\mathbf{k}_*=\pmatrix{k(x_*,x_{1};\boldsymbol{\theta}) \\ \vdots \\k(x_*,x_{d};\boldsymbol{\theta})}$$
i.e., conditional on observed data and hyperparameters, the distribution of the latent variable at a new point is still Gaussian, with the mean and standard deviation shown above.
However, we are interested in the distribution of a new observation $y_*$, not a new latent variable. This is easy because in our model the noise is additive, independent of all other variables and is normally distributed with zero mean and variance $\sigma^2$, thus we only need to add the noise variance:
$$p(y_*|\boldsymbol{\theta},\mathbf{y}) = \mathcal{N}(\mathbf{k}_*^T(K+\sigma^2I)^{-1}\mathbf{y},k(x_*,x_*)-\mathbf{k}_*^T(K+\sigma^2I)^{-1}\mathbf{k}_*+\sigma^2)$$
Note that I'm considering a single new observation $y_*$, so the distribution $p(y_*|\boldsymbol{\theta},\mathbf{y})$ is just a univariate Gaussian, and the variance is actually a variance and not a variance-covariance matrix.
To actually use this expression, you need values for the hyperparameters, which are not known. There are 2 ways out of this:
(the most common solution) the hyperparameters are estimated by MLE, or MAP, and the above expression is used. This approach completely neglects the
uncertainty in the estimation of the hyperparameters, thus it doesn't seem very safe.
in a fully Bayesian approach, you are not really interested in $p(y_*|\boldsymbol{\theta},\mathbf{y})$, but in the predictive distribution of $y_*$ given $\mathbf{y}$, which is obtained by $p(y_*|\boldsymbol{\theta},\mathbf{y})$ after integrating out the hyperparameters:
$$p(y_*|\mathbf{y})=\int{p(y_*,\boldsymbol{\theta}|\mathbf{y})}d\boldsymbol{\theta}=\int{p(y_*|\boldsymbol{\theta},\mathbf{y})p(\boldsymbol{\theta}|\mathbf{y})}d\boldsymbol{\theta}$$
There are two problems here: given a prior distribution for the hyperparameters $p(\boldsymbol{\theta})$, then the posterior distribution $p(\boldsymbol{\theta}|\mathbf{y})$, which appears in the integral, is not known but must be derived using the Bayes' theorem, which for most hyperpriors means having to run a MCMC. Thus we don't have an explicit expression for $p(\boldsymbol{\theta}|\mathbf{y})$, but only samples from the MCMC. And even if we had an expression for $p(\boldsymbol{\theta}|\mathbf{y})$, then the integral giving $p(y_*|\mathbf{y})$ would still be impossible to evaluate in a closed form in most cases. The solution is an hierarchical Bayes simulation: for each sample $\hat{\boldsymbol{\theta}}_i$ obtained from $p(\boldsymbol{\theta}|\mathbf{y})$ with the MCMC, you draw a sample $y^*_i$ from $p(y_*|\hat{\boldsymbol{\theta}}_i,\mathbf{y})$. Use these $m$ samples $y^*_i$ to estimate an HPD interval for $y_*$, and there you are.
From an intuitive point of view, the second solution draws samples from a distribution where the hyperparameters are "not fixed", but allowed to vary randomly according to their posterior distribution $p(\boldsymbol{\theta}|\mathbf{y})$. Thus the prediction interval obtained in the second case takes into account the uncertainty due to our lack of knowledge about the hyperparameters. | Gaussian process prediction interval
I will answer your question inside the Bayesian framework. If you specifically need a frequentist solution, you can get one by slightly modifying my answer, but I think it will underestimate the actua |
30,553 | Gaussian process prediction interval | If you're referring to Bayesian regression with Gaussian likelihood, the posterior distribution of a Gaussian process is Gaussian:
$$p(f(x)\mid X_n,Y_n) = \mathcal{N}\big(\mu_n(x),\sigma_n^2(x)\big)\,,$$
where $X_n$ are the data locations and $Y_n$ are the data values, and $\mu_n$ and $\sigma_n^2$ computed with Bayesian inference :
$$\mu_n(x) = \mathbf{k}_n(x)^\top C_n^{-1}Y_n \text{ and } \sigma_n^2(x) = k(x,x) - \mathbf{k}_n(x)^\top C_n^{-1} \mathbf{k}_n(x)\,,$$
where $\mathbf{k}_n(x) = [k(x_t, x)]_{x_t \in X_n}$ is the kernel vector between $x$ and $X_n$, and $C_n = K_n + \eta^2 I$ with $\eta^2$ the standard deviation of the observation noise and $K_n=[k(x_t,x_{t'})]_{x_t,x_{t'} \in X_n}$ the kernel matrix
(see the second chapter of Rasmussen and Williams' book).
Therefore a ~95% confidence interval for $x$ is simply $\mu_n(x) \pm 2 \sigma_n(x)$. | Gaussian process prediction interval | If you're referring to Bayesian regression with Gaussian likelihood, the posterior distribution of a Gaussian process is Gaussian:
$$p(f(x)\mid X_n,Y_n) = \mathcal{N}\big(\mu_n(x),\sigma_n^2(x)\big)\, | Gaussian process prediction interval
If you're referring to Bayesian regression with Gaussian likelihood, the posterior distribution of a Gaussian process is Gaussian:
$$p(f(x)\mid X_n,Y_n) = \mathcal{N}\big(\mu_n(x),\sigma_n^2(x)\big)\,,$$
where $X_n$ are the data locations and $Y_n$ are the data values, and $\mu_n$ and $\sigma_n^2$ computed with Bayesian inference :
$$\mu_n(x) = \mathbf{k}_n(x)^\top C_n^{-1}Y_n \text{ and } \sigma_n^2(x) = k(x,x) - \mathbf{k}_n(x)^\top C_n^{-1} \mathbf{k}_n(x)\,,$$
where $\mathbf{k}_n(x) = [k(x_t, x)]_{x_t \in X_n}$ is the kernel vector between $x$ and $X_n$, and $C_n = K_n + \eta^2 I$ with $\eta^2$ the standard deviation of the observation noise and $K_n=[k(x_t,x_{t'})]_{x_t,x_{t'} \in X_n}$ the kernel matrix
(see the second chapter of Rasmussen and Williams' book).
Therefore a ~95% confidence interval for $x$ is simply $\mu_n(x) \pm 2 \sigma_n(x)$. | Gaussian process prediction interval
If you're referring to Bayesian regression with Gaussian likelihood, the posterior distribution of a Gaussian process is Gaussian:
$$p(f(x)\mid X_n,Y_n) = \mathcal{N}\big(\mu_n(x),\sigma_n^2(x)\big)\, |
30,554 | How to calculate mean, median, mode, std dev from distribution | First a general comment on the mode:
You should not use that approach to get the mode of (at least notionally) continuously distributed data; you're unlikely to have any repeated values (unless you have truly huge samples it would be a minor miracle, and even then various numeric issues could make it behave in somewhat unexpected ways), and you'll generally just get the minimum value that way. It would be one way to find one of the global modes in discrete or categorical data, but I probably wouldn't do it that way even then. Here are several other approaches to get the mode for discrete or categorical data:
x = rpois(30,12.3)
tail(sort(table(x)),1) #1: category and count; if multimodal this only gives one
w=table(x); w[max(w)==w] #2: category and count; this can find more than one mode
which.max(table(x)) #3: category and *position in table*; only finds one mode
If you just want the value and not the count or position, names() will get it from those
To identify modes (there can be more than one local mode) for continuous data in a basic fashion, you could bin the data (as with a histogram) or you could smooth it (using density for example) and attempt to find one or more modes that way.
Fewer histogram bins will make your estimate of a mode less subject to noise, but the location won't be pinned down to better than the bin-width (i.e. you only get an interval). More bins may allow more precision within a bin, but noise may make it jump around across many such bins; a small change in bin-origin or bin width may produce relatively large changes in mode. (There's the same bias-variance tradeoff all over statistics.)
Note that summary will give you several basic statistics.
[You should use sd(x) rather than sqrt(var(x)); it's clearer for one thing]
--
In respect of q.2 yes; you could certainly show mean and median of the data on a display such as a histogram or a box plot. See here for some examples and code that you should be able to generalize to whatever cases you need. | How to calculate mean, median, mode, std dev from distribution | First a general comment on the mode:
You should not use that approach to get the mode of (at least notionally) continuously distributed data; you're unlikely to have any repeated values (unless you ha | How to calculate mean, median, mode, std dev from distribution
First a general comment on the mode:
You should not use that approach to get the mode of (at least notionally) continuously distributed data; you're unlikely to have any repeated values (unless you have truly huge samples it would be a minor miracle, and even then various numeric issues could make it behave in somewhat unexpected ways), and you'll generally just get the minimum value that way. It would be one way to find one of the global modes in discrete or categorical data, but I probably wouldn't do it that way even then. Here are several other approaches to get the mode for discrete or categorical data:
x = rpois(30,12.3)
tail(sort(table(x)),1) #1: category and count; if multimodal this only gives one
w=table(x); w[max(w)==w] #2: category and count; this can find more than one mode
which.max(table(x)) #3: category and *position in table*; only finds one mode
If you just want the value and not the count or position, names() will get it from those
To identify modes (there can be more than one local mode) for continuous data in a basic fashion, you could bin the data (as with a histogram) or you could smooth it (using density for example) and attempt to find one or more modes that way.
Fewer histogram bins will make your estimate of a mode less subject to noise, but the location won't be pinned down to better than the bin-width (i.e. you only get an interval). More bins may allow more precision within a bin, but noise may make it jump around across many such bins; a small change in bin-origin or bin width may produce relatively large changes in mode. (There's the same bias-variance tradeoff all over statistics.)
Note that summary will give you several basic statistics.
[You should use sd(x) rather than sqrt(var(x)); it's clearer for one thing]
--
In respect of q.2 yes; you could certainly show mean and median of the data on a display such as a histogram or a box plot. See here for some examples and code that you should be able to generalize to whatever cases you need. | How to calculate mean, median, mode, std dev from distribution
First a general comment on the mode:
You should not use that approach to get the mode of (at least notionally) continuously distributed data; you're unlikely to have any repeated values (unless you ha |
30,555 | How to calculate mean, median, mode, std dev from distribution | Some additional and not very well known descriptive statistics.
x<-rnorm(10)
sd(x) #Standard deviation
fivenum(x) #Tukey's five number summary, usefull for boxplots
IQR(x) #Interquartile range
quantile(x) #Compute sample quantiles
range(x) # Get minimum and maximum
I am sure you can find many others in one of those freely available R manuals. | How to calculate mean, median, mode, std dev from distribution | Some additional and not very well known descriptive statistics.
x<-rnorm(10)
sd(x) #Standard deviation
fivenum(x) #Tukey's five number summary, usefull for boxplots
IQR(x) #Interquartile range
qua | How to calculate mean, median, mode, std dev from distribution
Some additional and not very well known descriptive statistics.
x<-rnorm(10)
sd(x) #Standard deviation
fivenum(x) #Tukey's five number summary, usefull for boxplots
IQR(x) #Interquartile range
quantile(x) #Compute sample quantiles
range(x) # Get minimum and maximum
I am sure you can find many others in one of those freely available R manuals. | How to calculate mean, median, mode, std dev from distribution
Some additional and not very well known descriptive statistics.
x<-rnorm(10)
sd(x) #Standard deviation
fivenum(x) #Tukey's five number summary, usefull for boxplots
IQR(x) #Interquartile range
qua |
30,556 | How to calculate mean, median, mode, std dev from distribution | As @Glen_b described the mode of a continuous distribution is not as straightforward as it is for a vector of integers.
This R code will get the mode for a continuous distribution, using the incredibly useful hist() function from base R. As @Glen_b described this involves putting observations into bins - discrete categories where if the observation falls within the bin interval it is counted as an instance of that bin, which gets around the problem of it being highly unlikely in a continuous distribution to observe the exact same value twice.
set.seed(123)
dist <- rnorm(n=1000, m=24.2, sd=2.2)
h <- hist(dist, # vector
plot = F, # stops hist() from automatically plotting histogram
breaks = 40) # number of bins
Now we treat the midpoint of the bin interval that has the maximum count within it as the mode
h$mids[which.max(h$counts)]
# [1] 23.75
Voila! The mode.
p.s. you could also treat the start of the interval as the mode via h$breaks[which.max(h$counts)]. As discussed modes for continuous distributions are not simple and require decisions to be made, hence why there is no simple function for them like there is with mean() and median() | How to calculate mean, median, mode, std dev from distribution | As @Glen_b described the mode of a continuous distribution is not as straightforward as it is for a vector of integers.
This R code will get the mode for a continuous distribution, using the incredib | How to calculate mean, median, mode, std dev from distribution
As @Glen_b described the mode of a continuous distribution is not as straightforward as it is for a vector of integers.
This R code will get the mode for a continuous distribution, using the incredibly useful hist() function from base R. As @Glen_b described this involves putting observations into bins - discrete categories where if the observation falls within the bin interval it is counted as an instance of that bin, which gets around the problem of it being highly unlikely in a continuous distribution to observe the exact same value twice.
set.seed(123)
dist <- rnorm(n=1000, m=24.2, sd=2.2)
h <- hist(dist, # vector
plot = F, # stops hist() from automatically plotting histogram
breaks = 40) # number of bins
Now we treat the midpoint of the bin interval that has the maximum count within it as the mode
h$mids[which.max(h$counts)]
# [1] 23.75
Voila! The mode.
p.s. you could also treat the start of the interval as the mode via h$breaks[which.max(h$counts)]. As discussed modes for continuous distributions are not simple and require decisions to be made, hence why there is no simple function for them like there is with mean() and median() | How to calculate mean, median, mode, std dev from distribution
As @Glen_b described the mode of a continuous distribution is not as straightforward as it is for a vector of integers.
This R code will get the mode for a continuous distribution, using the incredib |
30,557 | What does the notation like 8.6e-28 mean? What is the 'e' for? | The e is standard scientific notation for powers of $10$: 8.6e-28 means $8.6 \cdot 10^{-28}$.
The White test tests for heteroscedasticity of a variable's distribution, most commonly in the residuals of your regression. A significant result indicates that your data are significantly heteroscedastic, and thus the assumption of homoscedasticity in the regression residuals is violated. In your case the data violate the assumption of homoscedasticity, as your $p$ value is $8.6 \cdot 10^{-28}$. The e is standard scientific notation for powers of $10$. | What does the notation like 8.6e-28 mean? What is the 'e' for? | The e is standard scientific notation for powers of $10$: 8.6e-28 means $8.6 \cdot 10^{-28}$.
The White test tests for heteroscedasticity of a variable's distribution, most commonly in the residuals | What does the notation like 8.6e-28 mean? What is the 'e' for?
The e is standard scientific notation for powers of $10$: 8.6e-28 means $8.6 \cdot 10^{-28}$.
The White test tests for heteroscedasticity of a variable's distribution, most commonly in the residuals of your regression. A significant result indicates that your data are significantly heteroscedastic, and thus the assumption of homoscedasticity in the regression residuals is violated. In your case the data violate the assumption of homoscedasticity, as your $p$ value is $8.6 \cdot 10^{-28}$. The e is standard scientific notation for powers of $10$. | What does the notation like 8.6e-28 mean? What is the 'e' for?
The e is standard scientific notation for powers of $10$: 8.6e-28 means $8.6 \cdot 10^{-28}$.
The White test tests for heteroscedasticity of a variable's distribution, most commonly in the residuals |
30,558 | What does the notation like 8.6e-28 mean? What is the 'e' for? | $8.6\mathrm{e}{-28} = 8.6 \times 10^{-28}$
This means a highly statistically significant result. If alpha (0.05) is greater than the p-value, then we can reject the null hypothesis. Hence we can say that homoscedasticity cannot be assumed. | What does the notation like 8.6e-28 mean? What is the 'e' for? | $8.6\mathrm{e}{-28} = 8.6 \times 10^{-28}$
This means a highly statistically significant result. If alpha (0.05) is greater than the p-value, then we can reject the null hypothesis. Hence we can say t | What does the notation like 8.6e-28 mean? What is the 'e' for?
$8.6\mathrm{e}{-28} = 8.6 \times 10^{-28}$
This means a highly statistically significant result. If alpha (0.05) is greater than the p-value, then we can reject the null hypothesis. Hence we can say that homoscedasticity cannot be assumed. | What does the notation like 8.6e-28 mean? What is the 'e' for?
$8.6\mathrm{e}{-28} = 8.6 \times 10^{-28}$
This means a highly statistically significant result. If alpha (0.05) is greater than the p-value, then we can reject the null hypothesis. Hence we can say t |
30,559 | lme4: Why is AIC no longer displayed when using REML [duplicate] | As far as I can tell this was implemented in Aug 2013 ; the logic would presumably be that models fitted with REML do not have a likelihood per se, and that one of the most common user errors is to compare REML criteria ("restricted likelihoods") across models with different fixed-effect components, which is meaningless. Comparing AIC/BIC would inherit the same problems.
Although lme4 follows a fairly standard R convention of reporting the AIC, BIC, etc. in summary, I actually think this is mostly useless anyway, since the AIC/BIC for a single model basically doesn't contain any information. You can use it to compare across models, but that's easier to do with anova(model1,model2) or AIC(model1,model2) (or bbmle::AICtab(model1,model2), which gives a more useful summary). | lme4: Why is AIC no longer displayed when using REML [duplicate] | As far as I can tell this was implemented in Aug 2013 ; the logic would presumably be that models fitted with REML do not have a likelihood per se, and that one of the most common user errors is to co | lme4: Why is AIC no longer displayed when using REML [duplicate]
As far as I can tell this was implemented in Aug 2013 ; the logic would presumably be that models fitted with REML do not have a likelihood per se, and that one of the most common user errors is to compare REML criteria ("restricted likelihoods") across models with different fixed-effect components, which is meaningless. Comparing AIC/BIC would inherit the same problems.
Although lme4 follows a fairly standard R convention of reporting the AIC, BIC, etc. in summary, I actually think this is mostly useless anyway, since the AIC/BIC for a single model basically doesn't contain any information. You can use it to compare across models, but that's easier to do with anova(model1,model2) or AIC(model1,model2) (or bbmle::AICtab(model1,model2), which gives a more useful summary). | lme4: Why is AIC no longer displayed when using REML [duplicate]
As far as I can tell this was implemented in Aug 2013 ; the logic would presumably be that models fitted with REML do not have a likelihood per se, and that one of the most common user errors is to co |
30,560 | How are the numbers of modes of marginal and joint distributions related? | One way to create a multimodal bivariate distribution out of unimodal marginals is with a mixture. The idea is that a mixture of Normal distributions can be unimodal, but bivariate versions of the same normals can have distinct peaks provided they are suitably correlated.
As a concrete example, let $f$ be an equal mixture of two bivariate Normal distributions. Both have unit variances and the same correlation $\rho$, but let their means be $(a,-a)$ and $(-a,a)$ for some $a\ge 0$. Provided $a\le 1,$ the marginals of $f$ (which are identical mixtures of two unit-variance Normals) will have just a single mode, but if we make $\rho$ close enough to $1$, $f$ will be distinctly bimodal. Here, for instance, are a contour and surface plot of $f$ for $a=1/2$ and $\rho=4/5$:
The common marginal has no hint of two modes:
The general technique illustrated here shows how a suitably chosen mixture of multivariate distributions can smooth out the marginals, causing them to be only unimodal. We see these kinds of things all the time when creating kernel density estimates of multivariate data: the density estimates have modes where the data cluster, but the marginals can be unimodal because the clusters do not align along any of the component directions.
To address the second question, observe that even a distribution all of whose marginals are Standard Normal can still be multimodal.
As a concrete example, let $f$ be the PDF of a bivariate Normal distribution with mean $(0,0)$, unit variances, and correlation $\rho$. Define
$$g(x,y) = \begin{cases}
f(-y,x) & -1<x<1\text{ and } -1<y<1 \\
f(x,y) & \text{otherwise}.
\end{cases}
$$
This rotates the graph of $g$ within the square $(-1,1)\times(-1,1)$ by 90 degrees.
Because the marginals of $f$ are identical and symmetric around $0$, $g$ has the same marginals as $f$. However, $g$ clearly has three modes--at $(0,0)$, $(1,1)$, and $(-1,-1)$--as this contour plot (with $\rho=4/5$) shows:
This example illustrates a general technique to answer questions about modes: cut pieces out of the PDF and move them around. | How are the numbers of modes of marginal and joint distributions related? | One way to create a multimodal bivariate distribution out of unimodal marginals is with a mixture. The idea is that a mixture of Normal distributions can be unimodal, but bivariate versions of the sam | How are the numbers of modes of marginal and joint distributions related?
One way to create a multimodal bivariate distribution out of unimodal marginals is with a mixture. The idea is that a mixture of Normal distributions can be unimodal, but bivariate versions of the same normals can have distinct peaks provided they are suitably correlated.
As a concrete example, let $f$ be an equal mixture of two bivariate Normal distributions. Both have unit variances and the same correlation $\rho$, but let their means be $(a,-a)$ and $(-a,a)$ for some $a\ge 0$. Provided $a\le 1,$ the marginals of $f$ (which are identical mixtures of two unit-variance Normals) will have just a single mode, but if we make $\rho$ close enough to $1$, $f$ will be distinctly bimodal. Here, for instance, are a contour and surface plot of $f$ for $a=1/2$ and $\rho=4/5$:
The common marginal has no hint of two modes:
The general technique illustrated here shows how a suitably chosen mixture of multivariate distributions can smooth out the marginals, causing them to be only unimodal. We see these kinds of things all the time when creating kernel density estimates of multivariate data: the density estimates have modes where the data cluster, but the marginals can be unimodal because the clusters do not align along any of the component directions.
To address the second question, observe that even a distribution all of whose marginals are Standard Normal can still be multimodal.
As a concrete example, let $f$ be the PDF of a bivariate Normal distribution with mean $(0,0)$, unit variances, and correlation $\rho$. Define
$$g(x,y) = \begin{cases}
f(-y,x) & -1<x<1\text{ and } -1<y<1 \\
f(x,y) & \text{otherwise}.
\end{cases}
$$
This rotates the graph of $g$ within the square $(-1,1)\times(-1,1)$ by 90 degrees.
Because the marginals of $f$ are identical and symmetric around $0$, $g$ has the same marginals as $f$. However, $g$ clearly has three modes--at $(0,0)$, $(1,1)$, and $(-1,-1)$--as this contour plot (with $\rho=4/5$) shows:
This example illustrates a general technique to answer questions about modes: cut pieces out of the PDF and move them around. | How are the numbers of modes of marginal and joint distributions related?
One way to create a multimodal bivariate distribution out of unimodal marginals is with a mixture. The idea is that a mixture of Normal distributions can be unimodal, but bivariate versions of the sam |
30,561 | How are the numbers of modes of marginal and joint distributions related? | Yes and yes, and examples are easy to devise.
Let $(X,Y)$ have discrete distribution that has
probability mass of $0.12$ at $(0,0)$ and $0.08$ at the $4$ points $(\pm 1,\pm 1)$.
probability mass of $0.07$ at each of $(\pm 2, \pm 2)$ and $(\pm 3, \pm 3)$.
This is a unimodal bivariate distribution with a mode of $0.12$ at $(0,0)$
However, the marginal distributions
are
$$\begin{array}{cccccccc}
-3& -2& -1& 0 & +1 & +2 & +3\\
0.14 & 0.14& 0.16 & 0.12 & 0.16 & 0.14 & 0.14
\end{array}$$
with twin peaks of $0.16$ at $\pm 1$ and least likely value $0$ where
the mode of the bivariate distribution is!
As an example of unimodal marginal distributions but a
multimodal joint distribution, consider random variables $X$ and $Y$
that have identical unimodal marginal distributions
$$\begin{array}{cccccccc}
-2& -1& 0 & +1 & +2 \\
0.05 & 0.2& 0.5 & 0.2 & 0.05
\end{array}$$
and bivariate distribution that has masses of $0.2$ at $(0,1), (1,0), (0,-1), (-1,0)$ and masses of $0.05$ at $(0,2), (2,0), (0,-2), (-2,0)$ which has
$4$ modes. | How are the numbers of modes of marginal and joint distributions related? | Yes and yes, and examples are easy to devise.
Let $(X,Y)$ have discrete distribution that has
probability mass of $0.12$ at $(0,0)$ and $0.08$ at the $4$ points $(\pm 1,\pm 1)$.
probability mass of $ | How are the numbers of modes of marginal and joint distributions related?
Yes and yes, and examples are easy to devise.
Let $(X,Y)$ have discrete distribution that has
probability mass of $0.12$ at $(0,0)$ and $0.08$ at the $4$ points $(\pm 1,\pm 1)$.
probability mass of $0.07$ at each of $(\pm 2, \pm 2)$ and $(\pm 3, \pm 3)$.
This is a unimodal bivariate distribution with a mode of $0.12$ at $(0,0)$
However, the marginal distributions
are
$$\begin{array}{cccccccc}
-3& -2& -1& 0 & +1 & +2 & +3\\
0.14 & 0.14& 0.16 & 0.12 & 0.16 & 0.14 & 0.14
\end{array}$$
with twin peaks of $0.16$ at $\pm 1$ and least likely value $0$ where
the mode of the bivariate distribution is!
As an example of unimodal marginal distributions but a
multimodal joint distribution, consider random variables $X$ and $Y$
that have identical unimodal marginal distributions
$$\begin{array}{cccccccc}
-2& -1& 0 & +1 & +2 \\
0.05 & 0.2& 0.5 & 0.2 & 0.05
\end{array}$$
and bivariate distribution that has masses of $0.2$ at $(0,1), (1,0), (0,-1), (-1,0)$ and masses of $0.05$ at $(0,2), (2,0), (0,-2), (-2,0)$ which has
$4$ modes. | How are the numbers of modes of marginal and joint distributions related?
Yes and yes, and examples are easy to devise.
Let $(X,Y)$ have discrete distribution that has
probability mass of $0.12$ at $(0,0)$ and $0.08$ at the $4$ points $(\pm 1,\pm 1)$.
probability mass of $ |
30,562 | What does it mean that a statistic $T(X)$ is sufficient for a parameter? | I think the best way to understand sufficiency is to consider familiar examples. Suppose we flip a (not necessarily fair) coin, where the probability of obtaining heads is some unknown parameter $p$. Then individual trials are IID Bernoulli(p) random variables, and we can think about the outcome of $n$ trials as being a vector $\boldsymbol X = (X_1, X_2, \ldots, X_n)$. Our intuition tells us that for a large number of trials, a "good" estimate of the parameter $p$ is the statistic $$\bar X = \frac{1}{n} \sum_{i=1}^n X_i.$$ Now think about a situation where I perform such an experiment. Could you estimate $p$ equally well if I inform you of $\bar X$, compared to $\boldsymbol X$? Sure. This is what sufficiency does for us: the statistic $T(\boldsymbol X) = \bar X$ is sufficient for $p$ because it preserves all the information we can get about $p$ from the original sample $\boldsymbol X$. (To prove this claim, however, needs more explanation.)
Here is a less trivial example. Suppose I have $n$ IID observations taken from a ${\rm Uniform}(0,\theta)$ distribution, where $\theta$ is the unknown parameter. What is a sufficient statistic for $\theta$? For instance, suppose I take $n = 5$ samples and I obtain $\boldsymbol X = (3, 1, 4, 5, 4)$. Your estimate for $\theta$ clearly must be at least $5$, since you were able to observe such a value. But that is the most knowledge you can extract from knowing the actual sample $\boldsymbol X$. The other observations convey no additional information about $\theta$ once you have observed $X_4 = 5$. So, we would intuitively expect that the statistic $$T(\boldsymbol X) = X_{(n)} = \max \boldsymbol X$$ is sufficient for $\theta$. Indeed, to prove this, we would write the joint density for $\boldsymbol X$ conditioned on $\theta$, and use the Factorization Theorem (but I will omit this in the interest of keeping the discussion informal).
Note that a sufficient statistic is not necessarily scalar-valued. For it may not be possible to achieve data reduction of the complete sample into a single scalar. This commonly arises when we want sufficiency for multiple parameters (which we can equivalently regard as a single vector-valued parameter). For example, a sufficient statistic for a Normal distribution with unknown mean $\mu$ and standard deviation $\sigma$ is $$\boldsymbol T(\boldsymbol X) = \left( \frac{1}{n} \sum_{i=1}^n X_i, \sqrt{\frac{1}{n-1} \sum_{i=1}^n (X_i - \bar X)^2} \right).$$ In fact, these are unbiased estimators of the mean and standard deviation. We can show that this is the maximum data reduction that can be achieved.
Note also that a sufficient statistic is not unique. In the coin toss example, if I give you $\bar X$, that will let you estimate $p$. But if I gave you $\sum_{i=1}^n X_i$, you can still estimate $p$. In fact, any one-to-one function $g$ of a sufficient statistic $T(\boldsymbol X)$ is also sufficient, since you can invert $g$ to recover $T$. So for the normal example with unknown mean and standard deviation, I could also have claimed that $\left( \sum_{i=1}^n X_i, \sum_{i=1}^n X_i^2 \right)$, i.e., the sum and sum of squared observations, are sufficient for $(\mu, \sigma)$. Indeed, the non-uniqueness of sufficiency is even more obvious, for $\boldsymbol T(\boldsymbol X) = \boldsymbol X$ is always sufficient for any parameter(s): the original sample always contains as much information as we can gather.
In summary, sufficiency is a desirable property of a statistic because it allows us to formally show that a statistic achieves some kind of data reduction. A sufficient statistic that achieves the maximum amount of data reduction is called a minimal sufficient statistic. | What does it mean that a statistic $T(X)$ is sufficient for a parameter? | I think the best way to understand sufficiency is to consider familiar examples. Suppose we flip a (not necessarily fair) coin, where the probability of obtaining heads is some unknown parameter $p$. | What does it mean that a statistic $T(X)$ is sufficient for a parameter?
I think the best way to understand sufficiency is to consider familiar examples. Suppose we flip a (not necessarily fair) coin, where the probability of obtaining heads is some unknown parameter $p$. Then individual trials are IID Bernoulli(p) random variables, and we can think about the outcome of $n$ trials as being a vector $\boldsymbol X = (X_1, X_2, \ldots, X_n)$. Our intuition tells us that for a large number of trials, a "good" estimate of the parameter $p$ is the statistic $$\bar X = \frac{1}{n} \sum_{i=1}^n X_i.$$ Now think about a situation where I perform such an experiment. Could you estimate $p$ equally well if I inform you of $\bar X$, compared to $\boldsymbol X$? Sure. This is what sufficiency does for us: the statistic $T(\boldsymbol X) = \bar X$ is sufficient for $p$ because it preserves all the information we can get about $p$ from the original sample $\boldsymbol X$. (To prove this claim, however, needs more explanation.)
Here is a less trivial example. Suppose I have $n$ IID observations taken from a ${\rm Uniform}(0,\theta)$ distribution, where $\theta$ is the unknown parameter. What is a sufficient statistic for $\theta$? For instance, suppose I take $n = 5$ samples and I obtain $\boldsymbol X = (3, 1, 4, 5, 4)$. Your estimate for $\theta$ clearly must be at least $5$, since you were able to observe such a value. But that is the most knowledge you can extract from knowing the actual sample $\boldsymbol X$. The other observations convey no additional information about $\theta$ once you have observed $X_4 = 5$. So, we would intuitively expect that the statistic $$T(\boldsymbol X) = X_{(n)} = \max \boldsymbol X$$ is sufficient for $\theta$. Indeed, to prove this, we would write the joint density for $\boldsymbol X$ conditioned on $\theta$, and use the Factorization Theorem (but I will omit this in the interest of keeping the discussion informal).
Note that a sufficient statistic is not necessarily scalar-valued. For it may not be possible to achieve data reduction of the complete sample into a single scalar. This commonly arises when we want sufficiency for multiple parameters (which we can equivalently regard as a single vector-valued parameter). For example, a sufficient statistic for a Normal distribution with unknown mean $\mu$ and standard deviation $\sigma$ is $$\boldsymbol T(\boldsymbol X) = \left( \frac{1}{n} \sum_{i=1}^n X_i, \sqrt{\frac{1}{n-1} \sum_{i=1}^n (X_i - \bar X)^2} \right).$$ In fact, these are unbiased estimators of the mean and standard deviation. We can show that this is the maximum data reduction that can be achieved.
Note also that a sufficient statistic is not unique. In the coin toss example, if I give you $\bar X$, that will let you estimate $p$. But if I gave you $\sum_{i=1}^n X_i$, you can still estimate $p$. In fact, any one-to-one function $g$ of a sufficient statistic $T(\boldsymbol X)$ is also sufficient, since you can invert $g$ to recover $T$. So for the normal example with unknown mean and standard deviation, I could also have claimed that $\left( \sum_{i=1}^n X_i, \sum_{i=1}^n X_i^2 \right)$, i.e., the sum and sum of squared observations, are sufficient for $(\mu, \sigma)$. Indeed, the non-uniqueness of sufficiency is even more obvious, for $\boldsymbol T(\boldsymbol X) = \boldsymbol X$ is always sufficient for any parameter(s): the original sample always contains as much information as we can gather.
In summary, sufficiency is a desirable property of a statistic because it allows us to formally show that a statistic achieves some kind of data reduction. A sufficient statistic that achieves the maximum amount of data reduction is called a minimal sufficient statistic. | What does it mean that a statistic $T(X)$ is sufficient for a parameter?
I think the best way to understand sufficiency is to consider familiar examples. Suppose we flip a (not necessarily fair) coin, where the probability of obtaining heads is some unknown parameter $p$. |
30,563 | Warning (in R): "ANOVA F-tests on an essentially perfect fit are unreliable" | The F-test is essentially a ratio of standard deviations. Every factor has only one observation in your sample data. Your standard deviation is zero. You get a test-statistic of zero because one cannot compare variances in your sample because there is no variance in your sample.
There is variance across factors but not within a factor. | Warning (in R): "ANOVA F-tests on an essentially perfect fit are unreliable" | The F-test is essentially a ratio of standard deviations. Every factor has only one observation in your sample data. Your standard deviation is zero. You get a test-statistic of zero because one canno | Warning (in R): "ANOVA F-tests on an essentially perfect fit are unreliable"
The F-test is essentially a ratio of standard deviations. Every factor has only one observation in your sample data. Your standard deviation is zero. You get a test-statistic of zero because one cannot compare variances in your sample because there is no variance in your sample.
There is variance across factors but not within a factor. | Warning (in R): "ANOVA F-tests on an essentially perfect fit are unreliable"
The F-test is essentially a ratio of standard deviations. Every factor has only one observation in your sample data. Your standard deviation is zero. You get a test-statistic of zero because one canno |
30,564 | Covariance matrix proposal distribution | Well, if you are looking "for any pointers"...
The (scaled)(inverse)Wishart distribution is often used because it is conjugate
to the multivariate likelihood function and thus simplifies Gibbs sampling.
In Stan, which uses Hamiltonian Monte Carlo sampling, there is no restriction for multivariate priors. The recommended approach is the separation strategy suggested by Barnard, McCulloch and Meng:
$$\Sigma=\text{diag_matrix}(\sigma)\;\Omega\;\text{diag_matrix}(\sigma)$$
where $\sigma$ is a vector of std devs and $\Omega$ is a correlation matrix.
The components of $\sigma$ can be given any reasonable prior. As to $\Omega$, the recommended prior is
$$\Omega\sim\text{LKJcorr}(\nu)$$
where "LKJ" means Lewandowski, Kurowicka and Joe. As $\nu$ increases, the prior increasingly concentrates around the unit correlation matrix, at $\nu=1$ the LKJ correlation distribution reduces to the identity distribution over correlation matrices. The LKJ prior may thus be used to control the expected amount of correlation among the parameters.
However, I've not (yet) tried non-normal distributions of random effects, so I hope I've not missed the point ;-) | Covariance matrix proposal distribution | Well, if you are looking "for any pointers"...
The (scaled)(inverse)Wishart distribution is often used because it is conjugate
to the multivariate likelihood function and thus simplifies Gibbs samplin | Covariance matrix proposal distribution
Well, if you are looking "for any pointers"...
The (scaled)(inverse)Wishart distribution is often used because it is conjugate
to the multivariate likelihood function and thus simplifies Gibbs sampling.
In Stan, which uses Hamiltonian Monte Carlo sampling, there is no restriction for multivariate priors. The recommended approach is the separation strategy suggested by Barnard, McCulloch and Meng:
$$\Sigma=\text{diag_matrix}(\sigma)\;\Omega\;\text{diag_matrix}(\sigma)$$
where $\sigma$ is a vector of std devs and $\Omega$ is a correlation matrix.
The components of $\sigma$ can be given any reasonable prior. As to $\Omega$, the recommended prior is
$$\Omega\sim\text{LKJcorr}(\nu)$$
where "LKJ" means Lewandowski, Kurowicka and Joe. As $\nu$ increases, the prior increasingly concentrates around the unit correlation matrix, at $\nu=1$ the LKJ correlation distribution reduces to the identity distribution over correlation matrices. The LKJ prior may thus be used to control the expected amount of correlation among the parameters.
However, I've not (yet) tried non-normal distributions of random effects, so I hope I've not missed the point ;-) | Covariance matrix proposal distribution
Well, if you are looking "for any pointers"...
The (scaled)(inverse)Wishart distribution is often used because it is conjugate
to the multivariate likelihood function and thus simplifies Gibbs samplin |
30,565 | Covariance matrix proposal distribution | I personally use Wishart proposals. For instance, if I want a proposal $\Sigma^*$ around $\Sigma$, I use:
$$ \Sigma^* \sim \mathcal{W}(\Sigma/a,a), $$
where $a$ is a large number, like 1000.
With that trick you will get $E[\Sigma^*]=\Sigma$ and you can adjust the variance with $a$.
If I am not mistaken, the ratio of proposals for $(p\times p)$ matrices has a closed form:
$$ \frac{q(\Sigma\to\Sigma^*)}{q(\Sigma^*\to\Sigma)} = \left(\frac{|\Sigma^*|}{|\Sigma|}\right)^{a-(p-1)/2} \cdot e^{[tr({\Sigma^*}^{-1}\Sigma)-tr({\Sigma}^{-1}\Sigma^*)] \cdot a/2}$$ | Covariance matrix proposal distribution | I personally use Wishart proposals. For instance, if I want a proposal $\Sigma^*$ around $\Sigma$, I use:
$$ \Sigma^* \sim \mathcal{W}(\Sigma/a,a), $$
where $a$ is a large number, like 1000.
With that | Covariance matrix proposal distribution
I personally use Wishart proposals. For instance, if I want a proposal $\Sigma^*$ around $\Sigma$, I use:
$$ \Sigma^* \sim \mathcal{W}(\Sigma/a,a), $$
where $a$ is a large number, like 1000.
With that trick you will get $E[\Sigma^*]=\Sigma$ and you can adjust the variance with $a$.
If I am not mistaken, the ratio of proposals for $(p\times p)$ matrices has a closed form:
$$ \frac{q(\Sigma\to\Sigma^*)}{q(\Sigma^*\to\Sigma)} = \left(\frac{|\Sigma^*|}{|\Sigma|}\right)^{a-(p-1)/2} \cdot e^{[tr({\Sigma^*}^{-1}\Sigma)-tr({\Sigma}^{-1}\Sigma^*)] \cdot a/2}$$ | Covariance matrix proposal distribution
I personally use Wishart proposals. For instance, if I want a proposal $\Sigma^*$ around $\Sigma$, I use:
$$ \Sigma^* \sim \mathcal{W}(\Sigma/a,a), $$
where $a$ is a large number, like 1000.
With that |
30,566 | Covariance matrix proposal distribution | It is well known that if you use non-Gaussian distributions, the conjugacy of the model is lost, see:
http://www.utstat.toronto.edu/wordpress/WSFiles/technicalreports/0610.pdf
Then, you need to use other MCMC methods, such as Metropolis within Gibbs sampling or some adaptive version of it. Fortunately, there is an R package for doing so:
http://cran.r-project.org/web/packages/spBayes/index.html
The recommended acceptance rate is 0.44 but, of course, there are some assumptions behind this number, similarly as in the case of the 0.234.
Are you THE Dimitris Rizopoulos? | Covariance matrix proposal distribution | It is well known that if you use non-Gaussian distributions, the conjugacy of the model is lost, see:
http://www.utstat.toronto.edu/wordpress/WSFiles/technicalreports/0610.pdf
Then, you need to use ot | Covariance matrix proposal distribution
It is well known that if you use non-Gaussian distributions, the conjugacy of the model is lost, see:
http://www.utstat.toronto.edu/wordpress/WSFiles/technicalreports/0610.pdf
Then, you need to use other MCMC methods, such as Metropolis within Gibbs sampling or some adaptive version of it. Fortunately, there is an R package for doing so:
http://cran.r-project.org/web/packages/spBayes/index.html
The recommended acceptance rate is 0.44 but, of course, there are some assumptions behind this number, similarly as in the case of the 0.234.
Are you THE Dimitris Rizopoulos? | Covariance matrix proposal distribution
It is well known that if you use non-Gaussian distributions, the conjugacy of the model is lost, see:
http://www.utstat.toronto.edu/wordpress/WSFiles/technicalreports/0610.pdf
Then, you need to use ot |
30,567 | Covariance matrix proposal distribution | Any proposal can be used if you define your log-posterior properly. You just need to use some tricks to implement it and properly define the support of your posterior, see:
How to find the support of the posterior distribution to apply Metropolis-Hastings MCMC algorithm?
There are tons of examples where a Gaussian proposal can be used for truncated posteriors. This is just an implementation trick. Again, you are asking a question with no general solution. Some proposals even have different performance for the same model and different data sets.
Good luck. | Covariance matrix proposal distribution | Any proposal can be used if you define your log-posterior properly. You just need to use some tricks to implement it and properly define the support of your posterior, see:
How to find the support of | Covariance matrix proposal distribution
Any proposal can be used if you define your log-posterior properly. You just need to use some tricks to implement it and properly define the support of your posterior, see:
How to find the support of the posterior distribution to apply Metropolis-Hastings MCMC algorithm?
There are tons of examples where a Gaussian proposal can be used for truncated posteriors. This is just an implementation trick. Again, you are asking a question with no general solution. Some proposals even have different performance for the same model and different data sets.
Good luck. | Covariance matrix proposal distribution
Any proposal can be used if you define your log-posterior properly. You just need to use some tricks to implement it and properly define the support of your posterior, see:
How to find the support of |
30,568 | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables | I always find it best in these situations to run a Monte Carlo simulation to check (roughly) what the correct answer should be. Here is some R code for doing that:
doRace <- function()
{
times <- rnorm(mean=c(60,61,58,63,61),sd=c(3,1,2.3,2.4,1.7),n=5)
winner <- which.min(times)
winner
}
winners <- replicate(n=10000,expr=doRace())
table(winners) / length(winners)
Which gives the following output for me (of course you will get slightly different answers depending on the state of your random number generator):
winners
1 2 3 4 5
0.2573 0.0317 0.6108 0.0282 0.0720
This indicates that the issue is with swimmer 2, as these results otherwise agree well with yours. I suspect you just have an incorrect cell reference somewhere. Note that a reasonable resolution to the problem is to use the Monte Carlo simulation not just as a verification method but as the final implementation for calculating the probabilities. After all, numerical integration is itself an approximate and computationally expensive procedure.
In order to be absolutely sure, we can use the integrate() function in R. First define the integral:
integral<- function(x,whichSwimmer)
{
means <- c(60,61,58,63,61)
sds <- c(3,1,2.3,2.4,1.7)
dnorm(x,mean=means[whichSwimmer],sd=sds[whichSwimmer]) *
(1 - pnorm(x,mean=means[-whichSwimmer][1],sd=sds[-whichSwimmer][1])) *
(1 - pnorm(x,mean=means[-whichSwimmer][2],sd=sds[-whichSwimmer][2])) *
(1 - pnorm(x,mean=means[-whichSwimmer][3],sd=sds[-whichSwimmer][3])) *
(1 - pnorm(x,mean=means[-whichSwimmer][4],sd=sds[-whichSwimmer][4]))
}
Then we can calculate the probability for each swimmer in turn:
>integrate(integral,whichSwimmer=1,lower=0,upper=100)
0.2596532 with absolute error < 2.5e-05
>integrate(integral,whichSwimmer=2,lower=0,upper=100)
0.03223977 with absolute error < 6.4e-06
>integrate(integral,whichSwimmer=3,lower=0,upper=100)
0.6119995 with absolute error < 1.5e-06
>integrate(integral,whichSwimmer=4,lower=0,upper=100)
0.02634785 with absolute error < 1.4e-06
>integrate(integral,whichSwimmer=5,lower=0,upper=100)
0.06975967 with absolute error < 8.1e-05
Which gives very good agreement with the Monte Carlo simulation.
Note that although you can technically give lower and upper bounds of negative/positive infinity to integrate() I found that this caused the procedure to break down, giving clearly incorrect results.
EDIT: I've just noticed you had a second question regarding the most likely ordering of swimmers. Again, we can easily check whether the intuition about just ordering the probability of each swimmer winning is correct by running a Monte Carlo simulation. We just need to adapt the sampling function to return the order of the swimmers rather than only the winner:
doRace <- function()
{
times <- rnorm(mean=c(60,61,58,63,61),sd=c(3,1,2.3,2.4,1.7),n=5)
finishOrder <- order(times)
paste(finishOrder,collapse="")
}
finishOrders <- replicate(n=1e6,expr=doRace())
which.max(table(finishOrders) / length(finishOrders))
I get the ouput:
31254
50
In other words, the most likely order is $3,1,2,5,4$ which is not the same as ordering the swimmers by their probability of winning!
For me, this is another reason to prefer the Monte Carlo approach as the final implementation as you can easily answer this and other questions - e.g. what is each swimmer's probability of finishing second or, given that swimmer $1$ finishes first, what is the most likely ordering of the remaining swimmers?
EDIT 2: To be able to answer these other questions, we need to change the sampling function again, this time to return the complete order in which the swimmers finish:
doRace <- function()
{
times <- rnorm(mean=c(60,61,58,63,61),sd=c(3,1,2.3,2.4,1.7),n=5)
finishOrder <- order(times)
finishOrder
}
finishOrders <- replicate(n=1e6,expr=doRace())
finishOrders is a matrix where each column corresponds to a single simulated race, the first row gives the winner of each race, the second row the second placed swimmer of each race and so on. So, to get the probability that each swimmer finishes second we do:
> table(finishOrders[2,]) / ncol(finishOrders)
1 2 3 4 5
0.271749 0.198205 0.235460 0.075165 0.219421
To find the most likely order given that swimmer $1$ wins the race is a little more fiddly. First, extract all races where the first row is equal to $1$:
finishOrdersWhen1WinsRace <- finishOrders[,finishOrders[1,]==1]
Then turn the finish order of each race from a vector of numbers into a character string so we can use the table function to find the most frequent one:
> which.max(table(apply(finishOrdersWhen1WinsRace,2,paste,collapse="")))
13254
8
In other words, given that swimmer $1$ wins the race, the most likely order of the remaining swimmers is $3,2,5,4$, which occurs:
> max(table(apply(finishOrdersWhen1WinsRace,2,paste,collapse="")) / ncol(finishOrdersWhen1WinsRace))
[1] 0.2341227
$23.4\%$ of the time.
I'm not sure whether a Monte Carlo approach is the only way to answer these questions but it seems likely that even if you can obtain closed-form expressions for the probabilities you'll need to rely on numerical integration like you did to find the winning probabilities. | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables | I always find it best in these situations to run a Monte Carlo simulation to check (roughly) what the correct answer should be. Here is some R code for doing that:
doRace <- function()
{
times <- rn | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables
I always find it best in these situations to run a Monte Carlo simulation to check (roughly) what the correct answer should be. Here is some R code for doing that:
doRace <- function()
{
times <- rnorm(mean=c(60,61,58,63,61),sd=c(3,1,2.3,2.4,1.7),n=5)
winner <- which.min(times)
winner
}
winners <- replicate(n=10000,expr=doRace())
table(winners) / length(winners)
Which gives the following output for me (of course you will get slightly different answers depending on the state of your random number generator):
winners
1 2 3 4 5
0.2573 0.0317 0.6108 0.0282 0.0720
This indicates that the issue is with swimmer 2, as these results otherwise agree well with yours. I suspect you just have an incorrect cell reference somewhere. Note that a reasonable resolution to the problem is to use the Monte Carlo simulation not just as a verification method but as the final implementation for calculating the probabilities. After all, numerical integration is itself an approximate and computationally expensive procedure.
In order to be absolutely sure, we can use the integrate() function in R. First define the integral:
integral<- function(x,whichSwimmer)
{
means <- c(60,61,58,63,61)
sds <- c(3,1,2.3,2.4,1.7)
dnorm(x,mean=means[whichSwimmer],sd=sds[whichSwimmer]) *
(1 - pnorm(x,mean=means[-whichSwimmer][1],sd=sds[-whichSwimmer][1])) *
(1 - pnorm(x,mean=means[-whichSwimmer][2],sd=sds[-whichSwimmer][2])) *
(1 - pnorm(x,mean=means[-whichSwimmer][3],sd=sds[-whichSwimmer][3])) *
(1 - pnorm(x,mean=means[-whichSwimmer][4],sd=sds[-whichSwimmer][4]))
}
Then we can calculate the probability for each swimmer in turn:
>integrate(integral,whichSwimmer=1,lower=0,upper=100)
0.2596532 with absolute error < 2.5e-05
>integrate(integral,whichSwimmer=2,lower=0,upper=100)
0.03223977 with absolute error < 6.4e-06
>integrate(integral,whichSwimmer=3,lower=0,upper=100)
0.6119995 with absolute error < 1.5e-06
>integrate(integral,whichSwimmer=4,lower=0,upper=100)
0.02634785 with absolute error < 1.4e-06
>integrate(integral,whichSwimmer=5,lower=0,upper=100)
0.06975967 with absolute error < 8.1e-05
Which gives very good agreement with the Monte Carlo simulation.
Note that although you can technically give lower and upper bounds of negative/positive infinity to integrate() I found that this caused the procedure to break down, giving clearly incorrect results.
EDIT: I've just noticed you had a second question regarding the most likely ordering of swimmers. Again, we can easily check whether the intuition about just ordering the probability of each swimmer winning is correct by running a Monte Carlo simulation. We just need to adapt the sampling function to return the order of the swimmers rather than only the winner:
doRace <- function()
{
times <- rnorm(mean=c(60,61,58,63,61),sd=c(3,1,2.3,2.4,1.7),n=5)
finishOrder <- order(times)
paste(finishOrder,collapse="")
}
finishOrders <- replicate(n=1e6,expr=doRace())
which.max(table(finishOrders) / length(finishOrders))
I get the ouput:
31254
50
In other words, the most likely order is $3,1,2,5,4$ which is not the same as ordering the swimmers by their probability of winning!
For me, this is another reason to prefer the Monte Carlo approach as the final implementation as you can easily answer this and other questions - e.g. what is each swimmer's probability of finishing second or, given that swimmer $1$ finishes first, what is the most likely ordering of the remaining swimmers?
EDIT 2: To be able to answer these other questions, we need to change the sampling function again, this time to return the complete order in which the swimmers finish:
doRace <- function()
{
times <- rnorm(mean=c(60,61,58,63,61),sd=c(3,1,2.3,2.4,1.7),n=5)
finishOrder <- order(times)
finishOrder
}
finishOrders <- replicate(n=1e6,expr=doRace())
finishOrders is a matrix where each column corresponds to a single simulated race, the first row gives the winner of each race, the second row the second placed swimmer of each race and so on. So, to get the probability that each swimmer finishes second we do:
> table(finishOrders[2,]) / ncol(finishOrders)
1 2 3 4 5
0.271749 0.198205 0.235460 0.075165 0.219421
To find the most likely order given that swimmer $1$ wins the race is a little more fiddly. First, extract all races where the first row is equal to $1$:
finishOrdersWhen1WinsRace <- finishOrders[,finishOrders[1,]==1]
Then turn the finish order of each race from a vector of numbers into a character string so we can use the table function to find the most frequent one:
> which.max(table(apply(finishOrdersWhen1WinsRace,2,paste,collapse="")))
13254
8
In other words, given that swimmer $1$ wins the race, the most likely order of the remaining swimmers is $3,2,5,4$, which occurs:
> max(table(apply(finishOrdersWhen1WinsRace,2,paste,collapse="")) / ncol(finishOrdersWhen1WinsRace))
[1] 0.2341227
$23.4\%$ of the time.
I'm not sure whether a Monte Carlo approach is the only way to answer these questions but it seems likely that even if you can obtain closed-form expressions for the probabilities you'll need to rely on numerical integration like you did to find the winning probabilities. | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables
I always find it best in these situations to run a Monte Carlo simulation to check (roughly) what the correct answer should be. Here is some R code for doing that:
doRace <- function()
{
times <- rn |
30,569 | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables | The answers above don't provide a closed-form solution; nor do the ones to the related question here. I will try to give an analytical answer. To fix notation, let:
$X_i$ be the independent random variables, with $X_i \sim N(\mu_i,\sigma_i^2)$
$Y_{i-1}:= X_1 - X_i, i =2,\ldots, n$.
Finally, let $e\in R^{n-1}$ be such that $(e)_i=1$.
Then
$P(X_1 \le X_i, i=2,\ldots,n) = P(Y_i \ge 0, i=2,\ldots,n)$
It is $Y_i \sim N(\mu_1-\mu_i, \sigma_1^2+\sigma_i^2)$ and moreover (straightforward calculation) $\text{cov} (Y_i, Y_j)=\sigma_1^2$.
so the covariance matrix $\Sigma$ of $Y$ is given by
$\Sigma = \text{diag}(\sigma_2^2,\ldots, \sigma_n^2) + \sigma_1^2 ee'$
Define $\nu_{i-1} := \mu_i-\mu_1, i =2,\ldots, n$. Now we use the standard affine transformation of a multivariate standard normal to obtain an arbitrarily distributed multivariate normal. Let $\xi \sim N(0, I)$ be a $(n-1)$-dimensional standard normal. We have $Y =_\text{dist} \nu + Q^{1/2} \xi$.
The square root $Q^{1/2}$ is uniquely identified.
The probability we want to estimate becomes
$P(Y \ge 0) = P(\xi \ge -Q^{-1/2} \nu) = \prod_{i=1}^{n-1} \bar \Phi( (-Q^{-1/2} \nu)_i)$
where the last equality follows from the independence of the $\xi_i$ an d $\bar \Phi$ is the complement of the cumulative distribution of the standard normal.
Last observation: $Q^{1/2}$ is trivial in the case where $\kappa:=\sigma_2=\ldots=\sigma_n$. I am omitting the derivation, but point out that there is one eigenvector $e$ with eigenvalue $\kappa^2+\sigma_1^2$. The other eigenvector lie in $[e]^\perp$ and have all eigenvalues equal to $\kappa^2$. | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables | The answers above don't provide a closed-form solution; nor do the ones to the related question here. I will try to give an analytical answer. To fix notation, let:
$X_i$ be the independent random var | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables
The answers above don't provide a closed-form solution; nor do the ones to the related question here. I will try to give an analytical answer. To fix notation, let:
$X_i$ be the independent random variables, with $X_i \sim N(\mu_i,\sigma_i^2)$
$Y_{i-1}:= X_1 - X_i, i =2,\ldots, n$.
Finally, let $e\in R^{n-1}$ be such that $(e)_i=1$.
Then
$P(X_1 \le X_i, i=2,\ldots,n) = P(Y_i \ge 0, i=2,\ldots,n)$
It is $Y_i \sim N(\mu_1-\mu_i, \sigma_1^2+\sigma_i^2)$ and moreover (straightforward calculation) $\text{cov} (Y_i, Y_j)=\sigma_1^2$.
so the covariance matrix $\Sigma$ of $Y$ is given by
$\Sigma = \text{diag}(\sigma_2^2,\ldots, \sigma_n^2) + \sigma_1^2 ee'$
Define $\nu_{i-1} := \mu_i-\mu_1, i =2,\ldots, n$. Now we use the standard affine transformation of a multivariate standard normal to obtain an arbitrarily distributed multivariate normal. Let $\xi \sim N(0, I)$ be a $(n-1)$-dimensional standard normal. We have $Y =_\text{dist} \nu + Q^{1/2} \xi$.
The square root $Q^{1/2}$ is uniquely identified.
The probability we want to estimate becomes
$P(Y \ge 0) = P(\xi \ge -Q^{-1/2} \nu) = \prod_{i=1}^{n-1} \bar \Phi( (-Q^{-1/2} \nu)_i)$
where the last equality follows from the independence of the $\xi_i$ an d $\bar \Phi$ is the complement of the cumulative distribution of the standard normal.
Last observation: $Q^{1/2}$ is trivial in the case where $\kappa:=\sigma_2=\ldots=\sigma_n$. I am omitting the derivation, but point out that there is one eigenvector $e$ with eigenvalue $\kappa^2+\sigma_1^2$. The other eigenvector lie in $[e]^\perp$ and have all eigenvalues equal to $\kappa^2$. | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables
The answers above don't provide a closed-form solution; nor do the ones to the related question here. I will try to give an analytical answer. To fix notation, let:
$X_i$ be the independent random var |
30,570 | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables | You had two questions
Question 1: What is the probability of an event where $X_i$ finishes first.
Your proposed solution look correct but, as you say, you clearly have an error in implelentation as the probablities do not add up to $1$. M. Berk has shown that it is likely to be an issue with Swimmer 2.
Question 2: If I calculate this for all swimmers, can I simply order the results to determine the most probable finishing order?
Not quite - if you have two swimmers with the same mean time in the middle of the group then the chance of one beating the other is $\frac12$, but the one with the higher standard deviation is more likely to be the overall winner: in your particular example, the chance of $X_2$ beating $X_5$ is $0.5$ but $X_5$ is more likely than $X_2$ to be the overall winner, so $X_5$ is less likely than $X_2$ to be third because of its higher standard deviation.
Using simulation, the most likely finishing order is $X_3,X_1,X_2,X_5,X_4$ (with a probability about 9.0%) above $X_3,X_1,X_5,X_2,X_4$ (about 8.0%), $X_1,X_3,X_2,X_5,X_4$ (about 6.1%), $X_3,X_2,X_5,X_1,X_4$ (about 5.8%), $X_1,X_3,X_5,X_2,X_4$ (also about 5.8%), $X_3,X_5,X_1,X_2,X_4$ (about 4.5%) and other less likely outcomes. Your idea would have predicted 31524, the second most likely outcome. | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables | You had two questions
Question 1: What is the probability of an event where $X_i$ finishes first.
Your proposed solution look correct but, as you say, you clearly have an error in implelentation as | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables
You had two questions
Question 1: What is the probability of an event where $X_i$ finishes first.
Your proposed solution look correct but, as you say, you clearly have an error in implelentation as the probablities do not add up to $1$. M. Berk has shown that it is likely to be an issue with Swimmer 2.
Question 2: If I calculate this for all swimmers, can I simply order the results to determine the most probable finishing order?
Not quite - if you have two swimmers with the same mean time in the middle of the group then the chance of one beating the other is $\frac12$, but the one with the higher standard deviation is more likely to be the overall winner: in your particular example, the chance of $X_2$ beating $X_5$ is $0.5$ but $X_5$ is more likely than $X_2$ to be the overall winner, so $X_5$ is less likely than $X_2$ to be third because of its higher standard deviation.
Using simulation, the most likely finishing order is $X_3,X_1,X_2,X_5,X_4$ (with a probability about 9.0%) above $X_3,X_1,X_5,X_2,X_4$ (about 8.0%), $X_1,X_3,X_2,X_5,X_4$ (about 6.1%), $X_3,X_2,X_5,X_1,X_4$ (about 5.8%), $X_1,X_3,X_5,X_2,X_4$ (also about 5.8%), $X_3,X_5,X_1,X_2,X_4$ (about 4.5%) and other less likely outcomes. Your idea would have predicted 31524, the second most likely outcome. | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables
You had two questions
Question 1: What is the probability of an event where $X_i$ finishes first.
Your proposed solution look correct but, as you say, you clearly have an error in implelentation as |
30,571 | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables | The formula at https://stats.stackexchange.com/a/44142/919 is correct.
Below is R code to implement it (as a function p.max). The code to input the data of the question and apply p.max is short:
X <- data.frame(Mean = c(60, 61, 58, 63, 61),
SD = c(3, 1, 2.3, 2.4, 1.7))
X$p <- sapply(seq_len(nrow(X)), p.max, mu=-X$Mean, sigma=X$SD)
(Note how supplying the negatives of the times enables p.max to compute the chances of being the smallest.)
This plot illustrates the five densities, colored according to the winning chances:
The sum of the computed chances is within $10^{-10}$ of equaling $1.$
#
# Given X[i] ~ Normal(mu[i], sigma[i]),
# compute the chance that the jth component is largest.
# `...` is passed to `integrate`.
#
p.max <- function(j, mu, sigma, Z=7, ...) {
if (is.infinite(mu[j])) {
if (mu[j] < 0) {
if (all(is.infinite(mu) & mu < 0)) return(1 / length(mu))
return(0)
}
return(1 / sum(is.infinite(mu) & mu > 0))
}
#
# Choose units that make X[j] standard Normal.
#
mu <- (mu[-j] - mu[j]) / sigma[j]
sigma <- sigma[-j] / sigma[j]
#
# Set integration limits.
#
xlim <- range(c(-Z, Z, mu-Z*sigma, mu+Z*sigma))
#
# Integrate.
#
h <- Vectorize(function(x)
exp(dnorm(x, log=TRUE) + sum(pnorm(x, mu, sigma, log.p=TRUE))))
integrate(h, xlim[1], xlim[2], ...)$value
} | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables | The formula at https://stats.stackexchange.com/a/44142/919 is correct.
Below is R code to implement it (as a function p.max). The code to input the data of the question and apply p.max is short:
X <- | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables
The formula at https://stats.stackexchange.com/a/44142/919 is correct.
Below is R code to implement it (as a function p.max). The code to input the data of the question and apply p.max is short:
X <- data.frame(Mean = c(60, 61, 58, 63, 61),
SD = c(3, 1, 2.3, 2.4, 1.7))
X$p <- sapply(seq_len(nrow(X)), p.max, mu=-X$Mean, sigma=X$SD)
(Note how supplying the negatives of the times enables p.max to compute the chances of being the smallest.)
This plot illustrates the five densities, colored according to the winning chances:
The sum of the computed chances is within $10^{-10}$ of equaling $1.$
#
# Given X[i] ~ Normal(mu[i], sigma[i]),
# compute the chance that the jth component is largest.
# `...` is passed to `integrate`.
#
p.max <- function(j, mu, sigma, Z=7, ...) {
if (is.infinite(mu[j])) {
if (mu[j] < 0) {
if (all(is.infinite(mu) & mu < 0)) return(1 / length(mu))
return(0)
}
return(1 / sum(is.infinite(mu) & mu > 0))
}
#
# Choose units that make X[j] standard Normal.
#
mu <- (mu[-j] - mu[j]) / sigma[j]
sigma <- sigma[-j] / sigma[j]
#
# Set integration limits.
#
xlim <- range(c(-Z, Z, mu-Z*sigma, mu+Z*sigma))
#
# Integrate.
#
h <- Vectorize(function(x)
exp(dnorm(x, log=TRUE) + sum(pnorm(x, mu, sigma, log.p=TRUE))))
integrate(h, xlim[1], xlim[2], ...)$value
} | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables
The formula at https://stats.stackexchange.com/a/44142/919 is correct.
Below is R code to implement it (as a function p.max). The code to input the data of the question and apply p.max is short:
X <- |
30,572 | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables | I 'm interested in this,
While I doubt there is an analytical solution, it's easy with Monte Carlo.
So if you want to apply this to the races (human, animal, snail ...) just use Monte Carlo.
But for some purposes such as if you are trying to work out the standard deviation model of your runners, you may need to do this integration many times and it may slow you down.
You can however always use Simpson's method to compute the integrals.
I used Laplace distributions instead of normal and worked out the integral for two runners, in analytical form.
Further than that I don't know. In (5) above what is Q ? | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables | I 'm interested in this,
While I doubt there is an analytical solution, it's easy with Monte Carlo.
So if you want to apply this to the races (human, animal, snail ...) just use Monte Carlo.
But for s | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables
I 'm interested in this,
While I doubt there is an analytical solution, it's easy with Monte Carlo.
So if you want to apply this to the races (human, animal, snail ...) just use Monte Carlo.
But for some purposes such as if you are trying to work out the standard deviation model of your runners, you may need to do this integration many times and it may slow you down.
You can however always use Simpson's method to compute the integrals.
I used Laplace distributions instead of normal and worked out the integral for two runners, in analytical form.
Further than that I don't know. In (5) above what is Q ? | $P(X_1 < \min(X_i,\ldots, X_n))$ across different normal random variables
I 'm interested in this,
While I doubt there is an analytical solution, it's easy with Monte Carlo.
So if you want to apply this to the races (human, animal, snail ...) just use Monte Carlo.
But for s |
30,573 | Recommendations for first time teacher (Intro to Biostatistics) | Here are a few examples which worked well for me when I was teaching statistics.
I like to begin the class with the martingale, because somehow everybody finds a winning strategy at roulette interesting, and it is fairly easy to grasp. Then later you can have people try it out for themselves, if you are doing computer labs and can find an online roulette simulator. [Warning: I once had a lab of students do this, and one of them ended up with a $60,000 profit. After that, it was not easy to convince them that the martingale is bad.]
A good way to illustrate faulty reasoning about independence is Munchhausen's Syndrome by Proxy. Allegedly several people went to prison because the doctor who invented this syndrome claimed in court that the deaths of children within the same family were indpendent events.
Everybody finds bad graphics like this one entertaining, and students often enjoy collecting them for themselves and bringing them to class.
When talking about expected value, the St. Petersburg paradox is a good one. Most people can understand it fairly quickly and it shows that the definition of expected value is tricky.
When teaching the central limit theorem, it's useful to have a wacky bimodal distribution to hand. A good one is the distirbution of the last two digits of the years on the one-cent coins which the students happen to have in their pockets. I got this one from a professor at Oberlin College.
Identifying a fake series of coin flips is a good one because the students can try it out on their friends.
The British magician Derren Brown has quite a few videos which relate to probability and statistics and are also entertaining. I used to show clips of these in class sometimes.
Finally, and most importantly, use data sets from the students' fields whenever you can. It doesn't matter exactly what, but it's really important to show them data of the type that they might plausibly collect in the future. Most students don't choose to take a statistics course. Showing students how it applies to them can make a huge difference to their enjoyment. There are statistics papers on virtually everything, even poetry. Or you are teaching life tables; instead of using boring data, how about making one for tyrannosaurs like in these notes? | Recommendations for first time teacher (Intro to Biostatistics) | Here are a few examples which worked well for me when I was teaching statistics.
I like to begin the class with the martingale, because somehow everybody finds a winning strategy at roulette interest | Recommendations for first time teacher (Intro to Biostatistics)
Here are a few examples which worked well for me when I was teaching statistics.
I like to begin the class with the martingale, because somehow everybody finds a winning strategy at roulette interesting, and it is fairly easy to grasp. Then later you can have people try it out for themselves, if you are doing computer labs and can find an online roulette simulator. [Warning: I once had a lab of students do this, and one of them ended up with a $60,000 profit. After that, it was not easy to convince them that the martingale is bad.]
A good way to illustrate faulty reasoning about independence is Munchhausen's Syndrome by Proxy. Allegedly several people went to prison because the doctor who invented this syndrome claimed in court that the deaths of children within the same family were indpendent events.
Everybody finds bad graphics like this one entertaining, and students often enjoy collecting them for themselves and bringing them to class.
When talking about expected value, the St. Petersburg paradox is a good one. Most people can understand it fairly quickly and it shows that the definition of expected value is tricky.
When teaching the central limit theorem, it's useful to have a wacky bimodal distribution to hand. A good one is the distirbution of the last two digits of the years on the one-cent coins which the students happen to have in their pockets. I got this one from a professor at Oberlin College.
Identifying a fake series of coin flips is a good one because the students can try it out on their friends.
The British magician Derren Brown has quite a few videos which relate to probability and statistics and are also entertaining. I used to show clips of these in class sometimes.
Finally, and most importantly, use data sets from the students' fields whenever you can. It doesn't matter exactly what, but it's really important to show them data of the type that they might plausibly collect in the future. Most students don't choose to take a statistics course. Showing students how it applies to them can make a huge difference to their enjoyment. There are statistics papers on virtually everything, even poetry. Or you are teaching life tables; instead of using boring data, how about making one for tyrannosaurs like in these notes? | Recommendations for first time teacher (Intro to Biostatistics)
Here are a few examples which worked well for me when I was teaching statistics.
I like to begin the class with the martingale, because somehow everybody finds a winning strategy at roulette interest |
30,574 | Recommendations for first time teacher (Intro to Biostatistics) | This site has a fantastic introductory biological statistics textbook written by a professor and offered online for free: http://udel.edu/~mcdonald/statintro.html It also has a link to a course that the professor teaches on biological data analysis with lectures and topics. It would probably be good form to send him an email asking if you can look over his lectures to help structure your class, but as a guy who wrote a whole textbook and offers it online for free, I would imagine he's pretty open to the free sharing of his work for educational purposes.
Good luck. | Recommendations for first time teacher (Intro to Biostatistics) | This site has a fantastic introductory biological statistics textbook written by a professor and offered online for free: http://udel.edu/~mcdonald/statintro.html It also has a link to a course that | Recommendations for first time teacher (Intro to Biostatistics)
This site has a fantastic introductory biological statistics textbook written by a professor and offered online for free: http://udel.edu/~mcdonald/statintro.html It also has a link to a course that the professor teaches on biological data analysis with lectures and topics. It would probably be good form to send him an email asking if you can look over his lectures to help structure your class, but as a guy who wrote a whole textbook and offers it online for free, I would imagine he's pretty open to the free sharing of his work for educational purposes.
Good luck. | Recommendations for first time teacher (Intro to Biostatistics)
This site has a fantastic introductory biological statistics textbook written by a professor and offered online for free: http://udel.edu/~mcdonald/statintro.html It also has a link to a course that |
30,575 | Recommendations for first time teacher (Intro to Biostatistics) | You might be interested in the book 'Teaching Statistics: A Bag of Tricks' by Andrew Gelman, which looks specifically at statistics pedagogy. | Recommendations for first time teacher (Intro to Biostatistics) | You might be interested in the book 'Teaching Statistics: A Bag of Tricks' by Andrew Gelman, which looks specifically at statistics pedagogy. | Recommendations for first time teacher (Intro to Biostatistics)
You might be interested in the book 'Teaching Statistics: A Bag of Tricks' by Andrew Gelman, which looks specifically at statistics pedagogy. | Recommendations for first time teacher (Intro to Biostatistics)
You might be interested in the book 'Teaching Statistics: A Bag of Tricks' by Andrew Gelman, which looks specifically at statistics pedagogy. |
30,576 | Normality of residuals vs sample data; what about t-tests? | It's the same for t-tests. There's no need for the data-set as a whole to be normally distributed (& if there is a difference in means between the groups it won't be), only the residuals. Of course, for a t-test, saying the residuals are normally distributed is the same as saying each group is normally distributed.
The distribution of the independent variables (in the case of t-tests it's the group label) is always irrelevant in ANOVA, regression, & the like: you're interested in the distribution of the response variable conditional on given values of the independent variables. | Normality of residuals vs sample data; what about t-tests? | It's the same for t-tests. There's no need for the data-set as a whole to be normally distributed (& if there is a difference in means between the groups it won't be), only the residuals. Of course, | Normality of residuals vs sample data; what about t-tests?
It's the same for t-tests. There's no need for the data-set as a whole to be normally distributed (& if there is a difference in means between the groups it won't be), only the residuals. Of course, for a t-test, saying the residuals are normally distributed is the same as saying each group is normally distributed.
The distribution of the independent variables (in the case of t-tests it's the group label) is always irrelevant in ANOVA, regression, & the like: you're interested in the distribution of the response variable conditional on given values of the independent variables. | Normality of residuals vs sample data; what about t-tests?
It's the same for t-tests. There's no need for the data-set as a whole to be normally distributed (& if there is a difference in means between the groups it won't be), only the residuals. Of course, |
30,577 | Normality of residuals vs sample data; what about t-tests? | All the procedures assume conditional normality, not marginal normality.
(Consider: a t-test is an ANOVA with two groups)
If you were to look at the distribution of the two groups separately in a t-test (reducing your ability to detect a common departure from normality, but on the other hand allowing you to see a large difference in the two distributional shapes), it doesn't matter whether or not you subtract the mean because you're still assessing conditional normality. | Normality of residuals vs sample data; what about t-tests? | All the procedures assume conditional normality, not marginal normality.
(Consider: a t-test is an ANOVA with two groups)
If you were to look at the distribution of the two groups separately in a t-t | Normality of residuals vs sample data; what about t-tests?
All the procedures assume conditional normality, not marginal normality.
(Consider: a t-test is an ANOVA with two groups)
If you were to look at the distribution of the two groups separately in a t-test (reducing your ability to detect a common departure from normality, but on the other hand allowing you to see a large difference in the two distributional shapes), it doesn't matter whether or not you subtract the mean because you're still assessing conditional normality. | Normality of residuals vs sample data; what about t-tests?
All the procedures assume conditional normality, not marginal normality.
(Consider: a t-test is an ANOVA with two groups)
If you were to look at the distribution of the two groups separately in a t-t |
30,578 | Calculating eta squared from F and df | We know that:
$$
F = \frac{MS_B} {MS_W} = \frac{SS_B/(k-1)} {SS_W/(N-k)}.
$$
Thus $SS_B = F \times MS_W \times (k-1)$, and $SS_W = MS_W \times (N-k)$.
We also know that:
$$
\eta^2 = \frac{SS_B}{SS_B + SS_W}
$$
Thus, if we substitute (1) in (2):
$$
\eta^2 = \frac{F \times MS_W \times (k-1)}{F \times MS_W \times (k-1) + MS_W \times (N-k)}
$$
The $MS_W$ terms in both numerator and denominator can be removed (simplified), leaving:
$$
\eta^2 = \frac{F (k-1)}{F (k-1) + (N-k)} = \frac{F (df_B)}{F (df_B) + (df_W)}
$$
So, it's possible to compute eta-squared using only F and degrees of freedom. | Calculating eta squared from F and df | We know that:
$$
F = \frac{MS_B} {MS_W} = \frac{SS_B/(k-1)} {SS_W/(N-k)}.
$$
Thus $SS_B = F \times MS_W \times (k-1)$, and $SS_W = MS_W \times (N-k)$.
We also know that:
$$
\eta^2 = \frac{SS_B}{SS_B + | Calculating eta squared from F and df
We know that:
$$
F = \frac{MS_B} {MS_W} = \frac{SS_B/(k-1)} {SS_W/(N-k)}.
$$
Thus $SS_B = F \times MS_W \times (k-1)$, and $SS_W = MS_W \times (N-k)$.
We also know that:
$$
\eta^2 = \frac{SS_B}{SS_B + SS_W}
$$
Thus, if we substitute (1) in (2):
$$
\eta^2 = \frac{F \times MS_W \times (k-1)}{F \times MS_W \times (k-1) + MS_W \times (N-k)}
$$
The $MS_W$ terms in both numerator and denominator can be removed (simplified), leaving:
$$
\eta^2 = \frac{F (k-1)}{F (k-1) + (N-k)} = \frac{F (df_B)}{F (df_B) + (df_W)}
$$
So, it's possible to compute eta-squared using only F and degrees of freedom. | Calculating eta squared from F and df
We know that:
$$
F = \frac{MS_B} {MS_W} = \frac{SS_B/(k-1)} {SS_W/(N-k)}.
$$
Thus $SS_B = F \times MS_W \times (k-1)$, and $SS_W = MS_W \times (N-k)$.
We also know that:
$$
\eta^2 = \frac{SS_B}{SS_B + |
30,579 | Calculating eta squared from F and df | This question was based on a huge and very basic error. F is not
$$
F = \frac{(N-k)ss_{between}}{(k-1)(ss_{between} + ss_{error})}
$$
But rather
$$
F = \frac{(N-k)ss_{between}}{(k-1)ss_{error}}
$$
With this correction, everything makes sense. Unfortunately, I think it also means that there is no way to calculate etasq if all you know is F and df.
Back to first-year stats for me! | Calculating eta squared from F and df | This question was based on a huge and very basic error. F is not
$$
F = \frac{(N-k)ss_{between}}{(k-1)(ss_{between} + ss_{error})}
$$
But rather
$$
F = \frac{(N-k)ss_{between}}{(k-1)ss_{error}}
$$
Wi | Calculating eta squared from F and df
This question was based on a huge and very basic error. F is not
$$
F = \frac{(N-k)ss_{between}}{(k-1)(ss_{between} + ss_{error})}
$$
But rather
$$
F = \frac{(N-k)ss_{between}}{(k-1)ss_{error}}
$$
With this correction, everything makes sense. Unfortunately, I think it also means that there is no way to calculate etasq if all you know is F and df.
Back to first-year stats for me! | Calculating eta squared from F and df
This question was based on a huge and very basic error. F is not
$$
F = \frac{(N-k)ss_{between}}{(k-1)(ss_{between} + ss_{error})}
$$
But rather
$$
F = \frac{(N-k)ss_{between}}{(k-1)ss_{error}}
$$
Wi |
30,580 | Calculating eta squared from F and df | This article by Daniel Lakens explains how eta squared can be calculated from only F and degrees of freedom, but only in cases of one-way ANOVA. This is the example:
For example, for an $F(1, 38) = 7.21$, $η2p = 7.21 \cdot 1/(7.21 \cdot 1 + 38) = 0.16$
Lakens, D. (2013). Calculating and reporting effect sizes to facilitate cumulative science: a practical primer for t-tests and ANOVAs. Frontiers in Psychology, 4. | Calculating eta squared from F and df | This article by Daniel Lakens explains how eta squared can be calculated from only F and degrees of freedom, but only in cases of one-way ANOVA. This is the example:
For example, for an $F(1, 38) = | Calculating eta squared from F and df
This article by Daniel Lakens explains how eta squared can be calculated from only F and degrees of freedom, but only in cases of one-way ANOVA. This is the example:
For example, for an $F(1, 38) = 7.21$, $η2p = 7.21 \cdot 1/(7.21 \cdot 1 + 38) = 0.16$
Lakens, D. (2013). Calculating and reporting effect sizes to facilitate cumulative science: a practical primer for t-tests and ANOVAs. Frontiers in Psychology, 4. | Calculating eta squared from F and df
This article by Daniel Lakens explains how eta squared can be calculated from only F and degrees of freedom, but only in cases of one-way ANOVA. This is the example:
For example, for an $F(1, 38) = |
30,581 | Calculating eta squared from F and df | At this IBM/SPSS help page we find:
Terms are defined elsewhere.
It's beyond me, but maybe others can make heads or tails of it. | Calculating eta squared from F and df | At this IBM/SPSS help page we find:
Terms are defined elsewhere.
It's beyond me, but maybe others can make heads or tails of it. | Calculating eta squared from F and df
At this IBM/SPSS help page we find:
Terms are defined elsewhere.
It's beyond me, but maybe others can make heads or tails of it. | Calculating eta squared from F and df
At this IBM/SPSS help page we find:
Terms are defined elsewhere.
It's beyond me, but maybe others can make heads or tails of it. |
30,582 | Calculating eta squared from F and df | Forgive unearthing an old story, but...
The main reason for confusion in this thread is that SPSS calculates the partial eta-squared instead of the normal eta-squared (and in some versions even incorrectly names it). Formulas which you used are correct, the calculations also, but you read an incorrect result in SPSS, and the problem is broadly described here:
Levine, T. R., & Hullett, C. R. (2002). Eta squared, partial eta squared, and misreporting of effect size in communication research. Human Communication Research, 28(4), 612-625.
https://msu.edu/~levinet/eta%20squared%20hcr.pdf | Calculating eta squared from F and df | Forgive unearthing an old story, but...
The main reason for confusion in this thread is that SPSS calculates the partial eta-squared instead of the normal eta-squared (and in some versions even incorr | Calculating eta squared from F and df
Forgive unearthing an old story, but...
The main reason for confusion in this thread is that SPSS calculates the partial eta-squared instead of the normal eta-squared (and in some versions even incorrectly names it). Formulas which you used are correct, the calculations also, but you read an incorrect result in SPSS, and the problem is broadly described here:
Levine, T. R., & Hullett, C. R. (2002). Eta squared, partial eta squared, and misreporting of effect size in communication research. Human Communication Research, 28(4), 612-625.
https://msu.edu/~levinet/eta%20squared%20hcr.pdf | Calculating eta squared from F and df
Forgive unearthing an old story, but...
The main reason for confusion in this thread is that SPSS calculates the partial eta-squared instead of the normal eta-squared (and in some versions even incorr |
30,583 | How to fit Bradley–Terry–Luce model in R, without complicated formula? | I think the best package for Paired Comparison (PC) data in R is the prefmod package, which allows to conveniently prepare data to fit (log linear) BTL models in R. It uses a Poisson GLM (more accurately, a multinomial logit in Poisson formulation see e.g. this discussion).
The nice thing is that it has a function prefmod::llbt.design that automatically converts your data into the necessary format and necessary design matrix.
For example, say you have 6 objects all pairwise compared. Then
R> library(prefmod)
R> des<-llbt.design(data, nitems=6)
will build the design matrix from a data matrix that looks like this:
P1 0 0 NA 2 2 2 0 0 1 0 0 0 1 0 1 1 2
P2 0 0 NA 0 2 2 0 2 2 2 0 2 2 0 2 1 1
P3 1 0 NA 0 0 2 0 0 1 0 0 0 1 0 1 1 2
P4 0 0 NA 0 2 0 0 0 0 0 0 0 0 0 2 1 1
P5 0 0 NA 2 2 2 2 2 2 0 0 0 0 0 2 2 2
P6 2 2 NA 0 0 0 2 2 2 2 0 0 0 0 2 1 2
with rows denoting people, columns denoting comparisons and 0 means undecided 1 means object 1 preferred and 2 means object 2 preferred. Missing values are allowed. Edit: As this is probably not something to infer simply from the data above, I spell it out here. The comparisons must be ordered the following way((12) mean comparison object 1 with object 2):
(12) (13) (23) (14) (24) (34) (15) (25) etc.
Fitting is than most conveniently carried out with the gnm::gnm function, as it allows you to do statistical modelling. (Edit: You can also use the prefmod::llbt.fit function, which is a bit simpler as it takes only the counts and the design matrix.)
R> res<-gnm(y~o1+o2+o3+o4+o5+o6, eliminate=mu, family=poisson, data=des)
R> summary(res)
Call:
gnm(formula = y ~ o1 + o2 + o3 + o4 + o5 + o6, eliminate = mu,
family = poisson, data = des)
Deviance Residuals:
Min 1Q Median 3Q Max
-7.669 -4.484 -2.234 4.625 10.353
Coefficients of interest:
Estimate Std. Error z value Pr(>|z|)
o1 1.05368 0.04665 22.586 < 2e-16 ***
o2 0.52833 0.04360 12.118 < 2e-16 ***
o3 0.13888 0.04297 3.232 0.00123 **
o4 0.24185 0.04238 5.707 1.15e-08 ***
o5 0.10699 0.04245 2.521 0.01171 *
o6 0.00000 NA NA NA
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Dispersion parameter for poisson family taken to be 1)
Std. Error is NA where coefficient has been constrained or is unidentified
Residual deviance: 2212.7 on 70 degrees of freedom
AIC: 2735.3
Please note that the eliminate term will omit the nuisance parameters from the summary. You then can get the worth parameters (your deltas) as
## calculating and plotting worth parameters
R> wmat<-llbt.worth(res)
worth
o1 0.50518407
o2 0.17666128
o3 0.08107183
o4 0.09961109
o5 0.07606193
o6 0.06140979
And you can plot them with
R> plotworth(wmat)
If you have many objects and want to write a formula object o1+o2+...+on fast, you can use
R> n<-30
R> objnam<-paste("o",1:n,sep="")
R> fmla<-as.formula(paste("y~",paste(objnam, collapse= "+")))
R> fmla
y ~ o1 + o2 + o3 + o4 + o5 + o6 + o7 + o8 + o9 + o10 + o11 +
o12 + o13 + o14 + o15 + o16 + o17 + o18 + o19 + o20 + o21 +
o22 + o23 + o24 + o25 + o26 + o27 + o28 + o29 + o30
to generate the formula for gnm (which you wouldn't need for llbt.fit).
There is a JSS article, see also https://r-forge.r-project.org/projects/prefmod/ and the documentation via ?llbt.design. | How to fit Bradley–Terry–Luce model in R, without complicated formula? | I think the best package for Paired Comparison (PC) data in R is the prefmod package, which allows to conveniently prepare data to fit (log linear) BTL models in R. It uses a Poisson GLM (more accurat | How to fit Bradley–Terry–Luce model in R, without complicated formula?
I think the best package for Paired Comparison (PC) data in R is the prefmod package, which allows to conveniently prepare data to fit (log linear) BTL models in R. It uses a Poisson GLM (more accurately, a multinomial logit in Poisson formulation see e.g. this discussion).
The nice thing is that it has a function prefmod::llbt.design that automatically converts your data into the necessary format and necessary design matrix.
For example, say you have 6 objects all pairwise compared. Then
R> library(prefmod)
R> des<-llbt.design(data, nitems=6)
will build the design matrix from a data matrix that looks like this:
P1 0 0 NA 2 2 2 0 0 1 0 0 0 1 0 1 1 2
P2 0 0 NA 0 2 2 0 2 2 2 0 2 2 0 2 1 1
P3 1 0 NA 0 0 2 0 0 1 0 0 0 1 0 1 1 2
P4 0 0 NA 0 2 0 0 0 0 0 0 0 0 0 2 1 1
P5 0 0 NA 2 2 2 2 2 2 0 0 0 0 0 2 2 2
P6 2 2 NA 0 0 0 2 2 2 2 0 0 0 0 2 1 2
with rows denoting people, columns denoting comparisons and 0 means undecided 1 means object 1 preferred and 2 means object 2 preferred. Missing values are allowed. Edit: As this is probably not something to infer simply from the data above, I spell it out here. The comparisons must be ordered the following way((12) mean comparison object 1 with object 2):
(12) (13) (23) (14) (24) (34) (15) (25) etc.
Fitting is than most conveniently carried out with the gnm::gnm function, as it allows you to do statistical modelling. (Edit: You can also use the prefmod::llbt.fit function, which is a bit simpler as it takes only the counts and the design matrix.)
R> res<-gnm(y~o1+o2+o3+o4+o5+o6, eliminate=mu, family=poisson, data=des)
R> summary(res)
Call:
gnm(formula = y ~ o1 + o2 + o3 + o4 + o5 + o6, eliminate = mu,
family = poisson, data = des)
Deviance Residuals:
Min 1Q Median 3Q Max
-7.669 -4.484 -2.234 4.625 10.353
Coefficients of interest:
Estimate Std. Error z value Pr(>|z|)
o1 1.05368 0.04665 22.586 < 2e-16 ***
o2 0.52833 0.04360 12.118 < 2e-16 ***
o3 0.13888 0.04297 3.232 0.00123 **
o4 0.24185 0.04238 5.707 1.15e-08 ***
o5 0.10699 0.04245 2.521 0.01171 *
o6 0.00000 NA NA NA
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Dispersion parameter for poisson family taken to be 1)
Std. Error is NA where coefficient has been constrained or is unidentified
Residual deviance: 2212.7 on 70 degrees of freedom
AIC: 2735.3
Please note that the eliminate term will omit the nuisance parameters from the summary. You then can get the worth parameters (your deltas) as
## calculating and plotting worth parameters
R> wmat<-llbt.worth(res)
worth
o1 0.50518407
o2 0.17666128
o3 0.08107183
o4 0.09961109
o5 0.07606193
o6 0.06140979
And you can plot them with
R> plotworth(wmat)
If you have many objects and want to write a formula object o1+o2+...+on fast, you can use
R> n<-30
R> objnam<-paste("o",1:n,sep="")
R> fmla<-as.formula(paste("y~",paste(objnam, collapse= "+")))
R> fmla
y ~ o1 + o2 + o3 + o4 + o5 + o6 + o7 + o8 + o9 + o10 + o11 +
o12 + o13 + o14 + o15 + o16 + o17 + o18 + o19 + o20 + o21 +
o22 + o23 + o24 + o25 + o26 + o27 + o28 + o29 + o30
to generate the formula for gnm (which you wouldn't need for llbt.fit).
There is a JSS article, see also https://r-forge.r-project.org/projects/prefmod/ and the documentation via ?llbt.design. | How to fit Bradley–Terry–Luce model in R, without complicated formula?
I think the best package for Paired Comparison (PC) data in R is the prefmod package, which allows to conveniently prepare data to fit (log linear) BTL models in R. It uses a Poisson GLM (more accurat |
30,584 | Difference between G-test and t-test and which should be used for A/B testing? | In general, the test which is less approximate in calculating the test statistics is better, although all will converge to the same results with increasing sample size.
So, since A/B-tests generally focus on binary outcomes, ...
Short answer:
Use the G-test, because it is less approximate.
Long answer:
The t-test, in A/B-tests the case of unequal sample sizes and unequal variance, approximates the difference of two distributions with a t-distribution, which is questionable itself. The two distributions may be unknown, but it is considered that their mean and variance is sufficient to describe it (otherwise any conclusion won't help much), which is of course true for the normal distribution.
In the special case of binary outcome, the binomial distribution can be approximated with a normal distribution with $\mu=np,\sigma^2=np(1-p)$, which is valid for $n*p*(1-p)\geq9$ (rule of the thumb, $n$=trials,$p$=success-rate).
So, in summary, although it is ok to apply the t-test, two approximations are performed to transform the binomial case to a more generic case, which is not necessary here, since less approximative tests like the G-test or (even better) Fisher's exact test are available for this special case. The Fisher's exact test should be applied especially if the sample-size is less equal 20 (another rule of the thumb), but I guess this does not matter in a solid A/B-test. | Difference between G-test and t-test and which should be used for A/B testing? | In general, the test which is less approximate in calculating the test statistics is better, although all will converge to the same results with increasing sample size.
So, since A/B-tests generally f | Difference between G-test and t-test and which should be used for A/B testing?
In general, the test which is less approximate in calculating the test statistics is better, although all will converge to the same results with increasing sample size.
So, since A/B-tests generally focus on binary outcomes, ...
Short answer:
Use the G-test, because it is less approximate.
Long answer:
The t-test, in A/B-tests the case of unequal sample sizes and unequal variance, approximates the difference of two distributions with a t-distribution, which is questionable itself. The two distributions may be unknown, but it is considered that their mean and variance is sufficient to describe it (otherwise any conclusion won't help much), which is of course true for the normal distribution.
In the special case of binary outcome, the binomial distribution can be approximated with a normal distribution with $\mu=np,\sigma^2=np(1-p)$, which is valid for $n*p*(1-p)\geq9$ (rule of the thumb, $n$=trials,$p$=success-rate).
So, in summary, although it is ok to apply the t-test, two approximations are performed to transform the binomial case to a more generic case, which is not necessary here, since less approximative tests like the G-test or (even better) Fisher's exact test are available for this special case. The Fisher's exact test should be applied especially if the sample-size is less equal 20 (another rule of the thumb), but I guess this does not matter in a solid A/B-test. | Difference between G-test and t-test and which should be used for A/B testing?
In general, the test which is less approximate in calculating the test statistics is better, although all will converge to the same results with increasing sample size.
So, since A/B-tests generally f |
30,585 | Difference between G-test and t-test and which should be used for A/B testing? | Ben Tilly's page that you referenced is an excellent summary of A/B testing for beginners. As you get into more detailed questions/study design problems, however, it is worth seeking out more detailed primary sources. Kohavi et al published a seminal paper on AB testing that is a good combination of comprehensiveness and readability. I highly recommend it: http://exp-platform.com/Documents/GuideControlledExperiments.pdf.
Back to your questions, the real questions you should be asking yourself are:
How many impressions do I need to get in the treatments and control for the result to be significantly significant?
What is the minimum effect size that I am concerned with? Are you interested in treatments that are at least 5% better than controls, or .005% better?
In case of multiple treatments, is there a scenario for comparing treatments to each other, or is it sufficient to compare each treatment to the control?
What variables are important to measure to ensure that treatment groups are not affected by unintentional side effects of your experiment. Kohavi paper has a great example of this in terms of web site performance: if your treatment experience is slower then control for whatever reason (more images, different server, quick-and-dirty code), this has potential to seriously derail the test.
Does it make more sense to enroll users or impressions into the experiments? In other words, does it make sense to ensure that the user always gets either control or treatment experience for the duration of session/trial period, or can you enroll each page impression into the test independently?
As you work through these questions, you will eventually end up with a better understanding of test parameters. Combined with your domain knowledge (e.g. whether your site experiences a strong cyclical pattern that you would like to control for), appetite for exposing users to experiments (are you actually willing to show the treatment experience to many users, or would you rather contain the potential damage) and desired speed of obtaining results, this understanding will guide you towards ultimately determining how to split up the overall traffic among controls and treatments.
I hate answering specific questions with "it depends", but in this case it really does depend on what is going on with your site and experiment. Under certain condition, it will not make a significant difference whether to split the traffic 50/50 or 90/10, while in different circumstances this may be very important. YMMV, but a good reference like the paper cited above will definitely move you in the right direction. | Difference between G-test and t-test and which should be used for A/B testing? | Ben Tilly's page that you referenced is an excellent summary of A/B testing for beginners. As you get into more detailed questions/study design problems, however, it is worth seeking out more detailed | Difference between G-test and t-test and which should be used for A/B testing?
Ben Tilly's page that you referenced is an excellent summary of A/B testing for beginners. As you get into more detailed questions/study design problems, however, it is worth seeking out more detailed primary sources. Kohavi et al published a seminal paper on AB testing that is a good combination of comprehensiveness and readability. I highly recommend it: http://exp-platform.com/Documents/GuideControlledExperiments.pdf.
Back to your questions, the real questions you should be asking yourself are:
How many impressions do I need to get in the treatments and control for the result to be significantly significant?
What is the minimum effect size that I am concerned with? Are you interested in treatments that are at least 5% better than controls, or .005% better?
In case of multiple treatments, is there a scenario for comparing treatments to each other, or is it sufficient to compare each treatment to the control?
What variables are important to measure to ensure that treatment groups are not affected by unintentional side effects of your experiment. Kohavi paper has a great example of this in terms of web site performance: if your treatment experience is slower then control for whatever reason (more images, different server, quick-and-dirty code), this has potential to seriously derail the test.
Does it make more sense to enroll users or impressions into the experiments? In other words, does it make sense to ensure that the user always gets either control or treatment experience for the duration of session/trial period, or can you enroll each page impression into the test independently?
As you work through these questions, you will eventually end up with a better understanding of test parameters. Combined with your domain knowledge (e.g. whether your site experiences a strong cyclical pattern that you would like to control for), appetite for exposing users to experiments (are you actually willing to show the treatment experience to many users, or would you rather contain the potential damage) and desired speed of obtaining results, this understanding will guide you towards ultimately determining how to split up the overall traffic among controls and treatments.
I hate answering specific questions with "it depends", but in this case it really does depend on what is going on with your site and experiment. Under certain condition, it will not make a significant difference whether to split the traffic 50/50 or 90/10, while in different circumstances this may be very important. YMMV, but a good reference like the paper cited above will definitely move you in the right direction. | Difference between G-test and t-test and which should be used for A/B testing?
Ben Tilly's page that you referenced is an excellent summary of A/B testing for beginners. As you get into more detailed questions/study design problems, however, it is worth seeking out more detailed |
30,586 | Difference between G-test and t-test and which should be used for A/B testing? | I can't comment on the original post since I lack StackExchange points or whatever, but I just wanted to point out that for the p-value, ABBA doesn't use a simple normal-approximation-based Z-test, though I can see how you might think that from a brief read of the page. ABBA uses exact binomial statistics up to sample size 100, beyond that it does rely on the normal approximation with a continuity correction. I haven't seen cases where it differs greatly from "less approximate" tests but I would be very interested in seeing any such cases if you run into them.
There are no t-distributions or t-tests present in any case.
For confidence intervals, it does always rely on a normal approximation, though it uses the Agresti-Coull method which performs pretty well. | Difference between G-test and t-test and which should be used for A/B testing? | I can't comment on the original post since I lack StackExchange points or whatever, but I just wanted to point out that for the p-value, ABBA doesn't use a simple normal-approximation-based Z-test, th | Difference between G-test and t-test and which should be used for A/B testing?
I can't comment on the original post since I lack StackExchange points or whatever, but I just wanted to point out that for the p-value, ABBA doesn't use a simple normal-approximation-based Z-test, though I can see how you might think that from a brief read of the page. ABBA uses exact binomial statistics up to sample size 100, beyond that it does rely on the normal approximation with a continuity correction. I haven't seen cases where it differs greatly from "less approximate" tests but I would be very interested in seeing any such cases if you run into them.
There are no t-distributions or t-tests present in any case.
For confidence intervals, it does always rely on a normal approximation, though it uses the Agresti-Coull method which performs pretty well. | Difference between G-test and t-test and which should be used for A/B testing?
I can't comment on the original post since I lack StackExchange points or whatever, but I just wanted to point out that for the p-value, ABBA doesn't use a simple normal-approximation-based Z-test, th |
30,587 | How can I produce a plot showing the directional angles of my points? [closed] | It sounds like the data consist of vectors of (x,y) coordinates and the angles. Let's simulate some as an example:
set.seed(43)
x <- rnorm(50)
y <- rnorm(50)
angles <- runif(50, min=-pi, max=pi)
Plot the locations:
plot(x, y, pch=19, cex=0.8, col="Blue")
Add arrows to show the orientations at these points:
length <- 0.2
arrows(x, y, x1=x+length*cos(angles), y1=y+length*sin(angles),
length=0.05, col="Gray") | How can I produce a plot showing the directional angles of my points? [closed] | It sounds like the data consist of vectors of (x,y) coordinates and the angles. Let's simulate some as an example:
set.seed(43)
x <- rnorm(50)
y <- rnorm(50)
angles <- runif(50, min=-pi, max=pi)
Plo | How can I produce a plot showing the directional angles of my points? [closed]
It sounds like the data consist of vectors of (x,y) coordinates and the angles. Let's simulate some as an example:
set.seed(43)
x <- rnorm(50)
y <- rnorm(50)
angles <- runif(50, min=-pi, max=pi)
Plot the locations:
plot(x, y, pch=19, cex=0.8, col="Blue")
Add arrows to show the orientations at these points:
length <- 0.2
arrows(x, y, x1=x+length*cos(angles), y1=y+length*sin(angles),
length=0.05, col="Gray") | How can I produce a plot showing the directional angles of my points? [closed]
It sounds like the data consist of vectors of (x,y) coordinates and the angles. Let's simulate some as an example:
set.seed(43)
x <- rnorm(50)
y <- rnorm(50)
angles <- runif(50, min=-pi, max=pi)
Plo |
30,588 | How can I produce a plot showing the directional angles of my points? [closed] | To add to the answer by @whuber. The ms.arrows and my.symbols functions in the TeachingDemos package for R might be of interest. They would also plot the arrows but you can give the anges directly rather than computing sine and cosine, it also makes it easier if you want the arrows centered on the points rather than originating from the points. | How can I produce a plot showing the directional angles of my points? [closed] | To add to the answer by @whuber. The ms.arrows and my.symbols functions in the TeachingDemos package for R might be of interest. They would also plot the arrows but you can give the anges directly r | How can I produce a plot showing the directional angles of my points? [closed]
To add to the answer by @whuber. The ms.arrows and my.symbols functions in the TeachingDemos package for R might be of interest. They would also plot the arrows but you can give the anges directly rather than computing sine and cosine, it also makes it easier if you want the arrows centered on the points rather than originating from the points. | How can I produce a plot showing the directional angles of my points? [closed]
To add to the answer by @whuber. The ms.arrows and my.symbols functions in the TeachingDemos package for R might be of interest. They would also plot the arrows but you can give the anges directly r |
30,589 | Are ecologists the only ones who didn't know that the arcsine is asinine? | I teach it to public health students for two reasons:
one of my colleagues teach it (in the introduction course) as magic recipe, I show them the Delta method and how it is derived;
I think the Delta method and variance stabilizing transformations are not asinine and can be useful. The confidence interval computed using arcsin transform with correction of continuity is not perfect but behaves reasonnably well, and for small samples it is much much better¹ than the Wald procedure, which is still widely used.
As John for psychology and neuroscience, I think many people in epidemiology don’t even care, they just use linear models in a push-button way.
¹ Pires, Amado, 2008. Interval estimators for a binomial proportion. | Are ecologists the only ones who didn't know that the arcsine is asinine? | I teach it to public health students for two reasons:
one of my colleagues teach it (in the introduction course) as magic recipe, I show them the Delta method and how it is derived;
I think the Delta | Are ecologists the only ones who didn't know that the arcsine is asinine?
I teach it to public health students for two reasons:
one of my colleagues teach it (in the introduction course) as magic recipe, I show them the Delta method and how it is derived;
I think the Delta method and variance stabilizing transformations are not asinine and can be useful. The confidence interval computed using arcsin transform with correction of continuity is not perfect but behaves reasonnably well, and for small samples it is much much better¹ than the Wald procedure, which is still widely used.
As John for psychology and neuroscience, I think many people in epidemiology don’t even care, they just use linear models in a push-button way.
¹ Pires, Amado, 2008. Interval estimators for a binomial proportion. | Are ecologists the only ones who didn't know that the arcsine is asinine?
I teach it to public health students for two reasons:
one of my colleagues teach it (in the introduction course) as magic recipe, I show them the Delta method and how it is derived;
I think the Delta |
30,590 | Are ecologists the only ones who didn't know that the arcsine is asinine? | I can speak from experience that psychology and neuroscience often don't even make the effort to transform % values in order to normalize them. The modal analysis is an ANOVA or t-test of the %correct or %error. | Are ecologists the only ones who didn't know that the arcsine is asinine? | I can speak from experience that psychology and neuroscience often don't even make the effort to transform % values in order to normalize them. The modal analysis is an ANOVA or t-test of the %correc | Are ecologists the only ones who didn't know that the arcsine is asinine?
I can speak from experience that psychology and neuroscience often don't even make the effort to transform % values in order to normalize them. The modal analysis is an ANOVA or t-test of the %correct or %error. | Are ecologists the only ones who didn't know that the arcsine is asinine?
I can speak from experience that psychology and neuroscience often don't even make the effort to transform % values in order to normalize them. The modal analysis is an ANOVA or t-test of the %correc |
30,591 | Are ecologists the only ones who didn't know that the arcsine is asinine? | The question about prevalence of use of arcsine transform in ecology and other
fields can be gauged by going to JStor, picking a few journals, and doing a
search on the word over the last 2 decades.
The discussion of the topic could be clarified by noting one (among many) reasons not to use the arcsin. Proportions are based on number of cases. Would you give the same weight to a proportion of 2 out of 4 cases (not very reliable) and a more reliable proportion of 20 out of 40 cases? The natural solution is to use the odds and odds ratio, and a binomial distribution to test for change in proportion as a change in the odds, as described in the arcsin asinine publication. That way you give 50 % of 40 its due, compared to 50% of 4. | Are ecologists the only ones who didn't know that the arcsine is asinine? | The question about prevalence of use of arcsine transform in ecology and other
fields can be gauged by going to JStor, picking a few journals, and doing a
search on the word over the last 2 decades. | Are ecologists the only ones who didn't know that the arcsine is asinine?
The question about prevalence of use of arcsine transform in ecology and other
fields can be gauged by going to JStor, picking a few journals, and doing a
search on the word over the last 2 decades.
The discussion of the topic could be clarified by noting one (among many) reasons not to use the arcsin. Proportions are based on number of cases. Would you give the same weight to a proportion of 2 out of 4 cases (not very reliable) and a more reliable proportion of 20 out of 40 cases? The natural solution is to use the odds and odds ratio, and a binomial distribution to test for change in proportion as a change in the odds, as described in the arcsin asinine publication. That way you give 50 % of 40 its due, compared to 50% of 4. | Are ecologists the only ones who didn't know that the arcsine is asinine?
The question about prevalence of use of arcsine transform in ecology and other
fields can be gauged by going to JStor, picking a few journals, and doing a
search on the word over the last 2 decades. |
30,592 | Scaling data that are on different orders of magnitude for plotting | It isn't unreasonable at the onset to plot the line charts as a series of small multiples, with different scales for the Y axis but with the X axis (dates) aligned.
I think this is a good start, as it allows one to examine the raw data, and allows for comparison of trends between different line charts. IMO you should look at the raw data first, then think about conversions or ways to normalize the charts to be comparable after you examine the raw data.
As King has already mentioned, it appears that your variables have a natural ordering based on the names and numbers, and assuming it is appropriate, I created three new variables based on the percentage converted at each state. The new variables are;
% Carts Created = Carts_Created/Visits
% Orders Created = Orders_Created/Carts_Created
% Carts Converted = Carts_Converted/Orders_Created
Making percentages is a way to bring the series closer to a common scale, but even then placing all of the lines on one chart (as below) is still difficult to visualize the series effectively. The level and variation of the orders created and carts converted series dwarfs that of the other series. You can't see any variation in the carts created series on this scale (and I suspect that is the one you are most interested in).
So again, IMO a better way to examine this is to use different scales. Below is the Percentage chart using different scales.
With these graphics, there doesn't appear to me to be any real meaningful correlation to me between the series, but you do have plenty of interesting variation within each series (especially the proportion converted). What's up with 2011-11-13? You had a much lower proportion of order's created but every one of the order's created was a converted cart. Did you have any other interventions which might explain trends in either site visits or proportion or percentage carts created?
This is all just exploratory data analysis, and to take any more steps I would need more insight into the data (I hope this is a good start though). You could normalize the line charts in other ways to be able to plot them on a comparable scale, but that is a difficult task, and I think can be done as effectively choosing arbitrary scales based what is informative given the data as opposed to choosing some default normalization schemes. Another interesting application of viewing many line graphs simultaneously is horizon graphs, but that is more for viewing many different line charts at once. | Scaling data that are on different orders of magnitude for plotting | It isn't unreasonable at the onset to plot the line charts as a series of small multiples, with different scales for the Y axis but with the X axis (dates) aligned.
I think this is a good start, as i | Scaling data that are on different orders of magnitude for plotting
It isn't unreasonable at the onset to plot the line charts as a series of small multiples, with different scales for the Y axis but with the X axis (dates) aligned.
I think this is a good start, as it allows one to examine the raw data, and allows for comparison of trends between different line charts. IMO you should look at the raw data first, then think about conversions or ways to normalize the charts to be comparable after you examine the raw data.
As King has already mentioned, it appears that your variables have a natural ordering based on the names and numbers, and assuming it is appropriate, I created three new variables based on the percentage converted at each state. The new variables are;
% Carts Created = Carts_Created/Visits
% Orders Created = Orders_Created/Carts_Created
% Carts Converted = Carts_Converted/Orders_Created
Making percentages is a way to bring the series closer to a common scale, but even then placing all of the lines on one chart (as below) is still difficult to visualize the series effectively. The level and variation of the orders created and carts converted series dwarfs that of the other series. You can't see any variation in the carts created series on this scale (and I suspect that is the one you are most interested in).
So again, IMO a better way to examine this is to use different scales. Below is the Percentage chart using different scales.
With these graphics, there doesn't appear to me to be any real meaningful correlation to me between the series, but you do have plenty of interesting variation within each series (especially the proportion converted). What's up with 2011-11-13? You had a much lower proportion of order's created but every one of the order's created was a converted cart. Did you have any other interventions which might explain trends in either site visits or proportion or percentage carts created?
This is all just exploratory data analysis, and to take any more steps I would need more insight into the data (I hope this is a good start though). You could normalize the line charts in other ways to be able to plot them on a comparable scale, but that is a difficult task, and I think can be done as effectively choosing arbitrary scales based what is informative given the data as opposed to choosing some default normalization schemes. Another interesting application of viewing many line graphs simultaneously is horizon graphs, but that is more for viewing many different line charts at once. | Scaling data that are on different orders of magnitude for plotting
It isn't unreasonable at the onset to plot the line charts as a series of small multiples, with different scales for the Y axis but with the X axis (dates) aligned.
I think this is a good start, as i |
30,593 | Scaling data that are on different orders of magnitude for plotting | You can have 2 separate y-axis, Visits (k) and Carts Created in one, the other 2 in another (or whichever way fits your purpose).
This is definitely not an elegant method, but I remember doing it years ago when I just wanted to compare trends across time.
OR
You can just plot the percentage change across time if it suits your purpose. | Scaling data that are on different orders of magnitude for plotting | You can have 2 separate y-axis, Visits (k) and Carts Created in one, the other 2 in another (or whichever way fits your purpose).
This is definitely not an elegant method, but I remember doing it year | Scaling data that are on different orders of magnitude for plotting
You can have 2 separate y-axis, Visits (k) and Carts Created in one, the other 2 in another (or whichever way fits your purpose).
This is definitely not an elegant method, but I remember doing it years ago when I just wanted to compare trends across time.
OR
You can just plot the percentage change across time if it suits your purpose. | Scaling data that are on different orders of magnitude for plotting
You can have 2 separate y-axis, Visits (k) and Carts Created in one, the other 2 in another (or whichever way fits your purpose).
This is definitely not an elegant method, but I remember doing it year |
30,594 | Scaling data that are on different orders of magnitude for plotting | In the end I decided to normalise the data by dividing each value by the maximum value and then multiplying by 100.
Find the maximum value:
Date Visits Carts carts Orders
Created converted Created
2011-11-11 12277 161 9 36
2011-11-12 11871 93 5 19
2011-11-13 13072 107 8 8
2011-11-14 13594 112 4 34
2011-11-15 12741 129 8 43
2011-11-16 15491 261 16 57
2011-11-17 13418 186 17 42
maximum 15491 261 17 57
Divide each number by the maximum and then multiply by 100:
Date Visits Carts carts Orders
Created converted Created
2011-11-11 79.25 61.68 52.94 63.15
2011-11-12 76.63 35.63 29.41 33.33
2011-11-13 84.38 40.99 47.05 14.03
2011-11-14 87.75 42.91 23.52 59.64
2011-11-15 82.24 49.42 47.05 75.43
2011-11-16 100 100 94.11 100
2011-11-17 86.61 71.26 100 73.68
I then plotted this on the graph, obviously this only demonstrates trend and the user has the table of data at the bottom of the page. | Scaling data that are on different orders of magnitude for plotting | In the end I decided to normalise the data by dividing each value by the maximum value and then multiplying by 100.
Find the maximum value:
Date Visits Carts carts Orders
| Scaling data that are on different orders of magnitude for plotting
In the end I decided to normalise the data by dividing each value by the maximum value and then multiplying by 100.
Find the maximum value:
Date Visits Carts carts Orders
Created converted Created
2011-11-11 12277 161 9 36
2011-11-12 11871 93 5 19
2011-11-13 13072 107 8 8
2011-11-14 13594 112 4 34
2011-11-15 12741 129 8 43
2011-11-16 15491 261 16 57
2011-11-17 13418 186 17 42
maximum 15491 261 17 57
Divide each number by the maximum and then multiply by 100:
Date Visits Carts carts Orders
Created converted Created
2011-11-11 79.25 61.68 52.94 63.15
2011-11-12 76.63 35.63 29.41 33.33
2011-11-13 84.38 40.99 47.05 14.03
2011-11-14 87.75 42.91 23.52 59.64
2011-11-15 82.24 49.42 47.05 75.43
2011-11-16 100 100 94.11 100
2011-11-17 86.61 71.26 100 73.68
I then plotted this on the graph, obviously this only demonstrates trend and the user has the table of data at the bottom of the page. | Scaling data that are on different orders of magnitude for plotting
In the end I decided to normalise the data by dividing each value by the maximum value and then multiplying by 100.
Find the maximum value:
Date Visits Carts carts Orders
|
30,595 | Scaling data that are on different orders of magnitude for plotting | That would be my approach too - - to adjust the different dimensions to the same scale by dividing by X but I would use avg value, not max or min value. The reason is -- as you add data over time, your max or min will likely change, and then what was 100% in the last chart is something else this time - the chart isn't as easily reconcilable to prior charts - - if you use avg then the changes are not as drastic. | Scaling data that are on different orders of magnitude for plotting | That would be my approach too - - to adjust the different dimensions to the same scale by dividing by X but I would use avg value, not max or min value. The reason is -- as you add data over time, yo | Scaling data that are on different orders of magnitude for plotting
That would be my approach too - - to adjust the different dimensions to the same scale by dividing by X but I would use avg value, not max or min value. The reason is -- as you add data over time, your max or min will likely change, and then what was 100% in the last chart is something else this time - the chart isn't as easily reconcilable to prior charts - - if you use avg then the changes are not as drastic. | Scaling data that are on different orders of magnitude for plotting
That would be my approach too - - to adjust the different dimensions to the same scale by dividing by X but I would use avg value, not max or min value. The reason is -- as you add data over time, yo |
30,596 | Cross validation with two parameters: elastic net case | The method to use in this case is exactly the same, though e.g. the glmnet package doesn't provide it out of the box.
Instead of working over 1 discrete set of parameter values (lambda), you now crossvalidate for a grid of parameter values, (lambda and alpha), then pick the best value (lambda.min and alpha.min), and then the lambda and alpha so that lambda is the biggest possible but its predictive measure is within 1 SE of that of lambda.min and alpha.min.
If you use R, you can probably do something like:
alphasOfInterest<-seq(0,1,by=0.1) #or something similar
#step 1: do all crossvalidations for each alpha
cvs<-lapply(alphasOfInterest, function(curAlpha){
cv.glmnet(myX, myY, alpha=curAlpha, some more parameters)
})
#step 2: collect the optimum lambda for each alpha
optimumPerAlpha<-sapply(seq_along(alphasOfInterest), function(curi){
curcvs<-cvs[[curi]]
curAlpha<-alphasOfInterest[curi]
indOfMin<-match(curcvs$lambda.min, curcvs$lambda)
c(lam=curcvs$lambda.min, alph=curAlpha, cvup=curcvs$cvup[indOfMin])
})
#step 3: find the overall optimum
posOfOptimum<-which.min(optimumPerAlpha["lam",])
overall.lambda.min<-optimumPerAlpha["lam",posOfOptimum]
overall.alpha.min<-optimumPerAlpha["alph",posOfOptimum]
overall.criterionthreshold<-optimumPerAlpha["cvup",posOfOptimum]
#step 4: now check for each alpha which lambda is the best within the threshold
corrected1se<-sapply(seq_along(alphasOfInterest), function(curi){
curcvs<-cvs[[curi]]
lams<-curcvs$lambda
lams[lams<overall.lambda.min]<-NA
lams[curcvs$cvm > overall.criterionthreshold]<-NA
lam1se<-max(lams, na.rm=TRUE)
c(lam=lam1se, alph=alphasOfInterest[curi])
})
#step 5: find the best (lowest) of these lambdas
overall.lambda.1se<-max(corrected1se["lam", ])
pos<-match(overall.lambda.1se, corrected1se["lam", ])
overall.alpha.&se<-corrected1se["alph", pos]
All this code is untested + needs attention if you use auc as your criterion (because then you need to look for the maximum of the criterion and some other details change), but the ideas are there.
Note: in the last step, you could, instead of going for the highest lambda, find the one that has the most parsimonious model (because higher lambda does not guarantee more parsimony over different alphas)
You may also want to collect all lambdas up front, and pass the collection of all those to every crossvalidation, so that you can ensure that each crossvalidation uses the same set of lambdas. This is easy to do but requires some extra steps. I'm not certain whether it is necessary... | Cross validation with two parameters: elastic net case | The method to use in this case is exactly the same, though e.g. the glmnet package doesn't provide it out of the box.
Instead of working over 1 discrete set of parameter values (lambda), you now cross | Cross validation with two parameters: elastic net case
The method to use in this case is exactly the same, though e.g. the glmnet package doesn't provide it out of the box.
Instead of working over 1 discrete set of parameter values (lambda), you now crossvalidate for a grid of parameter values, (lambda and alpha), then pick the best value (lambda.min and alpha.min), and then the lambda and alpha so that lambda is the biggest possible but its predictive measure is within 1 SE of that of lambda.min and alpha.min.
If you use R, you can probably do something like:
alphasOfInterest<-seq(0,1,by=0.1) #or something similar
#step 1: do all crossvalidations for each alpha
cvs<-lapply(alphasOfInterest, function(curAlpha){
cv.glmnet(myX, myY, alpha=curAlpha, some more parameters)
})
#step 2: collect the optimum lambda for each alpha
optimumPerAlpha<-sapply(seq_along(alphasOfInterest), function(curi){
curcvs<-cvs[[curi]]
curAlpha<-alphasOfInterest[curi]
indOfMin<-match(curcvs$lambda.min, curcvs$lambda)
c(lam=curcvs$lambda.min, alph=curAlpha, cvup=curcvs$cvup[indOfMin])
})
#step 3: find the overall optimum
posOfOptimum<-which.min(optimumPerAlpha["lam",])
overall.lambda.min<-optimumPerAlpha["lam",posOfOptimum]
overall.alpha.min<-optimumPerAlpha["alph",posOfOptimum]
overall.criterionthreshold<-optimumPerAlpha["cvup",posOfOptimum]
#step 4: now check for each alpha which lambda is the best within the threshold
corrected1se<-sapply(seq_along(alphasOfInterest), function(curi){
curcvs<-cvs[[curi]]
lams<-curcvs$lambda
lams[lams<overall.lambda.min]<-NA
lams[curcvs$cvm > overall.criterionthreshold]<-NA
lam1se<-max(lams, na.rm=TRUE)
c(lam=lam1se, alph=alphasOfInterest[curi])
})
#step 5: find the best (lowest) of these lambdas
overall.lambda.1se<-max(corrected1se["lam", ])
pos<-match(overall.lambda.1se, corrected1se["lam", ])
overall.alpha.&se<-corrected1se["alph", pos]
All this code is untested + needs attention if you use auc as your criterion (because then you need to look for the maximum of the criterion and some other details change), but the ideas are there.
Note: in the last step, you could, instead of going for the highest lambda, find the one that has the most parsimonious model (because higher lambda does not guarantee more parsimony over different alphas)
You may also want to collect all lambdas up front, and pass the collection of all those to every crossvalidation, so that you can ensure that each crossvalidation uses the same set of lambdas. This is easy to do but requires some extra steps. I'm not certain whether it is necessary... | Cross validation with two parameters: elastic net case
The method to use in this case is exactly the same, though e.g. the glmnet package doesn't provide it out of the box.
Instead of working over 1 discrete set of parameter values (lambda), you now cross |
30,597 | Cross validation with two parameters: elastic net case | If by error rate you mean the usual one (proportion classified correctly), this is a discontinuous improper scoring rule. An improper scoring rule is optimized by a bogus model. It will lead you to select the wrong features and to discard features that are predictive. It is better to use the most sensitive measure for assessing a model, which will be based on deviance or penalized deviance. In simpler cases where I'm only using a quadratic penalty, I solve for the optimum penalty using effective AIC. An example is in my book Regression Modeling Strategies. A simulation study of this approach is on http://biostat.mc.vanderbilt.edu/rms. | Cross validation with two parameters: elastic net case | If by error rate you mean the usual one (proportion classified correctly), this is a discontinuous improper scoring rule. An improper scoring rule is optimized by a bogus model. It will lead you to | Cross validation with two parameters: elastic net case
If by error rate you mean the usual one (proportion classified correctly), this is a discontinuous improper scoring rule. An improper scoring rule is optimized by a bogus model. It will lead you to select the wrong features and to discard features that are predictive. It is better to use the most sensitive measure for assessing a model, which will be based on deviance or penalized deviance. In simpler cases where I'm only using a quadratic penalty, I solve for the optimum penalty using effective AIC. An example is in my book Regression Modeling Strategies. A simulation study of this approach is on http://biostat.mc.vanderbilt.edu/rms. | Cross validation with two parameters: elastic net case
If by error rate you mean the usual one (proportion classified correctly), this is a discontinuous improper scoring rule. An improper scoring rule is optimized by a bogus model. It will lead you to |
30,598 | Cross validation with two parameters: elastic net case | Rather than use a grid search, use a numeric optimisation routine, such as the Nelder-Mead simplex algorithm. This is generally more efficient than grid search and it will be well worth the effort in the long run. In MATLAB this is implemented by the fminsearch routine of the optimisation toolbox, but I expect there is an R implementation as well. The cost function for the optimisation is simply the cross-validated performance estimate.
It is a good idea to re-parameterise the problem first so as to achieve a non-constrained optimisation problem (the regularisation parameters must be positive). I do this by optimising the logarithm of the regularisation parameters, and have found it generally works well. | Cross validation with two parameters: elastic net case | Rather than use a grid search, use a numeric optimisation routine, such as the Nelder-Mead simplex algorithm. This is generally more efficient than grid search and it will be well worth the effort in | Cross validation with two parameters: elastic net case
Rather than use a grid search, use a numeric optimisation routine, such as the Nelder-Mead simplex algorithm. This is generally more efficient than grid search and it will be well worth the effort in the long run. In MATLAB this is implemented by the fminsearch routine of the optimisation toolbox, but I expect there is an R implementation as well. The cost function for the optimisation is simply the cross-validated performance estimate.
It is a good idea to re-parameterise the problem first so as to achieve a non-constrained optimisation problem (the regularisation parameters must be positive). I do this by optimising the logarithm of the regularisation parameters, and have found it generally works well. | Cross validation with two parameters: elastic net case
Rather than use a grid search, use a numeric optimisation routine, such as the Nelder-Mead simplex algorithm. This is generally more efficient than grid search and it will be well worth the effort in |
30,599 | How to verify extremely low error rates | This is a common problem, especially with modern components or systems which can have failure rates as low as $10^{-9}$. To address it, you need to make assumptions, create models, and/or incorporate other forms of data.
Lee Cadwallader of INL writes,
When no operating experience data exist for a component, such as a
component in the design phase, the analyst has several options:
Decomposition—deconstructing a component into its constituent parts
and then assigning handbook failure rates to the parts. If the analyst
is confident in the accuracy of part data, this technique is tedious
but useful; if the data on parts are not accurate, other techniques
should be used.
Analyst judgment—may call for reverse estimation
based on a system availability requirement or simply engineering
judgment of the generic failure rates for that class of component.
Expert opinion—obtaining qualitative opinions from subject matter
experts and combining those to develop an order-of-magnitude failure
rate.
Component-specific techniques—for example, the Thomas method
for piping.
Decomposition is frequently used for electronic parts, as evidenced by manuals of component failure rates.
Other sources suggest that industry data or experience can be used to inform, or in place of, testing data.
Other techniques discussed on Weibull.com include
In order to assess wear-out time of a component, long-term testing may
be required. In some cases, a 100% duty cycle (running tires in a road
wear simulator 24 hours a day) may provide useful lifetime testing in
months. In other cases, actual product use may be 24 hours a day and
there is no way to accelerate the duty cycle. High level physical
stresses may need to be applied to shorten the test time. This is an
emerging technique of reliability assessment termed QALT (Quantitative
Accelerated Life Testing) that requires consideration of the physics
and engineering of the materials being tested.
On a cautionary note, there appears to be a close parallel between this problem and that of estimating other rare events such as asteroid strikes and catastrophic failures in the financial system--Taleb's "black swans.". The latter rates were notoriously underestimated. | How to verify extremely low error rates | This is a common problem, especially with modern components or systems which can have failure rates as low as $10^{-9}$. To address it, you need to make assumptions, create models, and/or incorporate | How to verify extremely low error rates
This is a common problem, especially with modern components or systems which can have failure rates as low as $10^{-9}$. To address it, you need to make assumptions, create models, and/or incorporate other forms of data.
Lee Cadwallader of INL writes,
When no operating experience data exist for a component, such as a
component in the design phase, the analyst has several options:
Decomposition—deconstructing a component into its constituent parts
and then assigning handbook failure rates to the parts. If the analyst
is confident in the accuracy of part data, this technique is tedious
but useful; if the data on parts are not accurate, other techniques
should be used.
Analyst judgment—may call for reverse estimation
based on a system availability requirement or simply engineering
judgment of the generic failure rates for that class of component.
Expert opinion—obtaining qualitative opinions from subject matter
experts and combining those to develop an order-of-magnitude failure
rate.
Component-specific techniques—for example, the Thomas method
for piping.
Decomposition is frequently used for electronic parts, as evidenced by manuals of component failure rates.
Other sources suggest that industry data or experience can be used to inform, or in place of, testing data.
Other techniques discussed on Weibull.com include
In order to assess wear-out time of a component, long-term testing may
be required. In some cases, a 100% duty cycle (running tires in a road
wear simulator 24 hours a day) may provide useful lifetime testing in
months. In other cases, actual product use may be 24 hours a day and
there is no way to accelerate the duty cycle. High level physical
stresses may need to be applied to shorten the test time. This is an
emerging technique of reliability assessment termed QALT (Quantitative
Accelerated Life Testing) that requires consideration of the physics
and engineering of the materials being tested.
On a cautionary note, there appears to be a close parallel between this problem and that of estimating other rare events such as asteroid strikes and catastrophic failures in the financial system--Taleb's "black swans.". The latter rates were notoriously underestimated. | How to verify extremely low error rates
This is a common problem, especially with modern components or systems which can have failure rates as low as $10^{-9}$. To address it, you need to make assumptions, create models, and/or incorporate |
30,600 | How to verify extremely low error rates | There's no way to prove an error rate < 1/1,000,000 with only 4,000 trials. You need to somehow select for errors (running more trials in parallel and only watching cases that result in an error) or apply some sort of stress that would increase the chance of an error, and then extrapolating from stressed conditions to normal conditions.
That's what geneticists would do, anyway.... | How to verify extremely low error rates | There's no way to prove an error rate < 1/1,000,000 with only 4,000 trials. You need to somehow select for errors (running more trials in parallel and only watching cases that result in an error) or | How to verify extremely low error rates
There's no way to prove an error rate < 1/1,000,000 with only 4,000 trials. You need to somehow select for errors (running more trials in parallel and only watching cases that result in an error) or apply some sort of stress that would increase the chance of an error, and then extrapolating from stressed conditions to normal conditions.
That's what geneticists would do, anyway.... | How to verify extremely low error rates
There's no way to prove an error rate < 1/1,000,000 with only 4,000 trials. You need to somehow select for errors (running more trials in parallel and only watching cases that result in an error) or |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.