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
27,701
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin
Because there are uncountably many solutions, let's find an efficient one. The idea behind this one starts with a standard way to implement a Bernoulli variable: compare a uniform random variable $U$ to the parameter $a/b$. When $U \lt a/b$, return $1$; otherwise, return $0$. We can use the $p$-coin as a uniform random number generator. To generate a number $U$ uniformly within any interval $[x, y)$, flip the coin. When it's heads, recursively generate a uniform value $X$ in the first $p$ part of the interval; when it's tails, recursively generate $X$ from the last $1-p$ part of the interval. At some point the target interval will become so small that it doesn't really matter how you pick a number from it: that's how the recursion gets started. It's obvious this procedure generates uniform variates (up to any desired precision), as is easily proven by induction. This idea is not efficient, but it leads to an efficient method. Since at each stage you are going to draw a number from some given interval $[x,y)$, why not first check whether you need to draw it at all? If your target value lies outside this interval, you already know the result of the comparison between the random value and the target. Thus, this algorithm tends to terminate rapidly. (This could be construed as the rejection sampling procedure requested in the question.) We can optimize this algorithm further. At any stage, we actually have two coins we can use: by relabelling our coin we can make it into one that is heads with chance $1-p$. Therefore, as a precomputation we may recursively choose whichever relabelling leads to the lower expected number of flips needed for termination. (This calculation can be an expensive step.) For example, it's inefficient to use a coin with $p=0.9$ to emulate a Bernoulli$(0.01)$ variable directly: it takes almost ten flips on average. But if we use a $p=1-0.9=0.1$ coin, then in just two flips we will sure to be done and the expected number of flips is just $1.2$. Here are the details. Partition any given half-open interval $I = [x, y)$ into the intervals $$[x,y) = [x, x + (y-x)p) \cup [x + (y-x)p, y) = s(I,H) \cup s(I,T).$$ This defines the two transformations $s(*,H)$ and $s(*,T)$ which operate on half-open intervals. As a matter of terminology, if $I$ is any set of real numbers let the expression $$t \lt I$$ mean that $t$ is a lower bound for $I$: $t \lt x$ for all $x \in I$. Similarly, $t \gt I$ means $t$ is an upper bound for $I$. Write $a/b = t$. (In fact, it will make no difference if $t$ is real instead of rational; we only require that $0 \le t \le 1$.) Here is the algorithm to produce a variate $Z$ with the desired Bernoulli parameter: Set $n=0$ and $I_n = I_0 = [0,1)$. While $(t\in I_{n})$ {Toss the coin to produce $X_{n+1}$. Set $I_{n+1} = S(I_n, X_{n+1}).$ Increment $n$.} If $t \gt I_{n+1}$ then set $Z=1$. Otherwise, set $Z=0$. ###Implementation To illustrate, here is an R implementation of the algorithm as the function draw. Its arguments are the target value $t$ and the interval $[x,y)$, initially $[0,1)$. It uses the auxiliary function s implementing $s$. Although it does not need to, also it tracks the number of coin tosses. It returns the random variable, the count of tosses, and the last interval it inspected. s <- function(x, ab, p) { d <- diff(ab) * p if (x == 1) c(ab[1], ab[1] + d) else c(ab[1] + d, ab[2]) } draw <- function(target, p) { between <- function(z, ab) prod(z - ab) <= 0 ab <- c(0,1) n <- 0 while(between(target, ab)) { n <- n+1; ab <- s(runif(1) < p, ab, p) } return(c(target > ab[2], n, ab)) } As an example of its use and test of its accuracy, take the case $t=1/100$ and $p=0.9$. Let's draw $10,000$ values using the algorithm, report on the mean (and its standard error), and indicate the average number of flips used. target <- 0.01 p <- 0.9 set.seed(17) sim <- replicate(1e4, draw(target, p)) (m <- mean(sim[1, ])) # The mean (m - target) / (sd(sim[1, ]) / sqrt(ncol(sim))) # A Z-score to compare to `target` mean(sim[2, ]) # Average number of flips In this simulation, $0.0095$ of the flips were heads. Although lower than the target of $0.01$, the Z-score of $-0.5154$ is not significant: this deviation can be attributed to chance. The average number of flips was $9.886$--a little less than ten. If we had used the $1-p$ coin, the mean would have been $0.0094$--still not significantly different than the target, but only $1.177$ flips would have been needed on average.
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin
Because there are uncountably many solutions, let's find an efficient one. The idea behind this one starts with a standard way to implement a Bernoulli variable: compare a uniform random variable $U$
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin Because there are uncountably many solutions, let's find an efficient one. The idea behind this one starts with a standard way to implement a Bernoulli variable: compare a uniform random variable $U$ to the parameter $a/b$. When $U \lt a/b$, return $1$; otherwise, return $0$. We can use the $p$-coin as a uniform random number generator. To generate a number $U$ uniformly within any interval $[x, y)$, flip the coin. When it's heads, recursively generate a uniform value $X$ in the first $p$ part of the interval; when it's tails, recursively generate $X$ from the last $1-p$ part of the interval. At some point the target interval will become so small that it doesn't really matter how you pick a number from it: that's how the recursion gets started. It's obvious this procedure generates uniform variates (up to any desired precision), as is easily proven by induction. This idea is not efficient, but it leads to an efficient method. Since at each stage you are going to draw a number from some given interval $[x,y)$, why not first check whether you need to draw it at all? If your target value lies outside this interval, you already know the result of the comparison between the random value and the target. Thus, this algorithm tends to terminate rapidly. (This could be construed as the rejection sampling procedure requested in the question.) We can optimize this algorithm further. At any stage, we actually have two coins we can use: by relabelling our coin we can make it into one that is heads with chance $1-p$. Therefore, as a precomputation we may recursively choose whichever relabelling leads to the lower expected number of flips needed for termination. (This calculation can be an expensive step.) For example, it's inefficient to use a coin with $p=0.9$ to emulate a Bernoulli$(0.01)$ variable directly: it takes almost ten flips on average. But if we use a $p=1-0.9=0.1$ coin, then in just two flips we will sure to be done and the expected number of flips is just $1.2$. Here are the details. Partition any given half-open interval $I = [x, y)$ into the intervals $$[x,y) = [x, x + (y-x)p) \cup [x + (y-x)p, y) = s(I,H) \cup s(I,T).$$ This defines the two transformations $s(*,H)$ and $s(*,T)$ which operate on half-open intervals. As a matter of terminology, if $I$ is any set of real numbers let the expression $$t \lt I$$ mean that $t$ is a lower bound for $I$: $t \lt x$ for all $x \in I$. Similarly, $t \gt I$ means $t$ is an upper bound for $I$. Write $a/b = t$. (In fact, it will make no difference if $t$ is real instead of rational; we only require that $0 \le t \le 1$.) Here is the algorithm to produce a variate $Z$ with the desired Bernoulli parameter: Set $n=0$ and $I_n = I_0 = [0,1)$. While $(t\in I_{n})$ {Toss the coin to produce $X_{n+1}$. Set $I_{n+1} = S(I_n, X_{n+1}).$ Increment $n$.} If $t \gt I_{n+1}$ then set $Z=1$. Otherwise, set $Z=0$. ###Implementation To illustrate, here is an R implementation of the algorithm as the function draw. Its arguments are the target value $t$ and the interval $[x,y)$, initially $[0,1)$. It uses the auxiliary function s implementing $s$. Although it does not need to, also it tracks the number of coin tosses. It returns the random variable, the count of tosses, and the last interval it inspected. s <- function(x, ab, p) { d <- diff(ab) * p if (x == 1) c(ab[1], ab[1] + d) else c(ab[1] + d, ab[2]) } draw <- function(target, p) { between <- function(z, ab) prod(z - ab) <= 0 ab <- c(0,1) n <- 0 while(between(target, ab)) { n <- n+1; ab <- s(runif(1) < p, ab, p) } return(c(target > ab[2], n, ab)) } As an example of its use and test of its accuracy, take the case $t=1/100$ and $p=0.9$. Let's draw $10,000$ values using the algorithm, report on the mean (and its standard error), and indicate the average number of flips used. target <- 0.01 p <- 0.9 set.seed(17) sim <- replicate(1e4, draw(target, p)) (m <- mean(sim[1, ])) # The mean (m - target) / (sd(sim[1, ]) / sqrt(ncol(sim))) # A Z-score to compare to `target` mean(sim[2, ]) # Average number of flips In this simulation, $0.0095$ of the flips were heads. Although lower than the target of $0.01$, the Z-score of $-0.5154$ is not significant: this deviation can be attributed to chance. The average number of flips was $9.886$--a little less than ten. If we had used the $1-p$ coin, the mean would have been $0.0094$--still not significantly different than the target, but only $1.177$ flips would have been needed on average.
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin Because there are uncountably many solutions, let's find an efficient one. The idea behind this one starts with a standard way to implement a Bernoulli variable: compare a uniform random variable $U$
27,702
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin
Here's a solution (bit of a messy one, but it's my first stab). You can actually ignore the $P(H) = p$ and WLOG assume $P(H)=1/2$. Why? There exists a clever algorithm to generate a unbiased coin flip from two biased coin flips. So we can assume $P(H)=1/2$. To generate a $\text{Bernoulli}(\frac{a}{b})$, I can think of two solutions (the first is not my own, but the second is a generalization): Solution 1 Flip the unbiased coin $b$ times. If $a$ heads are not present, start over. If $a$ heads are present, return whether the first coin is a heads or not (because $P(\text{first coin is heads | $a$ heads in $b$ coins}) = \frac{a}{b}$) Solution 2 This can be extended to any value of $\text{Bernoulli}(p)$. Write $p$ in binary form. For example, $0.1 = 0.0001100110011001100110011... \text{base 2}$ We'll create a new binary number using coin flips. Start with $0.$, and add digits depending on if a heads (1) or tails (0) appears. At each flip, compare your new binary number with the binary representation of $p$ up to the same digit. Eventually the two will diverge, and return if $bin(p)$ is greater than your binary number. In Python: def simulate(p): binary_p = float_to_binary(p) binary_string = '0.' index = 3 while True: binary_string += '0' if random.random() < 0.5 else '1' if binary_string != binary_p[:index]: return binary_string < binary_p[:index] index += 1 Some proof: np.mean([simulate(0.4) for i in range(10000)]) is about 0.4 (not fast however)
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin
Here's a solution (bit of a messy one, but it's my first stab). You can actually ignore the $P(H) = p$ and WLOG assume $P(H)=1/2$. Why? There exists a clever algorithm to generate a unbiased coin flip
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin Here's a solution (bit of a messy one, but it's my first stab). You can actually ignore the $P(H) = p$ and WLOG assume $P(H)=1/2$. Why? There exists a clever algorithm to generate a unbiased coin flip from two biased coin flips. So we can assume $P(H)=1/2$. To generate a $\text{Bernoulli}(\frac{a}{b})$, I can think of two solutions (the first is not my own, but the second is a generalization): Solution 1 Flip the unbiased coin $b$ times. If $a$ heads are not present, start over. If $a$ heads are present, return whether the first coin is a heads or not (because $P(\text{first coin is heads | $a$ heads in $b$ coins}) = \frac{a}{b}$) Solution 2 This can be extended to any value of $\text{Bernoulli}(p)$. Write $p$ in binary form. For example, $0.1 = 0.0001100110011001100110011... \text{base 2}$ We'll create a new binary number using coin flips. Start with $0.$, and add digits depending on if a heads (1) or tails (0) appears. At each flip, compare your new binary number with the binary representation of $p$ up to the same digit. Eventually the two will diverge, and return if $bin(p)$ is greater than your binary number. In Python: def simulate(p): binary_p = float_to_binary(p) binary_string = '0.' index = 3 while True: binary_string += '0' if random.random() < 0.5 else '1' if binary_string != binary_p[:index]: return binary_string < binary_p[:index] index += 1 Some proof: np.mean([simulate(0.4) for i in range(10000)]) is about 0.4 (not fast however)
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin Here's a solution (bit of a messy one, but it's my first stab). You can actually ignore the $P(H) = p$ and WLOG assume $P(H)=1/2$. Why? There exists a clever algorithm to generate a unbiased coin flip
27,703
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin
I see a simple solution, but no doubt there are many ways to do it, some presumably simpler than this. This approach can be broken down into two steps: Generating from two events with equal probability given an unfair coin-tossing procedure (the combination of the particular coin and the method by which it is tossed generating a head with probability $p$). We can call these two equally probable events $H^*$, and $T^*$. [There's a simple approach for this that requires taking pairs of tosses $H^*=(H,T)$ and $T^*=(T,H)$ to produce two equally-likely outcomes, with all other outcomes leading to generating a new pair of rolls to try again.] Now you generate a random walk with two absorbing states using the simulated fair coin. By choosing the distance of the absorbing states from the origin (one above and one below it), you can set the chance of absorption by say the upper absorbing state to be a desired ratio of integers. Specifically, if you place the upper absorbing barrier at $a$ and the lower one at $-(b-a)$ (and start the process from the origin), and run the random walk until absorption, the probability of absorption at the upper barrier is $\frac{a}{a+(b-a)} = \frac{a}{b}$. (There's some calculations to be done here to show it, but you can get the probabilities out fairly easily by working with recurrence relations ... or you can do it by summing infinite series ... or there are other ways.)
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin
I see a simple solution, but no doubt there are many ways to do it, some presumably simpler than this. This approach can be broken down into two steps: Generating from two events with equal probabili
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin I see a simple solution, but no doubt there are many ways to do it, some presumably simpler than this. This approach can be broken down into two steps: Generating from two events with equal probability given an unfair coin-tossing procedure (the combination of the particular coin and the method by which it is tossed generating a head with probability $p$). We can call these two equally probable events $H^*$, and $T^*$. [There's a simple approach for this that requires taking pairs of tosses $H^*=(H,T)$ and $T^*=(T,H)$ to produce two equally-likely outcomes, with all other outcomes leading to generating a new pair of rolls to try again.] Now you generate a random walk with two absorbing states using the simulated fair coin. By choosing the distance of the absorbing states from the origin (one above and one below it), you can set the chance of absorption by say the upper absorbing state to be a desired ratio of integers. Specifically, if you place the upper absorbing barrier at $a$ and the lower one at $-(b-a)$ (and start the process from the origin), and run the random walk until absorption, the probability of absorption at the upper barrier is $\frac{a}{a+(b-a)} = \frac{a}{b}$. (There's some calculations to be done here to show it, but you can get the probabilities out fairly easily by working with recurrence relations ... or you can do it by summing infinite series ... or there are other ways.)
Simulate a Bernoulli variable with probability ${a\over b}$ using a biased coin I see a simple solution, but no doubt there are many ways to do it, some presumably simpler than this. This approach can be broken down into two steps: Generating from two events with equal probabili
27,704
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution?
Dirac's delta is regarded as a Gaussian distribution when it is convenient to do so, and not so regarded when this viewpoint requires us to make exceptions. For example, $(X_1, X_2, \ldots, X_n)$ are said to enjoy a multivariate Gaussian distribution if $\sum_i a_iX_i$ is a Gaussian random variable for all choices of real numbers $a_1, a_2, \ldots, a_n$. (Note: this is a standard definition in "advanced" statistics). Since one choice is $a_1=a_2=\cdots=a_n=0$, the standard definition treats the constant $0$ (a degenerate random variable) as a Gaussian random variable (with mean and variance $0$). On the other hand, we ignore our regard for the Dirac delta as a Gaussian distribution when we are considering something like "The cumulative probability distribution function (CDF) of a zero-mean Gaussian random variable with standard deviation $\sigma$ is $$F_X(x) = P\{X \leq x\} = \Phi\left(\frac{x}{\sigma}\right)$$ where $\Phi(\cdot)$ is the CDF of a standard Gaussian random variable." Note that this statement is almost right but not quite right if we regard the Dirac delta as the limiting case of a sequence of zero-mean Gaussian random variables whose standard deviation approaches $0$ (and hence as a Gaussian random variable). The CDF of the Dirac delta has value $1$ for $x \geq 0$ whereas $$\lim_{\sigma\to 0}\Phi\left(\frac{x}{\sigma}\right) = \begin{cases} 0, & x < 0,\\ \frac 12, & x = 0,\\ 1, & x > 0.\end{cases}$$ But, lots of people will tell you that regarding a Dirac delta as a Gaussian distribution is sheer nonsense since their book says that the variance of a Gaussian random variable must be a positive number (and some of them will down-vote this answer to show their displeasure). There was a very vigorous and illuminating discussion of this point a few years ago on stats.SE but unfortunately it was only in the comments on an answer (by @Macro, I believe) and not as individual answers, and I cannot find it again.
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution?
Dirac's delta is regarded as a Gaussian distribution when it is convenient to do so, and not so regarded when this viewpoint requires us to make exceptions. For example, $(X_1, X_2, \ldots, X_n)$
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution? Dirac's delta is regarded as a Gaussian distribution when it is convenient to do so, and not so regarded when this viewpoint requires us to make exceptions. For example, $(X_1, X_2, \ldots, X_n)$ are said to enjoy a multivariate Gaussian distribution if $\sum_i a_iX_i$ is a Gaussian random variable for all choices of real numbers $a_1, a_2, \ldots, a_n$. (Note: this is a standard definition in "advanced" statistics). Since one choice is $a_1=a_2=\cdots=a_n=0$, the standard definition treats the constant $0$ (a degenerate random variable) as a Gaussian random variable (with mean and variance $0$). On the other hand, we ignore our regard for the Dirac delta as a Gaussian distribution when we are considering something like "The cumulative probability distribution function (CDF) of a zero-mean Gaussian random variable with standard deviation $\sigma$ is $$F_X(x) = P\{X \leq x\} = \Phi\left(\frac{x}{\sigma}\right)$$ where $\Phi(\cdot)$ is the CDF of a standard Gaussian random variable." Note that this statement is almost right but not quite right if we regard the Dirac delta as the limiting case of a sequence of zero-mean Gaussian random variables whose standard deviation approaches $0$ (and hence as a Gaussian random variable). The CDF of the Dirac delta has value $1$ for $x \geq 0$ whereas $$\lim_{\sigma\to 0}\Phi\left(\frac{x}{\sigma}\right) = \begin{cases} 0, & x < 0,\\ \frac 12, & x = 0,\\ 1, & x > 0.\end{cases}$$ But, lots of people will tell you that regarding a Dirac delta as a Gaussian distribution is sheer nonsense since their book says that the variance of a Gaussian random variable must be a positive number (and some of them will down-vote this answer to show their displeasure). There was a very vigorous and illuminating discussion of this point a few years ago on stats.SE but unfortunately it was only in the comments on an answer (by @Macro, I believe) and not as individual answers, and I cannot find it again.
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution? Dirac's delta is regarded as a Gaussian distribution when it is convenient to do so, and not so regarded when this viewpoint requires us to make exceptions. For example, $(X_1, X_2, \ldots, X_n)$
27,705
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution?
The delta functions fit into a mathematical theory of distributions (which is quite distinct from the theory of probability distributions, terminology here could not be more confusing). Essentially, distributions are generalized functions. They cannot be evaluated like a function can, but then can be integrated. More precisely, a distribution $D$ is defined as follows Let $T$ be the collection of test functions. A test function $\theta$ is a true, honest to god function, smooth, with compact support. A distribution is a linear mapping $D: T \rightarrow \mathbb{R}$ An honest function $f$ determines a distribution by the integration operator $$ T(\theta) = \int_{-\infty}^{+\infty} f(x)\theta(x) dx $$ There are distributions that are not associated to true functions, the dirac operator is one of them $$ \delta(\theta) = \theta(0) $$ In this sense, you can consider the dirac a limiting case of the normal distributions. If $N_t$ is the family of pdf's of normal distributions with mean zero and variance $t$, then for any test function $\theta$ $$ \theta(0) = \lim_{t \rightarrow 0} \int_{-\infty}^{+\infty} N_t(x) \theta(x) dx $$ This is probably more commonly expressed as $$ \theta(0) = \int_{-\infty}^{+\infty} \delta(x) \theta(x) dx = \lim_{t \rightarrow 0} \int_{-\infty}^{+\infty} N_t(x) \theta(x) dx $$ which a mathematician would consider an abuse of notation, because the expression $\delta(x)$ does not actually make any sense. But then again, who am I to criticize Dirac, who is the best. Of course, whether this makes the dirac a member of the family of normal distributions is a cultural question. Here I'm just giving a reason why it may make sense to consider it so.
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution?
The delta functions fit into a mathematical theory of distributions (which is quite distinct from the theory of probability distributions, terminology here could not be more confusing). Essentially, d
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution? The delta functions fit into a mathematical theory of distributions (which is quite distinct from the theory of probability distributions, terminology here could not be more confusing). Essentially, distributions are generalized functions. They cannot be evaluated like a function can, but then can be integrated. More precisely, a distribution $D$ is defined as follows Let $T$ be the collection of test functions. A test function $\theta$ is a true, honest to god function, smooth, with compact support. A distribution is a linear mapping $D: T \rightarrow \mathbb{R}$ An honest function $f$ determines a distribution by the integration operator $$ T(\theta) = \int_{-\infty}^{+\infty} f(x)\theta(x) dx $$ There are distributions that are not associated to true functions, the dirac operator is one of them $$ \delta(\theta) = \theta(0) $$ In this sense, you can consider the dirac a limiting case of the normal distributions. If $N_t$ is the family of pdf's of normal distributions with mean zero and variance $t$, then for any test function $\theta$ $$ \theta(0) = \lim_{t \rightarrow 0} \int_{-\infty}^{+\infty} N_t(x) \theta(x) dx $$ This is probably more commonly expressed as $$ \theta(0) = \int_{-\infty}^{+\infty} \delta(x) \theta(x) dx = \lim_{t \rightarrow 0} \int_{-\infty}^{+\infty} N_t(x) \theta(x) dx $$ which a mathematician would consider an abuse of notation, because the expression $\delta(x)$ does not actually make any sense. But then again, who am I to criticize Dirac, who is the best. Of course, whether this makes the dirac a member of the family of normal distributions is a cultural question. Here I'm just giving a reason why it may make sense to consider it so.
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution? The delta functions fit into a mathematical theory of distributions (which is quite distinct from the theory of probability distributions, terminology here could not be more confusing). Essentially, d
27,706
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution?
No. It's not a subclass of normal distribution. I think the confusion comes from one of the representations of Dirac function. Remember that it's defined as follows: $$\int_{-\infty}^\infty\delta(x)dx=1$$ $$\delta(x)=0,\forall x\ne 0$$ It's defined as an integral, which is great but sometime you need to operationalize it by a function representation rather than an integral. So, people came up with all kinds of alternatives, one of them looks like Gaussian density: $$\delta(x)=\lim_{\sigma\to 0} \frac{e^{\frac{-x^2}{2\sigma^2}}}{\sqrt{2\pi}\sigma}$$ However, this is not the only representation, e.g. there's this one: $$\delta(x)=\frac{1}{2\pi}\sum_{k=-\infty}^\infty e^{ikx}, \forall x\in (-\pi,\pi)$$ Hence, it's best to think of Dirac function in terms of its integral definition, and take the function representations, such as Gaussian, as tools of convenience. UPDATE To @whuber's point, a better even example is this representation of Dirac's delta: $$\delta(x)=\lim_{\sigma\to 0} \frac{e^{-\frac{|x|}{\sigma}}}{2\sigma}$$ Does this look like Laplacian distribution to you? Shouldn't we consider then Dirac's delta as a subclass of Laplacian distribution?
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution?
No. It's not a subclass of normal distribution. I think the confusion comes from one of the representations of Dirac function. Remember that it's defined as follows: $$\int_{-\infty}^\infty\delta(x)dx
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution? No. It's not a subclass of normal distribution. I think the confusion comes from one of the representations of Dirac function. Remember that it's defined as follows: $$\int_{-\infty}^\infty\delta(x)dx=1$$ $$\delta(x)=0,\forall x\ne 0$$ It's defined as an integral, which is great but sometime you need to operationalize it by a function representation rather than an integral. So, people came up with all kinds of alternatives, one of them looks like Gaussian density: $$\delta(x)=\lim_{\sigma\to 0} \frac{e^{\frac{-x^2}{2\sigma^2}}}{\sqrt{2\pi}\sigma}$$ However, this is not the only representation, e.g. there's this one: $$\delta(x)=\frac{1}{2\pi}\sum_{k=-\infty}^\infty e^{ikx}, \forall x\in (-\pi,\pi)$$ Hence, it's best to think of Dirac function in terms of its integral definition, and take the function representations, such as Gaussian, as tools of convenience. UPDATE To @whuber's point, a better even example is this representation of Dirac's delta: $$\delta(x)=\lim_{\sigma\to 0} \frac{e^{-\frac{|x|}{\sigma}}}{2\sigma}$$ Does this look like Laplacian distribution to you? Shouldn't we consider then Dirac's delta as a subclass of Laplacian distribution?
Should Dirac's delta function be regarded as a subclass of the Gaussian distribution? No. It's not a subclass of normal distribution. I think the confusion comes from one of the representations of Dirac function. Remember that it's defined as follows: $$\int_{-\infty}^\infty\delta(x)dx
27,707
What is the difference between sensitivity analysis and model validation?
This is a bit of an oversimplification, but model validation generally tells one about how well the current model fits the data at hand. Sensitivity analyses tell one how likely your results based upon that model would change given new information or changes to your assumptions. For example, someone could develop a model aimed at determining the impact that an intervention has on an outcome, and that model could validate well under their collected data (i.e. it seems very good at predicting response). However, that model rests on a number of assumptions – one being that all covariates are accounted for. A sensitivity analysis could tell one how much your model results would change if this new, "imaginary" variable, with certain properties, existed.
What is the difference between sensitivity analysis and model validation?
This is a bit of an oversimplification, but model validation generally tells one about how well the current model fits the data at hand. Sensitivity analyses tell one how likely your results based upo
What is the difference between sensitivity analysis and model validation? This is a bit of an oversimplification, but model validation generally tells one about how well the current model fits the data at hand. Sensitivity analyses tell one how likely your results based upon that model would change given new information or changes to your assumptions. For example, someone could develop a model aimed at determining the impact that an intervention has on an outcome, and that model could validate well under their collected data (i.e. it seems very good at predicting response). However, that model rests on a number of assumptions – one being that all covariates are accounted for. A sensitivity analysis could tell one how much your model results would change if this new, "imaginary" variable, with certain properties, existed.
What is the difference between sensitivity analysis and model validation? This is a bit of an oversimplification, but model validation generally tells one about how well the current model fits the data at hand. Sensitivity analyses tell one how likely your results based upo
27,708
What is the difference between sensitivity analysis and model validation?
In addition, sensitivity analysis can be considered as a tool to enhance model validity by choosing proper values(calibration) for the most critical input parameters. By using sensitivity analysis and defining input parameters values, we add more credibility to the model in hand.
What is the difference between sensitivity analysis and model validation?
In addition, sensitivity analysis can be considered as a tool to enhance model validity by choosing proper values(calibration) for the most critical input parameters. By using sensitivity analysis and
What is the difference between sensitivity analysis and model validation? In addition, sensitivity analysis can be considered as a tool to enhance model validity by choosing proper values(calibration) for the most critical input parameters. By using sensitivity analysis and defining input parameters values, we add more credibility to the model in hand.
What is the difference between sensitivity analysis and model validation? In addition, sensitivity analysis can be considered as a tool to enhance model validity by choosing proper values(calibration) for the most critical input parameters. By using sensitivity analysis and
27,709
Distribution of continuous uniform RV with upper limit being another continuous uniform RV
We can derive the distribution of $Y$ analytically. First, notice that it is $Y|X$ that follows the uniform distribution, i.e. $$f\left(y|x \right) = U(a, X) $$ and so $$\begin{align} f(y) = \int_{-\infty}^{\infty} f(y|x) f(x) dx & = \int_{y}^{b} \frac{1}{x-a} \frac{1}{b-a} dx \\ & = \frac{1}{b-a} \int_{y}^{b} \frac{1}{x-a} dx \\ &= \frac{1}{b-a} \left[ \log(b-a)-\log(y-a) \right] ,\quad a<y<b \end{align}$$ which is not a uniform distribution on account of $\log(y-a)$. Here is what the simulated density looks like for a $U(0,1)$ distribution, overlaid with what we just computed. y <- runif(1000, 0, runif(1000,0,1)) hist(y, prob =T) curve( -log(x), add = TRUE, lwd = 2)
Distribution of continuous uniform RV with upper limit being another continuous uniform RV
We can derive the distribution of $Y$ analytically. First, notice that it is $Y|X$ that follows the uniform distribution, i.e. $$f\left(y|x \right) = U(a, X) $$ and so $$\begin{align} f(y) = \int_{-\i
Distribution of continuous uniform RV with upper limit being another continuous uniform RV We can derive the distribution of $Y$ analytically. First, notice that it is $Y|X$ that follows the uniform distribution, i.e. $$f\left(y|x \right) = U(a, X) $$ and so $$\begin{align} f(y) = \int_{-\infty}^{\infty} f(y|x) f(x) dx & = \int_{y}^{b} \frac{1}{x-a} \frac{1}{b-a} dx \\ & = \frac{1}{b-a} \int_{y}^{b} \frac{1}{x-a} dx \\ &= \frac{1}{b-a} \left[ \log(b-a)-\log(y-a) \right] ,\quad a<y<b \end{align}$$ which is not a uniform distribution on account of $\log(y-a)$. Here is what the simulated density looks like for a $U(0,1)$ distribution, overlaid with what we just computed. y <- runif(1000, 0, runif(1000,0,1)) hist(y, prob =T) curve( -log(x), add = TRUE, lwd = 2)
Distribution of continuous uniform RV with upper limit being another continuous uniform RV We can derive the distribution of $Y$ analytically. First, notice that it is $Y|X$ that follows the uniform distribution, i.e. $$f\left(y|x \right) = U(a, X) $$ and so $$\begin{align} f(y) = \int_{-\i
27,710
Distribution of continuous uniform RV with upper limit being another continuous uniform RV
Definitely not. For simplicity, let us define $a = 0, b = 1$. Then $P(Y > 0.5) = P(Y > 0.5 | X > 0.5)P(X > 0.5)$ $ < P(X< 0.5) = 0.5$ Because of the strict inequality, it is not possible that $Y \sim $ Unif(0,1).
Distribution of continuous uniform RV with upper limit being another continuous uniform RV
Definitely not. For simplicity, let us define $a = 0, b = 1$. Then $P(Y > 0.5) = P(Y > 0.5 | X > 0.5)P(X > 0.5)$ $ < P(X< 0.5) = 0.5$ Because of the strict inequality, it is not possible that $Y \
Distribution of continuous uniform RV with upper limit being another continuous uniform RV Definitely not. For simplicity, let us define $a = 0, b = 1$. Then $P(Y > 0.5) = P(Y > 0.5 | X > 0.5)P(X > 0.5)$ $ < P(X< 0.5) = 0.5$ Because of the strict inequality, it is not possible that $Y \sim $ Unif(0,1).
Distribution of continuous uniform RV with upper limit being another continuous uniform RV Definitely not. For simplicity, let us define $a = 0, b = 1$. Then $P(Y > 0.5) = P(Y > 0.5 | X > 0.5)P(X > 0.5)$ $ < P(X< 0.5) = 0.5$ Because of the strict inequality, it is not possible that $Y \
27,711
How to sample from discrete distribution on the non-negative integers?
This is a Beta negative binomial distribution, with parameter $r=1$ in your case, using the Wikipedia notation. It also named Beta-Pascal distribution when $r$ is an integer. As you noted in a comment, this is a predictive distribution in the Bayesian negative binomial model with a conjugate Beta prior on the success probability. Thus you can sample it by sampling a $\text{Beta}(\alpha,\beta)$ variable $u$ and then sampling a negative binomial variable $\text{NB}(r,u)$ (with $r=1$ in your case, that is to say a geometric distribution). This distribution is implemented in the R package brr. The sampler has name rbeta_nbinom, the pmf has name dbeta_nbinom, etc. The notations are $a=r$, $c=\alpha$, $d=\beta$. Check: > Alpha <- 2; Beta <- 3 > a <- 1 > all.equal(brr::dbeta_nbinom(0:10, a, Alpha, Beta), beta(Alpha+a, Beta+0:10)/beta(Alpha,Beta)) [1] TRUE Looking at the code, one can see it actually calls the ghyper (generalized hypergeometric) family of distributions of the SuppDists package: brr::rbeta_nbinom function(n, a, c, d){ rghyper(n, -d, -a, c-1) } Ineed, the BNB distribution is known as a type IV generalized hypergeometric distribution. See the help of ghyper in the SuppDists package. I believe this can also be found in Johnson & al's book Univariate Discrete Distributions.
How to sample from discrete distribution on the non-negative integers?
This is a Beta negative binomial distribution, with parameter $r=1$ in your case, using the Wikipedia notation. It also named Beta-Pascal distribution when $r$ is an integer. As you noted in a comment
How to sample from discrete distribution on the non-negative integers? This is a Beta negative binomial distribution, with parameter $r=1$ in your case, using the Wikipedia notation. It also named Beta-Pascal distribution when $r$ is an integer. As you noted in a comment, this is a predictive distribution in the Bayesian negative binomial model with a conjugate Beta prior on the success probability. Thus you can sample it by sampling a $\text{Beta}(\alpha,\beta)$ variable $u$ and then sampling a negative binomial variable $\text{NB}(r,u)$ (with $r=1$ in your case, that is to say a geometric distribution). This distribution is implemented in the R package brr. The sampler has name rbeta_nbinom, the pmf has name dbeta_nbinom, etc. The notations are $a=r$, $c=\alpha$, $d=\beta$. Check: > Alpha <- 2; Beta <- 3 > a <- 1 > all.equal(brr::dbeta_nbinom(0:10, a, Alpha, Beta), beta(Alpha+a, Beta+0:10)/beta(Alpha,Beta)) [1] TRUE Looking at the code, one can see it actually calls the ghyper (generalized hypergeometric) family of distributions of the SuppDists package: brr::rbeta_nbinom function(n, a, c, d){ rghyper(n, -d, -a, c-1) } Ineed, the BNB distribution is known as a type IV generalized hypergeometric distribution. See the help of ghyper in the SuppDists package. I believe this can also be found in Johnson & al's book Univariate Discrete Distributions.
How to sample from discrete distribution on the non-negative integers? This is a Beta negative binomial distribution, with parameter $r=1$ in your case, using the Wikipedia notation. It also named Beta-Pascal distribution when $r$ is an integer. As you noted in a comment
27,712
How to sample from discrete distribution on the non-negative integers?
Given that $$\frac{\text{Beta}(\alpha+1, \beta+x)}{\text{Beta}(\alpha,\beta)}=\dfrac{\alpha}{\alpha+\beta+x}\dfrac{\beta+x-1}{\alpha+\beta+x-1}\cdots\dfrac{\beta}{\alpha+\beta}$$ is decreasing with $x$,I suggest generating a uniform variate $u\sim\mathcal{U}(0,1)$ and computing the cumulated sums$$S_k=\sum_{x=0}^k \frac{\text{Beta}(\alpha+1, \beta+x)}{\text{Beta}(\alpha,\beta)}$$ until $$S_k>u$$ The realisation is then equal to the corresponding $k$. Since $$\eqalign{R_x&=\frac{\text{Beta}(\alpha+1, \beta+x)}{\text{Beta}(\alpha,\beta)}\\&=\dfrac{\alpha}{\alpha+\beta+x}\dfrac{\beta+x-1}{\alpha+\beta+x-1}\cdots\dfrac{\beta}{\alpha+\beta}\\&=\frac{\alpha+\beta+x-1}{\alpha+\beta+x}\frac{\beta+x-1}{\alpha+\beta+x-1}R_{x-1}\\&=\frac{\beta+x-1}{\alpha+\beta+x}R_{x-1}}$$and$$S_k=S_k-1+R_k$$the computation can avoid using Gamma functions altogether.
How to sample from discrete distribution on the non-negative integers?
Given that $$\frac{\text{Beta}(\alpha+1, \beta+x)}{\text{Beta}(\alpha,\beta)}=\dfrac{\alpha}{\alpha+\beta+x}\dfrac{\beta+x-1}{\alpha+\beta+x-1}\cdots\dfrac{\beta}{\alpha+\beta}$$ is decreasing with $x
How to sample from discrete distribution on the non-negative integers? Given that $$\frac{\text{Beta}(\alpha+1, \beta+x)}{\text{Beta}(\alpha,\beta)}=\dfrac{\alpha}{\alpha+\beta+x}\dfrac{\beta+x-1}{\alpha+\beta+x-1}\cdots\dfrac{\beta}{\alpha+\beta}$$ is decreasing with $x$,I suggest generating a uniform variate $u\sim\mathcal{U}(0,1)$ and computing the cumulated sums$$S_k=\sum_{x=0}^k \frac{\text{Beta}(\alpha+1, \beta+x)}{\text{Beta}(\alpha,\beta)}$$ until $$S_k>u$$ The realisation is then equal to the corresponding $k$. Since $$\eqalign{R_x&=\frac{\text{Beta}(\alpha+1, \beta+x)}{\text{Beta}(\alpha,\beta)}\\&=\dfrac{\alpha}{\alpha+\beta+x}\dfrac{\beta+x-1}{\alpha+\beta+x-1}\cdots\dfrac{\beta}{\alpha+\beta}\\&=\frac{\alpha+\beta+x-1}{\alpha+\beta+x}\frac{\beta+x-1}{\alpha+\beta+x-1}R_{x-1}\\&=\frac{\beta+x-1}{\alpha+\beta+x}R_{x-1}}$$and$$S_k=S_k-1+R_k$$the computation can avoid using Gamma functions altogether.
How to sample from discrete distribution on the non-negative integers? Given that $$\frac{\text{Beta}(\alpha+1, \beta+x)}{\text{Beta}(\alpha,\beta)}=\dfrac{\alpha}{\alpha+\beta+x}\dfrac{\beta+x-1}{\alpha+\beta+x-1}\cdots\dfrac{\beta}{\alpha+\beta}$$ is decreasing with $x
27,713
Find close pairs in very high dimensional space with sparse vectors
It looks like the approach you're looking for is a combination of minhash signatures and Locality Sensitive Hashing (LSH); the (freely available) pdf of Mining Massive Datasets describes this approach (and other similarity measures) in some detail in Chapter 3, but briefly: A minhash signature is a condensed representation of your original matrix that is constructed by applying some number n of hash functions to features, thereby reducing the number of features per observation. This reduces the size of your data, however you'll probably notice that this still leaves you with a $O(N^2)$ problem. To address this, MMDS advises that if all you want to find is pairs above a certain threshold of similarity (which would seem to apply in your case), then you can focus only on those pairs that are most likely to be similar - this approach is called Locality Sensitive Hashing, and in section 3.4 they walk through an example of how to combine the minhash signature approach with LSH. In addition to the text, there are also lectures available on the Coursera course of the same name.
Find close pairs in very high dimensional space with sparse vectors
It looks like the approach you're looking for is a combination of minhash signatures and Locality Sensitive Hashing (LSH); the (freely available) pdf of Mining Massive Datasets describes this approach
Find close pairs in very high dimensional space with sparse vectors It looks like the approach you're looking for is a combination of minhash signatures and Locality Sensitive Hashing (LSH); the (freely available) pdf of Mining Massive Datasets describes this approach (and other similarity measures) in some detail in Chapter 3, but briefly: A minhash signature is a condensed representation of your original matrix that is constructed by applying some number n of hash functions to features, thereby reducing the number of features per observation. This reduces the size of your data, however you'll probably notice that this still leaves you with a $O(N^2)$ problem. To address this, MMDS advises that if all you want to find is pairs above a certain threshold of similarity (which would seem to apply in your case), then you can focus only on those pairs that are most likely to be similar - this approach is called Locality Sensitive Hashing, and in section 3.4 they walk through an example of how to combine the minhash signature approach with LSH. In addition to the text, there are also lectures available on the Coursera course of the same name.
Find close pairs in very high dimensional space with sparse vectors It looks like the approach you're looking for is a combination of minhash signatures and Locality Sensitive Hashing (LSH); the (freely available) pdf of Mining Massive Datasets describes this approach
27,714
Find close pairs in very high dimensional space with sparse vectors
I'm looking for the pairs of vectors that have at least $L$ features in common. This is just an inner product of binary feature vectors. When the inner product is greater than $L-1$, the pair will have at least $L$ elements in common. This should be a relatively fast computation -- at least, faster than euclidean distance, which would be wasteful and slow for this data. Because you stipulate that you're looking for pairs, this will inherently mean you have to do $\binom{N}{2}$ computations to compare every vector. Finding points that are close together is indeed a clustering problem. But the first step of the clustering algorithms that I'm familiar with is computing pairwise distances or similarities. I'm sure someone has developed more efficient alternatives. A point about terminology: having at least $L$ common neighbors is phrased as a similarity, not a distance! Inner products are, in this case, unnormalized cosine similarities. You can make this more tractable by only performing the inner product computation when the sum of the feature vector (which is in this case the same as the norm) for an observation is greater than $L-1$, since it's impossible for that binary feature vector to have an inner product with another binary feature vector which will satisfy my criterion when this sum is less than $L$. Obviously, computing these sums is only $O(N)$ complexity, so i's a cheap way to drive down the magnitude of the inner product step. But the classic way to reduce the scope of this problem is to do additional pre-filtering. Are you especially interested in when one, somewhat uncommon feature takes the value 1? If so, only perform the computation for those feature vectors. Or perhaps you could benefit from re-framing your problem. For example, sampling is known to have nice properties; inferential statistics develops on this idea to quite some depth. So perhaps it's unfeasible to analyze the entire data set, but it's perfectly feasible to examine a small sample. I don't know what question you're trying to answer, but if you carefully design your experiment, you may get away with only looking at a few thousand observations, with more than enough data left over for validation purposes. After some additional thought, I have a strong hunch that the data you're working with is some kind of graph $G$. It's very plausible that $G$ is composed of several connected components, in which case you can decompose $G$ into a set of graphs, with the happy side-effect of reducing the dimensionality of the data. Even if the graph is only two connected components of roughly the same size, that means your $O(N^2)$ pairwise comparisons has roughly $\frac{1}{4}$ the total cost! If the graph is symmetric, the following observations may be helpful: Define the Laplacian of your graph as $P=D-A$, where $D$ is a diagonal matrix of degree (the sum of each feature vector) and $A$ is the adjacency matrix (the stacking of feature vectors into a matrix). The number times $0$ appears as an eigenvalue of $P$ is the number of connected components of $G$. Decomposing the graph into its connected components and working solely with those components will have the side-effect of reducing the dimension of your data; computing your quantity of interest will be easier. But computing the eigendecomposition will be expensive for a million vertices... (After a full permutation) $P$ is a block diagonal matrix of the Laplacians of the connected components of $G$. $P$ is positive semidefinite. This is almost certainly useful somehow. The algebraic connectivity of $G$ is the value of the second-smallest eigenvalue of $P$. This tells you how well-connected $G$ is. Perhaps that will answer some of the questions you are interested in re: the vectors that have features in common. Spectral graph theory develops this idea in some more detail. "Is this an SNA problem?" I'm not sure. In one application the features describe behavior and we're looking to connect people with similar behaviors. Does that make this an SNA problem? If you have a bipartite graph connecting people to behaviors, you can think of this as an affiliation network $B$, with people as rows and behaviors as columns. If you want to connect people to people via the behaviors they have in common, you can compute $BB^T=A$. $A_{ij}$ is the number of behaviors the people have in common. Obviously, the set of vertices where $A_{ij}\ge L$ answers your question.
Find close pairs in very high dimensional space with sparse vectors
I'm looking for the pairs of vectors that have at least $L$ features in common. This is just an inner product of binary feature vectors. When the inner product is greater than $L-1$, the pair will ha
Find close pairs in very high dimensional space with sparse vectors I'm looking for the pairs of vectors that have at least $L$ features in common. This is just an inner product of binary feature vectors. When the inner product is greater than $L-1$, the pair will have at least $L$ elements in common. This should be a relatively fast computation -- at least, faster than euclidean distance, which would be wasteful and slow for this data. Because you stipulate that you're looking for pairs, this will inherently mean you have to do $\binom{N}{2}$ computations to compare every vector. Finding points that are close together is indeed a clustering problem. But the first step of the clustering algorithms that I'm familiar with is computing pairwise distances or similarities. I'm sure someone has developed more efficient alternatives. A point about terminology: having at least $L$ common neighbors is phrased as a similarity, not a distance! Inner products are, in this case, unnormalized cosine similarities. You can make this more tractable by only performing the inner product computation when the sum of the feature vector (which is in this case the same as the norm) for an observation is greater than $L-1$, since it's impossible for that binary feature vector to have an inner product with another binary feature vector which will satisfy my criterion when this sum is less than $L$. Obviously, computing these sums is only $O(N)$ complexity, so i's a cheap way to drive down the magnitude of the inner product step. But the classic way to reduce the scope of this problem is to do additional pre-filtering. Are you especially interested in when one, somewhat uncommon feature takes the value 1? If so, only perform the computation for those feature vectors. Or perhaps you could benefit from re-framing your problem. For example, sampling is known to have nice properties; inferential statistics develops on this idea to quite some depth. So perhaps it's unfeasible to analyze the entire data set, but it's perfectly feasible to examine a small sample. I don't know what question you're trying to answer, but if you carefully design your experiment, you may get away with only looking at a few thousand observations, with more than enough data left over for validation purposes. After some additional thought, I have a strong hunch that the data you're working with is some kind of graph $G$. It's very plausible that $G$ is composed of several connected components, in which case you can decompose $G$ into a set of graphs, with the happy side-effect of reducing the dimensionality of the data. Even if the graph is only two connected components of roughly the same size, that means your $O(N^2)$ pairwise comparisons has roughly $\frac{1}{4}$ the total cost! If the graph is symmetric, the following observations may be helpful: Define the Laplacian of your graph as $P=D-A$, where $D$ is a diagonal matrix of degree (the sum of each feature vector) and $A$ is the adjacency matrix (the stacking of feature vectors into a matrix). The number times $0$ appears as an eigenvalue of $P$ is the number of connected components of $G$. Decomposing the graph into its connected components and working solely with those components will have the side-effect of reducing the dimension of your data; computing your quantity of interest will be easier. But computing the eigendecomposition will be expensive for a million vertices... (After a full permutation) $P$ is a block diagonal matrix of the Laplacians of the connected components of $G$. $P$ is positive semidefinite. This is almost certainly useful somehow. The algebraic connectivity of $G$ is the value of the second-smallest eigenvalue of $P$. This tells you how well-connected $G$ is. Perhaps that will answer some of the questions you are interested in re: the vectors that have features in common. Spectral graph theory develops this idea in some more detail. "Is this an SNA problem?" I'm not sure. In one application the features describe behavior and we're looking to connect people with similar behaviors. Does that make this an SNA problem? If you have a bipartite graph connecting people to behaviors, you can think of this as an affiliation network $B$, with people as rows and behaviors as columns. If you want to connect people to people via the behaviors they have in common, you can compute $BB^T=A$. $A_{ij}$ is the number of behaviors the people have in common. Obviously, the set of vertices where $A_{ij}\ge L$ answers your question.
Find close pairs in very high dimensional space with sparse vectors I'm looking for the pairs of vectors that have at least $L$ features in common. This is just an inner product of binary feature vectors. When the inner product is greater than $L-1$, the pair will ha
27,715
Find close pairs in very high dimensional space with sparse vectors
On looking for people meeting in space-time blocks: split space into $Nspace$ blocks (city blocks, square km, whatever), and time into $Ntime$ blocks. There's a good chance that if people meet, they'll meet within the same block. So run NN within each block. Runtimes and error rates will of course depend on block sizes and shapes (also on what you can parallelize / MapReduce), but you have parameters to play with -- engineering, not wide-open $O( N^2 )$. See also: nearest-neighbors-search-for-very-high-dimensional-data on datascience.stackexchange pairwise.py: uses the Python Gensim library and heapq from the standard library to make massively fast and scalable pairwise comparisons between an aribtrarily large number of documents using TF-IDF and cosine distance.
Find close pairs in very high dimensional space with sparse vectors
On looking for people meeting in space-time blocks: split space into $Nspace$ blocks (city blocks, square km, whatever), and time into $Ntime$ blocks. There's a good chance that if people meet, they'l
Find close pairs in very high dimensional space with sparse vectors On looking for people meeting in space-time blocks: split space into $Nspace$ blocks (city blocks, square km, whatever), and time into $Ntime$ blocks. There's a good chance that if people meet, they'll meet within the same block. So run NN within each block. Runtimes and error rates will of course depend on block sizes and shapes (also on what you can parallelize / MapReduce), but you have parameters to play with -- engineering, not wide-open $O( N^2 )$. See also: nearest-neighbors-search-for-very-high-dimensional-data on datascience.stackexchange pairwise.py: uses the Python Gensim library and heapq from the standard library to make massively fast and scalable pairwise comparisons between an aribtrarily large number of documents using TF-IDF and cosine distance.
Find close pairs in very high dimensional space with sparse vectors On looking for people meeting in space-time blocks: split space into $Nspace$ blocks (city blocks, square km, whatever), and time into $Ntime$ blocks. There's a good chance that if people meet, they'l
27,716
Find close pairs in very high dimensional space with sparse vectors
Inverted dictionnary! Represent a point $x$ as $feat_1:value_1, feat_{101}:value_{101}$, the keys corresponding to non zero values (i.e. the features holding true). The average size of storage of an element will be $K$. Indeed, I only need $K$ strings to store the features and $K$ floats to hold the values. For each feature, build a dictionary holding the indexes sharing this feature. Hopefully, this number will not be too big (if you have a feature which is shared by all the indexes, this approach is ruined, you can stop reading here). This dictionary looks like : $feat_1 : \{1,101,202\}, feat_2 : \{7,202\},feat_3 : \{202\}...feat_M:\{3,45,6\}$. If I want to gain speed and save space, I can even drop the features that are only found with one element (here:$feat_3$) as they will not produce close pairs. This dictionary is built in $O(NK)$ operations. Now, when you want to evaluate the distance of an element $x$ to the others, generate (with the dictionary) the list of the indexes sharing at least one feature with $x$. You know that all the other elements are far from $x$ (they don't even share one feature!). If the average number of "elements per feature" is low (call it $P$), you need not to be in $O(N^2)$ any more. Now there is another big improvement if $x$ and $y$ are represented as dictionaries as well, since $d(x,y)$ or $<x,y>$ can be evaluated iterating over the keys of $x$ and $y$, in $O(K)$ operations. Your final complexity is $O(NPK)$ instead of the naive $O(MN^2)$ initial approach. I applied this method to implement a KNN over large text set (train : 2 000 000 lines, test 35 000 lines, number of features : 10 000, average number of features per element : 20), which ran in about an hour...
Find close pairs in very high dimensional space with sparse vectors
Inverted dictionnary! Represent a point $x$ as $feat_1:value_1, feat_{101}:value_{101}$, the keys corresponding to non zero values (i.e. the features holding true). The average size of storage of an e
Find close pairs in very high dimensional space with sparse vectors Inverted dictionnary! Represent a point $x$ as $feat_1:value_1, feat_{101}:value_{101}$, the keys corresponding to non zero values (i.e. the features holding true). The average size of storage of an element will be $K$. Indeed, I only need $K$ strings to store the features and $K$ floats to hold the values. For each feature, build a dictionary holding the indexes sharing this feature. Hopefully, this number will not be too big (if you have a feature which is shared by all the indexes, this approach is ruined, you can stop reading here). This dictionary looks like : $feat_1 : \{1,101,202\}, feat_2 : \{7,202\},feat_3 : \{202\}...feat_M:\{3,45,6\}$. If I want to gain speed and save space, I can even drop the features that are only found with one element (here:$feat_3$) as they will not produce close pairs. This dictionary is built in $O(NK)$ operations. Now, when you want to evaluate the distance of an element $x$ to the others, generate (with the dictionary) the list of the indexes sharing at least one feature with $x$. You know that all the other elements are far from $x$ (they don't even share one feature!). If the average number of "elements per feature" is low (call it $P$), you need not to be in $O(N^2)$ any more. Now there is another big improvement if $x$ and $y$ are represented as dictionaries as well, since $d(x,y)$ or $<x,y>$ can be evaluated iterating over the keys of $x$ and $y$, in $O(K)$ operations. Your final complexity is $O(NPK)$ instead of the naive $O(MN^2)$ initial approach. I applied this method to implement a KNN over large text set (train : 2 000 000 lines, test 35 000 lines, number of features : 10 000, average number of features per element : 20), which ran in about an hour...
Find close pairs in very high dimensional space with sparse vectors Inverted dictionnary! Represent a point $x$ as $feat_1:value_1, feat_{101}:value_{101}$, the keys corresponding to non zero values (i.e. the features holding true). The average size of storage of an e
27,717
Find close pairs in very high dimensional space with sparse vectors
I've found a reference that you might find helpful, and I believe it's asymptotically more efficient than every other solution presented so far. If I understand correctly, you can construct a $k$-nearest neighbor (KNN) graph in $O(LN\log(N))$ time. L. Erotz, M. Steinbach, and V. Kumar. "A new shared nearest neighbor clustering algorithm and its applications." Proceedings of the 1st Workshop on Clustering High Dimensional Data and its Applications, 2002.
Find close pairs in very high dimensional space with sparse vectors
I've found a reference that you might find helpful, and I believe it's asymptotically more efficient than every other solution presented so far. If I understand correctly, you can construct a $k$-near
Find close pairs in very high dimensional space with sparse vectors I've found a reference that you might find helpful, and I believe it's asymptotically more efficient than every other solution presented so far. If I understand correctly, you can construct a $k$-nearest neighbor (KNN) graph in $O(LN\log(N))$ time. L. Erotz, M. Steinbach, and V. Kumar. "A new shared nearest neighbor clustering algorithm and its applications." Proceedings of the 1st Workshop on Clustering High Dimensional Data and its Applications, 2002.
Find close pairs in very high dimensional space with sparse vectors I've found a reference that you might find helpful, and I believe it's asymptotically more efficient than every other solution presented so far. If I understand correctly, you can construct a $k$-near
27,718
Find close pairs in very high dimensional space with sparse vectors
A crazy, but likely to work approach might be to go to frequency domain. There is a crazy/sick fast fft called "sparse FFT" where you specify the number of modes you care about (your count of 100 features) and then you work in convolutions, and look for row-max greater than a threshold (look for bits in upper registers of your numbers). It is going to be $O(k \cdot \log{n} )$ where $ k << n $. Given that your k is 100 and your n is 1e6, this should give you ~1e4x speed up compared with classic FFT. If you need another 20x in speed, and you are a risk taker, then instead of convoluting all rows against the domain and looking for the peak, you could bootstrap a subset of rows. You might also prefilter columns by removing columns whose sums are below 50, or some other threshold that is on the order of half the number of rows you are looking to match. At the very least you should remove columns of all zeros and all 1's as non-informative. Same with rows that are entirely empty or empty enough, or rows that are so full that they are irrelevant. To-do: I should put an example here using synthetic data, and compare some of the methods.
Find close pairs in very high dimensional space with sparse vectors
A crazy, but likely to work approach might be to go to frequency domain. There is a crazy/sick fast fft called "sparse FFT" where you specify the number of modes you care about (your count of 100 fea
Find close pairs in very high dimensional space with sparse vectors A crazy, but likely to work approach might be to go to frequency domain. There is a crazy/sick fast fft called "sparse FFT" where you specify the number of modes you care about (your count of 100 features) and then you work in convolutions, and look for row-max greater than a threshold (look for bits in upper registers of your numbers). It is going to be $O(k \cdot \log{n} )$ where $ k << n $. Given that your k is 100 and your n is 1e6, this should give you ~1e4x speed up compared with classic FFT. If you need another 20x in speed, and you are a risk taker, then instead of convoluting all rows against the domain and looking for the peak, you could bootstrap a subset of rows. You might also prefilter columns by removing columns whose sums are below 50, or some other threshold that is on the order of half the number of rows you are looking to match. At the very least you should remove columns of all zeros and all 1's as non-informative. Same with rows that are entirely empty or empty enough, or rows that are so full that they are irrelevant. To-do: I should put an example here using synthetic data, and compare some of the methods.
Find close pairs in very high dimensional space with sparse vectors A crazy, but likely to work approach might be to go to frequency domain. There is a crazy/sick fast fft called "sparse FFT" where you specify the number of modes you care about (your count of 100 fea
27,719
Find close pairs in very high dimensional space with sparse vectors
I just came across a paper that is directly relevant. Randomized algorithms and NLP: using locality sensitive hash function for high speed noun clustering (Ravichandran et al, 2005) It is actually implemented in https://github.com/soundcloud/cosine-lsh-join-spark which is where I found it. It is based on locality sensitive hashing (already mentioned in other answers). After it has reduced the feature vectors to a low-dimensional space it uses a fast Hamming distance join to find the nearest neighbors.
Find close pairs in very high dimensional space with sparse vectors
I just came across a paper that is directly relevant. Randomized algorithms and NLP: using locality sensitive hash function for high speed noun clustering (Ravichandran et al, 2005) It is actually i
Find close pairs in very high dimensional space with sparse vectors I just came across a paper that is directly relevant. Randomized algorithms and NLP: using locality sensitive hash function for high speed noun clustering (Ravichandran et al, 2005) It is actually implemented in https://github.com/soundcloud/cosine-lsh-join-spark which is where I found it. It is based on locality sensitive hashing (already mentioned in other answers). After it has reduced the feature vectors to a low-dimensional space it uses a fast Hamming distance join to find the nearest neighbors.
Find close pairs in very high dimensional space with sparse vectors I just came across a paper that is directly relevant. Randomized algorithms and NLP: using locality sensitive hash function for high speed noun clustering (Ravichandran et al, 2005) It is actually i
27,720
applying two-sample t.test comparing multiple groups in two categories
There are various ways to do that, but I'm using a combination of dplyr and broom packages. The advantage of this process is that you export the t-test information as a dataset: library(dplyr) library(broom) set.seed(9) # example dataset dt = data.frame(species = c(rep("ARGAFF",6), rep("BATABY",6)), region = rep(c("EQ","OMZ"),6), N15 = rnorm(12,10,1)) dt_result = dt %>% group_by(species) %>% do(tidy(t.test(N15~region, data=.))) dt_result # species estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high # 1 ARGAFF 0.6029705 9.842659 9.239688 1.381967 0.2439265 3.732157 -0.6434982 1.849439 # 2 BATABY 1.0238324 10.740491 9.716659 1.994738 0.1673019 2.300604 -0.9298488 2.977514 Hope it works for you.
applying two-sample t.test comparing multiple groups in two categories
There are various ways to do that, but I'm using a combination of dplyr and broom packages. The advantage of this process is that you export the t-test information as a dataset: library(dplyr) library
applying two-sample t.test comparing multiple groups in two categories There are various ways to do that, but I'm using a combination of dplyr and broom packages. The advantage of this process is that you export the t-test information as a dataset: library(dplyr) library(broom) set.seed(9) # example dataset dt = data.frame(species = c(rep("ARGAFF",6), rep("BATABY",6)), region = rep(c("EQ","OMZ"),6), N15 = rnorm(12,10,1)) dt_result = dt %>% group_by(species) %>% do(tidy(t.test(N15~region, data=.))) dt_result # species estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high # 1 ARGAFF 0.6029705 9.842659 9.239688 1.381967 0.2439265 3.732157 -0.6434982 1.849439 # 2 BATABY 1.0238324 10.740491 9.716659 1.994738 0.1673019 2.300604 -0.9298488 2.977514 Hope it works for you.
applying two-sample t.test comparing multiple groups in two categories There are various ways to do that, but I'm using a combination of dplyr and broom packages. The advantage of this process is that you export the t-test information as a dataset: library(dplyr) library
27,721
applying two-sample t.test comparing multiple groups in two categories
First, in general it is a bad idea to attach a dataset. You can modify your lapply statement to do what you want I think. set.seed(9) # example dataset SIA <- data.frame(species = as.factor(c(rep("ARGAFF",6), rep("BATABY",6))), region = as.factor(rep(c("EQ","OMZ"),6)), N15 = rnorm(12,10,1)) spp <- split(SIA, SIA$species,drop=FALSE) out <- vector("list", length = length(spp)) out <- lapply(1:length(spp),function (x) out[[x]]<- t.test(spp[[x]]$N15 ~ spp[[x]]$region)) Then you can extract whatever features you want. > out [[1]] Welch Two Sample t-test data: spp[[x]]$N15 by spp[[x]]$region t = -0.7566, df = 2.4628, p-value = 0.515 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -4.617903 3.018924 sample estimates: mean in group EQ mean in group OMZ 9.982135 10.781625 [[2]] Welch Two Sample t-test data: spp[[x]]$N15 by spp[[x]]$region t = 0.66769, df = 3.2858, p-value = 0.5483 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -1.564611 2.448523 sample estimates: mean in group EQ mean in group OMZ 10.055578 9.613622
applying two-sample t.test comparing multiple groups in two categories
First, in general it is a bad idea to attach a dataset. You can modify your lapply statement to do what you want I think. set.seed(9) # example dataset SIA <- data.frame(species = as.factor(c(rep("AR
applying two-sample t.test comparing multiple groups in two categories First, in general it is a bad idea to attach a dataset. You can modify your lapply statement to do what you want I think. set.seed(9) # example dataset SIA <- data.frame(species = as.factor(c(rep("ARGAFF",6), rep("BATABY",6))), region = as.factor(rep(c("EQ","OMZ"),6)), N15 = rnorm(12,10,1)) spp <- split(SIA, SIA$species,drop=FALSE) out <- vector("list", length = length(spp)) out <- lapply(1:length(spp),function (x) out[[x]]<- t.test(spp[[x]]$N15 ~ spp[[x]]$region)) Then you can extract whatever features you want. > out [[1]] Welch Two Sample t-test data: spp[[x]]$N15 by spp[[x]]$region t = -0.7566, df = 2.4628, p-value = 0.515 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -4.617903 3.018924 sample estimates: mean in group EQ mean in group OMZ 9.982135 10.781625 [[2]] Welch Two Sample t-test data: spp[[x]]$N15 by spp[[x]]$region t = 0.66769, df = 3.2858, p-value = 0.5483 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -1.564611 2.448523 sample estimates: mean in group EQ mean in group OMZ 10.055578 9.613622
applying two-sample t.test comparing multiple groups in two categories First, in general it is a bad idea to attach a dataset. You can modify your lapply statement to do what you want I think. set.seed(9) # example dataset SIA <- data.frame(species = as.factor(c(rep("AR
27,722
applying two-sample t.test comparing multiple groups in two categories
Rstatix::t_test() is a user-friendly wrapper of t.test() that returns a tibble. library(tidyverse) library(rstatix) df <- tribble(~species, ~region, ~N15, "ARGAFF", "EQ", 9.85, "ARGAFF", "EQ", 10.42, "ARGAFF", "EQ", 10.43, "ARGAFF", "OMZ", 10.28, "ARGAFF", "OMZ", 10.30, "ARGAFF", "OMZ", 10.41, "BATABY", "EQ", 10.57, "BATABY", "EQ", 10.60, "BATABY", "EQ", 10.68, "BATABY", "OMZ", 9.21, "BATABY", "OMZ", 9.29, "BATABY", "OMZ", 9.67) df %>% group_by(species) %>% t_test(N15~region)
applying two-sample t.test comparing multiple groups in two categories
Rstatix::t_test() is a user-friendly wrapper of t.test() that returns a tibble. library(tidyverse) library(rstatix) df <- tribble(~species, ~region, ~N15, "ARGAFF", "EQ", 9.85
applying two-sample t.test comparing multiple groups in two categories Rstatix::t_test() is a user-friendly wrapper of t.test() that returns a tibble. library(tidyverse) library(rstatix) df <- tribble(~species, ~region, ~N15, "ARGAFF", "EQ", 9.85, "ARGAFF", "EQ", 10.42, "ARGAFF", "EQ", 10.43, "ARGAFF", "OMZ", 10.28, "ARGAFF", "OMZ", 10.30, "ARGAFF", "OMZ", 10.41, "BATABY", "EQ", 10.57, "BATABY", "EQ", 10.60, "BATABY", "EQ", 10.68, "BATABY", "OMZ", 9.21, "BATABY", "OMZ", 9.29, "BATABY", "OMZ", 9.67) df %>% group_by(species) %>% t_test(N15~region)
applying two-sample t.test comparing multiple groups in two categories Rstatix::t_test() is a user-friendly wrapper of t.test() that returns a tibble. library(tidyverse) library(rstatix) df <- tribble(~species, ~region, ~N15, "ARGAFF", "EQ", 9.85
27,723
What is calibration?
The term ``calibration'', as applied to survey weights, appears to have been coined by Deville and Sarndal (1992). They put an umbrella on a bunch of different procedures that used the known population totals: $$ \sum_{i \in \mathcal{U}} Y_i = T_i $$ where $Y_i$ is a vector of characteristics known for every unit in the population $\mathcal{U}$. For general human populations, these would be census data on demographic characteristics, like age, gender, race/ethnicity, education, geography (regions, states, provinces), and may be income. For establishment populations, these variables typically have to do with establishment size and income. For list samples -- whatever it is that you have attached to your sample. Deville and Sarndal (1992) discussed how to go from design weights (inverse probabilities of selection), $d_i, i\in \mathcal{S}$ where $\mathcal{S}$ is the sample drawn from $\mathcal{U}$, to calibrated weights $w_i$ such that $$ \sum_{i \in \mathcal{S}} w_i y_i = T_i $$ i.e., the sample agrees with the population on these variables. They did this by optimizing a distance function $$ F(w_i,d_i) \ge 0 \to \min, \quad F(r_i,r_i) = 0, \mbox{ subject to } \sum_{i \in \mathcal{S}} w_i y_i = T_i $$ Typically, as is often the case in statistics, bringing in additional information improves variances asymptotically, although may throw things off and introduce weird small sample biases. Deville and Sarndal (1992) quantified these asymptotic efficiency gains, which was their central contribution to the literature. In regards of using auxiliary data, survey statistics stands as a pretty unique branch. Bayesian folks utilize auxiliary data in their priors. The i.i.d. frequentists / likelihoodists usually don't have much of a way to incorporate auxiliary information, it seems, as all information must be contained in the likelihood. There is, however, a branch of empirical likelihood estimation where auxiliary information is being used to generate and/or aggregate estimating equations; in fact the empirical likelihood objective functions is one of the objective function cases considered by Deville and Sarndal (1992). (Econometricians should sniff, quite properly, and point out that they have known the ways to calibrate statistical models via generalized method of moments for more than 30 years by now, since Hansen (1982). A quadratic loss is another naturally interesting case in Deville and Sarndal (1992); while it is the easiest to compute, it can give rise to negative weights that are usually considered weird.) Another use of the term ``calibration'' in statistics that I heard of is the reverse regression, in which you have inaccurate measurements of the variable of interest and want to recover the value of the predictor (the running example I was given by my marathon runner of a stats professor was measuring the distance of the course by biking it and counting the revolutions of the bike wheels, vs. more accurate GPS measurements -- that was in the late 1990s era before smarthphones and handheld GPS devices.) You calibrate your bike on an established 1km course, and then try to bike around to get 42 that much. There may be yet other uses. I am not sure dumping them all in one entry is particularly wise though. You indicated factor analysis as one potential user of that term, but I am not particularly well aware of how it is used there.
What is calibration?
The term ``calibration'', as applied to survey weights, appears to have been coined by Deville and Sarndal (1992). They put an umbrella on a bunch of different procedures that used the known populatio
What is calibration? The term ``calibration'', as applied to survey weights, appears to have been coined by Deville and Sarndal (1992). They put an umbrella on a bunch of different procedures that used the known population totals: $$ \sum_{i \in \mathcal{U}} Y_i = T_i $$ where $Y_i$ is a vector of characteristics known for every unit in the population $\mathcal{U}$. For general human populations, these would be census data on demographic characteristics, like age, gender, race/ethnicity, education, geography (regions, states, provinces), and may be income. For establishment populations, these variables typically have to do with establishment size and income. For list samples -- whatever it is that you have attached to your sample. Deville and Sarndal (1992) discussed how to go from design weights (inverse probabilities of selection), $d_i, i\in \mathcal{S}$ where $\mathcal{S}$ is the sample drawn from $\mathcal{U}$, to calibrated weights $w_i$ such that $$ \sum_{i \in \mathcal{S}} w_i y_i = T_i $$ i.e., the sample agrees with the population on these variables. They did this by optimizing a distance function $$ F(w_i,d_i) \ge 0 \to \min, \quad F(r_i,r_i) = 0, \mbox{ subject to } \sum_{i \in \mathcal{S}} w_i y_i = T_i $$ Typically, as is often the case in statistics, bringing in additional information improves variances asymptotically, although may throw things off and introduce weird small sample biases. Deville and Sarndal (1992) quantified these asymptotic efficiency gains, which was their central contribution to the literature. In regards of using auxiliary data, survey statistics stands as a pretty unique branch. Bayesian folks utilize auxiliary data in their priors. The i.i.d. frequentists / likelihoodists usually don't have much of a way to incorporate auxiliary information, it seems, as all information must be contained in the likelihood. There is, however, a branch of empirical likelihood estimation where auxiliary information is being used to generate and/or aggregate estimating equations; in fact the empirical likelihood objective functions is one of the objective function cases considered by Deville and Sarndal (1992). (Econometricians should sniff, quite properly, and point out that they have known the ways to calibrate statistical models via generalized method of moments for more than 30 years by now, since Hansen (1982). A quadratic loss is another naturally interesting case in Deville and Sarndal (1992); while it is the easiest to compute, it can give rise to negative weights that are usually considered weird.) Another use of the term ``calibration'' in statistics that I heard of is the reverse regression, in which you have inaccurate measurements of the variable of interest and want to recover the value of the predictor (the running example I was given by my marathon runner of a stats professor was measuring the distance of the course by biking it and counting the revolutions of the bike wheels, vs. more accurate GPS measurements -- that was in the late 1990s era before smarthphones and handheld GPS devices.) You calibrate your bike on an established 1km course, and then try to bike around to get 42 that much. There may be yet other uses. I am not sure dumping them all in one entry is particularly wise though. You indicated factor analysis as one potential user of that term, but I am not particularly well aware of how it is used there.
What is calibration? The term ``calibration'', as applied to survey weights, appears to have been coined by Deville and Sarndal (1992). They put an umbrella on a bunch of different procedures that used the known populatio
27,724
What is calibration?
say you run a survey and get 1,000 responses. maybe you conducted your survey via cell phone and older people don't have cell phones at the same rate as younger people. so 5% of your survey respondents (N=50) were senior citizens but maybe according to the united states census bureau, 15% of americans are actually senior citizens. and let's say respondent age is going to matter for your survey analysis, for the stuff you ultimately publish. in order for your 1,000 responses to properly generalize to a more realistic population, you need to give your senior citizens weights of 3x (the weighted N needs to be 150) and scale everyone else's weights down a bit (the nonelderly N=950 should have a weighted N of 850). calibration, raking, post-stratification are techniques to bring your survey data set closer to some official total. this is a simple case, but most survey weights are re-computed based on more than just one factor (in this case, age)
What is calibration?
say you run a survey and get 1,000 responses. maybe you conducted your survey via cell phone and older people don't have cell phones at the same rate as younger people. so 5% of your survey responde
What is calibration? say you run a survey and get 1,000 responses. maybe you conducted your survey via cell phone and older people don't have cell phones at the same rate as younger people. so 5% of your survey respondents (N=50) were senior citizens but maybe according to the united states census bureau, 15% of americans are actually senior citizens. and let's say respondent age is going to matter for your survey analysis, for the stuff you ultimately publish. in order for your 1,000 responses to properly generalize to a more realistic population, you need to give your senior citizens weights of 3x (the weighted N needs to be 150) and scale everyone else's weights down a bit (the nonelderly N=950 should have a weighted N of 850). calibration, raking, post-stratification are techniques to bring your survey data set closer to some official total. this is a simple case, but most survey weights are re-computed based on more than just one factor (in this case, age)
What is calibration? say you run a survey and get 1,000 responses. maybe you conducted your survey via cell phone and older people don't have cell phones at the same rate as younger people. so 5% of your survey responde
27,725
What is calibration?
There are other uses of the term "calibration." For instance in this CV thread, Frank Harrell discusses it in the context of determining model fit: The key thing to check first is the model's calibration, either using the bootstrap to correct for overfitting or using a huge independent sample not used for model development or fitting. Understanding how good a prediction is, in logistic regression Typically, in predictive modeling, calibration of a model refers to evaluating the goodness-of-fit (or model accuracy) on the training data, whereas predictive error is evaluated on the test data.
What is calibration?
There are other uses of the term "calibration." For instance in this CV thread, Frank Harrell discusses it in the context of determining model fit: The key thing to check first is the model's calibra
What is calibration? There are other uses of the term "calibration." For instance in this CV thread, Frank Harrell discusses it in the context of determining model fit: The key thing to check first is the model's calibration, either using the bootstrap to correct for overfitting or using a huge independent sample not used for model development or fitting. Understanding how good a prediction is, in logistic regression Typically, in predictive modeling, calibration of a model refers to evaluating the goodness-of-fit (or model accuracy) on the training data, whereas predictive error is evaluated on the test data.
What is calibration? There are other uses of the term "calibration." For instance in this CV thread, Frank Harrell discusses it in the context of determining model fit: The key thing to check first is the model's calibra
27,726
What is calibration?
Calibration means that you set desired parameters with known good values which would result in expected outcomes. Calibrated values are well established values. The confidence of its values, which as depicted in the calibration curve σ, shows the confidence in the estimated values as deviation from the mean μ. Here, 68% of values are within one standard deviation σ away from the mean; while 95% of the values lie within two sigmas.
What is calibration?
Calibration means that you set desired parameters with known good values which would result in expected outcomes. Calibrated values are well established values. The confidence of its values, which as
What is calibration? Calibration means that you set desired parameters with known good values which would result in expected outcomes. Calibrated values are well established values. The confidence of its values, which as depicted in the calibration curve σ, shows the confidence in the estimated values as deviation from the mean μ. Here, 68% of values are within one standard deviation σ away from the mean; while 95% of the values lie within two sigmas.
What is calibration? Calibration means that you set desired parameters with known good values which would result in expected outcomes. Calibrated values are well established values. The confidence of its values, which as
27,727
What is calibration?
I'd like to share with you an intuitive example to explain the following statement: we desire that the estimated class probabilities are reflective of the true underlying probability of the sample. That is, the predicted class probability (or probability-like value) needs to be well-calibrated. To be well-calibrated, the probabilities must effectively reflect the true likelihood of the event of interest. Source: Applied Predictive Modeling on page 249 For a particular case it is hard to illustrate the probability, but when it comes to large size of cases the effect of calibration appears. For instance, the airline company use some algorithms, for instance the logistic regression(why?), to predict whether the passenger will show up on that day. They actually don't care about if the particular person will turn up or not, and what they concern is how many shows would be in total. What they do can be just adding all the probabilities of the predictions. If the sum is bellow the number of the seats they can overbook flights. Some classifiers are not well-calibrated for instance SVM. That's the score we get while predicting is not the true probability.
What is calibration?
I'd like to share with you an intuitive example to explain the following statement: we desire that the estimated class probabilities are reflective of the true underlying probability of the sample
What is calibration? I'd like to share with you an intuitive example to explain the following statement: we desire that the estimated class probabilities are reflective of the true underlying probability of the sample. That is, the predicted class probability (or probability-like value) needs to be well-calibrated. To be well-calibrated, the probabilities must effectively reflect the true likelihood of the event of interest. Source: Applied Predictive Modeling on page 249 For a particular case it is hard to illustrate the probability, but when it comes to large size of cases the effect of calibration appears. For instance, the airline company use some algorithms, for instance the logistic regression(why?), to predict whether the passenger will show up on that day. They actually don't care about if the particular person will turn up or not, and what they concern is how many shows would be in total. What they do can be just adding all the probabilities of the predictions. If the sum is bellow the number of the seats they can overbook flights. Some classifiers are not well-calibrated for instance SVM. That's the score we get while predicting is not the true probability.
What is calibration? I'd like to share with you an intuitive example to explain the following statement: we desire that the estimated class probabilities are reflective of the true underlying probability of the sample
27,728
Bayesian optimization or gradient descent?
I'm assuming that by Bayesian optimization you mean the standard method of fitting a Gaussian process or similar model to your observations, defining an acquisition function such as expected improvement or upper confidence bound, and querying the function at the maximum of that acquisition function. The most immediate difference is that Bayesian optimization is applicable when you don't know the gradients. If you can cheaply compute gradients of your function, you'll want to use a method that can incorporate those, since they can be extremely helpful in understanding the function. If you can't easily compute gradients and need to resort to finite differences approximations, in most cases you really don't want to do that. BO assumes that the function is fairly smooth (as defined by your kernel in the GP) but not convex. Gradient descent, if you want to find a global maximum, assumes convexity as well as some degree of smoothness (as used in the step size parameter). BO tries to minimize the number of calls to the objective function. If it is expensive to calculate, e.g. because it requires a lot of computation or even some interaction with the outside world, this is highly desirable. If the objective is cheap to calculate, it may be faster to not bother with the amount of side computation needed. BO typically does not scale well to high-dimensional functions, either statistically or computationally. Recent work has begun to address this issue, from various tacks. Gradient descent and similar methods often scale reasonably to higher dimensions, if you're careful. BO also doesn't typically scale well to evaluating the function many times, since GP inference is cubic in the number of input points. There's been a lot of recent work on speeding up GPs or using similar more scalable methods, which may or may not address this problem for your needs.
Bayesian optimization or gradient descent?
I'm assuming that by Bayesian optimization you mean the standard method of fitting a Gaussian process or similar model to your observations, defining an acquisition function such as expected improveme
Bayesian optimization or gradient descent? I'm assuming that by Bayesian optimization you mean the standard method of fitting a Gaussian process or similar model to your observations, defining an acquisition function such as expected improvement or upper confidence bound, and querying the function at the maximum of that acquisition function. The most immediate difference is that Bayesian optimization is applicable when you don't know the gradients. If you can cheaply compute gradients of your function, you'll want to use a method that can incorporate those, since they can be extremely helpful in understanding the function. If you can't easily compute gradients and need to resort to finite differences approximations, in most cases you really don't want to do that. BO assumes that the function is fairly smooth (as defined by your kernel in the GP) but not convex. Gradient descent, if you want to find a global maximum, assumes convexity as well as some degree of smoothness (as used in the step size parameter). BO tries to minimize the number of calls to the objective function. If it is expensive to calculate, e.g. because it requires a lot of computation or even some interaction with the outside world, this is highly desirable. If the objective is cheap to calculate, it may be faster to not bother with the amount of side computation needed. BO typically does not scale well to high-dimensional functions, either statistically or computationally. Recent work has begun to address this issue, from various tacks. Gradient descent and similar methods often scale reasonably to higher dimensions, if you're careful. BO also doesn't typically scale well to evaluating the function many times, since GP inference is cubic in the number of input points. There's been a lot of recent work on speeding up GPs or using similar more scalable methods, which may or may not address this problem for your needs.
Bayesian optimization or gradient descent? I'm assuming that by Bayesian optimization you mean the standard method of fitting a Gaussian process or similar model to your observations, defining an acquisition function such as expected improveme
27,729
Is Markov chain based sampling the "best" for Monte Carlo sampling? Are there alternative schemes available?
There is no reason to state that MCMC sampling is the "best" Monte Carlo method! Usually, it is on the opposite worse than iid sampling, at least in terms of variance of the resulting Monte Carlo estimators$$\frac{1}{T}\sum_{t=1}^T h(X_t)$$Indeed, while this average converges to the expectation $\mathbb{E}_{\pi}[h(X)]$ when $\pi$ is the stationary and limiting distribution of the Markov chain $(X_t)_t$, there are at least two drawbacks in using MCMC methods: The chain needs to "reach stationarity", meaning that it needs to forget about its starting value $X_0$. In other words, $t$ must be "large enough" for $X_t$ to be distributed from $\pi$. Sometimes "large enough" may exceed by several orders of magnitude the computing budget for the experiment. The values $X_t$ are correlated, leading to an asymptotic variance that involves $$\text{var}_\pi(X)+2\sum_{t=1}^\infty\text{cov}_\pi(X_0,X_t)$$ which generally exceeds $\text{var}_\pi(X)$ and hence requires longer simulations than for an iid sample. This being said, MCMC is very useful for handling settings where regular iid sampling is impossible or too costly and where importance sampling is quite difficult to calibrate, in particular because of the dimension of the random variable to be simulated. However, sequential Monte Carlo methods like particle filters may be more appropriate in dynamical models, where the data comes by bursts that need immediate attention and may even vanish (i.e., cannot be stored) after a short while. In conclusion, MCMC is a very useful (and very much used) tool to handle complex settings where regular Monte Carlo solutions fail.
Is Markov chain based sampling the "best" for Monte Carlo sampling? Are there alternative schemes av
There is no reason to state that MCMC sampling is the "best" Monte Carlo method! Usually, it is on the opposite worse than iid sampling, at least in terms of variance of the resulting Monte Carlo esti
Is Markov chain based sampling the "best" for Monte Carlo sampling? Are there alternative schemes available? There is no reason to state that MCMC sampling is the "best" Monte Carlo method! Usually, it is on the opposite worse than iid sampling, at least in terms of variance of the resulting Monte Carlo estimators$$\frac{1}{T}\sum_{t=1}^T h(X_t)$$Indeed, while this average converges to the expectation $\mathbb{E}_{\pi}[h(X)]$ when $\pi$ is the stationary and limiting distribution of the Markov chain $(X_t)_t$, there are at least two drawbacks in using MCMC methods: The chain needs to "reach stationarity", meaning that it needs to forget about its starting value $X_0$. In other words, $t$ must be "large enough" for $X_t$ to be distributed from $\pi$. Sometimes "large enough" may exceed by several orders of magnitude the computing budget for the experiment. The values $X_t$ are correlated, leading to an asymptotic variance that involves $$\text{var}_\pi(X)+2\sum_{t=1}^\infty\text{cov}_\pi(X_0,X_t)$$ which generally exceeds $\text{var}_\pi(X)$ and hence requires longer simulations than for an iid sample. This being said, MCMC is very useful for handling settings where regular iid sampling is impossible or too costly and where importance sampling is quite difficult to calibrate, in particular because of the dimension of the random variable to be simulated. However, sequential Monte Carlo methods like particle filters may be more appropriate in dynamical models, where the data comes by bursts that need immediate attention and may even vanish (i.e., cannot be stored) after a short while. In conclusion, MCMC is a very useful (and very much used) tool to handle complex settings where regular Monte Carlo solutions fail.
Is Markov chain based sampling the "best" for Monte Carlo sampling? Are there alternative schemes av There is no reason to state that MCMC sampling is the "best" Monte Carlo method! Usually, it is on the opposite worse than iid sampling, at least in terms of variance of the resulting Monte Carlo esti
27,730
Is Markov chain based sampling the "best" for Monte Carlo sampling? Are there alternative schemes available?
There are several ways to generate random values from a distribution, McMC is one of them, but several others would also be considered Monte Carlo methods (without the Markov chain part). The most direct for univariate sampling is to generate a uniform random variable, then plug this into the inverse CDF function. This works great if you have the inverse CDF, but is troublesome when the CDF and/or its inverse are hard to compute directly. For multivariate problems you can generate data from a copula, then use the inverse CDF method on the generated values to have some level of correlation between variables (though specifying the correct parameters to the copula to get the level of correlation desired often requires a bit of trial and error). Rejection sampling is another approach that can be used to generate data from a distribution (univariate or multivariate) where you don't need to know the CDF or its inverse (and you don't even need the normalizing constant for the density function), but this can be highly inefficient in some cases taking a lot of time. If you are interested in summaries of the generated data rather than the random points yourself, then importance sampling is another option. Gibbs sampling which is a form of McMC sampling lets you sample where you don't know the exact form of the multivariate distribution as long as you know the conditional distribution for each variable given the others. There are others as well, which is best depends on what you know and don't know and other details of the specific problem. McMC is popular because it works well for many situations and generalizes to many different cases.
Is Markov chain based sampling the "best" for Monte Carlo sampling? Are there alternative schemes av
There are several ways to generate random values from a distribution, McMC is one of them, but several others would also be considered Monte Carlo methods (without the Markov chain part). The most dir
Is Markov chain based sampling the "best" for Monte Carlo sampling? Are there alternative schemes available? There are several ways to generate random values from a distribution, McMC is one of them, but several others would also be considered Monte Carlo methods (without the Markov chain part). The most direct for univariate sampling is to generate a uniform random variable, then plug this into the inverse CDF function. This works great if you have the inverse CDF, but is troublesome when the CDF and/or its inverse are hard to compute directly. For multivariate problems you can generate data from a copula, then use the inverse CDF method on the generated values to have some level of correlation between variables (though specifying the correct parameters to the copula to get the level of correlation desired often requires a bit of trial and error). Rejection sampling is another approach that can be used to generate data from a distribution (univariate or multivariate) where you don't need to know the CDF or its inverse (and you don't even need the normalizing constant for the density function), but this can be highly inefficient in some cases taking a lot of time. If you are interested in summaries of the generated data rather than the random points yourself, then importance sampling is another option. Gibbs sampling which is a form of McMC sampling lets you sample where you don't know the exact form of the multivariate distribution as long as you know the conditional distribution for each variable given the others. There are others as well, which is best depends on what you know and don't know and other details of the specific problem. McMC is popular because it works well for many situations and generalizes to many different cases.
Is Markov chain based sampling the "best" for Monte Carlo sampling? Are there alternative schemes av There are several ways to generate random values from a distribution, McMC is one of them, but several others would also be considered Monte Carlo methods (without the Markov chain part). The most dir
27,731
Difference-in-difference-in-differences estimator
What you propose here is actually difference in difference in differences (DDD) instead of the usual difference in differences (see these lecture notes by Imbens and Wooldridge (2007) on the first two pages). This method can potentially account for the unobserved trends in wages of women across your two towns and the wage changes of both male and female workers in the treatment town. In this sense DDD is a more robust approach to the DD approach you had in mind previously. Let $\overline{y}$ be average income and index periods $1,2$, females and men $F,M$, and towns $X,Y$, then your DDD coefficient gives you $$ \begin{align} \widehat{\beta}_7 &= (\overline{y}_{X,F,2} - \overline{y}_{X,F,1}) \enspace\quad \text{the time change in $\overline{y}$ for women in town X} \newline &- (\overline{y}_{Y,F,2}-\overline{y}_{Y,F,1}) \qquad \text{the time change in $\overline{y}$ for women in town Y} \newline &-(\overline{y}_{X,M,2}-\overline{y}_{X,M,1}) \enspace\quad \text{the time change in $\overline{y}$ for men in town X} \end{align} $$ so your treatment effect will still be the effect of the policy on female wages relative to male wages in town $X$. The second term subtracts the potential wage trend of females that has nothing to do with the policy. This relates to what I mentioned in my response to your other question that you would need to know the common trends between male and female wages. This was to exclude the possibility that male and female wages are subject to systematically different changes that have nothing to do with the policy. Having untreated females in another town allows to you take out this potential female wage trend that might be different from the male wage trend. Read the Imbens and Wooldridge lecure very carefully because they do a great job on explaining this (especially see page 2 after equation 1.4). Even though this method is more robust, it does not mean that there is nothing left which can bias your estimates. If there is another policy at the same time, for instance a law for mothercare that affects female wages, this might still be picked up by your regression. In your work it will be your job to show that nothing else is going on in town $X$ besides your discrimination policy.
Difference-in-difference-in-differences estimator
What you propose here is actually difference in difference in differences (DDD) instead of the usual difference in differences (see these lecture notes by Imbens and Wooldridge (2007) on the first two
Difference-in-difference-in-differences estimator What you propose here is actually difference in difference in differences (DDD) instead of the usual difference in differences (see these lecture notes by Imbens and Wooldridge (2007) on the first two pages). This method can potentially account for the unobserved trends in wages of women across your two towns and the wage changes of both male and female workers in the treatment town. In this sense DDD is a more robust approach to the DD approach you had in mind previously. Let $\overline{y}$ be average income and index periods $1,2$, females and men $F,M$, and towns $X,Y$, then your DDD coefficient gives you $$ \begin{align} \widehat{\beta}_7 &= (\overline{y}_{X,F,2} - \overline{y}_{X,F,1}) \enspace\quad \text{the time change in $\overline{y}$ for women in town X} \newline &- (\overline{y}_{Y,F,2}-\overline{y}_{Y,F,1}) \qquad \text{the time change in $\overline{y}$ for women in town Y} \newline &-(\overline{y}_{X,M,2}-\overline{y}_{X,M,1}) \enspace\quad \text{the time change in $\overline{y}$ for men in town X} \end{align} $$ so your treatment effect will still be the effect of the policy on female wages relative to male wages in town $X$. The second term subtracts the potential wage trend of females that has nothing to do with the policy. This relates to what I mentioned in my response to your other question that you would need to know the common trends between male and female wages. This was to exclude the possibility that male and female wages are subject to systematically different changes that have nothing to do with the policy. Having untreated females in another town allows to you take out this potential female wage trend that might be different from the male wage trend. Read the Imbens and Wooldridge lecure very carefully because they do a great job on explaining this (especially see page 2 after equation 1.4). Even though this method is more robust, it does not mean that there is nothing left which can bias your estimates. If there is another policy at the same time, for instance a law for mothercare that affects female wages, this might still be picked up by your regression. In your work it will be your job to show that nothing else is going on in town $X$ besides your discrimination policy.
Difference-in-difference-in-differences estimator What you propose here is actually difference in difference in differences (DDD) instead of the usual difference in differences (see these lecture notes by Imbens and Wooldridge (2007) on the first two
27,732
R time-series forecasting with neural network, auto.arima and ets
In-sample fits are not a reliable guide to out-of-sample forecasting accuracy. The gold standard in forecasting accuracy measurement is to use a holdout sample. Remove the last 30 days from the training sample, fit your models to the rest of the data, use the fitted models to forecast the holdout sample and simply compare accuracies on the holdout, using Mean Absolute Deviations (MAD) or weighted Mean Absolute Percentage Errors (wMAPEs). Here is an example using R. I am using the 2000th series of the M3 competition, which already is divided into the training series M3[[2000]]$x and the test data M3[[2000]]$xx. This is monthly data. The last two lines output the wMAPE of the forecasts from the two models, and we see here that the ARIMA model (wMAPE 18.6%) outperforms the automatically fitted ETS model (32.4%): library(forecast) library(Mcomp) M3[[2000]] ets.model <- ets(M3[[2000]]$x) arima.model <- auto.arima(M3[[2000]]$x) ets.forecast <- forecast(ets.model,M3[[2000]]$h)$mean arima.forecast <- forecast(arima.model,M3[[2000]]$h)$mean sum(abs(ets.forecast-M3[[2000]]$xx))/sum(M3[[2000]]$xx) sum(abs(arima.forecast-M3[[2000]]$xx))/sum(M3[[2000]]$xx) In addition, it looks like there are abnormally high sales near indices 280-300. Could this be Christmas sales? If you know about calendar events like these, it would be best to feed those to your forecasting model as explanatory variables, which will give you a better forecast next time that Christmas rolls around. You can do that easily in ARIMA(X) and NNs, not so easily in ETS. Finally, I recommend this textbook on forecasting: http://otexts.com/fpp/
R time-series forecasting with neural network, auto.arima and ets
In-sample fits are not a reliable guide to out-of-sample forecasting accuracy. The gold standard in forecasting accuracy measurement is to use a holdout sample. Remove the last 30 days from the traini
R time-series forecasting with neural network, auto.arima and ets In-sample fits are not a reliable guide to out-of-sample forecasting accuracy. The gold standard in forecasting accuracy measurement is to use a holdout sample. Remove the last 30 days from the training sample, fit your models to the rest of the data, use the fitted models to forecast the holdout sample and simply compare accuracies on the holdout, using Mean Absolute Deviations (MAD) or weighted Mean Absolute Percentage Errors (wMAPEs). Here is an example using R. I am using the 2000th series of the M3 competition, which already is divided into the training series M3[[2000]]$x and the test data M3[[2000]]$xx. This is monthly data. The last two lines output the wMAPE of the forecasts from the two models, and we see here that the ARIMA model (wMAPE 18.6%) outperforms the automatically fitted ETS model (32.4%): library(forecast) library(Mcomp) M3[[2000]] ets.model <- ets(M3[[2000]]$x) arima.model <- auto.arima(M3[[2000]]$x) ets.forecast <- forecast(ets.model,M3[[2000]]$h)$mean arima.forecast <- forecast(arima.model,M3[[2000]]$h)$mean sum(abs(ets.forecast-M3[[2000]]$xx))/sum(M3[[2000]]$xx) sum(abs(arima.forecast-M3[[2000]]$xx))/sum(M3[[2000]]$xx) In addition, it looks like there are abnormally high sales near indices 280-300. Could this be Christmas sales? If you know about calendar events like these, it would be best to feed those to your forecasting model as explanatory variables, which will give you a better forecast next time that Christmas rolls around. You can do that easily in ARIMA(X) and NNs, not so easily in ETS. Finally, I recommend this textbook on forecasting: http://otexts.com/fpp/
R time-series forecasting with neural network, auto.arima and ets In-sample fits are not a reliable guide to out-of-sample forecasting accuracy. The gold standard in forecasting accuracy measurement is to use a holdout sample. Remove the last 30 days from the traini
27,733
R time-series forecasting with neural network, auto.arima and ets
Stephan's suggestion above is a good one. I would add that using AIC is definitely a valid way to choose within models--but not among them. I.e., you can (and should!) use information criteria to choose which ARIMA model(s), which exponential smoothing model(s), etc., and then compare your top candidates using out of sample prediction (MASE, MAPE, etc.). http://robjhyndman.com/hyndsight/aic/
R time-series forecasting with neural network, auto.arima and ets
Stephan's suggestion above is a good one. I would add that using AIC is definitely a valid way to choose within models--but not among them. I.e., you can (and should!) use information criteria to choo
R time-series forecasting with neural network, auto.arima and ets Stephan's suggestion above is a good one. I would add that using AIC is definitely a valid way to choose within models--but not among them. I.e., you can (and should!) use information criteria to choose which ARIMA model(s), which exponential smoothing model(s), etc., and then compare your top candidates using out of sample prediction (MASE, MAPE, etc.). http://robjhyndman.com/hyndsight/aic/
R time-series forecasting with neural network, auto.arima and ets Stephan's suggestion above is a good one. I would add that using AIC is definitely a valid way to choose within models--but not among them. I.e., you can (and should!) use information criteria to choo
27,734
R time-series forecasting with neural network, auto.arima and ets
Watch this video by Prof Rob https://www.youtube.com/watch?v=1Lh1HlBUf8k In the video, Prof Rob taught regarding the accuracy function and the differences between in sample accuracy and out of sample accuracy. i.e: Taking say 80-90% of your data, fit a model, forecast. Then check accuracy using the forecasted data with the 10% (since we have the actual value of your 10% data, we can check the out of sample accuracy of the model ) As well as refer to the online textbook in otext Like other mentioned, when we compare models vs models, we use the accuracy() to compare with the test set. Then you can have various error measure like MAE, MSE, RMSE... etc which are used to compare models vs models
R time-series forecasting with neural network, auto.arima and ets
Watch this video by Prof Rob https://www.youtube.com/watch?v=1Lh1HlBUf8k In the video, Prof Rob taught regarding the accuracy function and the differences between in sample accuracy and out of sample
R time-series forecasting with neural network, auto.arima and ets Watch this video by Prof Rob https://www.youtube.com/watch?v=1Lh1HlBUf8k In the video, Prof Rob taught regarding the accuracy function and the differences between in sample accuracy and out of sample accuracy. i.e: Taking say 80-90% of your data, fit a model, forecast. Then check accuracy using the forecasted data with the 10% (since we have the actual value of your 10% data, we can check the out of sample accuracy of the model ) As well as refer to the online textbook in otext Like other mentioned, when we compare models vs models, we use the accuracy() to compare with the test set. Then you can have various error measure like MAE, MSE, RMSE... etc which are used to compare models vs models
R time-series forecasting with neural network, auto.arima and ets Watch this video by Prof Rob https://www.youtube.com/watch?v=1Lh1HlBUf8k In the video, Prof Rob taught regarding the accuracy function and the differences between in sample accuracy and out of sample
27,735
R time-series forecasting with neural network, auto.arima and ets
Instead of giving name fit to NN model use fit_nn. Similarly, fit_arima and fit_ets. so that you can compare all models. library(caret) #ets fit_ets <- ets(x) #ANN fit_nn <- nnetar(x) plot(forecast(fit,h=60)) points(1:length(x),fitted(fit_nn),type="l",col="green") library(forecast) accuracy(fit_nn) accuracy(fit_ets) now, you can compare both models using ME, MAE or whatever you want.
R time-series forecasting with neural network, auto.arima and ets
Instead of giving name fit to NN model use fit_nn. Similarly, fit_arima and fit_ets. so that you can compare all models. library(caret) #ets fit_ets <- ets(x) #ANN fit_nn <- nnetar(x) plot(forecast(fi
R time-series forecasting with neural network, auto.arima and ets Instead of giving name fit to NN model use fit_nn. Similarly, fit_arima and fit_ets. so that you can compare all models. library(caret) #ets fit_ets <- ets(x) #ANN fit_nn <- nnetar(x) plot(forecast(fit,h=60)) points(1:length(x),fitted(fit_nn),type="l",col="green") library(forecast) accuracy(fit_nn) accuracy(fit_ets) now, you can compare both models using ME, MAE or whatever you want.
R time-series forecasting with neural network, auto.arima and ets Instead of giving name fit to NN model use fit_nn. Similarly, fit_arima and fit_ets. so that you can compare all models. library(caret) #ets fit_ets <- ets(x) #ANN fit_nn <- nnetar(x) plot(forecast(fi
27,736
Why is KNN not "model-based"?
It is quite hard to compare kNN and linear regression directly as they are very different things, however, I think the key point here is the difference between "modelling $f(x)$" and "having assumptions about $f(x)$". When doing linear regression, one specifically models the $f(x)$, often something among the lines of $f(x) = \mathbf{wx} + \epsilon$ where $\epsilon$ is a Gaussian noise term. You can work it out that the maximum likelihood model is equivalent to the minimal sum-of-squares error model. KNN, on the other hand, as your second point suggests, assumes that you could approximate that function by a locally constant function - some distance measure between the $x$-ses, without specifically modelling the whole distribution. In other words, linear regression will often have a good idea of value of $f(x)$ for some unseen $x$ from just the value of the $x$, whereas kNN would need some other information (i.e. the k neighbours), to make predictions about $f(x)$, because the value of $x$, and just the value itself, will not give any information, as there is no model for $f(x)$. EDIT: reiterating this below to re-express this clearer (see comments) It is clear that both linear regression and nearest neighbour methods aim at predicting value of $y=f(x)$ for a new $x$. Now there are two approaches. Linear regression goes on by assuming that the data falls on a straight line (plus minus some noise), and therefore the value of y is equal to the value of $f(x)$ times the slope of the line. In other words, the linear expression models the data as a straight line. Now nearest neighbour methods do not care about whether how the data looks like (doesn't model the data), that is, they do not care whether it is a line, a parabola, a circle, etc. All it assumes, is that $f(x_1)$ and $f(x_2)$ will be similar, if $x_1$ and $x_2$ are similar. Note that this assumption is roughly true for pretty much any model, including all the ones I mentioned above. However, a NN method could not tell how value of $f(x)$ is related to $x$ (whether it is a line, parabola, etc.), because it has no model of this relationship, it just assumes that it can be approximated by looking into near-points.
Why is KNN not "model-based"?
It is quite hard to compare kNN and linear regression directly as they are very different things, however, I think the key point here is the difference between "modelling $f(x)$" and "having assumptio
Why is KNN not "model-based"? It is quite hard to compare kNN and linear regression directly as they are very different things, however, I think the key point here is the difference between "modelling $f(x)$" and "having assumptions about $f(x)$". When doing linear regression, one specifically models the $f(x)$, often something among the lines of $f(x) = \mathbf{wx} + \epsilon$ where $\epsilon$ is a Gaussian noise term. You can work it out that the maximum likelihood model is equivalent to the minimal sum-of-squares error model. KNN, on the other hand, as your second point suggests, assumes that you could approximate that function by a locally constant function - some distance measure between the $x$-ses, without specifically modelling the whole distribution. In other words, linear regression will often have a good idea of value of $f(x)$ for some unseen $x$ from just the value of the $x$, whereas kNN would need some other information (i.e. the k neighbours), to make predictions about $f(x)$, because the value of $x$, and just the value itself, will not give any information, as there is no model for $f(x)$. EDIT: reiterating this below to re-express this clearer (see comments) It is clear that both linear regression and nearest neighbour methods aim at predicting value of $y=f(x)$ for a new $x$. Now there are two approaches. Linear regression goes on by assuming that the data falls on a straight line (plus minus some noise), and therefore the value of y is equal to the value of $f(x)$ times the slope of the line. In other words, the linear expression models the data as a straight line. Now nearest neighbour methods do not care about whether how the data looks like (doesn't model the data), that is, they do not care whether it is a line, a parabola, a circle, etc. All it assumes, is that $f(x_1)$ and $f(x_2)$ will be similar, if $x_1$ and $x_2$ are similar. Note that this assumption is roughly true for pretty much any model, including all the ones I mentioned above. However, a NN method could not tell how value of $f(x)$ is related to $x$ (whether it is a line, parabola, etc.), because it has no model of this relationship, it just assumes that it can be approximated by looking into near-points.
Why is KNN not "model-based"? It is quite hard to compare kNN and linear regression directly as they are very different things, however, I think the key point here is the difference between "modelling $f(x)$" and "having assumptio
27,737
Why is KNN not "model-based"?
Linear regression is model-based because it makes an assumption about the structure of the data in order to generate a model. When you load a data set into a statistical program and use it to run a linear regression the output is in fact a model: $\hat{f}(X)=\hat{\beta} X$ . You can feed new data into this model and get a predicted output because you have made assumptions about how the output variable is actually generated. With KNN there isn't really a model at all - there's just an assumption that the observations that are near each other in $X$-space will probably behave similarly in terms of the output variable. You don't feed a new observation into a 'KNN model', you just determine which existing observations are most similar to a new observation and predict the output variable for the new observation from the training data.
Why is KNN not "model-based"?
Linear regression is model-based because it makes an assumption about the structure of the data in order to generate a model. When you load a data set into a statistical program and use it to run a li
Why is KNN not "model-based"? Linear regression is model-based because it makes an assumption about the structure of the data in order to generate a model. When you load a data set into a statistical program and use it to run a linear regression the output is in fact a model: $\hat{f}(X)=\hat{\beta} X$ . You can feed new data into this model and get a predicted output because you have made assumptions about how the output variable is actually generated. With KNN there isn't really a model at all - there's just an assumption that the observations that are near each other in $X$-space will probably behave similarly in terms of the output variable. You don't feed a new observation into a 'KNN model', you just determine which existing observations are most similar to a new observation and predict the output variable for the new observation from the training data.
Why is KNN not "model-based"? Linear regression is model-based because it makes an assumption about the structure of the data in order to generate a model. When you load a data set into a statistical program and use it to run a li
27,738
Why is KNN not "model-based"?
The term model-based is synonymous with "distribution-based" when discussing clustering methods. Linear regression makes distributional assumptions (that the errors are Gaussian). KNN does not make any distributional assumptions. That is the distinction.
Why is KNN not "model-based"?
The term model-based is synonymous with "distribution-based" when discussing clustering methods. Linear regression makes distributional assumptions (that the errors are Gaussian). KNN does not make an
Why is KNN not "model-based"? The term model-based is synonymous with "distribution-based" when discussing clustering methods. Linear regression makes distributional assumptions (that the errors are Gaussian). KNN does not make any distributional assumptions. That is the distinction.
Why is KNN not "model-based"? The term model-based is synonymous with "distribution-based" when discussing clustering methods. Linear regression makes distributional assumptions (that the errors are Gaussian). KNN does not make an
27,739
Why is KNN not "model-based"?
kNN is instance-based In order to make a prediction for a new observation, you have to keep all the training dataset, because, there is no model about the dataset. This is how kNN works: given a new observation, we will calculate the distance between this new observation and all the other observations in the training dataset. Then you get the neighbours (the ones that are the closest to the new observation). If $k=5$, then we look at the 5 closest observations. "a locally constant function" means that after choosing these 5 observations, we don't care about the distances. They are the same, they have the same importance for the prediction. How can find a model ? Now, if we try to find a function that is not "locally constant", it would be a normal distribution. In this case, you will get an algorithm call Linear Discriminant Analysis or Naive Bayes (depending on some other assumptions).
Why is KNN not "model-based"?
kNN is instance-based In order to make a prediction for a new observation, you have to keep all the training dataset, because, there is no model about the dataset. This is how kNN works: given a new o
Why is KNN not "model-based"? kNN is instance-based In order to make a prediction for a new observation, you have to keep all the training dataset, because, there is no model about the dataset. This is how kNN works: given a new observation, we will calculate the distance between this new observation and all the other observations in the training dataset. Then you get the neighbours (the ones that are the closest to the new observation). If $k=5$, then we look at the 5 closest observations. "a locally constant function" means that after choosing these 5 observations, we don't care about the distances. They are the same, they have the same importance for the prediction. How can find a model ? Now, if we try to find a function that is not "locally constant", it would be a normal distribution. In this case, you will get an algorithm call Linear Discriminant Analysis or Naive Bayes (depending on some other assumptions).
Why is KNN not "model-based"? kNN is instance-based In order to make a prediction for a new observation, you have to keep all the training dataset, because, there is no model about the dataset. This is how kNN works: given a new o
27,740
Implications of current debate on statistical significance
Instead of using p-values to assess claims we should follow Robert Abelson's advice and use the MAGIC criteria: Magnitude Articulation Generality Interestingness Credibility For more on Abelson see my review of his book And we should be concentrating on effect sizes, not p-values in statistical output (with the possible exception of some sorts of data mining, on which I am not expert at all). And effect sizes are to be judged in context: 1 in 1000 pairs of pants gets the wrong size label - not a big deal 1 in 1000 airplanes are defective in a way that leads to crashes - a big deal 1 in 1000 nuclear reactors is defective in a way that leads to meltdown - uh oh A statistician/data analyst should not be some odd person, used like a black box into which data is put and out from which p values are gotten; he/she should be a collaborator in research designed to make a reasonable argument about the meaning of some set of data in the context of some field, given the current theories (or their lack) and current evidence (or lack of same). Unfortunately, this approach requires thought on the part of the substantive researchers, the data analyst and whoever reviews the results (be it a pointy haired boss, a dissertation committee, a journal editor or whoever). Oddly, even academics seem averse to this sort of thought. For more on my views, here is an article I wrote that got published in Sciences360.
Implications of current debate on statistical significance
Instead of using p-values to assess claims we should follow Robert Abelson's advice and use the MAGIC criteria: Magnitude Articulation Generality Interestingness Credibility For more on Abelson see m
Implications of current debate on statistical significance Instead of using p-values to assess claims we should follow Robert Abelson's advice and use the MAGIC criteria: Magnitude Articulation Generality Interestingness Credibility For more on Abelson see my review of his book And we should be concentrating on effect sizes, not p-values in statistical output (with the possible exception of some sorts of data mining, on which I am not expert at all). And effect sizes are to be judged in context: 1 in 1000 pairs of pants gets the wrong size label - not a big deal 1 in 1000 airplanes are defective in a way that leads to crashes - a big deal 1 in 1000 nuclear reactors is defective in a way that leads to meltdown - uh oh A statistician/data analyst should not be some odd person, used like a black box into which data is put and out from which p values are gotten; he/she should be a collaborator in research designed to make a reasonable argument about the meaning of some set of data in the context of some field, given the current theories (or their lack) and current evidence (or lack of same). Unfortunately, this approach requires thought on the part of the substantive researchers, the data analyst and whoever reviews the results (be it a pointy haired boss, a dissertation committee, a journal editor or whoever). Oddly, even academics seem averse to this sort of thought. For more on my views, here is an article I wrote that got published in Sciences360.
Implications of current debate on statistical significance Instead of using p-values to assess claims we should follow Robert Abelson's advice and use the MAGIC criteria: Magnitude Articulation Generality Interestingness Credibility For more on Abelson see m
27,741
Implications of current debate on statistical significance
The field of statistical science has addressed these issues since its outset. I keep saying the role of the statistician is to ensure that the type 1 error rate remains fixed. This implies that the risk of making false positive conclusions cannot be eliminated, but can be controlled. This should draw our attention to the extremely large volume of scientific research that's being conducted rather than toward the philosophy and ethics of general statistical practice. For every incredible (uncredible) result that surfaces in the media (or in government policy) at least 19 other uncredible results were shot down for their null findings. Indeed, if you go to, say, clinicaltrials.gov, you will observe there are (for almost any disease indication) well over 1,000 clinical trials for pharmaceutical agents going on in the US at this very moment. That means, that with a false positive error rate of 0.001, on average at least 1 drug will be put on the shelves that has no effect. The validity of 0.05 as a validated threshold for statistical significance has been challenged again and again. Ironically, it's only the statisticians who feel uncomfortable with using a 1/20 false positive error rate whereas financial stakeholders (be they PIs, or Merck) will pursue beliefs tenaciously regardless of in-vitro results, theoretical proofs, or strength of prior evidence. Honestly, that tenacity is a successful and laudable personal quality of many individuals who are successful in non-statistical roles. They are generally seated above statisticians, in their respective totems, who tend to leverage that tenacity. I think the Time quote you put forward is completely wrong. Power is the probability of rejecting the null hypothesis given it's false. This more importantly depends on exactly how "false" the null hypothesis is (which in turn depends on a measurable effect size). I rarely talk of power out of the context of the effect which we would deem "interesting" to detect. (for instance, a 4 month survival following chemotherapeutic treatment of stage 4 pancreatic cancer is not interesting, hence there's no reason to recruit 5,000 individuals for a phase 3 trial). To address the questions you asked ??? Multiplicity is difficult because it does not lead to an obvious decision rule about how to handle the data. For instance, suppose we are interested in a simple test of mean difference. Despite the infinite protestations of my colleagues, it is easy to show a t-test is well calibrated to detect differences in mean regardless of the sampling distribution of the data. Suppose we alternately pursued their path. They would begin by testing for normality using some variant of a well known distributional test (say calibration of the qqplot). If the data appeared sufficiently non-normal, they would then ask whether the data follow any well known transformation, and then apply a Box Cox transformation to determine a power transformation (possibly logarithmic) which maximizes entropy. If an obvious numerical value pops out, they will use that transformation. If not, they will use the "distribution free" Wilcoxon test. For this ad-hoc sequence of events, I cannot begin to hope how to calculate the calibration and power for a simple test of mean differences when the simple, stupid t-test would have sufficed. I suspect stupid acts like this can be linked mathematically to Hodge's superefficient estimation: estimators which are high power under a specific hypothesis we want to be true. Nonetheless, this process is not statistical because the false positive error rate has not been controlled. The concept that trends can be "discovered" erroneously in any random set of data probably traces back to the well written article by Martin called "Munchaesen's Statistical Grid". This is a very illuminating read and dates back to 1984 before the golden calf of machine learning was born unto us as we presently know it. Indeed, a correctly stated hypothesis is falsifiable, but type 1 errors have grown to be much more costly in our data driven society than they ever were before. Consider, for instance, the falsified evidence of the anti-vaccine research that has led to a massive sequence of pertussis deaths. The results which spurned the public defenestration of vaccines was linked a a single study (which, although wrong, was neither confirmed by external research). There is an ethical impetus to conduct results and report honest-to-goodness strength of evidence. How strong is evidence? It has little to do with the p-value you obtain, but the p-value you said you would call significant. And remember, fudging your data changes the value of p, even when the final confirmatory test reports something different (often much smaller). YES! You can clearly see in meta-analyses published by journals such as the Cochrane report that the distribution of test results looks more bimodal than noraml, with only positive and negative results making it into journals. This evidence is absolutely bonkers and confusing for anyone in clinical practice. If, instead, we publish null results (that come from studies whose results we would have been interested in, regardless of what they come to be), then we can expect meta-analyses to actually represent evidence that is meaningful and representative.
Implications of current debate on statistical significance
The field of statistical science has addressed these issues since its outset. I keep saying the role of the statistician is to ensure that the type 1 error rate remains fixed. This implies that the ri
Implications of current debate on statistical significance The field of statistical science has addressed these issues since its outset. I keep saying the role of the statistician is to ensure that the type 1 error rate remains fixed. This implies that the risk of making false positive conclusions cannot be eliminated, but can be controlled. This should draw our attention to the extremely large volume of scientific research that's being conducted rather than toward the philosophy and ethics of general statistical practice. For every incredible (uncredible) result that surfaces in the media (or in government policy) at least 19 other uncredible results were shot down for their null findings. Indeed, if you go to, say, clinicaltrials.gov, you will observe there are (for almost any disease indication) well over 1,000 clinical trials for pharmaceutical agents going on in the US at this very moment. That means, that with a false positive error rate of 0.001, on average at least 1 drug will be put on the shelves that has no effect. The validity of 0.05 as a validated threshold for statistical significance has been challenged again and again. Ironically, it's only the statisticians who feel uncomfortable with using a 1/20 false positive error rate whereas financial stakeholders (be they PIs, or Merck) will pursue beliefs tenaciously regardless of in-vitro results, theoretical proofs, or strength of prior evidence. Honestly, that tenacity is a successful and laudable personal quality of many individuals who are successful in non-statistical roles. They are generally seated above statisticians, in their respective totems, who tend to leverage that tenacity. I think the Time quote you put forward is completely wrong. Power is the probability of rejecting the null hypothesis given it's false. This more importantly depends on exactly how "false" the null hypothesis is (which in turn depends on a measurable effect size). I rarely talk of power out of the context of the effect which we would deem "interesting" to detect. (for instance, a 4 month survival following chemotherapeutic treatment of stage 4 pancreatic cancer is not interesting, hence there's no reason to recruit 5,000 individuals for a phase 3 trial). To address the questions you asked ??? Multiplicity is difficult because it does not lead to an obvious decision rule about how to handle the data. For instance, suppose we are interested in a simple test of mean difference. Despite the infinite protestations of my colleagues, it is easy to show a t-test is well calibrated to detect differences in mean regardless of the sampling distribution of the data. Suppose we alternately pursued their path. They would begin by testing for normality using some variant of a well known distributional test (say calibration of the qqplot). If the data appeared sufficiently non-normal, they would then ask whether the data follow any well known transformation, and then apply a Box Cox transformation to determine a power transformation (possibly logarithmic) which maximizes entropy. If an obvious numerical value pops out, they will use that transformation. If not, they will use the "distribution free" Wilcoxon test. For this ad-hoc sequence of events, I cannot begin to hope how to calculate the calibration and power for a simple test of mean differences when the simple, stupid t-test would have sufficed. I suspect stupid acts like this can be linked mathematically to Hodge's superefficient estimation: estimators which are high power under a specific hypothesis we want to be true. Nonetheless, this process is not statistical because the false positive error rate has not been controlled. The concept that trends can be "discovered" erroneously in any random set of data probably traces back to the well written article by Martin called "Munchaesen's Statistical Grid". This is a very illuminating read and dates back to 1984 before the golden calf of machine learning was born unto us as we presently know it. Indeed, a correctly stated hypothesis is falsifiable, but type 1 errors have grown to be much more costly in our data driven society than they ever were before. Consider, for instance, the falsified evidence of the anti-vaccine research that has led to a massive sequence of pertussis deaths. The results which spurned the public defenestration of vaccines was linked a a single study (which, although wrong, was neither confirmed by external research). There is an ethical impetus to conduct results and report honest-to-goodness strength of evidence. How strong is evidence? It has little to do with the p-value you obtain, but the p-value you said you would call significant. And remember, fudging your data changes the value of p, even when the final confirmatory test reports something different (often much smaller). YES! You can clearly see in meta-analyses published by journals such as the Cochrane report that the distribution of test results looks more bimodal than noraml, with only positive and negative results making it into journals. This evidence is absolutely bonkers and confusing for anyone in clinical practice. If, instead, we publish null results (that come from studies whose results we would have been interested in, regardless of what they come to be), then we can expect meta-analyses to actually represent evidence that is meaningful and representative.
Implications of current debate on statistical significance The field of statistical science has addressed these issues since its outset. I keep saying the role of the statistician is to ensure that the type 1 error rate remains fixed. This implies that the ri
27,742
Implications of current debate on statistical significance
First, I am not a statistician, just a researcher who has looked into it alot the last few years to figure out why the methods I observe being used around me are so lacking and why there is so much confusion about basic concepts like the "what is a p-value?" I will give my perspective. First, one clarification question: The Time magazine wrote, "A power of 0.8 means that of ten true hypotheses tested, only two will be ruled out > because their effects are not picked up in the data;" I am not sure how this fits into the definition of the power function I found in textbook, which is the probability of rejecting the null as a function of parameter θ. With different θ we have different power, so I don't quite understand the above quote. Power is a function of θ, variance, and sample size. I am not sure what the confusion is. Also for many cases in which significance testing is used null hypothesis of mean1=mean2 is always false. In these cases significance is only a function of sample size. Please read Paul Meehl's "Theory-Testing in Psychology and Physics: A Methodological Paradox" it clarified many things for me and I have never seen an adequate response. Paul Meehl has a few other papers on this you can find by searching his name. In my field of political science / economics, scholars simply use up all the country-year data available. Thus, should we not be concerned with sample fiddling here? If you read the Simmons 2011 paper this is only one of the "p-hacking" techniques mentioned. If it is true that there is only one data set and no one picks out selective samples from it then I guess there is no room for increasing sample size. Can the problem of running multiple tests but reporting only one model be fixed simply by the fact that someone else in the discipline will re-test your paper and strike you down immediately for not having robust results? Anticipating this, scholars in my field are more likely to include a robustness check section, where they show that multiple model specifications does not change the result. Is this sufficient? If replication was occurring without publication bias there would be no need for "journals of the null result". I would say the robustness check section is good to have but is not sufficient in the presence of researchers failing to publish what they consider null results. Also I would not consider a result robust just because multiple analysis techniques on the same data come to the same conclusion. A robust result is one that makes a correct prediction of effect/correlation/etc on new data. A replication is not getting p<0.05 both times. The theory should be considered more robust if it predicted a different effect/correlation/etc than used in the first study. I do not refer to the presence of an effect or correlation, but the precise value or a small range of values compared to possible range of values. The presence of increased/decreased effect or positive/negative correlation are 100% likely to be true in the case of the null hypothesis being false. Read Meehl. Andrew Gelman and others raise the point that no matter the data, it would be always possible to find and publish some "pattern" that isn't really there. But this should not be a concern, given the fact that any empirical "pattern" must be supported by a theory, and rival theories within a discipline will just engage in an debate / race to find which camp is able to find more "patterns" in various places. If a pattern is truly spurious, then the theory behind will be quickly struck down when there is no similar pattern in other samples / settings. Isn't this how science progresses? Science cannot function properly if researchers are failing to publish null results. Also just because the pattern was not discovered in the second sample/setting does not mean it does not exist under the conditions of the initial study. Assuming that the current trend of journals for null result will actually flourish, is there a way for us to aggregate all the null and positive results together and make an inference on the theory that they all try to test? This would be meta-analysis. There is nothing special about null results in this case other than that researchers do not publish them because the p-values were above the arbitrary threshold. In the presence of publication bias meta-analysis is unreliable as is the entire literature suffering from publication bias. While it can be useful, meta analysis is far inferior for assessing a theory than having that theory make a precise prediction that is then tested. Publication bias does not matter nearly as much as long as new predictions pan out and are replicated by independent groups.
Implications of current debate on statistical significance
First, I am not a statistician, just a researcher who has looked into it alot the last few years to figure out why the methods I observe being used around me are so lacking and why there is so much co
Implications of current debate on statistical significance First, I am not a statistician, just a researcher who has looked into it alot the last few years to figure out why the methods I observe being used around me are so lacking and why there is so much confusion about basic concepts like the "what is a p-value?" I will give my perspective. First, one clarification question: The Time magazine wrote, "A power of 0.8 means that of ten true hypotheses tested, only two will be ruled out > because their effects are not picked up in the data;" I am not sure how this fits into the definition of the power function I found in textbook, which is the probability of rejecting the null as a function of parameter θ. With different θ we have different power, so I don't quite understand the above quote. Power is a function of θ, variance, and sample size. I am not sure what the confusion is. Also for many cases in which significance testing is used null hypothesis of mean1=mean2 is always false. In these cases significance is only a function of sample size. Please read Paul Meehl's "Theory-Testing in Psychology and Physics: A Methodological Paradox" it clarified many things for me and I have never seen an adequate response. Paul Meehl has a few other papers on this you can find by searching his name. In my field of political science / economics, scholars simply use up all the country-year data available. Thus, should we not be concerned with sample fiddling here? If you read the Simmons 2011 paper this is only one of the "p-hacking" techniques mentioned. If it is true that there is only one data set and no one picks out selective samples from it then I guess there is no room for increasing sample size. Can the problem of running multiple tests but reporting only one model be fixed simply by the fact that someone else in the discipline will re-test your paper and strike you down immediately for not having robust results? Anticipating this, scholars in my field are more likely to include a robustness check section, where they show that multiple model specifications does not change the result. Is this sufficient? If replication was occurring without publication bias there would be no need for "journals of the null result". I would say the robustness check section is good to have but is not sufficient in the presence of researchers failing to publish what they consider null results. Also I would not consider a result robust just because multiple analysis techniques on the same data come to the same conclusion. A robust result is one that makes a correct prediction of effect/correlation/etc on new data. A replication is not getting p<0.05 both times. The theory should be considered more robust if it predicted a different effect/correlation/etc than used in the first study. I do not refer to the presence of an effect or correlation, but the precise value or a small range of values compared to possible range of values. The presence of increased/decreased effect or positive/negative correlation are 100% likely to be true in the case of the null hypothesis being false. Read Meehl. Andrew Gelman and others raise the point that no matter the data, it would be always possible to find and publish some "pattern" that isn't really there. But this should not be a concern, given the fact that any empirical "pattern" must be supported by a theory, and rival theories within a discipline will just engage in an debate / race to find which camp is able to find more "patterns" in various places. If a pattern is truly spurious, then the theory behind will be quickly struck down when there is no similar pattern in other samples / settings. Isn't this how science progresses? Science cannot function properly if researchers are failing to publish null results. Also just because the pattern was not discovered in the second sample/setting does not mean it does not exist under the conditions of the initial study. Assuming that the current trend of journals for null result will actually flourish, is there a way for us to aggregate all the null and positive results together and make an inference on the theory that they all try to test? This would be meta-analysis. There is nothing special about null results in this case other than that researchers do not publish them because the p-values were above the arbitrary threshold. In the presence of publication bias meta-analysis is unreliable as is the entire literature suffering from publication bias. While it can be useful, meta analysis is far inferior for assessing a theory than having that theory make a precise prediction that is then tested. Publication bias does not matter nearly as much as long as new predictions pan out and are replicated by independent groups.
Implications of current debate on statistical significance First, I am not a statistician, just a researcher who has looked into it alot the last few years to figure out why the methods I observe being used around me are so lacking and why there is so much co
27,743
Implications of current debate on statistical significance
I would put it simply as null hypothesis testing is really only about the null hypothesis. And generally, the null hypothesis isn't usually what is of interest, and may not even be "the status quo" - especially in regression type of hypothesis testing. Often in social science there is no status quo, so the null hypothesis can be quite arbitrary. This makes a huge difference to the analysis, as the starting point is undefined, so different researches are starting with different null hypothesis, most likely based on whatever data they have available. Compare this to something like Newton's laws of motion - it makes sense to have this as the null hypothesis, and try to find better theories from this starting point. Additionally, p-values don't calculate the correct probability - we don't want to know about tail probabilities, unless the alternative hypothesis is more likely as you move further into the tails. What you really want is how well the theory predicts what was actually seen. For example, suppose I predict that there is a 50% chance of a "light shower", and my competitor predicts that there is a 75% chance. This turns out to be correct, and we observe a light shower. Now when decide which weather-person is correct, you shouldn't give my prediction additional credit for also giving a 40% chance of a "thunderstorm", or take credit away from my competitor for giving "thunderstorm" a 0% chance. A bit of thinking about this will show you that it is not so much how well a given theory fits the data, but more about how poorly any alternative explanation fits the data. If you work in terms of Bayes Factors, you have prior information $I$, data $D$, and some hypothesis $H$, the bayes factor is given by: $$BF=\frac{P(D|HI)}{P(D|\overline{H}I)}$$ If the data is impossible given that $H$ is false, then $BF=\infty$ and we become certain of $H$. The p-value typically gives you the numerator (or some approximation/transformation thereof). But note also that a small p-value only constitutes evidence against the null if there is an alternative hypothesis that fitsthe data. You could invent situations where a p-value of $0.001$ actually provides support for the null hypothesis - it really depends on what the alternative is. There is a well known and easily misunderstood empirical example of this where a coin is tossed $104,490,000$ times and the number of heads is $52,263,471$ - slightly off one half. The null model is $y\sim Bin(n,0.5)$ and the alternative is $y|\theta\sim Bin(n,\theta)$ and $\theta\sim U(0,1)$ for a marginal model of $y\sim BetaBin(n,1,1)\sim DU(0,\dots,n)$ (DU= discrete uniform). The p-value for the null hypothesis is very small $p=0.00015$, so reject the null and publish right? But look at the bayes factor, given by: $$BF=\frac{{n\choose y}2^{-n}}{\frac{1}{n+1}}=\frac{(n+1)!}{2^ny!(n-y)!}=11.90$$ How can this be? The Bayes Factor supports the null hypothesis in spite of the small p-value? Well, look at the alternative - it gave a probability for the observed value of $\frac{1}{n+1}=0.0000000096$ - the alternative does not provide a good explanation for the facts - so the null is more likely, but only relative to the alternative. Note that the null only does marginally better than this - $0.00000011$. But this is still better than the alternative. This is especially true for the example that Gelman criticises - there was only ever really one hypothesis tested, and not much thought gone into a) what the alternatives explanations are (particularly on confounding and effects not controlled for), b) how much are the alternatives supported by previous research, and most importantly, c) what predictions do they make (if any) which are substantively different from the null? But note that $\overline{H}$ is undefined, and basically represents all other hypothesis consistent with the prior information. The only way you can really do hypothesis testing properly is by specifying a range of alternatives that you are going to compare. And even if you do that, say you have $H_1,\dots,H_K$, you can only report on the fact that the data supports $H_k$ relative to what you have specified. If you leave out important hypothesis from the set of alternatives, you can expect to get nonsensical results. Additionally, a given alternative may prove to be a much better fit that the others, but still not likely. If you have one test where a p-value is $0.01$ but the one hundred different tests where the p-value is $0.1$ it is much more likely that the "best hypothesis" (best has better connotations than true) actually comes from the group of "almost significant" results. The major point to stress is that a hypothesis can never ever exist in isolation to the alterantives. For, after specifying $K$ theories/models, you can always add a new hypothesis $$H_{K+1}=\text{Something else not yet thought of}$$ In effect this type of hypothesis is basically what progresses science - someone has a new idea/explanation for some kind of effect, and then tests this new theory against the current set of alternatives. Its $H_{K+1}$ vs $H_1,\dots,H_K$ and not simply $H_0$ vs $H_A$. The simplified version only applies when there is a very strongly supported hypothesis in $H_1,\dots,H_K$ - i.e, of all the ideas and explanations we currently have, there is one dominant theory that stands out. This is definitely not true for most areas of social/political science, economics, and psychology.
Implications of current debate on statistical significance
I would put it simply as null hypothesis testing is really only about the null hypothesis. And generally, the null hypothesis isn't usually what is of interest, and may not even be "the status quo" -
Implications of current debate on statistical significance I would put it simply as null hypothesis testing is really only about the null hypothesis. And generally, the null hypothesis isn't usually what is of interest, and may not even be "the status quo" - especially in regression type of hypothesis testing. Often in social science there is no status quo, so the null hypothesis can be quite arbitrary. This makes a huge difference to the analysis, as the starting point is undefined, so different researches are starting with different null hypothesis, most likely based on whatever data they have available. Compare this to something like Newton's laws of motion - it makes sense to have this as the null hypothesis, and try to find better theories from this starting point. Additionally, p-values don't calculate the correct probability - we don't want to know about tail probabilities, unless the alternative hypothesis is more likely as you move further into the tails. What you really want is how well the theory predicts what was actually seen. For example, suppose I predict that there is a 50% chance of a "light shower", and my competitor predicts that there is a 75% chance. This turns out to be correct, and we observe a light shower. Now when decide which weather-person is correct, you shouldn't give my prediction additional credit for also giving a 40% chance of a "thunderstorm", or take credit away from my competitor for giving "thunderstorm" a 0% chance. A bit of thinking about this will show you that it is not so much how well a given theory fits the data, but more about how poorly any alternative explanation fits the data. If you work in terms of Bayes Factors, you have prior information $I$, data $D$, and some hypothesis $H$, the bayes factor is given by: $$BF=\frac{P(D|HI)}{P(D|\overline{H}I)}$$ If the data is impossible given that $H$ is false, then $BF=\infty$ and we become certain of $H$. The p-value typically gives you the numerator (or some approximation/transformation thereof). But note also that a small p-value only constitutes evidence against the null if there is an alternative hypothesis that fitsthe data. You could invent situations where a p-value of $0.001$ actually provides support for the null hypothesis - it really depends on what the alternative is. There is a well known and easily misunderstood empirical example of this where a coin is tossed $104,490,000$ times and the number of heads is $52,263,471$ - slightly off one half. The null model is $y\sim Bin(n,0.5)$ and the alternative is $y|\theta\sim Bin(n,\theta)$ and $\theta\sim U(0,1)$ for a marginal model of $y\sim BetaBin(n,1,1)\sim DU(0,\dots,n)$ (DU= discrete uniform). The p-value for the null hypothesis is very small $p=0.00015$, so reject the null and publish right? But look at the bayes factor, given by: $$BF=\frac{{n\choose y}2^{-n}}{\frac{1}{n+1}}=\frac{(n+1)!}{2^ny!(n-y)!}=11.90$$ How can this be? The Bayes Factor supports the null hypothesis in spite of the small p-value? Well, look at the alternative - it gave a probability for the observed value of $\frac{1}{n+1}=0.0000000096$ - the alternative does not provide a good explanation for the facts - so the null is more likely, but only relative to the alternative. Note that the null only does marginally better than this - $0.00000011$. But this is still better than the alternative. This is especially true for the example that Gelman criticises - there was only ever really one hypothesis tested, and not much thought gone into a) what the alternatives explanations are (particularly on confounding and effects not controlled for), b) how much are the alternatives supported by previous research, and most importantly, c) what predictions do they make (if any) which are substantively different from the null? But note that $\overline{H}$ is undefined, and basically represents all other hypothesis consistent with the prior information. The only way you can really do hypothesis testing properly is by specifying a range of alternatives that you are going to compare. And even if you do that, say you have $H_1,\dots,H_K$, you can only report on the fact that the data supports $H_k$ relative to what you have specified. If you leave out important hypothesis from the set of alternatives, you can expect to get nonsensical results. Additionally, a given alternative may prove to be a much better fit that the others, but still not likely. If you have one test where a p-value is $0.01$ but the one hundred different tests where the p-value is $0.1$ it is much more likely that the "best hypothesis" (best has better connotations than true) actually comes from the group of "almost significant" results. The major point to stress is that a hypothesis can never ever exist in isolation to the alterantives. For, after specifying $K$ theories/models, you can always add a new hypothesis $$H_{K+1}=\text{Something else not yet thought of}$$ In effect this type of hypothesis is basically what progresses science - someone has a new idea/explanation for some kind of effect, and then tests this new theory against the current set of alternatives. Its $H_{K+1}$ vs $H_1,\dots,H_K$ and not simply $H_0$ vs $H_A$. The simplified version only applies when there is a very strongly supported hypothesis in $H_1,\dots,H_K$ - i.e, of all the ideas and explanations we currently have, there is one dominant theory that stands out. This is definitely not true for most areas of social/political science, economics, and psychology.
Implications of current debate on statistical significance I would put it simply as null hypothesis testing is really only about the null hypothesis. And generally, the null hypothesis isn't usually what is of interest, and may not even be "the status quo" -
27,744
Calculating Prediction Interval
Your predict.lm code is calculating confidence intervals for the fitted values. Your hand calculation is calculating prediction intervals for new data. If you want to get the same result from predict.lm that you got from the hand calculation then change interval="confidence" to interval="prediction"
Calculating Prediction Interval
Your predict.lm code is calculating confidence intervals for the fitted values. Your hand calculation is calculating prediction intervals for new data. If you want to get the same result from predict.
Calculating Prediction Interval Your predict.lm code is calculating confidence intervals for the fitted values. Your hand calculation is calculating prediction intervals for new data. If you want to get the same result from predict.lm that you got from the hand calculation then change interval="confidence" to interval="prediction"
Calculating Prediction Interval Your predict.lm code is calculating confidence intervals for the fitted values. Your hand calculation is calculating prediction intervals for new data. If you want to get the same result from predict.
27,745
Calculating Prediction Interval
Good answer from dpel. I would add that the difference between confidence interval and prediction interval can be stated like below: Confidence interval $$ s_{new}=\sqrt{s^2\left(\frac{1}{N}+\frac{(x_{new}-\bar x)^2}{\sum(x_i-\bar x)^2}\right)} $$ Prediction interval $$ s_{new}=\sqrt{s^2\left(1+\frac{1}{N}+\frac{(x_{new}-\bar x)^2}{\sum(x_i-\bar x)^2}\right)} $$ Source See slide page 5/17 and 11/17
Calculating Prediction Interval
Good answer from dpel. I would add that the difference between confidence interval and prediction interval can be stated like below: Confidence interval $$ s_{new}=\sqrt{s^2\left(\frac{1}{N}+\frac{(x
Calculating Prediction Interval Good answer from dpel. I would add that the difference between confidence interval and prediction interval can be stated like below: Confidence interval $$ s_{new}=\sqrt{s^2\left(\frac{1}{N}+\frac{(x_{new}-\bar x)^2}{\sum(x_i-\bar x)^2}\right)} $$ Prediction interval $$ s_{new}=\sqrt{s^2\left(1+\frac{1}{N}+\frac{(x_{new}-\bar x)^2}{\sum(x_i-\bar x)^2}\right)} $$ Source See slide page 5/17 and 11/17
Calculating Prediction Interval Good answer from dpel. I would add that the difference between confidence interval and prediction interval can be stated like below: Confidence interval $$ s_{new}=\sqrt{s^2\left(\frac{1}{N}+\frac{(x
27,746
A serious in-depth problem of probabilities for flipping coins
If I have understood correctly, then the problem is to find a probability distribution for the time at which the first run of $n$ or more heads ends. Edit The probabilities can be determined accurately and quickly using matrix multiplication, and it is also possible to analytically compute the mean as $\mu_-=2^{n+1}-1$ and the variance as $\sigma^2=2^{n+2}\left(\mu-n-3\right) -\mu^2 + 5\mu$ where $\mu=\mu_-+1$, but there is probably not a simple closed form for the distribution itself. Above a certain number of coin flips the distribution is essentially a geometric distribution: it would make sense to use this form for larger $t$. The evolution in time of the probability distribution in state space can be modelled using a transition matrix for $k=n+2$ states, where $n=$ the number of consecutive coin flips. The states are as follows: State $H_0$, no heads State $H_i$, $i$ heads, $1\le i\le(n-1)$ State $H_n$, $n$ or more heads State $H_*$, $n$ or more heads followed by a tail Once you get into state $H_*$ you can't get back to any of the other states. The state transition probabilities to get into the states are as follows State $H_0$: probability $\frac12$ from $H_i$, $i=0,\ldots,n-1$, i.e. including itself but not state $H_n$ State $H_i$: probability $\frac12$ from $H_{i-1}$ State $H_n$: probability $\frac12$ from $H_{n-1},H_n$, i.e. from the state with $n-1$ heads and itself State $H_*$: probability $\frac12$ from $H_n$ and probability 1 from $H_*$ (itself) So for example, for $n=4$, this gives the transition matrix $$ X = \left\{ \begin{array}{c|cccccc} & H_0 & H_1 & H_2 & H_3 & H_4 & H_* \\ \hline H_0 & \frac12 & \frac12& \frac12& \frac12 &0 & 0 \\ H_1 & \frac12 &0 & 0 &0 & 0 & 0 \\ H_2 & 0 & \frac12 &0 &0 & 0 & 0 \\ H_3 & 0 & 0 &\frac12 &0 & 0 & 0 \\ H_4 & 0 & 0 &0 &\frac12 & \frac12 & 0 \\ H_* & 0 & 0 & 0&0 &\frac12 & 1 \end{array}\right\} $$ For the case $n=4$, the initial vector of probabilities $\mathbf{p}$ is $\mathbf{p}=(1,0,0,0,0,0)$. In general the initial vector has $$\mathbf{p}_i=\begin{cases}1&i=0\\0&i>0\end{cases}$$ The vector $\mathbf{p}$ is the probability distribution in space for any given time. The required cdf is a cdf in time, and is the probability of having seen at least $n$ coin flips end by time $t$. It can be written as $(X^{t+1}\mathbf{p})_k$, noting that we reach state $H_*$ 1 timestep after the last in the run of consecutive coin flips. The required pmf in time can be written as $(X^{t+1}\mathbf{p})_k - (X^{t}\mathbf{p})_k$. However numerically this involves taking away a very small number from a much larger number ($\approx 1$) and restricts precision. Therefore in calculations it is better to set $X_{k,k}=0$ rather than 1. Then writing $X'$ for the resulting matrix $X'=X|X_{k,k}=0$, the pmf is $(X'^{t+1}\mathbf{p})_k$. This is what is implemented in the simple R program below, which works for any $n\ge 2$, n=4 k=n+2 X=matrix(c(rep(1,n),0,0, # first row rep(c(1,rep(0,k)),n-2), # to half-way thru penultimate row 1,rep(0,k),1,1,rep(0,k-1),1,0), # replace 0 by 2 for cdf byrow=T,nrow=k)/2 X t=10000 pt=rep(0,t) # probability at time t pv=c(1,rep(0,k-1)) # probability vector for(i in 1:(t+1)) { #pvk=pv[k]; # if calculating via cdf pv = X %*% pv; #pt[i-1]=pv[k]-pvk # if calculating via cdf pt[i-1]=pv[k] # if calculating pmf } m=sum((1:t)*pt) v=sum((1:t)^2*pt)-m^2 c(m, v) par(mfrow=c(3,1)) plot(pt[1:100],type="l") plot(pt[10:110],type="l") plot(pt[1010:1110],type="l") The upper plot shows the pmf between 0 and 100. The lower two plots show the pmf between 10 and 110 and also between 1010 and 1110, illustrating the self-similarity and the fact that as @Glen_b says, the distribution looks like it can be approximated by a geometric distribution after a settling down period. It's possible to investigate this behaviour further using an eigenvector decomposition of $X$. Doing so shows that the for sufficiently large $t$, $p_{t+1}\approx c(n)p_t$, where $c(n)$ is the solution of the equation $2^{n+1}c^n(c-1)+1=0$. This approximation gets better with increasing $n$ and is excellent for $t$ in the range from about 30 to 50, depending on the value of $n$, as shown in the plot of log error below for computing $p_{100}$ (rainbow colours, red on the left for $n=2$). (In fact for numerical reasons, it would actually be better to use the geometric approximation for probabilities when $t$ is larger.) I suspect(ed) there might be a closed form available for the distribution because the means and variances as I have calculated them as follows $$ \begin{array}{r|rr} n & \text{Mean} & \text{Variance} \\ \hline 2 &7& 24& \\ 3 &15& 144& \\ 4 &31& 736& \\ 5 &63& 3392& \\ 6 &127& 14720& \\ 7 &255& 61696& \\ 8 &511& 253440& \\ 9 &1023& 1029120& \\ 10&2047& 4151296& \\ \end{array} $$ (I had to bump up the number up the time horizon to t=100000 to get this but the program still ran for all $n=2,\ldots,10$ in less than about 10 seconds.) The means in particular follow a very obvious pattern; the variances less so. I have solved a simpler, 3-state transition system in the past, but so far I'm having no luck with a simple analytic solution to this one. Perhaps there's some useful theory that I'm not aware of, e.g. relating to transition matrices. Edit: after a lot of false starts I came up with a recurrence formula. Let $p_{i,t}$ be the probability of being in state $H_i$ at time $t$. Let $q_{*,t}$ be the cumulative probability of being in state $H_*$, i.e. the final state, at time $t$. NB For any given $t$, $p_{i,t}, 0\le i\le n$ and $q_{*,t}$ are a probability distribution over space $i$ , and immediately below I use the fact that their probabilities add to 1. $p_{*,t}$ form a probability distribution over time $t$. Later, I use this fact in deriving the means and variances. The probability of being at the first state at time $t+1$, i.e. no heads, is given by the transition probabilities from states that can return to it from time $t$ (using the theorem of total probability). \begin{align} p_{0,t+1} &= \frac12p_{0,t} + \frac12p_{1,t} + \ldots \frac12p_{n-1,t}\\ &= \frac12\sum_{i=0}^{n-1}p_{i,t}\\ &= \frac12\left( 1-p_{n,t}-q_{*,t} \right) \end{align} But to get from state $H_0$ to $H_{n-1}$ takes $n-1$ steps, hence $p_{n-1,t+n-1} = \frac1{2^{n-1}}p_{0,t}$ and $$ p_{n-1,t+n} = \frac1{2^n}\left( 1-p_{n,t}-q_{*,t} \right)$$ Once again by the theorem of total probability the probability of being at state $H_n$ at time $t+1$ is \begin{align} p_{n,t+1} &= \frac12p_{n,t} + \frac12p_{n-1,t}\\ &= \frac12p_{n,t} + \frac1{2^{n+1}}\left( 1-p_{n,t-n}-q_{*,t-n} \right)\;\;\;(\dagger)\\ \end{align} and using the fact that $q_{*,t+1}-q_{*,t}=\frac12p_{n,t} \implies p_{n,t} = 2q_{*,t+1}-2q_{*,t}$, \begin{align} 2q_{*,t+2} - 2q_{*,t+1} &= q_{*,t+1}-q_{*,t}+\frac1{2^{n+1}}\left( 1-2q_{*,t-n+1}+q_{*,t-n} \right) \end{align} Hence, changing $t\to t+n$, $$2q_{*,t+n+2} - 3q_{*,t+n+1} +q_{*,t+n} + \frac1{2^n}q_{*,t+1} - \frac1{2^{n+1}}q_{*,t} - \frac1{2^{n+1}} = 0$$ This recurrence formula checks out for the cases $n=4$ and $n=6$. E.g. for $n=6$ a plot of this formula using t=1:994;v=2*q[t+8]-3*q[t+7]+q[t+6]+q[t+1]/2**6-q[t]/2**7-1/2**7 gives machine order accuracy. Edit I can't see where to go to find a closed form from this recurrence relation. However, it is possible to get a closed form for the mean. Starting from $(\dagger)$, and noting that $p_{*,t+1}=\frac12p_{n,t}$, \begin{align} p_{n,t+1} &= \frac12p_{n,t} + \frac1{2^{n+1}}\left( 1-p_{n,t-n}-q_{*,t-n} \right)\;\;\;(\dagger)\\ 2^{n+1}\left(2p_{*,t+n+2}-p_{*,t+n+1}\right)+2p_{*,t+1} &= 1-q_{*,t} \end{align} Taking sums from $t=0$ to $\infty$ and applying the formula for the mean $E[X] = \sum_{x=0}^\infty (1-F(x))$ and noting that $p_{*,t}$ is a probability distribution gives \begin{align} 2^{n+1}\sum_{t=0}^\infty \left(2p_{*,t+n+2}-p_{*,t+n+1}\right) + 2\sum_{t=0}^\infty p_{*,t+1} &= \sum_{t=0}^\infty(1-q_{*,t}) \\ 2^{n+1} \left(2\left(1-\frac1{2^{n+1}}\right)-\;1\;\right) + 2 &= \mu \\ 2^{n+1} &= \mu \end{align} This is the mean for reaching state $H_*$; the mean for the end of the run of heads is one less than this. Edit A similar approach using the formula $E[X^2] = \sum_{x=0}^\infty (2x+1)(1-F(x))\;$ from this question yields the variance. \begin{align} \sum_{t=0}^\infty(2t+1)\left (2^{n+1}\left(2p_{*,t+n+2}-p_{*,t+n+1}\right) + 2 p_{*,t+1}\right) &= \sum_{t=0}^\infty(2t+1)(1-q_{*,t}) \\ 2\sum_{t=0}^\infty t\left (2^{n+1}\left(2p_{*,t+n+2}-p_{*,t+n+1}\right) + 2 p_{*,t+1}\right) + \mu &= \sigma^2 + \mu^2 \\ 2^{n+2}\left(2\left(\mu-(n+2)+\frac1{2^{n+1}}\right)-(\mu-(n+1))\right) + 4(\mu-1) &\\+ \mu &= \sigma^2 + \mu^2 \\ 2^{n+2}\left(2(\mu-(n+2))-(\mu-(n+1))\right) + 5\mu &= \sigma^2 + \mu^2 \\ 2^{n+2}\left(\mu-n-3\right) + 5\mu &= \sigma^2 + \mu^2 \\ 2^{n+2}\left(\mu-n-3\right) -\mu^2 + 5\mu &= \sigma^2 \end{align} The means and variances can easily be generated programmatically. E.g. to check the means and variances from the table above use n=2:10 m=c(0,2**(n+1)) v=2**(n+2)*(m[n]-n-3) + 5*m[n] - m[n]^2 Finally, I'm not sure what you wanted when you wrote when a tails hits and breaks the streak of heads the count would start again from the next flip. If you meant what is the probability distribution for the next time at which the first run of $n$ or more heads ends, then the crucial point is contained in this comment by @Glen_b, which is that the process begins again after one tail (c.f. the initial problem where you could get a run of $n$ or more heads immediately). This means that, for example, the mean time to the first event is $\mu-1$, but the mean time between events is always $\mu+1$ (the variance is the same). It's also possible to use a transition matrix to investigate the long-term probabilities of being in a state after the system has "settled down". To get the appropriate transition matrix, set $X_{k,k,}=0$ and $X_{1,k}=1$ so that the system return immediately to state $H_0$ from state $H_*$. Then the scaled first eigenvector of this new matrix gives the stationary probabilities. With $n=4$ these stationary probabilities are $$ \begin{array}{c|cccccc} & \text{probability} \\ \hline H_0 & 0.48484848 \\ H_1 & 0.24242424 \\ H_2 & 0.12121212 \\ H_3 & 0.06060606 \\ H_4 & 0.06060606 \\ H_* & 0.03030303 \end{array} $$ The expected time between states is given by the reciprocal of the probability. So the expected time between visits to $H_* = 1/0.03030303 = 33 = \mu + 1$. Appendix: Python program used to generate exact probabilities for n = number of consecutive heads over N tosses. import itertools, pylab def countinlist(n, N): count = [0] * N sub = 'h'*n+'t' for string in itertools.imap(''.join, itertools.product('ht', repeat=N+1)): f = string.find(sub) if (f>=0): f = f + n -1 # don't count t, and index in count from zero count[f] = count[f] +1 # uncomment the following line to print all matches # print "found at", f+1, "in", string return count, 1/float((2**(N+1))) n = 4 N = 24 counts, probperevent = countinlist(n,N) probs = [count*probperevent for count in counts] for i in range(N): print '{0:2d} {1:.10f}'.format(i+1,probs[i]) pylab.title('Probabilities of getting {0} consecutive heads in {1} tosses'.format(n, N)) pylab.xlabel('toss') pylab.ylabel('probability') pylab.plot(range(1,(N+1)), probs, 'o') pylab.show()
A serious in-depth problem of probabilities for flipping coins
If I have understood correctly, then the problem is to find a probability distribution for the time at which the first run of $n$ or more heads ends. Edit The probabilities can be determined accuratel
A serious in-depth problem of probabilities for flipping coins If I have understood correctly, then the problem is to find a probability distribution for the time at which the first run of $n$ or more heads ends. Edit The probabilities can be determined accurately and quickly using matrix multiplication, and it is also possible to analytically compute the mean as $\mu_-=2^{n+1}-1$ and the variance as $\sigma^2=2^{n+2}\left(\mu-n-3\right) -\mu^2 + 5\mu$ where $\mu=\mu_-+1$, but there is probably not a simple closed form for the distribution itself. Above a certain number of coin flips the distribution is essentially a geometric distribution: it would make sense to use this form for larger $t$. The evolution in time of the probability distribution in state space can be modelled using a transition matrix for $k=n+2$ states, where $n=$ the number of consecutive coin flips. The states are as follows: State $H_0$, no heads State $H_i$, $i$ heads, $1\le i\le(n-1)$ State $H_n$, $n$ or more heads State $H_*$, $n$ or more heads followed by a tail Once you get into state $H_*$ you can't get back to any of the other states. The state transition probabilities to get into the states are as follows State $H_0$: probability $\frac12$ from $H_i$, $i=0,\ldots,n-1$, i.e. including itself but not state $H_n$ State $H_i$: probability $\frac12$ from $H_{i-1}$ State $H_n$: probability $\frac12$ from $H_{n-1},H_n$, i.e. from the state with $n-1$ heads and itself State $H_*$: probability $\frac12$ from $H_n$ and probability 1 from $H_*$ (itself) So for example, for $n=4$, this gives the transition matrix $$ X = \left\{ \begin{array}{c|cccccc} & H_0 & H_1 & H_2 & H_3 & H_4 & H_* \\ \hline H_0 & \frac12 & \frac12& \frac12& \frac12 &0 & 0 \\ H_1 & \frac12 &0 & 0 &0 & 0 & 0 \\ H_2 & 0 & \frac12 &0 &0 & 0 & 0 \\ H_3 & 0 & 0 &\frac12 &0 & 0 & 0 \\ H_4 & 0 & 0 &0 &\frac12 & \frac12 & 0 \\ H_* & 0 & 0 & 0&0 &\frac12 & 1 \end{array}\right\} $$ For the case $n=4$, the initial vector of probabilities $\mathbf{p}$ is $\mathbf{p}=(1,0,0,0,0,0)$. In general the initial vector has $$\mathbf{p}_i=\begin{cases}1&i=0\\0&i>0\end{cases}$$ The vector $\mathbf{p}$ is the probability distribution in space for any given time. The required cdf is a cdf in time, and is the probability of having seen at least $n$ coin flips end by time $t$. It can be written as $(X^{t+1}\mathbf{p})_k$, noting that we reach state $H_*$ 1 timestep after the last in the run of consecutive coin flips. The required pmf in time can be written as $(X^{t+1}\mathbf{p})_k - (X^{t}\mathbf{p})_k$. However numerically this involves taking away a very small number from a much larger number ($\approx 1$) and restricts precision. Therefore in calculations it is better to set $X_{k,k}=0$ rather than 1. Then writing $X'$ for the resulting matrix $X'=X|X_{k,k}=0$, the pmf is $(X'^{t+1}\mathbf{p})_k$. This is what is implemented in the simple R program below, which works for any $n\ge 2$, n=4 k=n+2 X=matrix(c(rep(1,n),0,0, # first row rep(c(1,rep(0,k)),n-2), # to half-way thru penultimate row 1,rep(0,k),1,1,rep(0,k-1),1,0), # replace 0 by 2 for cdf byrow=T,nrow=k)/2 X t=10000 pt=rep(0,t) # probability at time t pv=c(1,rep(0,k-1)) # probability vector for(i in 1:(t+1)) { #pvk=pv[k]; # if calculating via cdf pv = X %*% pv; #pt[i-1]=pv[k]-pvk # if calculating via cdf pt[i-1]=pv[k] # if calculating pmf } m=sum((1:t)*pt) v=sum((1:t)^2*pt)-m^2 c(m, v) par(mfrow=c(3,1)) plot(pt[1:100],type="l") plot(pt[10:110],type="l") plot(pt[1010:1110],type="l") The upper plot shows the pmf between 0 and 100. The lower two plots show the pmf between 10 and 110 and also between 1010 and 1110, illustrating the self-similarity and the fact that as @Glen_b says, the distribution looks like it can be approximated by a geometric distribution after a settling down period. It's possible to investigate this behaviour further using an eigenvector decomposition of $X$. Doing so shows that the for sufficiently large $t$, $p_{t+1}\approx c(n)p_t$, where $c(n)$ is the solution of the equation $2^{n+1}c^n(c-1)+1=0$. This approximation gets better with increasing $n$ and is excellent for $t$ in the range from about 30 to 50, depending on the value of $n$, as shown in the plot of log error below for computing $p_{100}$ (rainbow colours, red on the left for $n=2$). (In fact for numerical reasons, it would actually be better to use the geometric approximation for probabilities when $t$ is larger.) I suspect(ed) there might be a closed form available for the distribution because the means and variances as I have calculated them as follows $$ \begin{array}{r|rr} n & \text{Mean} & \text{Variance} \\ \hline 2 &7& 24& \\ 3 &15& 144& \\ 4 &31& 736& \\ 5 &63& 3392& \\ 6 &127& 14720& \\ 7 &255& 61696& \\ 8 &511& 253440& \\ 9 &1023& 1029120& \\ 10&2047& 4151296& \\ \end{array} $$ (I had to bump up the number up the time horizon to t=100000 to get this but the program still ran for all $n=2,\ldots,10$ in less than about 10 seconds.) The means in particular follow a very obvious pattern; the variances less so. I have solved a simpler, 3-state transition system in the past, but so far I'm having no luck with a simple analytic solution to this one. Perhaps there's some useful theory that I'm not aware of, e.g. relating to transition matrices. Edit: after a lot of false starts I came up with a recurrence formula. Let $p_{i,t}$ be the probability of being in state $H_i$ at time $t$. Let $q_{*,t}$ be the cumulative probability of being in state $H_*$, i.e. the final state, at time $t$. NB For any given $t$, $p_{i,t}, 0\le i\le n$ and $q_{*,t}$ are a probability distribution over space $i$ , and immediately below I use the fact that their probabilities add to 1. $p_{*,t}$ form a probability distribution over time $t$. Later, I use this fact in deriving the means and variances. The probability of being at the first state at time $t+1$, i.e. no heads, is given by the transition probabilities from states that can return to it from time $t$ (using the theorem of total probability). \begin{align} p_{0,t+1} &= \frac12p_{0,t} + \frac12p_{1,t} + \ldots \frac12p_{n-1,t}\\ &= \frac12\sum_{i=0}^{n-1}p_{i,t}\\ &= \frac12\left( 1-p_{n,t}-q_{*,t} \right) \end{align} But to get from state $H_0$ to $H_{n-1}$ takes $n-1$ steps, hence $p_{n-1,t+n-1} = \frac1{2^{n-1}}p_{0,t}$ and $$ p_{n-1,t+n} = \frac1{2^n}\left( 1-p_{n,t}-q_{*,t} \right)$$ Once again by the theorem of total probability the probability of being at state $H_n$ at time $t+1$ is \begin{align} p_{n,t+1} &= \frac12p_{n,t} + \frac12p_{n-1,t}\\ &= \frac12p_{n,t} + \frac1{2^{n+1}}\left( 1-p_{n,t-n}-q_{*,t-n} \right)\;\;\;(\dagger)\\ \end{align} and using the fact that $q_{*,t+1}-q_{*,t}=\frac12p_{n,t} \implies p_{n,t} = 2q_{*,t+1}-2q_{*,t}$, \begin{align} 2q_{*,t+2} - 2q_{*,t+1} &= q_{*,t+1}-q_{*,t}+\frac1{2^{n+1}}\left( 1-2q_{*,t-n+1}+q_{*,t-n} \right) \end{align} Hence, changing $t\to t+n$, $$2q_{*,t+n+2} - 3q_{*,t+n+1} +q_{*,t+n} + \frac1{2^n}q_{*,t+1} - \frac1{2^{n+1}}q_{*,t} - \frac1{2^{n+1}} = 0$$ This recurrence formula checks out for the cases $n=4$ and $n=6$. E.g. for $n=6$ a plot of this formula using t=1:994;v=2*q[t+8]-3*q[t+7]+q[t+6]+q[t+1]/2**6-q[t]/2**7-1/2**7 gives machine order accuracy. Edit I can't see where to go to find a closed form from this recurrence relation. However, it is possible to get a closed form for the mean. Starting from $(\dagger)$, and noting that $p_{*,t+1}=\frac12p_{n,t}$, \begin{align} p_{n,t+1} &= \frac12p_{n,t} + \frac1{2^{n+1}}\left( 1-p_{n,t-n}-q_{*,t-n} \right)\;\;\;(\dagger)\\ 2^{n+1}\left(2p_{*,t+n+2}-p_{*,t+n+1}\right)+2p_{*,t+1} &= 1-q_{*,t} \end{align} Taking sums from $t=0$ to $\infty$ and applying the formula for the mean $E[X] = \sum_{x=0}^\infty (1-F(x))$ and noting that $p_{*,t}$ is a probability distribution gives \begin{align} 2^{n+1}\sum_{t=0}^\infty \left(2p_{*,t+n+2}-p_{*,t+n+1}\right) + 2\sum_{t=0}^\infty p_{*,t+1} &= \sum_{t=0}^\infty(1-q_{*,t}) \\ 2^{n+1} \left(2\left(1-\frac1{2^{n+1}}\right)-\;1\;\right) + 2 &= \mu \\ 2^{n+1} &= \mu \end{align} This is the mean for reaching state $H_*$; the mean for the end of the run of heads is one less than this. Edit A similar approach using the formula $E[X^2] = \sum_{x=0}^\infty (2x+1)(1-F(x))\;$ from this question yields the variance. \begin{align} \sum_{t=0}^\infty(2t+1)\left (2^{n+1}\left(2p_{*,t+n+2}-p_{*,t+n+1}\right) + 2 p_{*,t+1}\right) &= \sum_{t=0}^\infty(2t+1)(1-q_{*,t}) \\ 2\sum_{t=0}^\infty t\left (2^{n+1}\left(2p_{*,t+n+2}-p_{*,t+n+1}\right) + 2 p_{*,t+1}\right) + \mu &= \sigma^2 + \mu^2 \\ 2^{n+2}\left(2\left(\mu-(n+2)+\frac1{2^{n+1}}\right)-(\mu-(n+1))\right) + 4(\mu-1) &\\+ \mu &= \sigma^2 + \mu^2 \\ 2^{n+2}\left(2(\mu-(n+2))-(\mu-(n+1))\right) + 5\mu &= \sigma^2 + \mu^2 \\ 2^{n+2}\left(\mu-n-3\right) + 5\mu &= \sigma^2 + \mu^2 \\ 2^{n+2}\left(\mu-n-3\right) -\mu^2 + 5\mu &= \sigma^2 \end{align} The means and variances can easily be generated programmatically. E.g. to check the means and variances from the table above use n=2:10 m=c(0,2**(n+1)) v=2**(n+2)*(m[n]-n-3) + 5*m[n] - m[n]^2 Finally, I'm not sure what you wanted when you wrote when a tails hits and breaks the streak of heads the count would start again from the next flip. If you meant what is the probability distribution for the next time at which the first run of $n$ or more heads ends, then the crucial point is contained in this comment by @Glen_b, which is that the process begins again after one tail (c.f. the initial problem where you could get a run of $n$ or more heads immediately). This means that, for example, the mean time to the first event is $\mu-1$, but the mean time between events is always $\mu+1$ (the variance is the same). It's also possible to use a transition matrix to investigate the long-term probabilities of being in a state after the system has "settled down". To get the appropriate transition matrix, set $X_{k,k,}=0$ and $X_{1,k}=1$ so that the system return immediately to state $H_0$ from state $H_*$. Then the scaled first eigenvector of this new matrix gives the stationary probabilities. With $n=4$ these stationary probabilities are $$ \begin{array}{c|cccccc} & \text{probability} \\ \hline H_0 & 0.48484848 \\ H_1 & 0.24242424 \\ H_2 & 0.12121212 \\ H_3 & 0.06060606 \\ H_4 & 0.06060606 \\ H_* & 0.03030303 \end{array} $$ The expected time between states is given by the reciprocal of the probability. So the expected time between visits to $H_* = 1/0.03030303 = 33 = \mu + 1$. Appendix: Python program used to generate exact probabilities for n = number of consecutive heads over N tosses. import itertools, pylab def countinlist(n, N): count = [0] * N sub = 'h'*n+'t' for string in itertools.imap(''.join, itertools.product('ht', repeat=N+1)): f = string.find(sub) if (f>=0): f = f + n -1 # don't count t, and index in count from zero count[f] = count[f] +1 # uncomment the following line to print all matches # print "found at", f+1, "in", string return count, 1/float((2**(N+1))) n = 4 N = 24 counts, probperevent = countinlist(n,N) probs = [count*probperevent for count in counts] for i in range(N): print '{0:2d} {1:.10f}'.format(i+1,probs[i]) pylab.title('Probabilities of getting {0} consecutive heads in {1} tosses'.format(n, N)) pylab.xlabel('toss') pylab.ylabel('probability') pylab.plot(range(1,(N+1)), probs, 'o') pylab.show()
A serious in-depth problem of probabilities for flipping coins If I have understood correctly, then the problem is to find a probability distribution for the time at which the first run of $n$ or more heads ends. Edit The probabilities can be determined accuratel
27,747
A serious in-depth problem of probabilities for flipping coins
I am not sure the beta will be likely to be particularly suitable as a way of dealing with this problem -- "The number of plays until ..." is clearly a count. It's an integer, and there is no upper limit on values where you get positive probability. By contrast the beta distribution is continuous, and on a bounded interval, so it would seem to be an unusual choice. If you moment match a scaled beta, the cumulative distribution functions might perhaps approximate not so badly in the central body of the distribution. However, some other choice is likely to substantially better further into either tail. If you have either an expression for the probabilities or simulations from the distribution (which you presumably need in order to find an approximating beta), why would you not use those directly? If your interest is in finding expressions for probabilities or the probability distribution of the number of tosses required, probably the simplest idea is to work with probability generating functions. These are useful for deriving functions from recursive relationships among probabilities, which functions (the pgf) in turn allow us to extract whatever probabilities we require. Here's a post with a good answer taking the algebraic approach, which explains both the difficulties and makes good use of pgfs and recurrence relations. It has specific expressions for mean and variance in the "two successes in a row" case: https://math.stackexchange.com/questions/73758/probability-of-n-successes-in-a-row-at-the-k-th-bernoulli-trial-geometric The four successes case will be substantially more difficult of course. On the other hand, $p = \frac{1}{2}$ does simplify things somewhat. -- If you just want numerical answers, simulation is relatively straightforward. The probability estimates could be used directly, or alternatively it would be reasonable to smooth the simulated probabilities. If you must use an approximating distribution, you can probably choose something that does pretty well. It's possible a mixture of negative binomials (the 'number of trials' version rather than 'the number of successes' version) might be reasonable. Two or three components should be expected to give a good approximation in all but the extreme tail. If you want a single continuous distribution for an approximation, there may be better choices than the beta distribution; it would be something to investigate. Okay, I've since done a little algebra, some playing with recurrence relations, some simulation and even a little thinking. To a very good approximation, I think you can get away with simply specifying the first four nonzero probabilities (which is easy), computing the next few handfuls of values via recurrence (also easy) and then using a geometric tail once the recurrence relation has smoothed out the initially less smooth progression of probabilities. It looks like you can use the geometric tail to very high accuracy past k=20, though if you're only worried about say 4 figure accuracy you could bring it in earlier. This should let you compute the pdf and cdf to good accuracy. I'm a little concerned - my calculations give that the mean number of tosses is 30.0, and the standard deviation is 27.1; if I understood what you mean by "x" and "u", you got 40 and 28 in your tossing. The 28 looks okay but the 40 seems quite a way off what I got... which makes me worry I did something wrong. ==== NOTE: Given the complexities between first time and subsequent times that we encountered, I just want to be absolutely certain now that we are counting the same thing. Here's a short sequence, with the ends of the '4 or more H' sequences marked (pointing to the gap between flips immediately after the last H) \/ \/ TTHHHHHHTTHTTTTTHHTTHTTHHTHHHHHT... /\ /\ Between those two marks I count 23 flips; that is as soon as the previous sequence of (6 in this case) H's ends, we start counting at the immediately following T and then we count right to the end of the sequence of 5 H's (in this case) that ends the next sequence, giving a count of 23 in this case. Is that how you count them? Given the above is correct, this is what the probability function of the number of tosses after one run of at least 4 heads is complete until the next run of at least 4 heads is complete looks like: At first glance it looks like it's flat for the first few values, then has a geometric tail, but that impression is not quite accurate - it takes a while to settle down to an effectively geometric tail. I am working on coming up with a suitable approximation you can use to answer whatever questions you'd have about probabilities associated with this process to good accuracy that is at the same time as simple as possible. I have a pretty good approximation that should work (that I have already checked against a simulation of a billion coin tosses) but there's some (small but consistent) bias in the probabilities the approximation gives in part of the range and I'd like to see if I can get an extra digit of accuracy out of it. It may be that the best way to do it is simply to give you a table of the probability function and cdf out to a point beyond which a geometric distribution can be used. However, it would help if you can give some idea of the range of things you need to use the approximation for. I hope to follow through on the pgf approach, but it's possible someone else will be more proficient with them than me and can do not just the 4-case but other cases.
A serious in-depth problem of probabilities for flipping coins
I am not sure the beta will be likely to be particularly suitable as a way of dealing with this problem -- "The number of plays until ..." is clearly a count. It's an integer, and there is no upper li
A serious in-depth problem of probabilities for flipping coins I am not sure the beta will be likely to be particularly suitable as a way of dealing with this problem -- "The number of plays until ..." is clearly a count. It's an integer, and there is no upper limit on values where you get positive probability. By contrast the beta distribution is continuous, and on a bounded interval, so it would seem to be an unusual choice. If you moment match a scaled beta, the cumulative distribution functions might perhaps approximate not so badly in the central body of the distribution. However, some other choice is likely to substantially better further into either tail. If you have either an expression for the probabilities or simulations from the distribution (which you presumably need in order to find an approximating beta), why would you not use those directly? If your interest is in finding expressions for probabilities or the probability distribution of the number of tosses required, probably the simplest idea is to work with probability generating functions. These are useful for deriving functions from recursive relationships among probabilities, which functions (the pgf) in turn allow us to extract whatever probabilities we require. Here's a post with a good answer taking the algebraic approach, which explains both the difficulties and makes good use of pgfs and recurrence relations. It has specific expressions for mean and variance in the "two successes in a row" case: https://math.stackexchange.com/questions/73758/probability-of-n-successes-in-a-row-at-the-k-th-bernoulli-trial-geometric The four successes case will be substantially more difficult of course. On the other hand, $p = \frac{1}{2}$ does simplify things somewhat. -- If you just want numerical answers, simulation is relatively straightforward. The probability estimates could be used directly, or alternatively it would be reasonable to smooth the simulated probabilities. If you must use an approximating distribution, you can probably choose something that does pretty well. It's possible a mixture of negative binomials (the 'number of trials' version rather than 'the number of successes' version) might be reasonable. Two or three components should be expected to give a good approximation in all but the extreme tail. If you want a single continuous distribution for an approximation, there may be better choices than the beta distribution; it would be something to investigate. Okay, I've since done a little algebra, some playing with recurrence relations, some simulation and even a little thinking. To a very good approximation, I think you can get away with simply specifying the first four nonzero probabilities (which is easy), computing the next few handfuls of values via recurrence (also easy) and then using a geometric tail once the recurrence relation has smoothed out the initially less smooth progression of probabilities. It looks like you can use the geometric tail to very high accuracy past k=20, though if you're only worried about say 4 figure accuracy you could bring it in earlier. This should let you compute the pdf and cdf to good accuracy. I'm a little concerned - my calculations give that the mean number of tosses is 30.0, and the standard deviation is 27.1; if I understood what you mean by "x" and "u", you got 40 and 28 in your tossing. The 28 looks okay but the 40 seems quite a way off what I got... which makes me worry I did something wrong. ==== NOTE: Given the complexities between first time and subsequent times that we encountered, I just want to be absolutely certain now that we are counting the same thing. Here's a short sequence, with the ends of the '4 or more H' sequences marked (pointing to the gap between flips immediately after the last H) \/ \/ TTHHHHHHTTHTTTTTHHTTHTTHHTHHHHHT... /\ /\ Between those two marks I count 23 flips; that is as soon as the previous sequence of (6 in this case) H's ends, we start counting at the immediately following T and then we count right to the end of the sequence of 5 H's (in this case) that ends the next sequence, giving a count of 23 in this case. Is that how you count them? Given the above is correct, this is what the probability function of the number of tosses after one run of at least 4 heads is complete until the next run of at least 4 heads is complete looks like: At first glance it looks like it's flat for the first few values, then has a geometric tail, but that impression is not quite accurate - it takes a while to settle down to an effectively geometric tail. I am working on coming up with a suitable approximation you can use to answer whatever questions you'd have about probabilities associated with this process to good accuracy that is at the same time as simple as possible. I have a pretty good approximation that should work (that I have already checked against a simulation of a billion coin tosses) but there's some (small but consistent) bias in the probabilities the approximation gives in part of the range and I'd like to see if I can get an extra digit of accuracy out of it. It may be that the best way to do it is simply to give you a table of the probability function and cdf out to a point beyond which a geometric distribution can be used. However, it would help if you can give some idea of the range of things you need to use the approximation for. I hope to follow through on the pgf approach, but it's possible someone else will be more proficient with them than me and can do not just the 4-case but other cases.
A serious in-depth problem of probabilities for flipping coins I am not sure the beta will be likely to be particularly suitable as a way of dealing with this problem -- "The number of plays until ..." is clearly a count. It's an integer, and there is no upper li
27,748
A serious in-depth problem of probabilities for flipping coins
You want the geometric distribution. From Wikipedia: The probability distribution of the number $X$ of Bernoulli trials needed to get one success, supported on the set { 1, 2, 3, ...}. Let heads H be a failure and tails T be a success. The random variable $X$ is then the number of coin flips needed to see the first tails. For example, $X=4$ will be the sequence HHHT. Here is the probability distribution for $X$: $$ P(X=x)=(1-p)^{x-1}p $$ However, we only want the number of heads. Let's instead define $Y=X-1$ as the number of heads. Here is it's distribution: $$ P(Y+1=x) = (1-p)^{x-1}p \\ P(Y=x-1) = (1-p)^{x-1}p \\ P(Y=y) = (1-p)^yp $$ for $y=0,1,2,3...$. We assume a fair coin, making $p=0.5$. Therefore: $$ \begin{align} P(Y=y) &= (0.5)^y(0.5) \\ &= 0.5^{y+1} \end{align} $$ This all assumes the number of flips $n$ is sufficiently large (like 10,000). For smaller (finite) $n$, we would need to add a normalization factor to the expression. Put simply, we need to ensure that the total sum is equal to 1. We can do this by dividing by the sum of all probabilities, defined here as $\alpha$: $$ \alpha = \sum_{i=0}^{n-1}{P(Y=i)} $$ This means the corrected form of $Y$, denoted $Z$, will be: $$ \begin{align} P(Z=z) &= \frac{1}{\alpha}(1-p)^zp \\ &= \frac{1}{\sum_{i=0}^{n-1}{(1-p)^ip}}(1-p)^zp \end{align} $$ Again, with $p=0.5$, we can reduce this even further, using a geomoetric series summation: $$ \begin{align} P(Z=z) &= \frac{1}{\sum_{i=0}^{n-1}{0.5^{i+1}}} 0.5^{z+1} \\ &= \frac{1}{1-0.5^n} 0.5^{z+1} \\ &= \frac{0.5^{z+1}}{1-0.5^n} \end{align} $$ And we can see that, as $n \rightarrow \infty$, our modified version $Z$ approaches $Y$ from earlier.
A serious in-depth problem of probabilities for flipping coins
You want the geometric distribution. From Wikipedia: The probability distribution of the number $X$ of Bernoulli trials needed to get one success, supported on the set { 1, 2, 3, ...}. Let heads H
A serious in-depth problem of probabilities for flipping coins You want the geometric distribution. From Wikipedia: The probability distribution of the number $X$ of Bernoulli trials needed to get one success, supported on the set { 1, 2, 3, ...}. Let heads H be a failure and tails T be a success. The random variable $X$ is then the number of coin flips needed to see the first tails. For example, $X=4$ will be the sequence HHHT. Here is the probability distribution for $X$: $$ P(X=x)=(1-p)^{x-1}p $$ However, we only want the number of heads. Let's instead define $Y=X-1$ as the number of heads. Here is it's distribution: $$ P(Y+1=x) = (1-p)^{x-1}p \\ P(Y=x-1) = (1-p)^{x-1}p \\ P(Y=y) = (1-p)^yp $$ for $y=0,1,2,3...$. We assume a fair coin, making $p=0.5$. Therefore: $$ \begin{align} P(Y=y) &= (0.5)^y(0.5) \\ &= 0.5^{y+1} \end{align} $$ This all assumes the number of flips $n$ is sufficiently large (like 10,000). For smaller (finite) $n$, we would need to add a normalization factor to the expression. Put simply, we need to ensure that the total sum is equal to 1. We can do this by dividing by the sum of all probabilities, defined here as $\alpha$: $$ \alpha = \sum_{i=0}^{n-1}{P(Y=i)} $$ This means the corrected form of $Y$, denoted $Z$, will be: $$ \begin{align} P(Z=z) &= \frac{1}{\alpha}(1-p)^zp \\ &= \frac{1}{\sum_{i=0}^{n-1}{(1-p)^ip}}(1-p)^zp \end{align} $$ Again, with $p=0.5$, we can reduce this even further, using a geomoetric series summation: $$ \begin{align} P(Z=z) &= \frac{1}{\sum_{i=0}^{n-1}{0.5^{i+1}}} 0.5^{z+1} \\ &= \frac{1}{1-0.5^n} 0.5^{z+1} \\ &= \frac{0.5^{z+1}}{1-0.5^n} \end{align} $$ And we can see that, as $n \rightarrow \infty$, our modified version $Z$ approaches $Y$ from earlier.
A serious in-depth problem of probabilities for flipping coins You want the geometric distribution. From Wikipedia: The probability distribution of the number $X$ of Bernoulli trials needed to get one success, supported on the set { 1, 2, 3, ...}. Let heads H
27,749
Doane's formula for histogram binning
This answer has undergone significant changes as I investigate the Wikipedia page. I've left the answers largely as they were but added to them, so at present this forms a progression of understanding; the last parts are where the best information is. Short answer: the Wikipedia page (at the time the question was posted) - and the OP's formula, which seems to have been the same - are simply wrong, for at least three different reasons. I'll leave my original discussion (which assumed that the OP and Wikipedia had it right) since that explains some issues. Better discussion follows later. The short advice: simply forget Doane. If you must use it, use what Wikipedia says now, around April 2013 (I fixed it; hopefully someone doesn't reinsert it later). I believe that formula must refer to excess kurtosis; my reason for that is that it modifies a formula for normal data to account for non-normal data so you'd expect it to reproduce the unmodified one at the normal. It does that if you use excess kurtosis. That does, however, raise the problem that the term in the log can go negative with large samples (indeed, it's possible to be be $\leq 0$ at quite small $n$). I'd suggest not using it with negative excess kurtosis (I'd never use it beyond unimodality anyway; once things get multimodal you want to apply the excess kurtosis idea to each mode, not smooth over them!), though with mild cases (excess kurtosis just less than 0) and modest sample sizes it won't be a big issue. I'd also suggest that in any case it's going to give far too few bins at large sample sizes, even when it works as intended. You may find this paper (by regular CVer Rob Hyndman): http://www.robjhyndman.com/papers/sturges.pdf of some interest. If Sturges' argument is wrong, Doane's formula has the same problem... as Rob clearly notes in the paper. In that paper (and in this answer) he gives a nod to the Freedman-Diaconis rule. In the paper he also points to the approach mentioned by Matt Wand (he refers to the working paper which doesn't seem to be online, but the subsequent paper is available if you have access): http://www.jstor.org/discover/10.2307/2684697 [Edit: actually a link to the working paper is on the citeseer page] That approach involves approximately estimating particular functionals in order to get approximately optimal (in terms of mean integrated squared error, MISE) bin widths for estimating the underlying density. While these work well and give many more bins than Sturges or Doane in general, sometimes I still prefer to use more bins still, though it's usually a very good first attempt. Frankly I don't know why Wand's approach (or at the very least the Freedman-Diaconis rule) isn't a default pretty much everywhere. R does at least offer the Freedman-Diaconis calculation of the number of bins: nclass.FD(rnorm(100)) [1] 11 nclass.FD(runif(100)) [1] 6 nclass.FD(rt(100,1)) [1] 71 See ?nclass.FD Personally, for me that's too few bins in the first two cases at least; I'd double both of those in spite of the fact that it might be a bit noisier than optimal. As $n$ becomes large, I think it does very well in most cases. Edit 2: I decided to investigate the skewness vs kurtosis issue that @PeterFlom rightly expressed puzzlement at. I just had a look at the Doane paper wiso linked to (I'd read it before .... but that was almost 30 years ago) - it makes no reference to kurtosis at all, only to skewness. Doane's actual formula is: $K_e = \log_2(1+\frac{g_1}{\sigma_{g_1}})$ where $K_e$ is the number of added bins, $g_1$ is the 3rd moment skewness. [Well actually, Doane, following fairly common usage of the time, uses $\sqrt{b_1}$ for the signed (!) 3rd moment skewness; the origin of this particularly unedifying abuse of notation is quite old and I'm not going to pursue it, except to say that it was quite widespread and understood as including a sign, but even then it frequently led to confusion - indeed it looks like it fooled Doane and the referees, or an editor in the Doane paper itself - it's fortunately appearing much less often now.] Now at the normal, $\sigma_{g_1} = \sqrt{\frac{6(n-2)}{(n+1)(n+3)}} \approx \sqrt{\frac{6}{n}}$ (although that approximation is pretty poor until $n$ is well past 100; Doane uses the first form). However, it seems that along the way someone has tried to adapt it to kurtosis (at the time I write this Wikipedia has it in terms of kurtosis, for example, and I don't think they made it up) - but there's clear reason to believe that the formula is simply wrong (note that the standard error used is that final approximation for the s.e. of the skewness I gave above). I think I've seen this use of kurtosis in several places other than Wikipedia, but besides not being in Doane's paper, it isn't present in Scott's paper, nor the Hyndman paper I point to, nor in Wand's paper. It does seem to have come from somewhere, however (i.e. I am sure it's not original to Wikipedia), because Doane doesn't have the approximation to $\sigma_{g_1}$. It looks like it's been played with several times before it ended up there; I'd be interested if anyone tracked it down. It does look to me like Doane's argument should happily extend to kurtosis, but the correct standard error would have to be used. However, since Doane relies on Sturges and Sturges' argument seems to be flawed, perhaps the entire enterprise is doomed. In any case I have edited the Histogram talk page on wikipedia noting the error. --- Edit 3: I have corrected the wikipedia page (but I took the liberty of taking the absolute value of the skewness, otherwise Doane's original formula can't be used for left-skewed distributions as it stood - clearly for number of bins the sign of the skewness is immaterial). Strictly speaking I should have presented the formula in its original (wrong) form, and then explained why it doesn't make sense but I think that's problematic for several reasons - not least that people will be tempted to just copy the formula and ignore an explanation. I believe it actually covers Doane's original intent. In any case it's a vast improvement over the nonsense that was in the original. (Please, anyone who can access the original paper, take a look at it and how $\sqrt{b_1}$ is defined and check my changes on Wikipedia to make sure it's reasonable - there were at least three things wrong - the kurtosis, the standard error, and the wrong base of logs, plus Doane's own small error.)
Doane's formula for histogram binning
This answer has undergone significant changes as I investigate the Wikipedia page. I've left the answers largely as they were but added to them, so at present this forms a progression of understanding
Doane's formula for histogram binning This answer has undergone significant changes as I investigate the Wikipedia page. I've left the answers largely as they were but added to them, so at present this forms a progression of understanding; the last parts are where the best information is. Short answer: the Wikipedia page (at the time the question was posted) - and the OP's formula, which seems to have been the same - are simply wrong, for at least three different reasons. I'll leave my original discussion (which assumed that the OP and Wikipedia had it right) since that explains some issues. Better discussion follows later. The short advice: simply forget Doane. If you must use it, use what Wikipedia says now, around April 2013 (I fixed it; hopefully someone doesn't reinsert it later). I believe that formula must refer to excess kurtosis; my reason for that is that it modifies a formula for normal data to account for non-normal data so you'd expect it to reproduce the unmodified one at the normal. It does that if you use excess kurtosis. That does, however, raise the problem that the term in the log can go negative with large samples (indeed, it's possible to be be $\leq 0$ at quite small $n$). I'd suggest not using it with negative excess kurtosis (I'd never use it beyond unimodality anyway; once things get multimodal you want to apply the excess kurtosis idea to each mode, not smooth over them!), though with mild cases (excess kurtosis just less than 0) and modest sample sizes it won't be a big issue. I'd also suggest that in any case it's going to give far too few bins at large sample sizes, even when it works as intended. You may find this paper (by regular CVer Rob Hyndman): http://www.robjhyndman.com/papers/sturges.pdf of some interest. If Sturges' argument is wrong, Doane's formula has the same problem... as Rob clearly notes in the paper. In that paper (and in this answer) he gives a nod to the Freedman-Diaconis rule. In the paper he also points to the approach mentioned by Matt Wand (he refers to the working paper which doesn't seem to be online, but the subsequent paper is available if you have access): http://www.jstor.org/discover/10.2307/2684697 [Edit: actually a link to the working paper is on the citeseer page] That approach involves approximately estimating particular functionals in order to get approximately optimal (in terms of mean integrated squared error, MISE) bin widths for estimating the underlying density. While these work well and give many more bins than Sturges or Doane in general, sometimes I still prefer to use more bins still, though it's usually a very good first attempt. Frankly I don't know why Wand's approach (or at the very least the Freedman-Diaconis rule) isn't a default pretty much everywhere. R does at least offer the Freedman-Diaconis calculation of the number of bins: nclass.FD(rnorm(100)) [1] 11 nclass.FD(runif(100)) [1] 6 nclass.FD(rt(100,1)) [1] 71 See ?nclass.FD Personally, for me that's too few bins in the first two cases at least; I'd double both of those in spite of the fact that it might be a bit noisier than optimal. As $n$ becomes large, I think it does very well in most cases. Edit 2: I decided to investigate the skewness vs kurtosis issue that @PeterFlom rightly expressed puzzlement at. I just had a look at the Doane paper wiso linked to (I'd read it before .... but that was almost 30 years ago) - it makes no reference to kurtosis at all, only to skewness. Doane's actual formula is: $K_e = \log_2(1+\frac{g_1}{\sigma_{g_1}})$ where $K_e$ is the number of added bins, $g_1$ is the 3rd moment skewness. [Well actually, Doane, following fairly common usage of the time, uses $\sqrt{b_1}$ for the signed (!) 3rd moment skewness; the origin of this particularly unedifying abuse of notation is quite old and I'm not going to pursue it, except to say that it was quite widespread and understood as including a sign, but even then it frequently led to confusion - indeed it looks like it fooled Doane and the referees, or an editor in the Doane paper itself - it's fortunately appearing much less often now.] Now at the normal, $\sigma_{g_1} = \sqrt{\frac{6(n-2)}{(n+1)(n+3)}} \approx \sqrt{\frac{6}{n}}$ (although that approximation is pretty poor until $n$ is well past 100; Doane uses the first form). However, it seems that along the way someone has tried to adapt it to kurtosis (at the time I write this Wikipedia has it in terms of kurtosis, for example, and I don't think they made it up) - but there's clear reason to believe that the formula is simply wrong (note that the standard error used is that final approximation for the s.e. of the skewness I gave above). I think I've seen this use of kurtosis in several places other than Wikipedia, but besides not being in Doane's paper, it isn't present in Scott's paper, nor the Hyndman paper I point to, nor in Wand's paper. It does seem to have come from somewhere, however (i.e. I am sure it's not original to Wikipedia), because Doane doesn't have the approximation to $\sigma_{g_1}$. It looks like it's been played with several times before it ended up there; I'd be interested if anyone tracked it down. It does look to me like Doane's argument should happily extend to kurtosis, but the correct standard error would have to be used. However, since Doane relies on Sturges and Sturges' argument seems to be flawed, perhaps the entire enterprise is doomed. In any case I have edited the Histogram talk page on wikipedia noting the error. --- Edit 3: I have corrected the wikipedia page (but I took the liberty of taking the absolute value of the skewness, otherwise Doane's original formula can't be used for left-skewed distributions as it stood - clearly for number of bins the sign of the skewness is immaterial). Strictly speaking I should have presented the formula in its original (wrong) form, and then explained why it doesn't make sense but I think that's problematic for several reasons - not least that people will be tempted to just copy the formula and ignore an explanation. I believe it actually covers Doane's original intent. In any case it's a vast improvement over the nonsense that was in the original. (Please, anyone who can access the original paper, take a look at it and how $\sqrt{b_1}$ is defined and check my changes on Wikipedia to make sure it's reasonable - there were at least three things wrong - the kurtosis, the standard error, and the wrong base of logs, plus Doane's own small error.)
Doane's formula for histogram binning This answer has undergone significant changes as I investigate the Wikipedia page. I've left the answers largely as they were but added to them, so at present this forms a progression of understanding
27,750
Doane's formula for histogram binning
The kurtosis measure defined in terms of the second and fourth moments is never negative (see), then the log(1+...)>0. This quantity is implemented in the command kurtosis() from the R library moments. In addition, using the command hist() you can specify the number of breaks as follows library(moments) n <- 250 data <- rnorm(n) # Sturges formula log_2(n) + 1 hist(data,breaks = "Sturges") # Doane's formula Doane <- 1 + log(n) + log(1 + kurtosis(data) * sqrt(n / 6.)) hist(data,breaks = Doane) The formula used in the command kurtosis() is simply mean((data - mean(data))^4)/mean((data - mean(data))^2)^2. Now, if you want to investigate what is the ``best'' formula, then you will need a criterion. Consider that this has been laaaaaargely discussed in the statistical literature.
Doane's formula for histogram binning
The kurtosis measure defined in terms of the second and fourth moments is never negative (see), then the log(1+...)>0. This quantity is implemented in the command kurtosis() from the R library moments
Doane's formula for histogram binning The kurtosis measure defined in terms of the second and fourth moments is never negative (see), then the log(1+...)>0. This quantity is implemented in the command kurtosis() from the R library moments. In addition, using the command hist() you can specify the number of breaks as follows library(moments) n <- 250 data <- rnorm(n) # Sturges formula log_2(n) + 1 hist(data,breaks = "Sturges") # Doane's formula Doane <- 1 + log(n) + log(1 + kurtosis(data) * sqrt(n / 6.)) hist(data,breaks = Doane) The formula used in the command kurtosis() is simply mean((data - mean(data))^4)/mean((data - mean(data))^2)^2. Now, if you want to investigate what is the ``best'' formula, then you will need a criterion. Consider that this has been laaaaaargely discussed in the statistical literature.
Doane's formula for histogram binning The kurtosis measure defined in terms of the second and fourth moments is never negative (see), then the log(1+...)>0. This quantity is implemented in the command kurtosis() from the R library moments
27,751
auto.arima warns NaNs produced on std error
The sum of the AR coefficients is close to 1 which shows that the parameters are near the edge of the stationarity region. That will cause difficulties in trying to compute the standard errors. However, there is nothing wrong with the estimates, so if all you need is the value of $L_0$, you've got it. auto.arima() takes a few short-cuts to try to speed up the computation, and when it gives a model that looks suspect, it is a good idea to turn those short-cuts off and see what you get. In this case: > n.auto <- auto.arima(log(L),xreg=year,stepwise=FALSE,approx=FALSE) > > n.auto Series: log(L) ARIMA(2,0,0) with non-zero mean Coefficients: ar1 ar2 intercept year 1.8544 -0.9061 11.0776 0.0081 s.e. 0.0721 0.0714 0.0102 0.0008 sigma^2 estimated as 1.594e-06: log likelihood=107.19 AIC=-204.38 AICc=-200.38 BIC=-199.15 This model is a little better (a smaller AIC for example).
auto.arima warns NaNs produced on std error
The sum of the AR coefficients is close to 1 which shows that the parameters are near the edge of the stationarity region. That will cause difficulties in trying to compute the standard errors. Howeve
auto.arima warns NaNs produced on std error The sum of the AR coefficients is close to 1 which shows that the parameters are near the edge of the stationarity region. That will cause difficulties in trying to compute the standard errors. However, there is nothing wrong with the estimates, so if all you need is the value of $L_0$, you've got it. auto.arima() takes a few short-cuts to try to speed up the computation, and when it gives a model that looks suspect, it is a good idea to turn those short-cuts off and see what you get. In this case: > n.auto <- auto.arima(log(L),xreg=year,stepwise=FALSE,approx=FALSE) > > n.auto Series: log(L) ARIMA(2,0,0) with non-zero mean Coefficients: ar1 ar2 intercept year 1.8544 -0.9061 11.0776 0.0081 s.e. 0.0721 0.0714 0.0102 0.0008 sigma^2 estimated as 1.594e-06: log likelihood=107.19 AIC=-204.38 AICc=-200.38 BIC=-199.15 This model is a little better (a smaller AIC for example).
auto.arima warns NaNs produced on std error The sum of the AR coefficients is close to 1 which shows that the parameters are near the edge of the stationarity region. That will cause difficulties in trying to compute the standard errors. Howeve
27,752
auto.arima warns NaNs produced on std error
Your problem arises from an over-specification. A simple first difference model with an AR(1) is quite sufficient. No MA structure or power transform is required. You could also simply model this as a second difference model since the ar(1) coefficient is close to 1.0. A plot of the Actual/fit/forecast is and a residual plot with equation In summary Estimation is subject to Model Specification which in this case is found wanting ["mene mene tekel upharsin"]. Seriously, I suggest that you familiarize yourself with model identification strategies and not try to kitchen-sink your models with unwarranted structure. Sometimes less is more! Parsimony is an objective! Hope this helps. To further answer your questions “Why would auto.arima selects the best model with std error of these ar* ma* coefficients Not a Number?” The probable answer is that the state-space solution isn't all that it might be because of the assumptive models that it tries. But that's just my guess. The true cause of the failure might be your assumption of a log xform. Transformations are like drugs — some are good for you and some are not good for you. Power transformations should ONLY be used to decouple the expected value from the standard deviation of the residuals. If there is linkage, then a Box-Cox transform (which includes logs) might be appropriate. Pulling a transform from behind your ears may not be a good idea. Is this selected model valid after all? Definitely not!
auto.arima warns NaNs produced on std error
Your problem arises from an over-specification. A simple first difference model with an AR(1) is quite sufficient. No MA structure or power transform is required. You could also simply model this as a
auto.arima warns NaNs produced on std error Your problem arises from an over-specification. A simple first difference model with an AR(1) is quite sufficient. No MA structure or power transform is required. You could also simply model this as a second difference model since the ar(1) coefficient is close to 1.0. A plot of the Actual/fit/forecast is and a residual plot with equation In summary Estimation is subject to Model Specification which in this case is found wanting ["mene mene tekel upharsin"]. Seriously, I suggest that you familiarize yourself with model identification strategies and not try to kitchen-sink your models with unwarranted structure. Sometimes less is more! Parsimony is an objective! Hope this helps. To further answer your questions “Why would auto.arima selects the best model with std error of these ar* ma* coefficients Not a Number?” The probable answer is that the state-space solution isn't all that it might be because of the assumptive models that it tries. But that's just my guess. The true cause of the failure might be your assumption of a log xform. Transformations are like drugs — some are good for you and some are not good for you. Power transformations should ONLY be used to decouple the expected value from the standard deviation of the residuals. If there is linkage, then a Box-Cox transform (which includes logs) might be appropriate. Pulling a transform from behind your ears may not be a good idea. Is this selected model valid after all? Definitely not!
auto.arima warns NaNs produced on std error Your problem arises from an over-specification. A simple first difference model with an AR(1) is quite sufficient. No MA structure or power transform is required. You could also simply model this as a
27,753
auto.arima warns NaNs produced on std error
I've faced with similar issues. Please, try to play with optim.control and optim.method. These NaNs are sqrt of negative values of diagonal elements of Hesse matrix. Fitting of ARIMA(2,0,2) is nonlinear problem and optim seemed to converged to a saddle point (where gradient is zero, but Hesse matrix is not positive-defined) instead of likelihood maximum.
auto.arima warns NaNs produced on std error
I've faced with similar issues. Please, try to play with optim.control and optim.method. These NaNs are sqrt of negative values of diagonal elements of Hesse matrix. Fitting of ARIMA(2,0,2) is nonline
auto.arima warns NaNs produced on std error I've faced with similar issues. Please, try to play with optim.control and optim.method. These NaNs are sqrt of negative values of diagonal elements of Hesse matrix. Fitting of ARIMA(2,0,2) is nonlinear problem and optim seemed to converged to a saddle point (where gradient is zero, but Hesse matrix is not positive-defined) instead of likelihood maximum.
auto.arima warns NaNs produced on std error I've faced with similar issues. Please, try to play with optim.control and optim.method. These NaNs are sqrt of negative values of diagonal elements of Hesse matrix. Fitting of ARIMA(2,0,2) is nonline
27,754
How to compute the Kullback-Leibler divergence when the PMF contains 0s?
One standard trick to deal with this problem is to use what's called a Laplace correction. In effect, you add one "count" to all bins, and renormalize. There are also good reasons to add a 0.5 count instead: this particular estimator is called the Krichevsky-Trofimov estimator.
How to compute the Kullback-Leibler divergence when the PMF contains 0s?
One standard trick to deal with this problem is to use what's called a Laplace correction. In effect, you add one "count" to all bins, and renormalize. There are also good reasons to add a 0.5 count i
How to compute the Kullback-Leibler divergence when the PMF contains 0s? One standard trick to deal with this problem is to use what's called a Laplace correction. In effect, you add one "count" to all bins, and renormalize. There are also good reasons to add a 0.5 count instead: this particular estimator is called the Krichevsky-Trofimov estimator.
How to compute the Kullback-Leibler divergence when the PMF contains 0s? One standard trick to deal with this problem is to use what's called a Laplace correction. In effect, you add one "count" to all bins, and renormalize. There are also good reasons to add a 0.5 count i
27,755
How to compute the Kullback-Leibler divergence when the PMF contains 0s?
One way to think about your problem is that you don't really have confidence in the PMF you have calculated from the histogram. You might need a slight prior in your model. Since if you were confident in the PMF, then the KL divergence should be infinity since you got values in one PMF that are impossible in the other PMF. If, on the other hand you had a slight, uninformative prior then there is always some small probability of seeing a certain outcome. One way of introducing this would be to add a vector of ones times some scalar to the histogram. The theoretical prior distribution you would be using is the dirichlet distribution, which is the conjugate prior of the categorical distribution. But for practical purposes you can do something like pmf_unnorm = scipy.histogram(samples, bins=bins, density=True)[0] + w * scipy.ones(len(bins)-1) pmf = pmf_unnor / sum(pmf_unnorm) where w is some positive weight, depending on how strong a prior you want to have.
How to compute the Kullback-Leibler divergence when the PMF contains 0s?
One way to think about your problem is that you don't really have confidence in the PMF you have calculated from the histogram. You might need a slight prior in your model. Since if you were confident
How to compute the Kullback-Leibler divergence when the PMF contains 0s? One way to think about your problem is that you don't really have confidence in the PMF you have calculated from the histogram. You might need a slight prior in your model. Since if you were confident in the PMF, then the KL divergence should be infinity since you got values in one PMF that are impossible in the other PMF. If, on the other hand you had a slight, uninformative prior then there is always some small probability of seeing a certain outcome. One way of introducing this would be to add a vector of ones times some scalar to the histogram. The theoretical prior distribution you would be using is the dirichlet distribution, which is the conjugate prior of the categorical distribution. But for practical purposes you can do something like pmf_unnorm = scipy.histogram(samples, bins=bins, density=True)[0] + w * scipy.ones(len(bins)-1) pmf = pmf_unnor / sum(pmf_unnorm) where w is some positive weight, depending on how strong a prior you want to have.
How to compute the Kullback-Leibler divergence when the PMF contains 0s? One way to think about your problem is that you don't really have confidence in the PMF you have calculated from the histogram. You might need a slight prior in your model. Since if you were confident
27,756
How to compute the Kullback-Leibler divergence when the PMF contains 0s?
I would bin the data so you can compare the two PMFs; given two PMF estimates $\hat P$ and $\hat Q$, you can calculate the KLD simply as: $D_{KL}(\hat P \| \hat Q) \equiv \sum_i \hat P(i) \log \dfrac{\hat P(i)}{\hat Q(i)}$, where $i$ runs over the bins. Sorry, I don't know R.
How to compute the Kullback-Leibler divergence when the PMF contains 0s?
I would bin the data so you can compare the two PMFs; given two PMF estimates $\hat P$ and $\hat Q$, you can calculate the KLD simply as: $D_{KL}(\hat P \| \hat Q) \equiv \sum_i \hat P(i) \log \dfrac{
How to compute the Kullback-Leibler divergence when the PMF contains 0s? I would bin the data so you can compare the two PMFs; given two PMF estimates $\hat P$ and $\hat Q$, you can calculate the KLD simply as: $D_{KL}(\hat P \| \hat Q) \equiv \sum_i \hat P(i) \log \dfrac{\hat P(i)}{\hat Q(i)}$, where $i$ runs over the bins. Sorry, I don't know R.
How to compute the Kullback-Leibler divergence when the PMF contains 0s? I would bin the data so you can compare the two PMFs; given two PMF estimates $\hat P$ and $\hat Q$, you can calculate the KLD simply as: $D_{KL}(\hat P \| \hat Q) \equiv \sum_i \hat P(i) \log \dfrac{
27,757
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$?
It's the $L^p$ norm. See for example the Wikipedia articles: $L^p$ space Minkowski distance If you use $p = 2$, you'll find it resolves to the more familiar Euclidean norm -- i.e. the most familiar measure used as length of the vector $a$. Other values of p give others ways of measuring length as outlined in the article -- see the sections on Euclidean norm, Taxicab norm, etc.
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$?
It's the $L^p$ norm. See for example the Wikipedia articles: $L^p$ space Minkowski distance If you use $p = 2$, you'll find it resolves to the more familiar Euclidean norm -- i.e. the most familiar
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$? It's the $L^p$ norm. See for example the Wikipedia articles: $L^p$ space Minkowski distance If you use $p = 2$, you'll find it resolves to the more familiar Euclidean norm -- i.e. the most familiar measure used as length of the vector $a$. Other values of p give others ways of measuring length as outlined in the article -- see the sections on Euclidean norm, Taxicab norm, etc.
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$? It's the $L^p$ norm. See for example the Wikipedia articles: $L^p$ space Minkowski distance If you use $p = 2$, you'll find it resolves to the more familiar Euclidean norm -- i.e. the most familiar
27,758
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$?
This paper does not appear to use $L^p$ norms in any essential way--every one of the results references the $L^1$ norm explicitly. The problem itself determines which norm to use. In this case interest focuses on the cardinality of multisets. A multiset is represented as a vector of counts of its elements, whence its cardinality happens to be the same as its $L^1$ norm. Often results proven for one norm may hold without any change needed in the proof for a wide range of $p$ (typically $1 \le p \le \infty$). The opportunity for greater generality at no cost will lead many papers like this to talk about $L^p$ norms. $L^p$ norms come into their own in discussions of duality in Hilbert and Banach space theory. Advanced, but introductory (it's not a contradiction!) books on analysis usually cover this material thoroughly. For an introduction to some of the relationships among these norms, read about the Holder Inequality and the Minkowski Inequality.
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$?
This paper does not appear to use $L^p$ norms in any essential way--every one of the results references the $L^1$ norm explicitly. The problem itself determines which norm to use. In this case inter
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$? This paper does not appear to use $L^p$ norms in any essential way--every one of the results references the $L^1$ norm explicitly. The problem itself determines which norm to use. In this case interest focuses on the cardinality of multisets. A multiset is represented as a vector of counts of its elements, whence its cardinality happens to be the same as its $L^1$ norm. Often results proven for one norm may hold without any change needed in the proof for a wide range of $p$ (typically $1 \le p \le \infty$). The opportunity for greater generality at no cost will lead many papers like this to talk about $L^p$ norms. $L^p$ norms come into their own in discussions of duality in Hilbert and Banach space theory. Advanced, but introductory (it's not a contradiction!) books on analysis usually cover this material thoroughly. For an introduction to some of the relationships among these norms, read about the Holder Inequality and the Minkowski Inequality.
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$? This paper does not appear to use $L^p$ norms in any essential way--every one of the results references the $L^1$ norm explicitly. The problem itself determines which norm to use. In this case inter
27,759
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$?
$||a||$ denotes a specific function, called norm, defined on a vector space. It maps a $n$-dimensional element of a vector space into a non-negative real number. $||a||_p$ denotes a yet particular norm defined on the vector space. Let $V$ be a vector space. Any function $p:V\to R_+$, also denoted $p(v)\equiv ||v||$ such that $ p $ is finite and convex $ p(x)=0 \implies x=0 $ $ \forall \alpha_{}\in R, \forall x\in V, p(\alpha_{}x)=|\alpha_{}|p(x) $ is called a norm in $V$ and $(V,p)\equiv (V,||\cdot||$ is then called a normed space. You can check that your function satisfies all these properties. In your example, also, $V$ is a space of functions, that is $a_i:T\to T'$. That is a generalization of the Euclidean space (with Euclidean norm) that you may be familiar with, which is just a particular case of normed space where the underlying set is the (n-dimensional) real numbers and the norm is the called Euclidean norm, a particular case of the function that appears in your question. For instance, the euclidean plane is a normed space such that $V=R^2$, $x=(x_1,x_2)\in R^2$, and define the norm on $R^2$ as $p(x)=||x||_2=||x||=\sqrt{(x_1+x_2)^2}=(\sum_{i=1}^2x_i^2)^{1/2}$. So it is just a plane and the norm gives the "magnitude" of the vector. Note that it is just a special case of the norm you mentioned such that $n=2, p=2, a_i(x)=x_i$, and you don't need the absolute value operator because it is a sum of squared terms. Those topics are covered either in Real Analysis or Linear Algebra (in a more restricted way) textbooks under the rubric of norms or normed spaces.
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$?
$||a||$ denotes a specific function, called norm, defined on a vector space. It maps a $n$-dimensional element of a vector space into a non-negative real number. $||a||_p$ denotes a yet particular nor
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$? $||a||$ denotes a specific function, called norm, defined on a vector space. It maps a $n$-dimensional element of a vector space into a non-negative real number. $||a||_p$ denotes a yet particular norm defined on the vector space. Let $V$ be a vector space. Any function $p:V\to R_+$, also denoted $p(v)\equiv ||v||$ such that $ p $ is finite and convex $ p(x)=0 \implies x=0 $ $ \forall \alpha_{}\in R, \forall x\in V, p(\alpha_{}x)=|\alpha_{}|p(x) $ is called a norm in $V$ and $(V,p)\equiv (V,||\cdot||$ is then called a normed space. You can check that your function satisfies all these properties. In your example, also, $V$ is a space of functions, that is $a_i:T\to T'$. That is a generalization of the Euclidean space (with Euclidean norm) that you may be familiar with, which is just a particular case of normed space where the underlying set is the (n-dimensional) real numbers and the norm is the called Euclidean norm, a particular case of the function that appears in your question. For instance, the euclidean plane is a normed space such that $V=R^2$, $x=(x_1,x_2)\in R^2$, and define the norm on $R^2$ as $p(x)=||x||_2=||x||=\sqrt{(x_1+x_2)^2}=(\sum_{i=1}^2x_i^2)^{1/2}$. So it is just a plane and the norm gives the "magnitude" of the vector. Note that it is just a special case of the norm you mentioned such that $n=2, p=2, a_i(x)=x_i$, and you don't need the absolute value operator because it is a sum of squared terms. Those topics are covered either in Real Analysis or Linear Algebra (in a more restricted way) textbooks under the rubric of norms or normed spaces.
What is the meaning of $\|a\|_p=\left(\sum _{i=1}^n \left|a_i(t)\right|{}^p\right){}^{\frac{1}{p}}$? $||a||$ denotes a specific function, called norm, defined on a vector space. It maps a $n$-dimensional element of a vector space into a non-negative real number. $||a||_p$ denotes a yet particular nor
27,760
Is higher AUC always better?
AUC is a simplified performance measure AUC collapses the ROC curve into a single number. Because of that a comparison of two ROC curves based on AUC might miss out on particular details that are left out in the transformation of the ROC curve into the single number. So a higher AUC does not mean a uniform better performance. Example of ROC curves that are better in different parts are in this image, from this question Why did meta-learning (or model stacking) underperform the individual base learners? You can see on the right that the black curve has a larger AUC, but there is a region where it performs less good. Related question: Determine how good an AUC is (Area under the Curve of ROC)
Is higher AUC always better?
AUC is a simplified performance measure AUC collapses the ROC curve into a single number. Because of that a comparison of two ROC curves based on AUC might miss out on particular details that are left
Is higher AUC always better? AUC is a simplified performance measure AUC collapses the ROC curve into a single number. Because of that a comparison of two ROC curves based on AUC might miss out on particular details that are left out in the transformation of the ROC curve into the single number. So a higher AUC does not mean a uniform better performance. Example of ROC curves that are better in different parts are in this image, from this question Why did meta-learning (or model stacking) underperform the individual base learners? You can see on the right that the black curve has a larger AUC, but there is a region where it performs less good. Related question: Determine how good an AUC is (Area under the Curve of ROC)
Is higher AUC always better? AUC is a simplified performance measure AUC collapses the ROC curve into a single number. Because of that a comparison of two ROC curves based on AUC might miss out on particular details that are left
27,761
Is higher AUC always better?
(observed) AUC can be influenced by statistical fluctuations The ROC Curve is usually based on a sample of real world data and taking a sample is a random process. So there is some randomness in the AUC and if you compare two ROC curves, one might be better just by chance. A good approach is to plot the ROC together with an indication of the remaining error, for example with a 95% confidence interval. You can also compute formal tests whether the difference between to AUCs is significant. (Should you happen to use R, the pROC package can do both.)
Is higher AUC always better?
(observed) AUC can be influenced by statistical fluctuations The ROC Curve is usually based on a sample of real world data and taking a sample is a random process. So there is some randomness in the A
Is higher AUC always better? (observed) AUC can be influenced by statistical fluctuations The ROC Curve is usually based on a sample of real world data and taking a sample is a random process. So there is some randomness in the AUC and if you compare two ROC curves, one might be better just by chance. A good approach is to plot the ROC together with an indication of the remaining error, for example with a 95% confidence interval. You can also compute formal tests whether the difference between to AUCs is significant. (Should you happen to use R, the pROC package can do both.)
Is higher AUC always better? (observed) AUC can be influenced by statistical fluctuations The ROC Curve is usually based on a sample of real world data and taking a sample is a random process. So there is some randomness in the A
27,762
How to compare -50% and +100%
The problem is twofold: You shouldn't subtract one. Just divide one by the other, and you'll get relative numbers 1, 2, 0.5 -- equivalent to 100 % (no change), 200 % (double) and 50 % (half.) Then to get the average relative change, you take the geometric mean: multiply the relative changes and take the root. $\sqrt[3]{1 × 2 × 0.5} = 1$, leaving the value unchanged after all three steps.
How to compare -50% and +100%
The problem is twofold: You shouldn't subtract one. Just divide one by the other, and you'll get relative numbers 1, 2, 0.5 -- equivalent to 100 % (no change), 200 % (double) and 50 % (half.) Then to
How to compare -50% and +100% The problem is twofold: You shouldn't subtract one. Just divide one by the other, and you'll get relative numbers 1, 2, 0.5 -- equivalent to 100 % (no change), 200 % (double) and 50 % (half.) Then to get the average relative change, you take the geometric mean: multiply the relative changes and take the root. $\sqrt[3]{1 × 2 × 0.5} = 1$, leaving the value unchanged after all three steps.
How to compare -50% and +100% The problem is twofold: You shouldn't subtract one. Just divide one by the other, and you'll get relative numbers 1, 2, 0.5 -- equivalent to 100 % (no change), 200 % (double) and 50 % (half.) Then to
27,763
How to compare -50% and +100%
As good as is kqr answer, I would go for another method, which would work even if you have a 0 value somewhere and would keep his way of calculating the relative change When you ask the question "how to correctly compute and average these relative changes" we could also first do the average then compute the relative change. You would then have id until_2000 after_2000 rel_change total 4 4 0 Then you can calculate the difference as you were calculating before The average and the sum of the different rows lead to the same result here as your denominator is the same for both (3 rows) $\frac{sumAfter/nRows - sumUntil/nRows}{sumUntil/nRows} = \frac{sumAfter - sumUntil}{sumUntil}$
How to compare -50% and +100%
As good as is kqr answer, I would go for another method, which would work even if you have a 0 value somewhere and would keep his way of calculating the relative change When you ask the question "how
How to compare -50% and +100% As good as is kqr answer, I would go for another method, which would work even if you have a 0 value somewhere and would keep his way of calculating the relative change When you ask the question "how to correctly compute and average these relative changes" we could also first do the average then compute the relative change. You would then have id until_2000 after_2000 rel_change total 4 4 0 Then you can calculate the difference as you were calculating before The average and the sum of the different rows lead to the same result here as your denominator is the same for both (3 rows) $\frac{sumAfter/nRows - sumUntil/nRows}{sumUntil/nRows} = \frac{sumAfter - sumUntil}{sumUntil}$
How to compare -50% and +100% As good as is kqr answer, I would go for another method, which would work even if you have a 0 value somewhere and would keep his way of calculating the relative change When you ask the question "how
27,764
How to compare -50% and +100%
Adding the numbers and then dividing by the count is the arithmetic mean. When dealing with relative change, it often makes more sense to use the geometric mean, which is where you take the product of the numbers and then taking the nth root. So if you take 0.512 and then take the third root, you get 1, which makes more sense as the "average" change. If you had 0.5, 1, 2, and 2, then you'd take the fourth root of 2, which is 1.189 You can also take the logs of the ratio. You can then take the arithmetic mean of the logs. If you want to convert back to relative change, you can then take the exponential of the result. Taking the log, then the arithmetic mean, then taking the exponential of the result gives you the same answer as the geometric mean.
How to compare -50% and +100%
Adding the numbers and then dividing by the count is the arithmetic mean. When dealing with relative change, it often makes more sense to use the geometric mean, which is where you take the product of
How to compare -50% and +100% Adding the numbers and then dividing by the count is the arithmetic mean. When dealing with relative change, it often makes more sense to use the geometric mean, which is where you take the product of the numbers and then taking the nth root. So if you take 0.512 and then take the third root, you get 1, which makes more sense as the "average" change. If you had 0.5, 1, 2, and 2, then you'd take the fourth root of 2, which is 1.189 You can also take the logs of the ratio. You can then take the arithmetic mean of the logs. If you want to convert back to relative change, you can then take the exponential of the result. Taking the log, then the arithmetic mean, then taking the exponential of the result gives you the same answer as the geometric mean.
How to compare -50% and +100% Adding the numbers and then dividing by the count is the arithmetic mean. When dealing with relative change, it often makes more sense to use the geometric mean, which is where you take the product of
27,765
How to compare -50% and +100%
Alternatively you can use log returns (there are issues with division by 0, same as multiplication by 0 with a geometric mean). > df=structure(list(id = 1:3, until_2000 = c(1L, 1L, 2L), after_2000 = c(1L, 2L, 1L)), class = "data.frame", row.names = c("1", "2", "3")) > log(df$after_2000/df$until_2000) [1] 0.0000000 0.6931472 -0.6931472 and you can use a regular average now (which is 0 in this case). Adding another row > df=rbind(df,c(4,3,5)) > log(df$after_2000/df$until_2000) [1] 0.0000000 0.6931472 -0.6931472 0.5108256 the regular average of these 4 log values is $0.1277064$, an overall $\approx 12.7 \%$ increase. Compare this to kqr's method: Edit after the correct formula for the geometric mean was written down > prod(df$after_2000/df$until_2000)^(1/nrow(df)) [1] 1.136219 so an average $13.6 \%$ increase.
How to compare -50% and +100%
Alternatively you can use log returns (there are issues with division by 0, same as multiplication by 0 with a geometric mean). > df=structure(list(id = 1:3, until_2000 = c(1L, 1L, 2L), after_2000 = c
How to compare -50% and +100% Alternatively you can use log returns (there are issues with division by 0, same as multiplication by 0 with a geometric mean). > df=structure(list(id = 1:3, until_2000 = c(1L, 1L, 2L), after_2000 = c(1L, 2L, 1L)), class = "data.frame", row.names = c("1", "2", "3")) > log(df$after_2000/df$until_2000) [1] 0.0000000 0.6931472 -0.6931472 and you can use a regular average now (which is 0 in this case). Adding another row > df=rbind(df,c(4,3,5)) > log(df$after_2000/df$until_2000) [1] 0.0000000 0.6931472 -0.6931472 0.5108256 the regular average of these 4 log values is $0.1277064$, an overall $\approx 12.7 \%$ increase. Compare this to kqr's method: Edit after the correct formula for the geometric mean was written down > prod(df$after_2000/df$until_2000)^(1/nrow(df)) [1] 1.136219 so an average $13.6 \%$ increase.
How to compare -50% and +100% Alternatively you can use log returns (there are issues with division by 0, same as multiplication by 0 with a geometric mean). > df=structure(list(id = 1:3, until_2000 = c(1L, 1L, 2L), after_2000 = c
27,766
self study: why is my neural network so much worse than my random forest
By default, nnet is doing classification. You want to set linout=T to make it do regression. Then, increase the number of hidden units as suggested by Sycorax, and/or increase the number of iterations n_its. For example: library(nnet) nn = nnet(y~x, data = df_train, size = 25, linout=T) yh2 = predict(nn, newdata = df_test) plot(df_test$x,df_test$y) points(df_test$x, yh2, col = 'blue')
self study: why is my neural network so much worse than my random forest
By default, nnet is doing classification. You want to set linout=T to make it do regression. Then, increase the number of hidden units as suggested by Sycorax, and/or increase the number of iterations
self study: why is my neural network so much worse than my random forest By default, nnet is doing classification. You want to set linout=T to make it do regression. Then, increase the number of hidden units as suggested by Sycorax, and/or increase the number of iterations n_its. For example: library(nnet) nn = nnet(y~x, data = df_train, size = 25, linout=T) yh2 = predict(nn, newdata = df_test) plot(df_test$x,df_test$y) points(df_test$x, yh2, col = 'blue')
self study: why is my neural network so much worse than my random forest By default, nnet is doing classification. You want to set linout=T to make it do regression. Then, increase the number of hidden units as suggested by Sycorax, and/or increase the number of iterations
27,767
Suppose I have 100 integers and I sample 10 without repetition. What is the expected rank of the lowest out of 10 samples?
To obtain an answer we must know how many ties there are among these $100$ integers and where they occur: that's too complicated and likely is not the intent of the question. (Nevertheless, the techniques applied below continue to work.) Henceforth, then, suppose all these integers are unique. Without any loss of generality they might as well be the ordered set of their ranks, $1 \lt 2 \lt \cdots \lt 100.$ Let $S(k)$ be the chance that the smallest element of the sample is $k$ or larger. These events correspond to samples of $\{k, k+1, k+2, \ldots, 100\},$ a set with $101-k$ elements. When sampling without replacement, these constitute $\binom{101-k}{10}$ out of the $\binom{100}{10}$ equiprobable samples. When sampling with replacement, they constitute $(101-k)^{10}$ out of the $100^{10}$ equiprobable samples. The expectation is the sum of the $S(k)$ beginning with $k=1.$ The two answers therefore are $$\sum_{k=1}^\infty \frac{\binom{101-k}{10}}{\binom{100}{10}} = \frac{101}{11}$$ (without replacement) and $$\begin{aligned} &\sum_{k=1}^{100} \frac{(101-k)^{10}}{100^{10}} \\&=\frac{6(100)^{10} + 33(100)^9 + 55(100)^8 - 66(100)^6 + 66(100)^4 - 33(100)^2 + 5}{66(100)^9} \end{aligned}$$ (with replacement). As decimals they equal $9.\overline{18}$ and $9.599241\ldots,$ respectively.
Suppose I have 100 integers and I sample 10 without repetition. What is the expected rank of the low
To obtain an answer we must know how many ties there are among these $100$ integers and where they occur: that's too complicated and likely is not the intent of the question. (Nevertheless, the techn
Suppose I have 100 integers and I sample 10 without repetition. What is the expected rank of the lowest out of 10 samples? To obtain an answer we must know how many ties there are among these $100$ integers and where they occur: that's too complicated and likely is not the intent of the question. (Nevertheless, the techniques applied below continue to work.) Henceforth, then, suppose all these integers are unique. Without any loss of generality they might as well be the ordered set of their ranks, $1 \lt 2 \lt \cdots \lt 100.$ Let $S(k)$ be the chance that the smallest element of the sample is $k$ or larger. These events correspond to samples of $\{k, k+1, k+2, \ldots, 100\},$ a set with $101-k$ elements. When sampling without replacement, these constitute $\binom{101-k}{10}$ out of the $\binom{100}{10}$ equiprobable samples. When sampling with replacement, they constitute $(101-k)^{10}$ out of the $100^{10}$ equiprobable samples. The expectation is the sum of the $S(k)$ beginning with $k=1.$ The two answers therefore are $$\sum_{k=1}^\infty \frac{\binom{101-k}{10}}{\binom{100}{10}} = \frac{101}{11}$$ (without replacement) and $$\begin{aligned} &\sum_{k=1}^{100} \frac{(101-k)^{10}}{100^{10}} \\&=\frac{6(100)^{10} + 33(100)^9 + 55(100)^8 - 66(100)^6 + 66(100)^4 - 33(100)^2 + 5}{66(100)^9} \end{aligned}$$ (with replacement). As decimals they equal $9.\overline{18}$ and $9.599241\ldots,$ respectively.
Suppose I have 100 integers and I sample 10 without repetition. What is the expected rank of the low To obtain an answer we must know how many ties there are among these $100$ integers and where they occur: that's too complicated and likely is not the intent of the question. (Nevertheless, the techn
27,768
Differences Between the Central Limit Theorem and Consistency
Consistency is a property of an estimator. The central limit theorem is, well, a theorem: it relates to the asymptotic property of the sample average under certain conditions, and that they tend to a normal distribution with variance equal to the inverse of the information matrix at a rate of root-n. Not all estimators are sample averages. And if they're lucky enough to have an asymptotic distributions, it may not be normal. For instance, you can estimate the upper bound of a uniform (0, $\theta$) distribution by $X_{(n)}$, the sample maximum. This is a biased estimator, but it is consistent because the bias goes to 0 in large samples. The bias can be corrected by a factor of $n/(n-1)$ and this estimator has an asymptotically exponential distribution due to Huzurbazar.
Differences Between the Central Limit Theorem and Consistency
Consistency is a property of an estimator. The central limit theorem is, well, a theorem: it relates to the asymptotic property of the sample average under certain conditions, and that they tend to a
Differences Between the Central Limit Theorem and Consistency Consistency is a property of an estimator. The central limit theorem is, well, a theorem: it relates to the asymptotic property of the sample average under certain conditions, and that they tend to a normal distribution with variance equal to the inverse of the information matrix at a rate of root-n. Not all estimators are sample averages. And if they're lucky enough to have an asymptotic distributions, it may not be normal. For instance, you can estimate the upper bound of a uniform (0, $\theta$) distribution by $X_{(n)}$, the sample maximum. This is a biased estimator, but it is consistent because the bias goes to 0 in large samples. The bias can be corrected by a factor of $n/(n-1)$ and this estimator has an asymptotically exponential distribution due to Huzurbazar.
Differences Between the Central Limit Theorem and Consistency Consistency is a property of an estimator. The central limit theorem is, well, a theorem: it relates to the asymptotic property of the sample average under certain conditions, and that they tend to a
27,769
Differences Between the Central Limit Theorem and Consistency
Here is my attempt to explain the similarities and differences between the CLT and consistency from a statistical point of view using a particular example. My main focus here is intuition and I completely understand that this example is not flawless but I hope this is still useful. Suppose that $X_1,\ldots,X_n$ are iid random variables such that $\operatorname EX_1=\mu$ and $\operatorname{Var}X_1=1$. Our goal is to learn the value of $\mu$ (which is unobservable) using the observations $X_1,\ldots,X_n$. The natural estimator of $\mu$ is the sample mean given by $$ \bar X_n=\frac1n\sum_{k=1}^nX_k $$ for $n\ge1$. Of course, we need to investigate how good this estimator is. For example, are we be able to obtain more and more accurate information when the sample size increases? The answer is yes and that is what consistency tells us. For all $\varepsilon>0$, we have that $$ P(|\bar X_n-\mu|>\varepsilon)\to0 $$ as $n\to\infty$. In simple terms, if we choose any accuracy level $\varepsilon>0$, the probability that the value of the estimator is further away from $\mu$ than the accuracy level $\varepsilon>0$ gets smaller and smaller when the sample size increases. However, we are not able to saying anything beyond that. If we want to know more, we can investigate the error that we make by estimating $\mu$ further. Using the CLT, we have that $$ \sqrt n(\bar X_n-\mu)\to N(0,1) $$ as $n\to\infty$. Observe that the CLT implies consistency (see here). This tells us that not only the error goes to $0$ in probability as $n\to\infty$ but also gives us some approximate information about the distribution of the error. For large values of $n$, $$ P(|\bar X_n-\mu|> z_{\alpha/2}/\sqrt n)\approx\alpha, $$ where $z_{\alpha/2}$ is the $\alpha/2$-level quantile of the standard normal distribution. Intuitively, we can think that we are interested in the same thing: the accuracy of $\bar X_n$. This is what is similar between consistency and the CLT. The difference between consistency and the CLT is the information that we obtain. If we only have consistency, we know that the probability to observe a large error gets smaller and smaller when the sample size increases. If we have the CLT, in addition to having consistency, we are able to obtain approximate information about the distribution of the error. I hope this is useful.
Differences Between the Central Limit Theorem and Consistency
Here is my attempt to explain the similarities and differences between the CLT and consistency from a statistical point of view using a particular example. My main focus here is intuition and I comple
Differences Between the Central Limit Theorem and Consistency Here is my attempt to explain the similarities and differences between the CLT and consistency from a statistical point of view using a particular example. My main focus here is intuition and I completely understand that this example is not flawless but I hope this is still useful. Suppose that $X_1,\ldots,X_n$ are iid random variables such that $\operatorname EX_1=\mu$ and $\operatorname{Var}X_1=1$. Our goal is to learn the value of $\mu$ (which is unobservable) using the observations $X_1,\ldots,X_n$. The natural estimator of $\mu$ is the sample mean given by $$ \bar X_n=\frac1n\sum_{k=1}^nX_k $$ for $n\ge1$. Of course, we need to investigate how good this estimator is. For example, are we be able to obtain more and more accurate information when the sample size increases? The answer is yes and that is what consistency tells us. For all $\varepsilon>0$, we have that $$ P(|\bar X_n-\mu|>\varepsilon)\to0 $$ as $n\to\infty$. In simple terms, if we choose any accuracy level $\varepsilon>0$, the probability that the value of the estimator is further away from $\mu$ than the accuracy level $\varepsilon>0$ gets smaller and smaller when the sample size increases. However, we are not able to saying anything beyond that. If we want to know more, we can investigate the error that we make by estimating $\mu$ further. Using the CLT, we have that $$ \sqrt n(\bar X_n-\mu)\to N(0,1) $$ as $n\to\infty$. Observe that the CLT implies consistency (see here). This tells us that not only the error goes to $0$ in probability as $n\to\infty$ but also gives us some approximate information about the distribution of the error. For large values of $n$, $$ P(|\bar X_n-\mu|> z_{\alpha/2}/\sqrt n)\approx\alpha, $$ where $z_{\alpha/2}$ is the $\alpha/2$-level quantile of the standard normal distribution. Intuitively, we can think that we are interested in the same thing: the accuracy of $\bar X_n$. This is what is similar between consistency and the CLT. The difference between consistency and the CLT is the information that we obtain. If we only have consistency, we know that the probability to observe a large error gets smaller and smaller when the sample size increases. If we have the CLT, in addition to having consistency, we are able to obtain approximate information about the distribution of the error. I hope this is useful.
Differences Between the Central Limit Theorem and Consistency Here is my attempt to explain the similarities and differences between the CLT and consistency from a statistical point of view using a particular example. My main focus here is intuition and I comple
27,770
Accuracy of Volatility Forecast
The point of volatility forecasting is to forecast the full predictive density. For instance, you might assume a normal future density with mean zero, and forecast the one free parameter, which happens to be the variance. Or use some nonparametric approach. The method of choice for evaluating predictive densities is a proper scoring rule. We have a scoring-rules tag. Its tag wiki contains a few pointers to literature. As an example, I randomly picked the first relevant article in the current issue of the International Journal of Forecasting, which just happened to be "Forecasting volatility with time-varying leverage and volatility of volatility effects" by Catania & Proietti (2020, IJF). They use the continuous ranked probability score (CRPS), which is one very commonly used proper scoring rule.
Accuracy of Volatility Forecast
The point of volatility forecasting is to forecast the full predictive density. For instance, you might assume a normal future density with mean zero, and forecast the one free parameter, which happen
Accuracy of Volatility Forecast The point of volatility forecasting is to forecast the full predictive density. For instance, you might assume a normal future density with mean zero, and forecast the one free parameter, which happens to be the variance. Or use some nonparametric approach. The method of choice for evaluating predictive densities is a proper scoring rule. We have a scoring-rules tag. Its tag wiki contains a few pointers to literature. As an example, I randomly picked the first relevant article in the current issue of the International Journal of Forecasting, which just happened to be "Forecasting volatility with time-varying leverage and volatility of volatility effects" by Catania & Proietti (2020, IJF). They use the continuous ranked probability score (CRPS), which is one very commonly used proper scoring rule.
Accuracy of Volatility Forecast The point of volatility forecasting is to forecast the full predictive density. For instance, you might assume a normal future density with mean zero, and forecast the one free parameter, which happen
27,771
Accuracy of Volatility Forecast
Speaking about evaluating volatility forecasts in general (not GARCH in specific), I will mention an alternative to Stephan Kolassa's answer. One can also study proper scoring rules for statistics or "properties" of distributions; this area is sometimes called elicitation. There, one can ask the following question: Is there a "proper" scoring rule $S(v, y)$ that evaluates a forecast $v$ of the variance of a random variable using a sample $y$? Here the notion of proper should be that expected score is maximized when $v$ is the true variance. It turns out that the answer is no. However, there is a trick. There is certainly such a scoring rule for the mean, e.g. $S(u, y) = - (u - y)^2$. It follows that there is a scoring rule for the second moment (not centered), e.g. $S(w, y) = - (w - y^2)^2$. Therefore, to evaluate a forecast of variance in an unbiased way, it suffices in this case to query the forecast for just two parameters, the first and second moments, which determine the variance. In other words, it's not actually necessary to produce and evaluate the full distribution. (This is basically your proposal: we first evaluate the conditional mean, then the residual, roughly.) There are of course other measures of volatility than variance, and there is research on whether they are "directly elicitable" (i.e. there exists a proper scoring rule eliciting them) or, if not, their "elicitation complexity" (i.e. how many parameters must be extracted from the underlying distribution in order to evaluate it). One place this is studied is for risk measures in finance. The statistics studied include expectiles, value-at-risk, and conditional-value-at-risk. There is some general discussion in Gneiting, Making and Evaluating Point Forecasts, Journal of the American Statistical Association (2011). https://arxiv.org/abs/0912.0902 . Elicitation complexity is studied in Frongillo and Kash, Vector Valued Property Elicitation, Conference on Learning Theory (COLT, 2015). http://proceedings.mlr.press/v40/Frongillo15.html
Accuracy of Volatility Forecast
Speaking about evaluating volatility forecasts in general (not GARCH in specific), I will mention an alternative to Stephan Kolassa's answer. One can also study proper scoring rules for statistics or
Accuracy of Volatility Forecast Speaking about evaluating volatility forecasts in general (not GARCH in specific), I will mention an alternative to Stephan Kolassa's answer. One can also study proper scoring rules for statistics or "properties" of distributions; this area is sometimes called elicitation. There, one can ask the following question: Is there a "proper" scoring rule $S(v, y)$ that evaluates a forecast $v$ of the variance of a random variable using a sample $y$? Here the notion of proper should be that expected score is maximized when $v$ is the true variance. It turns out that the answer is no. However, there is a trick. There is certainly such a scoring rule for the mean, e.g. $S(u, y) = - (u - y)^2$. It follows that there is a scoring rule for the second moment (not centered), e.g. $S(w, y) = - (w - y^2)^2$. Therefore, to evaluate a forecast of variance in an unbiased way, it suffices in this case to query the forecast for just two parameters, the first and second moments, which determine the variance. In other words, it's not actually necessary to produce and evaluate the full distribution. (This is basically your proposal: we first evaluate the conditional mean, then the residual, roughly.) There are of course other measures of volatility than variance, and there is research on whether they are "directly elicitable" (i.e. there exists a proper scoring rule eliciting them) or, if not, their "elicitation complexity" (i.e. how many parameters must be extracted from the underlying distribution in order to evaluate it). One place this is studied is for risk measures in finance. The statistics studied include expectiles, value-at-risk, and conditional-value-at-risk. There is some general discussion in Gneiting, Making and Evaluating Point Forecasts, Journal of the American Statistical Association (2011). https://arxiv.org/abs/0912.0902 . Elicitation complexity is studied in Frongillo and Kash, Vector Valued Property Elicitation, Conference on Learning Theory (COLT, 2015). http://proceedings.mlr.press/v40/Frongillo15.html
Accuracy of Volatility Forecast Speaking about evaluating volatility forecasts in general (not GARCH in specific), I will mention an alternative to Stephan Kolassa's answer. One can also study proper scoring rules for statistics or
27,772
Accuracy of Volatility Forecast
Maybe keep the thing as simple as possible is what shenflow looking for. So: But how do we correctly evaluate ARCH/GARCH forecasts? The things is not so different than in conditional mean case, like ARMA. The trick is that you have to care about what you try to forecast. For example with financial returns ($r_t$) is common to identify the volatility as the squared returns, say $r_t^2$. Now, model like ARCH/GARCH give you a specification for conditional variance: $V[r_t|r_{t-1},…, r_{t-p}]$ For example in ARCH(1) case we have $V[r_t|r_{t-1}]= \omega + \alpha_1 r_{t-1}^2 $ Then for evaluate the forecast accuracy you have to compare the conditional variance (volatility forecast) against the squared return (observed volatility). Then, for accuracy evaluation mean square loss is common. In the ARCH(1) case: $ MSE [r_t^2 - (\omega + \alpha_1 r_{t-1}^2)] $ for some $t$ Note that behind this example there is the assumption of zero conditional mean for $r_t$. Otherwise, even if the idea is not so different, the second moments and variances do not coincide and the things become more complicated.
Accuracy of Volatility Forecast
Maybe keep the thing as simple as possible is what shenflow looking for. So: But how do we correctly evaluate ARCH/GARCH forecasts? The things is not so different than in conditional mean case, like
Accuracy of Volatility Forecast Maybe keep the thing as simple as possible is what shenflow looking for. So: But how do we correctly evaluate ARCH/GARCH forecasts? The things is not so different than in conditional mean case, like ARMA. The trick is that you have to care about what you try to forecast. For example with financial returns ($r_t$) is common to identify the volatility as the squared returns, say $r_t^2$. Now, model like ARCH/GARCH give you a specification for conditional variance: $V[r_t|r_{t-1},…, r_{t-p}]$ For example in ARCH(1) case we have $V[r_t|r_{t-1}]= \omega + \alpha_1 r_{t-1}^2 $ Then for evaluate the forecast accuracy you have to compare the conditional variance (volatility forecast) against the squared return (observed volatility). Then, for accuracy evaluation mean square loss is common. In the ARCH(1) case: $ MSE [r_t^2 - (\omega + \alpha_1 r_{t-1}^2)] $ for some $t$ Note that behind this example there is the assumption of zero conditional mean for $r_t$. Otherwise, even if the idea is not so different, the second moments and variances do not coincide and the things become more complicated.
Accuracy of Volatility Forecast Maybe keep the thing as simple as possible is what shenflow looking for. So: But how do we correctly evaluate ARCH/GARCH forecasts? The things is not so different than in conditional mean case, like
27,773
Why not to use Bayes theorem in the form $p(\theta | x) = \frac{L(\theta | x) p(\theta)}{p(x)}$?
There are two basic results from probability that are at work in Bayes' theorem. One is a way of rewriting a joint probability density function: $$p(x,\,y)=p(x\,|\,y)p(y).$$ The other is a formula for computing a conditional probability density function: $$p(y\,|\,x)=\frac{p(x,\,y)}{p(x)}.$$ Bayes' theorem just stitches these two things together: $$p(\theta\,|\,x)=\frac{p(x,\,\theta)}{p(x)}=\frac{p(x\,|\,\theta)p(\theta)}{p(x)}$$ So both the data $x$ and the parameters $\theta$ are random variables with joint pdf $$p(x,\,\theta)=p(x\,|\,\theta)p(\theta),$$ and that's what shows up in the numerator in Bayes' theorem. So writing the likelihood as a conditional probability density instead of as a function $L$ of the parameters makes clear the basic probability at play. That all said, you'll see people use either, like here or here.
Why not to use Bayes theorem in the form $p(\theta | x) = \frac{L(\theta | x) p(\theta)}{p(x)}$?
There are two basic results from probability that are at work in Bayes' theorem. One is a way of rewriting a joint probability density function: $$p(x,\,y)=p(x\,|\,y)p(y).$$ The other is a formula for
Why not to use Bayes theorem in the form $p(\theta | x) = \frac{L(\theta | x) p(\theta)}{p(x)}$? There are two basic results from probability that are at work in Bayes' theorem. One is a way of rewriting a joint probability density function: $$p(x,\,y)=p(x\,|\,y)p(y).$$ The other is a formula for computing a conditional probability density function: $$p(y\,|\,x)=\frac{p(x,\,y)}{p(x)}.$$ Bayes' theorem just stitches these two things together: $$p(\theta\,|\,x)=\frac{p(x,\,\theta)}{p(x)}=\frac{p(x\,|\,\theta)p(\theta)}{p(x)}$$ So both the data $x$ and the parameters $\theta$ are random variables with joint pdf $$p(x,\,\theta)=p(x\,|\,\theta)p(\theta),$$ and that's what shows up in the numerator in Bayes' theorem. So writing the likelihood as a conditional probability density instead of as a function $L$ of the parameters makes clear the basic probability at play. That all said, you'll see people use either, like here or here.
Why not to use Bayes theorem in the form $p(\theta | x) = \frac{L(\theta | x) p(\theta)}{p(x)}$? There are two basic results from probability that are at work in Bayes' theorem. One is a way of rewriting a joint probability density function: $$p(x,\,y)=p(x\,|\,y)p(y).$$ The other is a formula for
27,774
Why not to use Bayes theorem in the form $p(\theta | x) = \frac{L(\theta | x) p(\theta)}{p(x)}$?
The likelihood function is merely proportional to the sampling density, in the sense that you have $L_x(\theta) = k(x) \cdot p(x|\theta)$ for some constant $k(x) > 0$ (though you should note that the likelihood is a function of the parameter, not the data). If you want to use this in your expression for Bayes theorem then you need to include the same scaling constant in the denominator: $$p(\theta|x) = \frac{L_x(\theta) \cdot p(\theta)}{k(x) \cdot p(x)} = \frac{L_x(\theta) \cdot p(\theta)}{\int L_x(\theta) \cdot p(\theta) \ d \theta} \propto L_x(\theta) \cdot p(\theta).$$ If you instead use the formula you have proposed, then you will end up with a kernel of the posterior density, but it may not integrate to one (and thus it is not generally a density).
Why not to use Bayes theorem in the form $p(\theta | x) = \frac{L(\theta | x) p(\theta)}{p(x)}$?
The likelihood function is merely proportional to the sampling density, in the sense that you have $L_x(\theta) = k(x) \cdot p(x|\theta)$ for some constant $k(x) > 0$ (though you should note that the
Why not to use Bayes theorem in the form $p(\theta | x) = \frac{L(\theta | x) p(\theta)}{p(x)}$? The likelihood function is merely proportional to the sampling density, in the sense that you have $L_x(\theta) = k(x) \cdot p(x|\theta)$ for some constant $k(x) > 0$ (though you should note that the likelihood is a function of the parameter, not the data). If you want to use this in your expression for Bayes theorem then you need to include the same scaling constant in the denominator: $$p(\theta|x) = \frac{L_x(\theta) \cdot p(\theta)}{k(x) \cdot p(x)} = \frac{L_x(\theta) \cdot p(\theta)}{\int L_x(\theta) \cdot p(\theta) \ d \theta} \propto L_x(\theta) \cdot p(\theta).$$ If you instead use the formula you have proposed, then you will end up with a kernel of the posterior density, but it may not integrate to one (and thus it is not generally a density).
Why not to use Bayes theorem in the form $p(\theta | x) = \frac{L(\theta | x) p(\theta)}{p(x)}$? The likelihood function is merely proportional to the sampling density, in the sense that you have $L_x(\theta) = k(x) \cdot p(x|\theta)$ for some constant $k(x) > 0$ (though you should note that the
27,775
Maximum likelihood is not re-parametrization invariant. So how can one justify using it?
Looking at your graph, it appears that $\hat{t} \in \{0.7753975, 2.346194\}$ is a pretty reasonable guess at the MLE(s) of $t$. Running those values through the $\sin$ function to get back to $\mu$ results in $\hat{\mu} = \{0.7, 0.7\}$ or $0.7$, just as it should. So, there is no disagreement between the MLE of $\mu$ and the MLE(s) of $t$. What is happening is that you have created a map from $\mu \to t$ that is not 1-1. In this case, the true value of $\mu$ maps to multiple values of $t$, so not surprisingly you will have multiple maxima when working with $t$. Note, however, that this would be the same if you were doing a Bayesian analysis, unless your prior restricted $t$ to the interval $[-\pi/2, \pi/2)$ or some such. If you did so, for comparability, you should restrict the range of the MLE of $t$ to the same range, in which case you won't get multiple maxima for the likelihood function any more. ETA: In retrospect I focused too much on explanation-by-example and not enough on the underlying principle. One can hardly do better than @whuber's comment in response to the OP in this regard. In general, if you have a parameter $\theta$ and an associated MLE $\hat{\theta}$, and you construct a function $\theta = f(t)$, you've effectively created an alternate parameter $t$. The MLE of $t$, label it $\hat{t}$, will be those values of $t$ such that $f(t) = \hat{\theta}$, i.e., $f(\hat{t}) = \hat{\theta}$.
Maximum likelihood is not re-parametrization invariant. So how can one justify using it?
Looking at your graph, it appears that $\hat{t} \in \{0.7753975, 2.346194\}$ is a pretty reasonable guess at the MLE(s) of $t$. Running those values through the $\sin$ function to get back to $\mu$ r
Maximum likelihood is not re-parametrization invariant. So how can one justify using it? Looking at your graph, it appears that $\hat{t} \in \{0.7753975, 2.346194\}$ is a pretty reasonable guess at the MLE(s) of $t$. Running those values through the $\sin$ function to get back to $\mu$ results in $\hat{\mu} = \{0.7, 0.7\}$ or $0.7$, just as it should. So, there is no disagreement between the MLE of $\mu$ and the MLE(s) of $t$. What is happening is that you have created a map from $\mu \to t$ that is not 1-1. In this case, the true value of $\mu$ maps to multiple values of $t$, so not surprisingly you will have multiple maxima when working with $t$. Note, however, that this would be the same if you were doing a Bayesian analysis, unless your prior restricted $t$ to the interval $[-\pi/2, \pi/2)$ or some such. If you did so, for comparability, you should restrict the range of the MLE of $t$ to the same range, in which case you won't get multiple maxima for the likelihood function any more. ETA: In retrospect I focused too much on explanation-by-example and not enough on the underlying principle. One can hardly do better than @whuber's comment in response to the OP in this regard. In general, if you have a parameter $\theta$ and an associated MLE $\hat{\theta}$, and you construct a function $\theta = f(t)$, you've effectively created an alternate parameter $t$. The MLE of $t$, label it $\hat{t}$, will be those values of $t$ such that $f(t) = \hat{\theta}$, i.e., $f(\hat{t}) = \hat{\theta}$.
Maximum likelihood is not re-parametrization invariant. So how can one justify using it? Looking at your graph, it appears that $\hat{t} \in \{0.7753975, 2.346194\}$ is a pretty reasonable guess at the MLE(s) of $t$. Running those values through the $\sin$ function to get back to $\mu$ r
27,776
Maximum likelihood is not re-parametrization invariant. So how can one justify using it?
As my previous answer wasn't completely clear about the need for bijectivness or not (one could argue my answer was just plain wrong). I did some research about the whole reparametrizing thing and here is what I found out. Both @whuber and @jbowman touch upon some of the same things. Theory So, in theory, the maximum likelihood estimator $\hat{\theta}$ of the likelihood function $L\left(\theta\right)$, is invariant to re-parametrization. So, say you have some known function $g$, which re-parametrizes $\theta$ into $\lambda=g(\theta)$ (where the dimensions of $\theta$ and $\lambda$ are not necessarily the same). Then two facts hold true, Maximizing $L\left(\theta\right)$ wrt. $\theta$, that is, finding the MLE, $\hat{\theta}$, and then reparametrizing it, $g(\hat{\theta})$, yields the MLE of $\hat{\lambda}$. In short, $\hat{\lambda}=g\left(\hat{\theta}\right)$. Further, if $g$ has an inverse, maximizing $L\left(g^{-1}(\lambda)\right)$ wrt. $\lambda$, that is, finding the MLE $\hat{\lambda}$ yields the same maximum as $\hat{\theta}$. So the MLE of $\theta$ is $\hat{\theta}=g^{-1}\left(\hat{\lambda}\right)$. Splitting the invariance in these two sub-cases can seem a bit artificial, but I find it useful since they represent two different use-cases of re-parametrization. In practice The first use-case is where you somehow can identify the MLE for some parameter, but you actually need a certain transformation of that variable. For example you have an estimator, $\hat{\sigma},$ for the parameter $\sigma$ in the normal distribution, but you are actually interested in the MLE for the variance $\sigma^{2}$. Then you can use the invariance principle and simply square the $\sigma$-MLE, $\hat{\sigma^{2}}=(\hat{\sigma})^{2}$. An example for the second use-case, is that you have a numerical algorithm, like gradient descent or Newton-Raphson, to maximize the likelihood function. Say, you want to estimate the parameter $\sigma^{2}$ from a normal distribution. The parameter is strictly positive by definition, but the numerical procedure doesn't allow you to make constraints. Well, you can use the invariance property to set $\sigma^{2}=\exp(\lambda)$ and let the algorithm vary $\lambda$ instead of $\sigma^{2}$, this way ensuring that $\sigma^{2}$ stays positive. The exponential is bijective, but this is not strictly required. We could have used $\sigma^{2}=\lambda^{2}$ instead, which is not bijective. But using a bijection is more practical, since we can go from $\sigma^{2}$ to $\lambda$ and back in a unique fashion. The formalities To define the MLE of $\lambda$ more formally we need to define what is called the profile likelihood function as, $$L^{\ast}(\lambda)=\sup_{\theta\vert\lambda=g\left(\theta\right)}L\left(\theta\right).$$ So, for a given $\lambda$-value the profile likelihood value, is the supremum over all $\theta$'s which ensure that $g\left(\theta\right)$ equals $\lambda$. With the profile likelihood defined we can then define the MLE for $\lambda$, denoted $\hat{\lambda}$, as the value which maximizes $L^{\ast}\left(\lambda\right)$. With these definitions in place the invariance of re-parametrization boils down to, $$ L^{\ast}\left(\hat{\lambda}\right)=L\left(\hat{\theta}\right) $$ which can be proved by, $$L^{\ast}\left(\hat{\lambda}\right)=\max_{\lambda}L^{\ast}\left(\lambda\right)=\max_{\lambda}\sup_{\theta\vert\lambda=g\left(\theta\right)}L\left(\theta\right)=\sup_{\theta}L\left(\theta\right)=\max_{\theta}L\left(\theta\right)$$ where I have assumed that $L\left(\theta\right)$ has a maximum. If the re-parametrization is a bijection i.e. it is invertible, then $L^{\ast}\left(\lambda\right)$ is simply $L(g(\theta))$ since each $\theta$ uniquely maps to a $\lambda$, and hence the supremum over ``all'' $\theta$'s just collapses to the unique $L(\theta)$. So, we get that, \begin{align*} L^{\ast}\left(\lambda\right) & =L\left(g\left(\theta\right)\right)\\ L^{\ast}\left(g^{-1}(\lambda)\right) & =L\left(\theta\right) \end{align*} and hence, $$\hat{\theta}=g^{-1}\left(\hat{\lambda}\right).$$ References: Invariance property of MLE: what is the MLE of $\theta^2$ of normal, $\bar{X}^2$? http://www.stats.ox.ac.uk/~dlunn/b8_02/b8pdf_6.pdf http://www.stat.unc.edu/faculty/cji/lecture7.pdf https://en.wikipedia.org/wiki/Maximum_likelihood_estimation#Functional_invariance
Maximum likelihood is not re-parametrization invariant. So how can one justify using it?
As my previous answer wasn't completely clear about the need for bijectivness or not (one could argue my answer was just plain wrong). I did some research about the whole reparametrizing thing and her
Maximum likelihood is not re-parametrization invariant. So how can one justify using it? As my previous answer wasn't completely clear about the need for bijectivness or not (one could argue my answer was just plain wrong). I did some research about the whole reparametrizing thing and here is what I found out. Both @whuber and @jbowman touch upon some of the same things. Theory So, in theory, the maximum likelihood estimator $\hat{\theta}$ of the likelihood function $L\left(\theta\right)$, is invariant to re-parametrization. So, say you have some known function $g$, which re-parametrizes $\theta$ into $\lambda=g(\theta)$ (where the dimensions of $\theta$ and $\lambda$ are not necessarily the same). Then two facts hold true, Maximizing $L\left(\theta\right)$ wrt. $\theta$, that is, finding the MLE, $\hat{\theta}$, and then reparametrizing it, $g(\hat{\theta})$, yields the MLE of $\hat{\lambda}$. In short, $\hat{\lambda}=g\left(\hat{\theta}\right)$. Further, if $g$ has an inverse, maximizing $L\left(g^{-1}(\lambda)\right)$ wrt. $\lambda$, that is, finding the MLE $\hat{\lambda}$ yields the same maximum as $\hat{\theta}$. So the MLE of $\theta$ is $\hat{\theta}=g^{-1}\left(\hat{\lambda}\right)$. Splitting the invariance in these two sub-cases can seem a bit artificial, but I find it useful since they represent two different use-cases of re-parametrization. In practice The first use-case is where you somehow can identify the MLE for some parameter, but you actually need a certain transformation of that variable. For example you have an estimator, $\hat{\sigma},$ for the parameter $\sigma$ in the normal distribution, but you are actually interested in the MLE for the variance $\sigma^{2}$. Then you can use the invariance principle and simply square the $\sigma$-MLE, $\hat{\sigma^{2}}=(\hat{\sigma})^{2}$. An example for the second use-case, is that you have a numerical algorithm, like gradient descent or Newton-Raphson, to maximize the likelihood function. Say, you want to estimate the parameter $\sigma^{2}$ from a normal distribution. The parameter is strictly positive by definition, but the numerical procedure doesn't allow you to make constraints. Well, you can use the invariance property to set $\sigma^{2}=\exp(\lambda)$ and let the algorithm vary $\lambda$ instead of $\sigma^{2}$, this way ensuring that $\sigma^{2}$ stays positive. The exponential is bijective, but this is not strictly required. We could have used $\sigma^{2}=\lambda^{2}$ instead, which is not bijective. But using a bijection is more practical, since we can go from $\sigma^{2}$ to $\lambda$ and back in a unique fashion. The formalities To define the MLE of $\lambda$ more formally we need to define what is called the profile likelihood function as, $$L^{\ast}(\lambda)=\sup_{\theta\vert\lambda=g\left(\theta\right)}L\left(\theta\right).$$ So, for a given $\lambda$-value the profile likelihood value, is the supremum over all $\theta$'s which ensure that $g\left(\theta\right)$ equals $\lambda$. With the profile likelihood defined we can then define the MLE for $\lambda$, denoted $\hat{\lambda}$, as the value which maximizes $L^{\ast}\left(\lambda\right)$. With these definitions in place the invariance of re-parametrization boils down to, $$ L^{\ast}\left(\hat{\lambda}\right)=L\left(\hat{\theta}\right) $$ which can be proved by, $$L^{\ast}\left(\hat{\lambda}\right)=\max_{\lambda}L^{\ast}\left(\lambda\right)=\max_{\lambda}\sup_{\theta\vert\lambda=g\left(\theta\right)}L\left(\theta\right)=\sup_{\theta}L\left(\theta\right)=\max_{\theta}L\left(\theta\right)$$ where I have assumed that $L\left(\theta\right)$ has a maximum. If the re-parametrization is a bijection i.e. it is invertible, then $L^{\ast}\left(\lambda\right)$ is simply $L(g(\theta))$ since each $\theta$ uniquely maps to a $\lambda$, and hence the supremum over ``all'' $\theta$'s just collapses to the unique $L(\theta)$. So, we get that, \begin{align*} L^{\ast}\left(\lambda\right) & =L\left(g\left(\theta\right)\right)\\ L^{\ast}\left(g^{-1}(\lambda)\right) & =L\left(\theta\right) \end{align*} and hence, $$\hat{\theta}=g^{-1}\left(\hat{\lambda}\right).$$ References: Invariance property of MLE: what is the MLE of $\theta^2$ of normal, $\bar{X}^2$? http://www.stats.ox.ac.uk/~dlunn/b8_02/b8pdf_6.pdf http://www.stat.unc.edu/faculty/cji/lecture7.pdf https://en.wikipedia.org/wiki/Maximum_likelihood_estimation#Functional_invariance
Maximum likelihood is not re-parametrization invariant. So how can one justify using it? As my previous answer wasn't completely clear about the need for bijectivness or not (one could argue my answer was just plain wrong). I did some research about the whole reparametrizing thing and her
27,777
Understanding degenerate multivariate normal distribution
A joint density function, say of two random variables $X$ and $Y$, is $f_{X,Y}(x,y)$ is an ordinary function of two real variables and the meaning that we ascribe to it is that if $\mathcal B$ is a region of very small area $b$ with the property that $(x_0, y_0) \in \mathcal B$, then $$P\{(X,Y)\in \mathcal B\} \approx f_{X,Y}(x_0,y_0)\cdot b \tag 1$$ and that this approximation gets better and better as $\mathcal B$ shrinks in area, and $b \to 0$. Of course, both sides of $(1)$ approach $0$ as $b \to 0$, but the ratio $\frac{P\{(X,Y)\in \mathcal B\}}{b}$ is converging to $f_{X,Y}(x_0,y_0)$. If we think of probability as probability mass spread over the $x$-$y$ plane, then $f_{X,Y}(x_0,y_0)$ is the density of the probability mass at the point $(x_0,y_0)$. Note that $f_{X,Y}(x,y)$ is not a probability, but a probability density, and it is measured in probability mass per unit area. In particular, note that it is possible for $f_{X,Y}(x_0,y_0)$ to exceed $1$ (probability mass is very dense at $(x_0,y_0)$), and we need to multiply it by an area (as in $(1)$) to get a probability from it. With that as prologue, consider the case when $Y = \alpha X + \beta$. Now, the random point $(X,Y)$ is constrained to lie on the straight line $y = \alpha x + \beta$ in the $x$-$y$ plane. Consequently, $X$ and $Y$ do not enjoy a joint density because all the probability mass lies on the straight line which has zero area. (Remember that old shibboleth about a line having zero width that you learned in muddle school?) So, we cannot write something like $(1)$. The probability mass is all there; it lies along the straight line $y = \alpha x + \beta$, but its joint density (in terms of mass per unit area) is infinite along that straight line. So, now what? Well, the trick is to understand that we really have just one random variable, and questions about $(X,Y)$ can be translated into questions about just $X$, and answered in terms of $X$ alone. For example, (with $\alpha > 0$) $$F_{X,Y}(x_0,y_0) = P\{X\leq x_0, Y\leq y_0\} = P\{X\leq x_0, \alpha X + \beta \leq y_0\} = P\left\{X \leq \min\left(x_0, \frac{y_0-\beta}{\alpha}\right)\right\}.$$ Note that all the usual rules apply even though $X$ and $Y$ do not have a joint density. For example, $$\operatorname{cov}(X,Y)= \operatorname{cov}(X,\alpha X+\beta) = \alpha \operatorname{var}(X)$$ and so on. Finally, if you are still paying attention, if $n$ jointly normal random variables $X_i$ have a singular covariance matrix $\Sigma$ and mean vector $\mathbf m$, then that means that there are $m < n$ independent standard normal random variables $Y_j$ such that $$(X_1,X_2,\ldots, X_n) = (Y_1,Y_2,\ldots, Y_m)\mathbf A + \mathbf m$$ where $\mathbf A$ is a $m\times n$ matrix, and all questions about $(X_1,X_2,\ldots, X_n)$ can be stated in terms of $(Y_1,Y_2,\ldots, Y_m)$ and answered in terms of these iid random variables. Note that $\Sigma = \mathbf A^T\mathbf A$.
Understanding degenerate multivariate normal distribution
A joint density function, say of two random variables $X$ and $Y$, is $f_{X,Y}(x,y)$ is an ordinary function of two real variables and the meaning that we ascribe to it is that if $\mathcal B$ is a re
Understanding degenerate multivariate normal distribution A joint density function, say of two random variables $X$ and $Y$, is $f_{X,Y}(x,y)$ is an ordinary function of two real variables and the meaning that we ascribe to it is that if $\mathcal B$ is a region of very small area $b$ with the property that $(x_0, y_0) \in \mathcal B$, then $$P\{(X,Y)\in \mathcal B\} \approx f_{X,Y}(x_0,y_0)\cdot b \tag 1$$ and that this approximation gets better and better as $\mathcal B$ shrinks in area, and $b \to 0$. Of course, both sides of $(1)$ approach $0$ as $b \to 0$, but the ratio $\frac{P\{(X,Y)\in \mathcal B\}}{b}$ is converging to $f_{X,Y}(x_0,y_0)$. If we think of probability as probability mass spread over the $x$-$y$ plane, then $f_{X,Y}(x_0,y_0)$ is the density of the probability mass at the point $(x_0,y_0)$. Note that $f_{X,Y}(x,y)$ is not a probability, but a probability density, and it is measured in probability mass per unit area. In particular, note that it is possible for $f_{X,Y}(x_0,y_0)$ to exceed $1$ (probability mass is very dense at $(x_0,y_0)$), and we need to multiply it by an area (as in $(1)$) to get a probability from it. With that as prologue, consider the case when $Y = \alpha X + \beta$. Now, the random point $(X,Y)$ is constrained to lie on the straight line $y = \alpha x + \beta$ in the $x$-$y$ plane. Consequently, $X$ and $Y$ do not enjoy a joint density because all the probability mass lies on the straight line which has zero area. (Remember that old shibboleth about a line having zero width that you learned in muddle school?) So, we cannot write something like $(1)$. The probability mass is all there; it lies along the straight line $y = \alpha x + \beta$, but its joint density (in terms of mass per unit area) is infinite along that straight line. So, now what? Well, the trick is to understand that we really have just one random variable, and questions about $(X,Y)$ can be translated into questions about just $X$, and answered in terms of $X$ alone. For example, (with $\alpha > 0$) $$F_{X,Y}(x_0,y_0) = P\{X\leq x_0, Y\leq y_0\} = P\{X\leq x_0, \alpha X + \beta \leq y_0\} = P\left\{X \leq \min\left(x_0, \frac{y_0-\beta}{\alpha}\right)\right\}.$$ Note that all the usual rules apply even though $X$ and $Y$ do not have a joint density. For example, $$\operatorname{cov}(X,Y)= \operatorname{cov}(X,\alpha X+\beta) = \alpha \operatorname{var}(X)$$ and so on. Finally, if you are still paying attention, if $n$ jointly normal random variables $X_i$ have a singular covariance matrix $\Sigma$ and mean vector $\mathbf m$, then that means that there are $m < n$ independent standard normal random variables $Y_j$ such that $$(X_1,X_2,\ldots, X_n) = (Y_1,Y_2,\ldots, Y_m)\mathbf A + \mathbf m$$ where $\mathbf A$ is a $m\times n$ matrix, and all questions about $(X_1,X_2,\ldots, X_n)$ can be stated in terms of $(Y_1,Y_2,\ldots, Y_m)$ and answered in terms of these iid random variables. Note that $\Sigma = \mathbf A^T\mathbf A$.
Understanding degenerate multivariate normal distribution A joint density function, say of two random variables $X$ and $Y$, is $f_{X,Y}(x,y)$ is an ordinary function of two real variables and the meaning that we ascribe to it is that if $\mathcal B$ is a re
27,778
limit of $x \left[1-F(x) \right]$ as $x \to \infty$
Assuming that the expectation exists and for convenience that the random variable has a density (equivalently that it is absolutely continuous with respect to the Lebesgue measure), we are going to show that $$\lim_{x\to\infty} x \left [1-F(x)\right]=0$$ The existence of the expectation implies that the distribution is not very fat-tailed, unlike the Cauchy distribution for instance. Since the expectation exists, we have that $$E(X)=\lim_{u\to \infty} \int_{-\infty}^u xf(x) \mathrm{dx} = \int_{-\infty}^{\infty} x f(x) \mathrm{dx} < \infty$$ and this is always well-defined. Now note that for $u \geq 0$, $$\int_{u}^{\infty} x f(x) \mathrm{dx} \geq u \int_{u}^{\infty} f(x) \mathrm{dx} = u \left[1-F(u) \right]$$ and from these two it follows that $$\lim_{u \to \infty} \left[ E(X) - \int_{-\infty}^u xf(x) \mathrm{dx} \right] = \lim_{u\to \infty} \int_{u}^{\infty} x f(x) \mathrm{dx}=0$$ as in the limit the term $\int_{-\infty}^u xf(x) \mathrm{dx}$ approaches the expectation. By our inequality and the nonnonegativity of the integrand then, we have our result. Hope this helps.
limit of $x \left[1-F(x) \right]$ as $x \to \infty$
Assuming that the expectation exists and for convenience that the random variable has a density (equivalently that it is absolutely continuous with respect to the Lebesgue measure), we are going to sh
limit of $x \left[1-F(x) \right]$ as $x \to \infty$ Assuming that the expectation exists and for convenience that the random variable has a density (equivalently that it is absolutely continuous with respect to the Lebesgue measure), we are going to show that $$\lim_{x\to\infty} x \left [1-F(x)\right]=0$$ The existence of the expectation implies that the distribution is not very fat-tailed, unlike the Cauchy distribution for instance. Since the expectation exists, we have that $$E(X)=\lim_{u\to \infty} \int_{-\infty}^u xf(x) \mathrm{dx} = \int_{-\infty}^{\infty} x f(x) \mathrm{dx} < \infty$$ and this is always well-defined. Now note that for $u \geq 0$, $$\int_{u}^{\infty} x f(x) \mathrm{dx} \geq u \int_{u}^{\infty} f(x) \mathrm{dx} = u \left[1-F(u) \right]$$ and from these two it follows that $$\lim_{u \to \infty} \left[ E(X) - \int_{-\infty}^u xf(x) \mathrm{dx} \right] = \lim_{u\to \infty} \int_{u}^{\infty} x f(x) \mathrm{dx}=0$$ as in the limit the term $\int_{-\infty}^u xf(x) \mathrm{dx}$ approaches the expectation. By our inequality and the nonnonegativity of the integrand then, we have our result. Hope this helps.
limit of $x \left[1-F(x) \right]$ as $x \to \infty$ Assuming that the expectation exists and for convenience that the random variable has a density (equivalently that it is absolutely continuous with respect to the Lebesgue measure), we are going to sh
27,779
limit of $x \left[1-F(x) \right]$ as $x \to \infty$
For any nonnegative random variable $Y$ , we have (see (21.9) of Billingsley's Probability and measure): $$E[Y] = \int Y dP = \int_0^\infty P[Y > t] dt. \tag{$*$}$$ For $M > 0$, substituting $Y$ in $(*)$ with $XI_{[X > M]}$ to \begin{align} \int XI_{[X > M]} dP &= \int_0^\infty P[XI_{[X > M]} > t]dt \\ &= \int_0^M P[XI_{[X > M]} > t]dt + \int_M^\infty P[XI_{[X > M]} > t]dt \\ &= MP[X > M] + \int_M^\infty P[X > t] dt \geq MP[X > M]. \tag{$**$} \end{align} The third equality holds because for every $t \in [0, M]$, $\{XI_{[X > M]} > t\} = \{X > M\}$, and for every $t > M$, $\{XI_{[X > M]} > t\} = \{X > t\}$. To wit, say, if we want to show for every $t \in [0, M]$, $\{XI_{[X > M]} > t\} = \{X > M\}$, just note \begin{align} \{XI_{[X > M]} > t\} &= (\{XI_{[X > M]} > t\} \cap \{X > M\}) \cup (\{XI_{[X > M]} > t\} \cap \{X \leq M\}) \\ &= (\{X > t\} \cap \{X > M\}) \cup (\{0 > t\} \cap \{X \leq M\}) \\ &= \{X > M\} \cup \varnothing = \{X > M\}. \end{align} Similarly it is easy to show for every $t > M$, $\{XI_{[X > M]} > t\} = \{X > t\}$. Assume that $X$ is integrable (i.e., $E[|X|]< \infty$), then the left hand side of $(**)$ converges to $0$ as $M \to \infty$, by the dominated convergence theorem. It then follows that $$0 \geq \limsup_{M \to \infty} MP[X > M] \geq \liminf_{M \to \infty} MP[X > M] \geq 0.$$ Hence the result follows. Remark: This proof uses some measure theory, which I think is worthwhile as the proof assuming the existence of densities doesn't address a majority class of random variables, for example, discrete random variables such as binomial and Poisson.
limit of $x \left[1-F(x) \right]$ as $x \to \infty$
For any nonnegative random variable $Y$ , we have (see (21.9) of Billingsley's Probability and measure): $$E[Y] = \int Y dP = \int_0^\infty P[Y > t] dt. \tag{$*$}$$ For $M > 0$, substituting $Y$ in $(
limit of $x \left[1-F(x) \right]$ as $x \to \infty$ For any nonnegative random variable $Y$ , we have (see (21.9) of Billingsley's Probability and measure): $$E[Y] = \int Y dP = \int_0^\infty P[Y > t] dt. \tag{$*$}$$ For $M > 0$, substituting $Y$ in $(*)$ with $XI_{[X > M]}$ to \begin{align} \int XI_{[X > M]} dP &= \int_0^\infty P[XI_{[X > M]} > t]dt \\ &= \int_0^M P[XI_{[X > M]} > t]dt + \int_M^\infty P[XI_{[X > M]} > t]dt \\ &= MP[X > M] + \int_M^\infty P[X > t] dt \geq MP[X > M]. \tag{$**$} \end{align} The third equality holds because for every $t \in [0, M]$, $\{XI_{[X > M]} > t\} = \{X > M\}$, and for every $t > M$, $\{XI_{[X > M]} > t\} = \{X > t\}$. To wit, say, if we want to show for every $t \in [0, M]$, $\{XI_{[X > M]} > t\} = \{X > M\}$, just note \begin{align} \{XI_{[X > M]} > t\} &= (\{XI_{[X > M]} > t\} \cap \{X > M\}) \cup (\{XI_{[X > M]} > t\} \cap \{X \leq M\}) \\ &= (\{X > t\} \cap \{X > M\}) \cup (\{0 > t\} \cap \{X \leq M\}) \\ &= \{X > M\} \cup \varnothing = \{X > M\}. \end{align} Similarly it is easy to show for every $t > M$, $\{XI_{[X > M]} > t\} = \{X > t\}$. Assume that $X$ is integrable (i.e., $E[|X|]< \infty$), then the left hand side of $(**)$ converges to $0$ as $M \to \infty$, by the dominated convergence theorem. It then follows that $$0 \geq \limsup_{M \to \infty} MP[X > M] \geq \liminf_{M \to \infty} MP[X > M] \geq 0.$$ Hence the result follows. Remark: This proof uses some measure theory, which I think is worthwhile as the proof assuming the existence of densities doesn't address a majority class of random variables, for example, discrete random variables such as binomial and Poisson.
limit of $x \left[1-F(x) \right]$ as $x \to \infty$ For any nonnegative random variable $Y$ , we have (see (21.9) of Billingsley's Probability and measure): $$E[Y] = \int Y dP = \int_0^\infty P[Y > t] dt. \tag{$*$}$$ For $M > 0$, substituting $Y$ in $(
27,780
How Does Kriging Interpolation work?
This answer consists of an introductory section I wrote recently for a paper describing a (modest) spatio-temporal extension of "Universal Kriging" (UK), which itself is a modest generalization of "Ordinary Kriging." It has three sub-sections: Theory gives a statistical model and assumptions; Estimation briefly reviews least-squares parameter estimation; and Prediction shows how kriging fits into the Generalized Least Squares (GLS) framework. I have made an effort to adopt notation familiar to statisticians, especially visitors to this site, and to use concepts that are well-explained here. To summarize, kriging is the Best Linear Unbiased Prediction (BLUP) of a random field. What this means is that the predicted value at any unsampled location is obtained as a linear combination of the values and covariates observed at sampled locations. The (unknown, random) value there has an assumed correlation with the sample values (and the sample values are correlated among themselves). This correlation information is readily translated into the variance of the prediction. One chooses coefficients in the linear combination (the "kriging weights") that make this variance as small as possible, subject to a condition of zero bias in the prediction. The details follow. Theory UK comprises two procedures – one of estimation and the other of prediction – carried out in the context of a GLS model for a study area. The GLS model supposes that the sample data $z_i,\ (i = 1, 2, ..., n)$ are the result of random deviations around a trend and that those deviations are correlated. A trend is meant in the general sense of a value that can be determined by a linear combination of $p$ unknown coefficients (parameters) $\beta=(\beta_1,\beta_2,\ldots,\beta_p)^\prime$. (Throughout this post, the prime $^\prime$ denotes matrix transpose and all vectors are considered column vectors.) At any location within a study area there is available a tuple of numerical attributes $\mathbf y = (y_1, y_2, \ldots, y_p)^\prime$ termed “independent variables” or “covariates.” (Typically $y_1 = 1$ is a “constant term,” $y_2$ and $y_3$ may be spatial coordinates, and the additional $y_i$ may represent spatial information as well as other ancillary information that is available at all locations in the study area, such as porosity of an aquifer or distance to a pumping well.) At each data location $i$, in addition to its covariates $y_i = (y_{i1}, y_{i2}, \ldots, y_{ip})^\prime$, the associated observation $z_i$ is considered to be a realization of a random variable $Z_i$. In contrast, the $y_i$ are thought of as values determined by or characterizing the points or small regions represented by the observations (the data “supports”). The $y_i$ are not considered to be realizations of random variables and are required to be unrelated to the properties of any of the $Z_i$. The linear combination $$ {\bf{E}}\left[ {Z_i } \right] = {\bf{y'}}_i {\bf{\beta }} = y_{i1} \beta _1 + y_{i2} \beta _2 + \cdots + y_{ip} \beta _p $$ expresses the expected value of $Z_i$ in terms of the parameters $\beta$, which is the value of the trend at location $i$. The estimation process uses the data to find values $\hat\beta_i$ that represent the unknown parameters $\beta_i$, whereas the prediction process uses the data at locations $i = 1, 2, \ldots, n$ to compute a value at an un-sampled location, which is here indexed as $i = 0$. The targets of estimation are fixed (i.e., non-random) parameters whereas the target of prediction is random, because the value $z_0$ includes a random fluctuation around its trend $y_0^\prime\beta$. Typically, predictions are made for multiple locations using the same data by varying location $0$. For example, predictions are often made to map out a surface along a regular grid of points suitable for contouring. Estimation Classical kriging assumes the random fluctuations $Z_i$ have expected values of zero and their covariances are known. Write the covariance between $Z_i$ and $Z_j$ as $c_{ij}$. Using this covariance, estimation is performed using GLS. Its solution is the following: $$ \hat\beta=\bf{Hz},\ {\bf{H}} = \left( {{\bf{Y'C}}^{{\bf{ - 1}}} {\bf{Y}}} \right)^{{\bf{ - 1}}} {\bf{Y'C}}^{{\bf{ - 1}}} $$ where ${\bf {z}} = (z_1, z_2, \ldots, z_n)$ is the $n$-vector of the observations, ${\bf Y} = (y_{ij})$ (the “design matrix”) is the $n$ by $p$ matrix whose rows are the vectors $y_i^\prime, 1 \le i \le n$, and $\mathbf C = (c_{ij})$ is the $n$-by-$n$ covariance matrix which is assumed to be invertible (Draper & Smith (1981), section 2.11). The $p$ by $n$ matrix $\mathbf H$, which projects the data $\mathbf z$ onto the parameter estimates $\hat \beta$, is called the “hat matrix.” The formulation of $\hat\beta$ as the application of the hat matrix to the data explicitly shows how the parameter estimates depend linearly on the data. The covariances $\mathbf C = (c_{ij})$ are classically computed using a variogram which gives the covariance in terms of the data locations, though it is immaterial how the covariance is actually calculated. Prediction UK similarly predicts $z_0$ by means of a linear combination of the data $$ \hat z_0 = \lambda _1 z_1 + \lambda _2 z_2 + \cdots + \lambda _n z_n = {\bf{\lambda 'z}}. $$ The $\lambda_i$ are called the “kriging weights” for the prediction of $z_0$. UK accomplishes this prediction of $z_0$ by meeting two criteria. First, the prediction should be unbiased, which is expressed by requiring that the linear combination of the random variables $Z_i$ equals $Z_0$ on average: $$ 0 = {\bf{E}}\left[ {\hat Z_0 - Z_0 } \right] = {\bf{E}}\left[ {{\bf{\lambda 'Z}} - Z_0 } \right]. $$ This expectation is taken over the joint $n+1$-variate distribution of $Z_0$ and $\mathbf Z = (Z_1, Z_2, \ldots, Z_n)$. Linearity of expectation together with the trend assumption (1) implies: $$ \eqalign{ 0 &= {\bf{E}}\left[ {{\bf{\lambda 'Z}} - Z_0 } \right] = {\bf{\lambda 'E}}\left[ {\bf{Z}} \right] - {\bf{E}}\left[ {Z_0 } \right] = {\bf{\lambda '}}\left( {{\bf{Y\beta }}} \right) - {\bf{y'}}_0 {\bf{\beta }} = \left( {{\bf{\lambda 'Y}} - {\bf{y'}}_0 } \right){\bf{\beta }}\\ &= {\bf{\beta '}}\left( {{\bf{Y'\lambda }} - {\bf{y}}_0 } \right) }$$ no matter what $\beta$ may be. This will be the case provided that $$\hat{\mathbf Y}^\prime \lambda = \mathbf{y}_0.$$ Among all the possible solutions of this underdetermined system of equations, UK chooses $\lambda$ to minimize the variance of the prediction error $\hat Z_0 - Z_0$. In this sense, UK is “best” among all unbiased linear predictors. Because this last relationship implies the prediction error is zero on average, the variance is simply the expectation of the squared prediction error: $$ {\rm{Var}}\left( {\hat Z_0 - Z_0 } \right) = {\bf{E}}\left[ {\left( {\hat Z_0 - Z_0 } \right)^2 } \right] = {\bf{E}}\left[ {\left( {{\bf{\lambda 'Z}} - Z_0 } \right)^2 } \right] = c_{00} - 2{\bf{\lambda 'c}}_0 + {\bf{\lambda 'C\lambda }}$$ where $\mathbf c_0 = (c_{01}, c_{02}, \ldots, c_{0n})^\prime$ is the vector of covariances between $Z_0$ and the $Z_i,\ i \ge 1$, and $c_{00}$ is the variance of $Z_0$. To minimize the variance, differentiate with respect to $\lambda$ and introduce a vector of $p$ Lagrange multipliers $\mu$ to incorporate into the constraint $\hat{\mathbf Y}^\prime \lambda = \mathbf{y}_0$. This yields a system of $n+p$ linear equations, written in block-matrix form as $$ \left( {\begin{array}{*{20}c} {\bf{C}} & {\bf{Y}} \\ {{\bf{Y'}}} & {\bf{0}} \\ \end{array}} \right)\left( {\begin{array}{*{20}c} {\bf{\lambda }} \\ {\bf{\mu }} \\ \end{array}} \right) = \left( {\begin{array}{*{20}c} {{\bf{c}}_{\bf{0}} } \\ {{\bf{y}}_{\bf{0}} } \\ \end{array}} \right)$$ where $\mathbf 0$ represents a $p$ by $p$ matrix of zeros. Writing $\mathbf 1$ for the $n$ by $n$ identity matrix, the unique solution for $\lambda$ is given by $$ {\bf{\lambda }} = {\bf{H'y}}_0 + {\bf{C}}^{ - 1} \left( {{\bf{1}} - {\bf{YH}}} \right){\bf{c}}_0. $$ (Readers familiar with multiple regression may find it instructive to compare this solution to the covariance-based solution of the ordinary least squares Normal equations, which looks almost exactly the same, but with no Lagrange multiplier terms.) This relationship presents the kriging weights, $\lambda$, as the sum of a term depending only on the hat matrix and the covariates at the prediction location $[\mathbf H^\prime\, \mathbf y_0]$, plus a term depending on the covariances among the data and the predictand, $Z_0$. Substituting it into the right hand side of the variance equation yields the kriging prediction variance, which can be used to construct prediction limits around $\hat z_0$.
How Does Kriging Interpolation work?
This answer consists of an introductory section I wrote recently for a paper describing a (modest) spatio-temporal extension of "Universal Kriging" (UK), which itself is a modest generalization of "Or
How Does Kriging Interpolation work? This answer consists of an introductory section I wrote recently for a paper describing a (modest) spatio-temporal extension of "Universal Kriging" (UK), which itself is a modest generalization of "Ordinary Kriging." It has three sub-sections: Theory gives a statistical model and assumptions; Estimation briefly reviews least-squares parameter estimation; and Prediction shows how kriging fits into the Generalized Least Squares (GLS) framework. I have made an effort to adopt notation familiar to statisticians, especially visitors to this site, and to use concepts that are well-explained here. To summarize, kriging is the Best Linear Unbiased Prediction (BLUP) of a random field. What this means is that the predicted value at any unsampled location is obtained as a linear combination of the values and covariates observed at sampled locations. The (unknown, random) value there has an assumed correlation with the sample values (and the sample values are correlated among themselves). This correlation information is readily translated into the variance of the prediction. One chooses coefficients in the linear combination (the "kriging weights") that make this variance as small as possible, subject to a condition of zero bias in the prediction. The details follow. Theory UK comprises two procedures – one of estimation and the other of prediction – carried out in the context of a GLS model for a study area. The GLS model supposes that the sample data $z_i,\ (i = 1, 2, ..., n)$ are the result of random deviations around a trend and that those deviations are correlated. A trend is meant in the general sense of a value that can be determined by a linear combination of $p$ unknown coefficients (parameters) $\beta=(\beta_1,\beta_2,\ldots,\beta_p)^\prime$. (Throughout this post, the prime $^\prime$ denotes matrix transpose and all vectors are considered column vectors.) At any location within a study area there is available a tuple of numerical attributes $\mathbf y = (y_1, y_2, \ldots, y_p)^\prime$ termed “independent variables” or “covariates.” (Typically $y_1 = 1$ is a “constant term,” $y_2$ and $y_3$ may be spatial coordinates, and the additional $y_i$ may represent spatial information as well as other ancillary information that is available at all locations in the study area, such as porosity of an aquifer or distance to a pumping well.) At each data location $i$, in addition to its covariates $y_i = (y_{i1}, y_{i2}, \ldots, y_{ip})^\prime$, the associated observation $z_i$ is considered to be a realization of a random variable $Z_i$. In contrast, the $y_i$ are thought of as values determined by or characterizing the points or small regions represented by the observations (the data “supports”). The $y_i$ are not considered to be realizations of random variables and are required to be unrelated to the properties of any of the $Z_i$. The linear combination $$ {\bf{E}}\left[ {Z_i } \right] = {\bf{y'}}_i {\bf{\beta }} = y_{i1} \beta _1 + y_{i2} \beta _2 + \cdots + y_{ip} \beta _p $$ expresses the expected value of $Z_i$ in terms of the parameters $\beta$, which is the value of the trend at location $i$. The estimation process uses the data to find values $\hat\beta_i$ that represent the unknown parameters $\beta_i$, whereas the prediction process uses the data at locations $i = 1, 2, \ldots, n$ to compute a value at an un-sampled location, which is here indexed as $i = 0$. The targets of estimation are fixed (i.e., non-random) parameters whereas the target of prediction is random, because the value $z_0$ includes a random fluctuation around its trend $y_0^\prime\beta$. Typically, predictions are made for multiple locations using the same data by varying location $0$. For example, predictions are often made to map out a surface along a regular grid of points suitable for contouring. Estimation Classical kriging assumes the random fluctuations $Z_i$ have expected values of zero and their covariances are known. Write the covariance between $Z_i$ and $Z_j$ as $c_{ij}$. Using this covariance, estimation is performed using GLS. Its solution is the following: $$ \hat\beta=\bf{Hz},\ {\bf{H}} = \left( {{\bf{Y'C}}^{{\bf{ - 1}}} {\bf{Y}}} \right)^{{\bf{ - 1}}} {\bf{Y'C}}^{{\bf{ - 1}}} $$ where ${\bf {z}} = (z_1, z_2, \ldots, z_n)$ is the $n$-vector of the observations, ${\bf Y} = (y_{ij})$ (the “design matrix”) is the $n$ by $p$ matrix whose rows are the vectors $y_i^\prime, 1 \le i \le n$, and $\mathbf C = (c_{ij})$ is the $n$-by-$n$ covariance matrix which is assumed to be invertible (Draper & Smith (1981), section 2.11). The $p$ by $n$ matrix $\mathbf H$, which projects the data $\mathbf z$ onto the parameter estimates $\hat \beta$, is called the “hat matrix.” The formulation of $\hat\beta$ as the application of the hat matrix to the data explicitly shows how the parameter estimates depend linearly on the data. The covariances $\mathbf C = (c_{ij})$ are classically computed using a variogram which gives the covariance in terms of the data locations, though it is immaterial how the covariance is actually calculated. Prediction UK similarly predicts $z_0$ by means of a linear combination of the data $$ \hat z_0 = \lambda _1 z_1 + \lambda _2 z_2 + \cdots + \lambda _n z_n = {\bf{\lambda 'z}}. $$ The $\lambda_i$ are called the “kriging weights” for the prediction of $z_0$. UK accomplishes this prediction of $z_0$ by meeting two criteria. First, the prediction should be unbiased, which is expressed by requiring that the linear combination of the random variables $Z_i$ equals $Z_0$ on average: $$ 0 = {\bf{E}}\left[ {\hat Z_0 - Z_0 } \right] = {\bf{E}}\left[ {{\bf{\lambda 'Z}} - Z_0 } \right]. $$ This expectation is taken over the joint $n+1$-variate distribution of $Z_0$ and $\mathbf Z = (Z_1, Z_2, \ldots, Z_n)$. Linearity of expectation together with the trend assumption (1) implies: $$ \eqalign{ 0 &= {\bf{E}}\left[ {{\bf{\lambda 'Z}} - Z_0 } \right] = {\bf{\lambda 'E}}\left[ {\bf{Z}} \right] - {\bf{E}}\left[ {Z_0 } \right] = {\bf{\lambda '}}\left( {{\bf{Y\beta }}} \right) - {\bf{y'}}_0 {\bf{\beta }} = \left( {{\bf{\lambda 'Y}} - {\bf{y'}}_0 } \right){\bf{\beta }}\\ &= {\bf{\beta '}}\left( {{\bf{Y'\lambda }} - {\bf{y}}_0 } \right) }$$ no matter what $\beta$ may be. This will be the case provided that $$\hat{\mathbf Y}^\prime \lambda = \mathbf{y}_0.$$ Among all the possible solutions of this underdetermined system of equations, UK chooses $\lambda$ to minimize the variance of the prediction error $\hat Z_0 - Z_0$. In this sense, UK is “best” among all unbiased linear predictors. Because this last relationship implies the prediction error is zero on average, the variance is simply the expectation of the squared prediction error: $$ {\rm{Var}}\left( {\hat Z_0 - Z_0 } \right) = {\bf{E}}\left[ {\left( {\hat Z_0 - Z_0 } \right)^2 } \right] = {\bf{E}}\left[ {\left( {{\bf{\lambda 'Z}} - Z_0 } \right)^2 } \right] = c_{00} - 2{\bf{\lambda 'c}}_0 + {\bf{\lambda 'C\lambda }}$$ where $\mathbf c_0 = (c_{01}, c_{02}, \ldots, c_{0n})^\prime$ is the vector of covariances between $Z_0$ and the $Z_i,\ i \ge 1$, and $c_{00}$ is the variance of $Z_0$. To minimize the variance, differentiate with respect to $\lambda$ and introduce a vector of $p$ Lagrange multipliers $\mu$ to incorporate into the constraint $\hat{\mathbf Y}^\prime \lambda = \mathbf{y}_0$. This yields a system of $n+p$ linear equations, written in block-matrix form as $$ \left( {\begin{array}{*{20}c} {\bf{C}} & {\bf{Y}} \\ {{\bf{Y'}}} & {\bf{0}} \\ \end{array}} \right)\left( {\begin{array}{*{20}c} {\bf{\lambda }} \\ {\bf{\mu }} \\ \end{array}} \right) = \left( {\begin{array}{*{20}c} {{\bf{c}}_{\bf{0}} } \\ {{\bf{y}}_{\bf{0}} } \\ \end{array}} \right)$$ where $\mathbf 0$ represents a $p$ by $p$ matrix of zeros. Writing $\mathbf 1$ for the $n$ by $n$ identity matrix, the unique solution for $\lambda$ is given by $$ {\bf{\lambda }} = {\bf{H'y}}_0 + {\bf{C}}^{ - 1} \left( {{\bf{1}} - {\bf{YH}}} \right){\bf{c}}_0. $$ (Readers familiar with multiple regression may find it instructive to compare this solution to the covariance-based solution of the ordinary least squares Normal equations, which looks almost exactly the same, but with no Lagrange multiplier terms.) This relationship presents the kriging weights, $\lambda$, as the sum of a term depending only on the hat matrix and the covariates at the prediction location $[\mathbf H^\prime\, \mathbf y_0]$, plus a term depending on the covariances among the data and the predictand, $Z_0$. Substituting it into the right hand side of the variance equation yields the kriging prediction variance, which can be used to construct prediction limits around $\hat z_0$.
How Does Kriging Interpolation work? This answer consists of an introductory section I wrote recently for a paper describing a (modest) spatio-temporal extension of "Universal Kriging" (UK), which itself is a modest generalization of "Or
27,781
How to represent kWh usage by year against average temperature?
I would like to suggest that the important thing is to develop a physically realistic, practically useful model of energy cost. That will work better to detect changes in costs than any visualization of the raw data can accomplish. By comparing this to the solution offered on SO, we have a very nice case study in the difference between fitting a curve to data and performing a meaningful statistical analysis. (This suggestion is based on having fit such a model to my own household usage a decade ago and applying it to track changes during that period. Note that once the model is fit, it can easily be calculated in a spreadsheet for the purpose of tracking changes, so we should not feel limited by the (in)capabilities of spreadsheet software.) For these data, such a physically plausible model produces a substantially different picture of energy costs and usage patterns than a simple alternative model (a quadratic least-squares fit of daily usage against monthly mean temperature). Consequently, the simpler model cannot be considered a reliable tool for understanding, predicting, or comparing energy use patterns. Analysis Newton's Law of Cooling says that, to a good approximation, the cost of heating (during a unit of time) should be directly proportional to the difference between the outside temperature $t$ and the inside temperature $t_0$. Let that constant of proportionality be $-\alpha$. The cost of cooling also should be proportional to that temperature difference, with a similar--but not necessarily identical--constant of proportionality $\beta$. (Each of these is determined by the insulating capability of the house as well as the efficiencies of the heating and cooling systems.) Estimating $\alpha$ and $\beta$ (which are expressed as kilowatts (or dollars) per degree per unit time) are among the most important things that can be accomplished, because they enable us to predict future costs, as well as measure the efficiencies of the house and its energy systems. Because these data are total electricity usage, they include non-heating costs such as lighting, cooking, computing, and entertainment. Also of interest is an estimate of this average base energy usage (per unit time), which I will call $\gamma$: it provides a floor on how much energy can be saved and enables predictions of future costs when efficiency improvements of known magnitude are made. (For instance, after four years I replaced a furnace by one claimed to be 30% more efficient--and indeed it was exactly that.) Finally, as a (gross) approximation I will assume the house is maintained at a nearly constant temperature $t_0$ throughout the year. (In my personal model I assume two temperatures, $t_0 \le t_1$, for winter and summer respectively--but there aren't yet enough data in this example to estimate both of them reliably and they would be pretty close anyway.) Knowing this value helps one evaluate the consequences of maintaining the house at a slightly different temperature, which is one important energy-saving option. The data present a singularly important and interesting complication: they reflect total costs during periods when outside temperatures fluctuate--and they fluctuate a lot, usually about one-quarter of their annual range each month. As we will see, this creates a substantial difference between the correct underlying instantaneous model just described and the values of the monthly totals. The effect is especially pronounced in the in-between months, where both (or neither) heating and cooling take place. Any model that does not account for this variation would mistakenly "think" energy costs should be at the base rate $\gamma$ during any month with an average temperature of $t_0$, but the reality is far different. We don't (readily) have detailed information about the monthly temperature fluctuations apart from their ranges. I propose handling that with an approach that is practical, but a tiny bit inconsistent. Except at the extreme temperatures, each month will usually experience gradual increases or decreases in temperature. This means we can take the distribution to be approximately uniform. When the range of a uniform variable has length $L$, that variable has a standard deviation of $s = L/\sqrt{6}$. I use this relationship to convert the ranges (from Avg. Low to Avg. High) to standard deviations. But then, essentially to obtain a nicely behaved model, I will downweight the variation at the ends of these ranges by using Normal distributions (with these estimated SDs and means given by Avg. Temp). Finally, we must standardize the data to a common unit time. Although that's already present in the Daily kWh Avg. variable, it lacks precision, so let's instead divide the total by the number of days in order to gain back the lost precision. Thus, the model of unit-time cooling costs $Y$ at an outdoor temperature of $t$ is $$y(t) = \gamma + \alpha(t-t_0)I(t\lt t_0) + \beta(t-t_0)I(t\gt t_0) + \varepsilon(t)$$ where $I$ is the indicator function and $\varepsilon$ represents everything not otherwise explicitly captured in this model. It has four parameters to estimate: $\alpha,\beta,\gamma$, and $t_0$. (If you're really sure of $t_0$ you could fix its value rather than estimating it.) The reported total costs during a time period $x_0$ to $x_1$ when the temperature $t(x)$ varies with time $x$ will therefore be $$\eqalign{ &\text{Cost}(x_0,x_1) = \int_{x_0}^{x_1} y(t)dt \\ &=\int_{x_0}^{x_1} \left(\gamma + \alpha(t(x)-t_0)I(t(x)\lt t_0) + \beta(t(x)-t_0)I(t(x)\gt t_0) + \varepsilon(t(x))\right) t^\prime(x) dx. }$$ If the model is any good at all, the fluctuations in $\varepsilon(t)$ ought to average to a value $\bar\varepsilon$ close to zero and will appear to randomly change month to month. Approximating the fluctuations in $t(x)$ with a Normal distribution of mean $\bar{t}$ (the monthly average) and standard deviation $s(\bar t)$ (as previously given from the monthly range) and doing the integrals yields $$\bar{y}(\bar{t}) = \gamma + (\beta-\alpha)s(\bar t)^2 \phi_s(\bar t-t_0) + (\bar{t}-t_0)\left(\beta + (\alpha-\beta)\Phi_s(t_0 - \bar{t})\right) + \bar\varepsilon(\bar{t}).$$ In this formula, $\Phi_s$ is the cumulative distribution of a Normal variate of zero mean and standard deviation $s(\bar t)$; $\phi$ is its density. Model fitting This model, although expressing a nonlinear relationship between costs and temperature, is nevertheless linear in the variables $\alpha,\beta,$ and $\gamma$. However, since it is nonlinear in $t_0$, and $t_0$ is not known, we need a nonlinear fitting procedure. To illustrate, I simply dumped it into a likelihood maximizer (using R for the computation), assuming the $\bar\varepsilon$ are independent and identically distributed, with normal distributions of mean zero and common standard deviation $\sigma$. For these data, the estimates are $$(\hat\alpha,\hat\beta,\hat\gamma,\hat {t_0}, \hat\sigma) = (-1.489, 1.371, 10.2, 63.4, 1.80).$$ This means: The cost to heat is approximately $1.49$ kWh/day/degree F. The cost to cool is approximately $1.37$ kWh/day/degree F. Cooling is a little more efficient. The base (non-heating/cooling) energy usage is $10.2$ kWh/day. (This number is fairly uncertain; additional data will help pin it down better.) The house is maintained at a temperature near $63.4$ degrees F. The other variations not explicitly accounted for in the model have a standard deviation of $1.80$ kWh/day. Confidence intervals and other quantitative expressions of uncertainty in these estimates can be obtained in standard ways with the maximum likelihood machinery. Visualization To illustrate this model, the following figure plots the data, the underlying model, the fit to the monthly averages, and a simple least-squares quadratic fit. The monthly data are shown as dark crosses. The horizontal gray lines on which they lie show the monthly temperature ranges. Our underlying model, reflecting Newton's law, is shown by the red and blue line segments meeting at a temperature of $t_0$. Our fit to the data is not a curve, because it depends on the temperature ranges. It is shown therefore as individual solid blue and red points. (Nevertheless, because the monthly ranges do not vary a lot, these points do seem to trace out a curve--almost the same as the dashed quadratic curve.) Finally, the dashed curve is the quadratic least squares fit (to the dark crosses). Notice how much the fits depart from the underlying (instantaneous) model, especially in the middle temperatures! This is the effect of monthly averaging. (Think of the heights of the red and blue lines being "smeared" across each horizontal gray segment. At extreme temperatures everything is centered at the lines, but at middle temperatures the two sides of the "V" get averaged together, reflecting the need for heating at some times and cooling at other times during the month.) Model comparison The two fits--the one painstakingly developed here and the simple, easy, quadratic fit--agree closely both with each other and with the data points. The quadratic fit is not quite as good, but it's still decent: its adjusted mean residual (for three parameters) is $2.07$ kWh/day, whereas the adjusted mean residual of the Newton's law model (for four parameters) is $1.97$ kWh/day, about 5% lower. If all you want to do is plot a curve through the data points, then the simplicity and relative fidelity of the quadratic fit would recommend it. However, the quadratic fit is utterly useless for learning what's going on! Its formula, $$\bar y(\bar t) = 219.95 - 6.241 \bar t + 0.04879 (\bar t)^2,$$ reveals nothing of use directly. In all fairness, we could analyze it a little: This is a parabola with vertex at $\hat t_0 = 6.241/(2\times 0.04879) = 64.0$ degrees F. We could take this as an estimate of the constant house temperature. It does not differ significantly from our first estimate of $63.4$ degrees. However, the predicted cost at this temperature is $219.95 - 6.241(63.4) + 0.04879(63.4)^2 = 20.4$ kWh/day. This is twice the base energy usage fit with Newton's Law. The marginal cost of heating or cooling is obtained from the absolute value of the derivative, $\bar{y}^\prime(\bar t) = -6.241 + 2(0.04879)\bar{t}$. For example, using this formula we would estimate the cost of heating a house when the outside temperature is $90$ degrees as $-6.241 + 2(0.04879)(90) = 2.54$ kWh/day/degree F. This is twice the value estimated with Newton's Law. Similarly, the cost to heat the house at an outdoor temperature of $32$ degrees would be estimated as $|-6.241 + 2(0.04879)(32)| = 3.12$ kWh/day/degree F. This is more than twice the value estimated with Newton's Law. At the middle temperatures, the quadratic fit errs in the other direction. Indeed, at its vertex in the $60$ to $68$ degree range it predicts nearly zero marginal heating or cooling costs, even though this mean temperature comprises days as cool as $50$ degrees and as warm as $78$ degrees. (Few people reading this post will still have their heat off at $50$ degrees (=$10$ degrees C)!) In brief, although it looks almost as good in the visualization, the quadratic fit grossly errs in estimating fundamental quantities of interest related to energy usage. Its use for evaluating changes in usage is therefore problematic and should be discouraged. Computation This R code performed all the computing and plotting. It can readily be adapted to similar datasets. # # Read and process the raw data. # x <- read.csv("F:/temp/energy.csv") x$Daily <- x$Usage / x$Length x <- x[order(x$Temp), ] #pairs(x) # # Fit a quadratic curve. # fit.quadratic <- lm(Daily ~ Temp+I(Temp^2), data=x) # par(mfrow=c(2,2)) # plot(fit.quadratic) # par(mfrow=c(1,1)) # # Fit a simple but realistic heating-cooling model with maximum likelihood. # response <- function(theta, x, s) { alpha <- theta[1]; beta <- theta[2]; gamma <- theta[3]; t.0 <- theta[4] x <- x - t.0 gamma + (beta-alpha)*s^2*dnorm(x, 0, s) + x*(beta + (alpha-beta)*pnorm(-x, 0, s)) } log.L <- function(theta, y, x, s) { # theta = (alpha, beta, gamma, t.0, sigma) # x = time # s = estimated SD # y = response y.hat <- response(theta, x, s) sigma <- theta[5] sum((((y - y.hat) / sigma) ^2 + log(2 * pi * sigma^2))/2) } theta <- c(alpha=-1, beta=5/4, gamma=20, t.0=65, sigma=2) # Initial guess x$Spread <- (x$Temp.high - x$Temp.low)/sqrt(6) # Uniform estimate fit <- nlm(log.L, theta, y=x$Daily, x=x$Temp, x$Spread) names(fit$estimate) <- names(theta) #$ # Set up for plotting. # i.pad <- 10 plot(range(x$Temp)+c(-i.pad,i.pad), c(0, max(x$Daily)+20), type="n", xlab="Temp", ylab="Cost, kWh/day", main="Data, Model, and Fits") # # Plot the data. # l <- matrix(mapply(function(l,r,h) {c(l,h,r,h,NA,NA)}, x$Temp.low, x$Temp.high, x$Daily), 2) lines(l[1,], l[2,], col="Gray") points(x$Temp, x$Daily, type="p", pch=3) # # Draw the models. # x0 <- seq(min(x$Temp)-i.pad, max(x$Temp)+i.pad, length.out=401) lines(x0, cbind(1, x0, x0^2) %*% coef(fit.quadratic), lwd=3, lty=3) #curve(response(fit$estimate, x, 0), add=TRUE, lwd=2, lty=1) t.0 <- fit$estimate["t.0"] alpha <- fit$estimate["alpha"] beta <- fit$estimate["beta"] gamma <- fit$estimate["gamma"] cool <- "#1020c0"; heat <- "#c02010" lines(c(t.0, 0), gamma + c(0, -alpha*t.0), lwd=2, lty=1, col=cool) lines(c(t.0, 100), gamma + c(0, beta*(100-t.0)), lwd=2, lty=1, col=heat) # # Display the fit. # pred <- response(fit$estimate, x$Temp, x$Spread) points(x$Temp, pred, pch=16, cex=1, col=ifelse(x$Temp < t.0, cool, heat)) #lines(lowess(x$Temp, pred, f=1/4)) # # Estimate the residual standard deviations. # residuals <- x$Daily - pred sqrt(sum(residuals^2) / (length(residuals) - 4)) sqrt(sum(resid(fit.quadratic)^2) / (length(residuals) - 3))
How to represent kWh usage by year against average temperature?
I would like to suggest that the important thing is to develop a physically realistic, practically useful model of energy cost. That will work better to detect changes in costs than any visualization
How to represent kWh usage by year against average temperature? I would like to suggest that the important thing is to develop a physically realistic, practically useful model of energy cost. That will work better to detect changes in costs than any visualization of the raw data can accomplish. By comparing this to the solution offered on SO, we have a very nice case study in the difference between fitting a curve to data and performing a meaningful statistical analysis. (This suggestion is based on having fit such a model to my own household usage a decade ago and applying it to track changes during that period. Note that once the model is fit, it can easily be calculated in a spreadsheet for the purpose of tracking changes, so we should not feel limited by the (in)capabilities of spreadsheet software.) For these data, such a physically plausible model produces a substantially different picture of energy costs and usage patterns than a simple alternative model (a quadratic least-squares fit of daily usage against monthly mean temperature). Consequently, the simpler model cannot be considered a reliable tool for understanding, predicting, or comparing energy use patterns. Analysis Newton's Law of Cooling says that, to a good approximation, the cost of heating (during a unit of time) should be directly proportional to the difference between the outside temperature $t$ and the inside temperature $t_0$. Let that constant of proportionality be $-\alpha$. The cost of cooling also should be proportional to that temperature difference, with a similar--but not necessarily identical--constant of proportionality $\beta$. (Each of these is determined by the insulating capability of the house as well as the efficiencies of the heating and cooling systems.) Estimating $\alpha$ and $\beta$ (which are expressed as kilowatts (or dollars) per degree per unit time) are among the most important things that can be accomplished, because they enable us to predict future costs, as well as measure the efficiencies of the house and its energy systems. Because these data are total electricity usage, they include non-heating costs such as lighting, cooking, computing, and entertainment. Also of interest is an estimate of this average base energy usage (per unit time), which I will call $\gamma$: it provides a floor on how much energy can be saved and enables predictions of future costs when efficiency improvements of known magnitude are made. (For instance, after four years I replaced a furnace by one claimed to be 30% more efficient--and indeed it was exactly that.) Finally, as a (gross) approximation I will assume the house is maintained at a nearly constant temperature $t_0$ throughout the year. (In my personal model I assume two temperatures, $t_0 \le t_1$, for winter and summer respectively--but there aren't yet enough data in this example to estimate both of them reliably and they would be pretty close anyway.) Knowing this value helps one evaluate the consequences of maintaining the house at a slightly different temperature, which is one important energy-saving option. The data present a singularly important and interesting complication: they reflect total costs during periods when outside temperatures fluctuate--and they fluctuate a lot, usually about one-quarter of their annual range each month. As we will see, this creates a substantial difference between the correct underlying instantaneous model just described and the values of the monthly totals. The effect is especially pronounced in the in-between months, where both (or neither) heating and cooling take place. Any model that does not account for this variation would mistakenly "think" energy costs should be at the base rate $\gamma$ during any month with an average temperature of $t_0$, but the reality is far different. We don't (readily) have detailed information about the monthly temperature fluctuations apart from their ranges. I propose handling that with an approach that is practical, but a tiny bit inconsistent. Except at the extreme temperatures, each month will usually experience gradual increases or decreases in temperature. This means we can take the distribution to be approximately uniform. When the range of a uniform variable has length $L$, that variable has a standard deviation of $s = L/\sqrt{6}$. I use this relationship to convert the ranges (from Avg. Low to Avg. High) to standard deviations. But then, essentially to obtain a nicely behaved model, I will downweight the variation at the ends of these ranges by using Normal distributions (with these estimated SDs and means given by Avg. Temp). Finally, we must standardize the data to a common unit time. Although that's already present in the Daily kWh Avg. variable, it lacks precision, so let's instead divide the total by the number of days in order to gain back the lost precision. Thus, the model of unit-time cooling costs $Y$ at an outdoor temperature of $t$ is $$y(t) = \gamma + \alpha(t-t_0)I(t\lt t_0) + \beta(t-t_0)I(t\gt t_0) + \varepsilon(t)$$ where $I$ is the indicator function and $\varepsilon$ represents everything not otherwise explicitly captured in this model. It has four parameters to estimate: $\alpha,\beta,\gamma$, and $t_0$. (If you're really sure of $t_0$ you could fix its value rather than estimating it.) The reported total costs during a time period $x_0$ to $x_1$ when the temperature $t(x)$ varies with time $x$ will therefore be $$\eqalign{ &\text{Cost}(x_0,x_1) = \int_{x_0}^{x_1} y(t)dt \\ &=\int_{x_0}^{x_1} \left(\gamma + \alpha(t(x)-t_0)I(t(x)\lt t_0) + \beta(t(x)-t_0)I(t(x)\gt t_0) + \varepsilon(t(x))\right) t^\prime(x) dx. }$$ If the model is any good at all, the fluctuations in $\varepsilon(t)$ ought to average to a value $\bar\varepsilon$ close to zero and will appear to randomly change month to month. Approximating the fluctuations in $t(x)$ with a Normal distribution of mean $\bar{t}$ (the monthly average) and standard deviation $s(\bar t)$ (as previously given from the monthly range) and doing the integrals yields $$\bar{y}(\bar{t}) = \gamma + (\beta-\alpha)s(\bar t)^2 \phi_s(\bar t-t_0) + (\bar{t}-t_0)\left(\beta + (\alpha-\beta)\Phi_s(t_0 - \bar{t})\right) + \bar\varepsilon(\bar{t}).$$ In this formula, $\Phi_s$ is the cumulative distribution of a Normal variate of zero mean and standard deviation $s(\bar t)$; $\phi$ is its density. Model fitting This model, although expressing a nonlinear relationship between costs and temperature, is nevertheless linear in the variables $\alpha,\beta,$ and $\gamma$. However, since it is nonlinear in $t_0$, and $t_0$ is not known, we need a nonlinear fitting procedure. To illustrate, I simply dumped it into a likelihood maximizer (using R for the computation), assuming the $\bar\varepsilon$ are independent and identically distributed, with normal distributions of mean zero and common standard deviation $\sigma$. For these data, the estimates are $$(\hat\alpha,\hat\beta,\hat\gamma,\hat {t_0}, \hat\sigma) = (-1.489, 1.371, 10.2, 63.4, 1.80).$$ This means: The cost to heat is approximately $1.49$ kWh/day/degree F. The cost to cool is approximately $1.37$ kWh/day/degree F. Cooling is a little more efficient. The base (non-heating/cooling) energy usage is $10.2$ kWh/day. (This number is fairly uncertain; additional data will help pin it down better.) The house is maintained at a temperature near $63.4$ degrees F. The other variations not explicitly accounted for in the model have a standard deviation of $1.80$ kWh/day. Confidence intervals and other quantitative expressions of uncertainty in these estimates can be obtained in standard ways with the maximum likelihood machinery. Visualization To illustrate this model, the following figure plots the data, the underlying model, the fit to the monthly averages, and a simple least-squares quadratic fit. The monthly data are shown as dark crosses. The horizontal gray lines on which they lie show the monthly temperature ranges. Our underlying model, reflecting Newton's law, is shown by the red and blue line segments meeting at a temperature of $t_0$. Our fit to the data is not a curve, because it depends on the temperature ranges. It is shown therefore as individual solid blue and red points. (Nevertheless, because the monthly ranges do not vary a lot, these points do seem to trace out a curve--almost the same as the dashed quadratic curve.) Finally, the dashed curve is the quadratic least squares fit (to the dark crosses). Notice how much the fits depart from the underlying (instantaneous) model, especially in the middle temperatures! This is the effect of monthly averaging. (Think of the heights of the red and blue lines being "smeared" across each horizontal gray segment. At extreme temperatures everything is centered at the lines, but at middle temperatures the two sides of the "V" get averaged together, reflecting the need for heating at some times and cooling at other times during the month.) Model comparison The two fits--the one painstakingly developed here and the simple, easy, quadratic fit--agree closely both with each other and with the data points. The quadratic fit is not quite as good, but it's still decent: its adjusted mean residual (for three parameters) is $2.07$ kWh/day, whereas the adjusted mean residual of the Newton's law model (for four parameters) is $1.97$ kWh/day, about 5% lower. If all you want to do is plot a curve through the data points, then the simplicity and relative fidelity of the quadratic fit would recommend it. However, the quadratic fit is utterly useless for learning what's going on! Its formula, $$\bar y(\bar t) = 219.95 - 6.241 \bar t + 0.04879 (\bar t)^2,$$ reveals nothing of use directly. In all fairness, we could analyze it a little: This is a parabola with vertex at $\hat t_0 = 6.241/(2\times 0.04879) = 64.0$ degrees F. We could take this as an estimate of the constant house temperature. It does not differ significantly from our first estimate of $63.4$ degrees. However, the predicted cost at this temperature is $219.95 - 6.241(63.4) + 0.04879(63.4)^2 = 20.4$ kWh/day. This is twice the base energy usage fit with Newton's Law. The marginal cost of heating or cooling is obtained from the absolute value of the derivative, $\bar{y}^\prime(\bar t) = -6.241 + 2(0.04879)\bar{t}$. For example, using this formula we would estimate the cost of heating a house when the outside temperature is $90$ degrees as $-6.241 + 2(0.04879)(90) = 2.54$ kWh/day/degree F. This is twice the value estimated with Newton's Law. Similarly, the cost to heat the house at an outdoor temperature of $32$ degrees would be estimated as $|-6.241 + 2(0.04879)(32)| = 3.12$ kWh/day/degree F. This is more than twice the value estimated with Newton's Law. At the middle temperatures, the quadratic fit errs in the other direction. Indeed, at its vertex in the $60$ to $68$ degree range it predicts nearly zero marginal heating or cooling costs, even though this mean temperature comprises days as cool as $50$ degrees and as warm as $78$ degrees. (Few people reading this post will still have their heat off at $50$ degrees (=$10$ degrees C)!) In brief, although it looks almost as good in the visualization, the quadratic fit grossly errs in estimating fundamental quantities of interest related to energy usage. Its use for evaluating changes in usage is therefore problematic and should be discouraged. Computation This R code performed all the computing and plotting. It can readily be adapted to similar datasets. # # Read and process the raw data. # x <- read.csv("F:/temp/energy.csv") x$Daily <- x$Usage / x$Length x <- x[order(x$Temp), ] #pairs(x) # # Fit a quadratic curve. # fit.quadratic <- lm(Daily ~ Temp+I(Temp^2), data=x) # par(mfrow=c(2,2)) # plot(fit.quadratic) # par(mfrow=c(1,1)) # # Fit a simple but realistic heating-cooling model with maximum likelihood. # response <- function(theta, x, s) { alpha <- theta[1]; beta <- theta[2]; gamma <- theta[3]; t.0 <- theta[4] x <- x - t.0 gamma + (beta-alpha)*s^2*dnorm(x, 0, s) + x*(beta + (alpha-beta)*pnorm(-x, 0, s)) } log.L <- function(theta, y, x, s) { # theta = (alpha, beta, gamma, t.0, sigma) # x = time # s = estimated SD # y = response y.hat <- response(theta, x, s) sigma <- theta[5] sum((((y - y.hat) / sigma) ^2 + log(2 * pi * sigma^2))/2) } theta <- c(alpha=-1, beta=5/4, gamma=20, t.0=65, sigma=2) # Initial guess x$Spread <- (x$Temp.high - x$Temp.low)/sqrt(6) # Uniform estimate fit <- nlm(log.L, theta, y=x$Daily, x=x$Temp, x$Spread) names(fit$estimate) <- names(theta) #$ # Set up for plotting. # i.pad <- 10 plot(range(x$Temp)+c(-i.pad,i.pad), c(0, max(x$Daily)+20), type="n", xlab="Temp", ylab="Cost, kWh/day", main="Data, Model, and Fits") # # Plot the data. # l <- matrix(mapply(function(l,r,h) {c(l,h,r,h,NA,NA)}, x$Temp.low, x$Temp.high, x$Daily), 2) lines(l[1,], l[2,], col="Gray") points(x$Temp, x$Daily, type="p", pch=3) # # Draw the models. # x0 <- seq(min(x$Temp)-i.pad, max(x$Temp)+i.pad, length.out=401) lines(x0, cbind(1, x0, x0^2) %*% coef(fit.quadratic), lwd=3, lty=3) #curve(response(fit$estimate, x, 0), add=TRUE, lwd=2, lty=1) t.0 <- fit$estimate["t.0"] alpha <- fit$estimate["alpha"] beta <- fit$estimate["beta"] gamma <- fit$estimate["gamma"] cool <- "#1020c0"; heat <- "#c02010" lines(c(t.0, 0), gamma + c(0, -alpha*t.0), lwd=2, lty=1, col=cool) lines(c(t.0, 100), gamma + c(0, beta*(100-t.0)), lwd=2, lty=1, col=heat) # # Display the fit. # pred <- response(fit$estimate, x$Temp, x$Spread) points(x$Temp, pred, pch=16, cex=1, col=ifelse(x$Temp < t.0, cool, heat)) #lines(lowess(x$Temp, pred, f=1/4)) # # Estimate the residual standard deviations. # residuals <- x$Daily - pred sqrt(sum(residuals^2) / (length(residuals) - 4)) sqrt(sum(resid(fit.quadratic)^2) / (length(residuals) - 3))
How to represent kWh usage by year against average temperature? I would like to suggest that the important thing is to develop a physically realistic, practically useful model of energy cost. That will work better to detect changes in costs than any visualization
27,782
How to represent kWh usage by year against average temperature?
I received an answer over at StackOverflow. If anyone has additional thoughts, I am still very interested in alternative solutions. https://stackoverflow.com/questions/29777890/data-visualization-how-to-represent-kwh-usage-by-year-against-average-temperatu
How to represent kWh usage by year against average temperature?
I received an answer over at StackOverflow. If anyone has additional thoughts, I am still very interested in alternative solutions. https://stackoverflow.com/questions/29777890/data-visualization-how
How to represent kWh usage by year against average temperature? I received an answer over at StackOverflow. If anyone has additional thoughts, I am still very interested in alternative solutions. https://stackoverflow.com/questions/29777890/data-visualization-how-to-represent-kwh-usage-by-year-against-average-temperatu
How to represent kWh usage by year against average temperature? I received an answer over at StackOverflow. If anyone has additional thoughts, I am still very interested in alternative solutions. https://stackoverflow.com/questions/29777890/data-visualization-how
27,783
Extended Cox model and cox.zph
An extended Cox model is really technically the same as a regular Cox model. If your data set is properly constructed to accommodate time dependent covariates (multiple rows per subject, start and end times etc..), than cox.ph and cox.zph should handle your data just fine. Having time dependent covariates doesn't change the fact that you should check for proportionality assumption, in this case using the Schoenfeld residuals against the transformed time using cox.zph. Having very small p values indicates that there are time dependent coefficients which you need to take care of. Two main methods are (1) time interactions and (2) step functions. The former is easier to do and to read, but if it does not change the p values than use the later: Note that it would be easier if you provided your own data, so the following is based on sample data I use (1) Interaction with time Here we use simple interaction with time on the problematic variable(s). Note that you don't need to add time itself to the model as it is the baseline. > model.coxph0 <- coxph(Surv(t1, t2, event) ~ female + var2, data = data) > summary(model.coxph0) coef exp(coef) se(coef) z Pr(>|z|) female 0.1699562 1.1852530 0.1605322 1.059 0.290 var2 -0.0002503 0.9997497 0.0004652 -0.538 0.591 Checking for proportional assumption violations: > (viol.cox0<- cox.zph(model.coxph0)) rho chisq p female 0.0501 1.16 0.2811 var2 0.1020 4.35 0.0370 GLOBAL NA 5.31 0.0704 So var2 is problematic. lets try using interaction with time: > model.coxph0 <- coxph(Surv(t1, t2, event) ~ + female + var2 + var2:t2, data = data) > summary(model.coxph0) coef exp(coef) se(coef) z Pr(>|z|) female 1.665e-01 1.181e+00 1.605e-01 1.038 0.29948 var2 -1.358e-03 9.986e-01 6.852e-04 -1.982 0.04746 * var2:t2 5.803e-05 1.000e+00 2.106e-05 2.756 0.00586 ** Now lets check again with zph: > (viol.cox0<- cox.zph(model.coxph0)) rho chisq p female 0.0486 1.095 0.295 var2 -0.0250 0.258 0.611 var2:t2 0.0282 0.322 0.570 GLOBAL NA 1.462 0.691 As you can see - that's the ticket. (2) Step functions Here we create a model devided by time segments according to how the residuals are plotted, and add a strata to the specific problematic variable(s). > model.coxph1 <- coxph(Surv(t1, t2, event) ~ female + contributions, data = data) > summary(model.coxph1) coef exp(coef) se(coef) z Pr(>|z|) female 1.204e-01 1.128e+00 1.609e-01 0.748 0.454 contributions 2.138e-04 1.000e+00 3.584e-05 5.964 2.46e-09 *** Now with zph: > (viol.cox1<- cox.zph(model.coxph1)) rho chisq p female 0.0296 0.41 5.22e-01 contributions 0.2068 21.31 3.91e-06 GLOBAL NA 22.38 1.38e-05 > plot(viol.cox1) So the contributions coefficient appears to be time dependent. I tried interaction with time that didn't work. So here is using step functions: You first need to view the graph (above) and visually check where the lines change angle. Here it seems to be around time spell 8 and 40. So we will create data using survSplit grouping at the aforementioned times: sandbox_data <- survSplit(Surv(t1, t2, event) ~ female +contributions, data = data, cut = c(8,40), episode = "tgroup", id = "id") And then run the model with strata: > model.coxph2 <- coxph(Surv(t1, t2, event) ~ female + contributions:strata(tgroup), data = sandbox_data) > summary(model.coxph2) coef exp(coef) se(coef) z Pr(>|z|) female 1.249e-01 1.133e+00 1.615e-01 0.774 0.4390 contributions:strata(tgroup)tgroup=1 1.048e-04 1.000e+00 5.380e-05 1.948 0.0514 . contributions:strata(tgroup)tgroup=2 3.119e-04 1.000e+00 5.825e-05 5.355 8.54e-08 *** contributions:strata(tgroup)tgroup=3 6.894e-04 1.001e+00 1.179e-04 5.845 5.06e-09 *** And viola - > (viol.cox1<- cox.zph(model.coxph1)) rho chisq p female 0.0410 0.781 0.377 contributions:strata(tgroup)tgroup=1 0.0363 0.826 0.364 contributions:strata(tgroup)tgroup=2 0.0479 0.958 0.328 contributions:strata(tgroup)tgroup=3 0.0172 0.140 0.708 GLOBAL NA 2.956 0.565
Extended Cox model and cox.zph
An extended Cox model is really technically the same as a regular Cox model. If your data set is properly constructed to accommodate time dependent covariates (multiple rows per subject, start and end
Extended Cox model and cox.zph An extended Cox model is really technically the same as a regular Cox model. If your data set is properly constructed to accommodate time dependent covariates (multiple rows per subject, start and end times etc..), than cox.ph and cox.zph should handle your data just fine. Having time dependent covariates doesn't change the fact that you should check for proportionality assumption, in this case using the Schoenfeld residuals against the transformed time using cox.zph. Having very small p values indicates that there are time dependent coefficients which you need to take care of. Two main methods are (1) time interactions and (2) step functions. The former is easier to do and to read, but if it does not change the p values than use the later: Note that it would be easier if you provided your own data, so the following is based on sample data I use (1) Interaction with time Here we use simple interaction with time on the problematic variable(s). Note that you don't need to add time itself to the model as it is the baseline. > model.coxph0 <- coxph(Surv(t1, t2, event) ~ female + var2, data = data) > summary(model.coxph0) coef exp(coef) se(coef) z Pr(>|z|) female 0.1699562 1.1852530 0.1605322 1.059 0.290 var2 -0.0002503 0.9997497 0.0004652 -0.538 0.591 Checking for proportional assumption violations: > (viol.cox0<- cox.zph(model.coxph0)) rho chisq p female 0.0501 1.16 0.2811 var2 0.1020 4.35 0.0370 GLOBAL NA 5.31 0.0704 So var2 is problematic. lets try using interaction with time: > model.coxph0 <- coxph(Surv(t1, t2, event) ~ + female + var2 + var2:t2, data = data) > summary(model.coxph0) coef exp(coef) se(coef) z Pr(>|z|) female 1.665e-01 1.181e+00 1.605e-01 1.038 0.29948 var2 -1.358e-03 9.986e-01 6.852e-04 -1.982 0.04746 * var2:t2 5.803e-05 1.000e+00 2.106e-05 2.756 0.00586 ** Now lets check again with zph: > (viol.cox0<- cox.zph(model.coxph0)) rho chisq p female 0.0486 1.095 0.295 var2 -0.0250 0.258 0.611 var2:t2 0.0282 0.322 0.570 GLOBAL NA 1.462 0.691 As you can see - that's the ticket. (2) Step functions Here we create a model devided by time segments according to how the residuals are plotted, and add a strata to the specific problematic variable(s). > model.coxph1 <- coxph(Surv(t1, t2, event) ~ female + contributions, data = data) > summary(model.coxph1) coef exp(coef) se(coef) z Pr(>|z|) female 1.204e-01 1.128e+00 1.609e-01 0.748 0.454 contributions 2.138e-04 1.000e+00 3.584e-05 5.964 2.46e-09 *** Now with zph: > (viol.cox1<- cox.zph(model.coxph1)) rho chisq p female 0.0296 0.41 5.22e-01 contributions 0.2068 21.31 3.91e-06 GLOBAL NA 22.38 1.38e-05 > plot(viol.cox1) So the contributions coefficient appears to be time dependent. I tried interaction with time that didn't work. So here is using step functions: You first need to view the graph (above) and visually check where the lines change angle. Here it seems to be around time spell 8 and 40. So we will create data using survSplit grouping at the aforementioned times: sandbox_data <- survSplit(Surv(t1, t2, event) ~ female +contributions, data = data, cut = c(8,40), episode = "tgroup", id = "id") And then run the model with strata: > model.coxph2 <- coxph(Surv(t1, t2, event) ~ female + contributions:strata(tgroup), data = sandbox_data) > summary(model.coxph2) coef exp(coef) se(coef) z Pr(>|z|) female 1.249e-01 1.133e+00 1.615e-01 0.774 0.4390 contributions:strata(tgroup)tgroup=1 1.048e-04 1.000e+00 5.380e-05 1.948 0.0514 . contributions:strata(tgroup)tgroup=2 3.119e-04 1.000e+00 5.825e-05 5.355 8.54e-08 *** contributions:strata(tgroup)tgroup=3 6.894e-04 1.001e+00 1.179e-04 5.845 5.06e-09 *** And viola - > (viol.cox1<- cox.zph(model.coxph1)) rho chisq p female 0.0410 0.781 0.377 contributions:strata(tgroup)tgroup=1 0.0363 0.826 0.364 contributions:strata(tgroup)tgroup=2 0.0479 0.958 0.328 contributions:strata(tgroup)tgroup=3 0.0172 0.140 0.708 GLOBAL NA 2.956 0.565
Extended Cox model and cox.zph An extended Cox model is really technically the same as a regular Cox model. If your data set is properly constructed to accommodate time dependent covariates (multiple rows per subject, start and end
27,784
Extended Cox model and cox.zph
This question deserves a more up-to-date answer on a few accounts. First, the cox.zph() function has substantially changed with recent versions of the survival package, so there might be confusion with outputs not looking the same. Second, there can be some hidden "gotchas" when you are dealing with time-dependent covariates, as in this question. Third, although much of another answer is fine, there may be a serious error in one of the proposed ways to specify time-dependent coefficients. Finally, the proper way to deal with that last problem makes it impossible (currently, at least) to use cox.zph() to check proportional hazards (PH) in the final model. For many years the cox.zph() function performed its tests of PH with an approximation, the correlation coefficient between scaled Schoenfeld residuals and (possibly transformed) time. That correlation coefficient was reported as "rho", as shown in another answer. Since Version 3.0-10 of the package, cox.zph() is now an exact score test. There is no longer a value of "rho" to report. With time-dependent covariates there can be a problem with causality. For example, I recently helped analyze some data in which patients' use of a drug prescribed for chronic conditions was included as a covariate. As people get older they are increasingly likely to be using that drug. To include that drug as a time-dependent covariate would be problematic, as it might just be a marker of already having survived longer. A time-dependent covariate can too easily be a proxy for longer survival, which (in addition to the causality problem) might show up as a PH problem. I suspect that might have been part of the problem in the initial question here. To quote from the time-dependent vignette by Therneau, Crowson and Atkinson: The key rule for time dependent covariates in a Cox model is simple and essentially the same as that for gambling: you cannot look into the future. Time-dependent coefficients can help with PH problems whether or not there are time-dependent covariates. Modeling coefficients with step functions as a function of time, one of the approaches proposed in another answer, is valid. As @bandwagoner notes in a comment on that question, the other proposed approach, a covariate-time interaction, might not be.* Quoting again from the vignette: This mistake has been made often enough th[at] the coxph routine has been updated to print an error message for such attempts. The issue is that the above code does not actually create a time dependent covariate, rather it creates a time-static value for each subject based on their value for the covariate time; no differently than if we had constructed the variable outside of a coxph call. This variable most definitely breaks the rule about not looking into the future, and one would quickly find the circularity: large values of time appear to predict long survival because long survival leads to large values for time. The survival package provides a correct way to specify coefficients as arbitrary functions of time, through a user-defined tt() function. Unfortunately, as the NEWS file for the package says, from version 3.1-2 "The cox.zph command now refuses models with tt() terms, before it had an incorrect computation." So for now it seems that evaluation of time-dependent coefficients will depend on how well the user-defined tt() function matches the form of the time-dependency seen with the time-independent coefficients and on other graphical evaluations. *The answer from Yuval Spiegler doesn't specify the full nature of the data preparation. If it's done with something like the unfold() function used by Fox and Weisberg, then you have one separate stop, start, event line for each individual for each at-risk time. With that format, the design matrix will contain a current covariate:time interaction value for all individuals at risk at any event time. If the other answer used data prepared that way, then the analysis with the explicit covariate:time interaction term would be OK. The start, stop, event data produced by the tmerge() function used by the survival package time-dependent vignette doesn't produce separate rows for each at-risk time; it breaks up data for an individual into full periods having constant covariate values. With that (much shorter) data format you have to use the tt() functionality to specify a covariate:time interaction correctly.
Extended Cox model and cox.zph
This question deserves a more up-to-date answer on a few accounts. First, the cox.zph() function has substantially changed with recent versions of the survival package, so there might be confusion wit
Extended Cox model and cox.zph This question deserves a more up-to-date answer on a few accounts. First, the cox.zph() function has substantially changed with recent versions of the survival package, so there might be confusion with outputs not looking the same. Second, there can be some hidden "gotchas" when you are dealing with time-dependent covariates, as in this question. Third, although much of another answer is fine, there may be a serious error in one of the proposed ways to specify time-dependent coefficients. Finally, the proper way to deal with that last problem makes it impossible (currently, at least) to use cox.zph() to check proportional hazards (PH) in the final model. For many years the cox.zph() function performed its tests of PH with an approximation, the correlation coefficient between scaled Schoenfeld residuals and (possibly transformed) time. That correlation coefficient was reported as "rho", as shown in another answer. Since Version 3.0-10 of the package, cox.zph() is now an exact score test. There is no longer a value of "rho" to report. With time-dependent covariates there can be a problem with causality. For example, I recently helped analyze some data in which patients' use of a drug prescribed for chronic conditions was included as a covariate. As people get older they are increasingly likely to be using that drug. To include that drug as a time-dependent covariate would be problematic, as it might just be a marker of already having survived longer. A time-dependent covariate can too easily be a proxy for longer survival, which (in addition to the causality problem) might show up as a PH problem. I suspect that might have been part of the problem in the initial question here. To quote from the time-dependent vignette by Therneau, Crowson and Atkinson: The key rule for time dependent covariates in a Cox model is simple and essentially the same as that for gambling: you cannot look into the future. Time-dependent coefficients can help with PH problems whether or not there are time-dependent covariates. Modeling coefficients with step functions as a function of time, one of the approaches proposed in another answer, is valid. As @bandwagoner notes in a comment on that question, the other proposed approach, a covariate-time interaction, might not be.* Quoting again from the vignette: This mistake has been made often enough th[at] the coxph routine has been updated to print an error message for such attempts. The issue is that the above code does not actually create a time dependent covariate, rather it creates a time-static value for each subject based on their value for the covariate time; no differently than if we had constructed the variable outside of a coxph call. This variable most definitely breaks the rule about not looking into the future, and one would quickly find the circularity: large values of time appear to predict long survival because long survival leads to large values for time. The survival package provides a correct way to specify coefficients as arbitrary functions of time, through a user-defined tt() function. Unfortunately, as the NEWS file for the package says, from version 3.1-2 "The cox.zph command now refuses models with tt() terms, before it had an incorrect computation." So for now it seems that evaluation of time-dependent coefficients will depend on how well the user-defined tt() function matches the form of the time-dependency seen with the time-independent coefficients and on other graphical evaluations. *The answer from Yuval Spiegler doesn't specify the full nature of the data preparation. If it's done with something like the unfold() function used by Fox and Weisberg, then you have one separate stop, start, event line for each individual for each at-risk time. With that format, the design matrix will contain a current covariate:time interaction value for all individuals at risk at any event time. If the other answer used data prepared that way, then the analysis with the explicit covariate:time interaction term would be OK. The start, stop, event data produced by the tmerge() function used by the survival package time-dependent vignette doesn't produce separate rows for each at-risk time; it breaks up data for an individual into full periods having constant covariate values. With that (much shorter) data format you have to use the tt() functionality to specify a covariate:time interaction correctly.
Extended Cox model and cox.zph This question deserves a more up-to-date answer on a few accounts. First, the cox.zph() function has substantially changed with recent versions of the survival package, so there might be confusion wit
27,785
Random walk estimation with AR(1)
We estimate by OLS the model $$x_{t} = \rho x_{t-1} + u_t,\;\; E(u_t \mid \{x_{t-1}, x_{t-2},...\}) =0,\;x_0 =0$$ For a sample of size T, the estimator is $$\hat \rho = \frac {\sum_{t=1}^T x_{t}x_{t-1}}{\sum_{t=1}^T x_{t-1}^2} = \rho + \frac {\sum_{t=1}^T u_tx_{t-1}}{\sum_{t=1}^T x_{t-1}^2}$$ If the true data generating mechanism is a pure random walk, then $\rho=1$, and $$x_{t} = x_{t-1} + u_t \implies x_t= \sum_{i=1}^t u_i$$ The sampling distribution of the OLS estimator, or equivalently, the sampling distribution of $\hat \rho - 1$, is not symmetric around zero, but rather it is skewed to the left of zero, with $\approx 68$% of obtained values (i.e. $\approx$ probability mass) being negative, and so we obtain more often than not $\hat \rho < 1$. Here is a relative frequency distribution $$\begin{align} \text{Mean:} -0.0017773\\ \text{Median:} -0.00085984\\ \text{Minimum: } -0.042875\\ \text{Maximum: } 0.0052173\\ \text{Standard deviation: } 0.0031625\\ \text{Skewness: } -2.2568\\ \text{Ex. kurtosis: } 8.3017\\ \end{align}$$ This is sometimes called the "Dickey-Fuller" distribution, because it is the base for the critical values used to perform the Unit-Root tests of the same name. I don't recollect seeing an attempt to provide intuition for the shape of the sampling distribution. We are looking at the sampling distribution of the random variable $$\hat \rho - 1 = \left(\sum_{t=1}^T u_tx_{t-1}\right)\cdot \left(\frac {1}{\sum_{t=1}^T x_{t-1}^2}\right)$$ If $u_t$'s are Standard Normal, then the first component of $\hat \rho - 1$ is the sum of non-independent Product-Normal distributions (or "Normal-Product"). The second component of $\hat \rho - 1$ is the reciprocal of the sum of non-independent Gamma distributions (scaled chi-squares of one degree of freedom, actually). For neither do we have analytical results so let's simulate (for a sample size of $T=5$). If we sum independent Product Normals we get a distribution that remains symmetric around zero. For example: But if we sum non-independent Product Normals as is our case we get which is skewed to the right but with more probability mass allocated to the negative values. And the mass appears to being pushed even more to the left if we increase the sample size and add more correlated elements to the sum. The reciprocal of the sum of non-independent Gammas is a non-negative random variable with positive skew. Then we can imagine that, if we take the product of these two random variables, the comparatively greater probability mass in the negative orthant of the first, combined with the positive-only values that occur in the second (and the positive skewness which may add a dash of larger negative values), create the negative skew that characterizes the distribution of $\hat \rho -1$.
Random walk estimation with AR(1)
We estimate by OLS the model $$x_{t} = \rho x_{t-1} + u_t,\;\; E(u_t \mid \{x_{t-1}, x_{t-2},...\}) =0,\;x_0 =0$$ For a sample of size T, the estimator is $$\hat \rho = \frac {\sum_{t=1}^T x_{t}x_{t-
Random walk estimation with AR(1) We estimate by OLS the model $$x_{t} = \rho x_{t-1} + u_t,\;\; E(u_t \mid \{x_{t-1}, x_{t-2},...\}) =0,\;x_0 =0$$ For a sample of size T, the estimator is $$\hat \rho = \frac {\sum_{t=1}^T x_{t}x_{t-1}}{\sum_{t=1}^T x_{t-1}^2} = \rho + \frac {\sum_{t=1}^T u_tx_{t-1}}{\sum_{t=1}^T x_{t-1}^2}$$ If the true data generating mechanism is a pure random walk, then $\rho=1$, and $$x_{t} = x_{t-1} + u_t \implies x_t= \sum_{i=1}^t u_i$$ The sampling distribution of the OLS estimator, or equivalently, the sampling distribution of $\hat \rho - 1$, is not symmetric around zero, but rather it is skewed to the left of zero, with $\approx 68$% of obtained values (i.e. $\approx$ probability mass) being negative, and so we obtain more often than not $\hat \rho < 1$. Here is a relative frequency distribution $$\begin{align} \text{Mean:} -0.0017773\\ \text{Median:} -0.00085984\\ \text{Minimum: } -0.042875\\ \text{Maximum: } 0.0052173\\ \text{Standard deviation: } 0.0031625\\ \text{Skewness: } -2.2568\\ \text{Ex. kurtosis: } 8.3017\\ \end{align}$$ This is sometimes called the "Dickey-Fuller" distribution, because it is the base for the critical values used to perform the Unit-Root tests of the same name. I don't recollect seeing an attempt to provide intuition for the shape of the sampling distribution. We are looking at the sampling distribution of the random variable $$\hat \rho - 1 = \left(\sum_{t=1}^T u_tx_{t-1}\right)\cdot \left(\frac {1}{\sum_{t=1}^T x_{t-1}^2}\right)$$ If $u_t$'s are Standard Normal, then the first component of $\hat \rho - 1$ is the sum of non-independent Product-Normal distributions (or "Normal-Product"). The second component of $\hat \rho - 1$ is the reciprocal of the sum of non-independent Gamma distributions (scaled chi-squares of one degree of freedom, actually). For neither do we have analytical results so let's simulate (for a sample size of $T=5$). If we sum independent Product Normals we get a distribution that remains symmetric around zero. For example: But if we sum non-independent Product Normals as is our case we get which is skewed to the right but with more probability mass allocated to the negative values. And the mass appears to being pushed even more to the left if we increase the sample size and add more correlated elements to the sum. The reciprocal of the sum of non-independent Gammas is a non-negative random variable with positive skew. Then we can imagine that, if we take the product of these two random variables, the comparatively greater probability mass in the negative orthant of the first, combined with the positive-only values that occur in the second (and the positive skewness which may add a dash of larger negative values), create the negative skew that characterizes the distribution of $\hat \rho -1$.
Random walk estimation with AR(1) We estimate by OLS the model $$x_{t} = \rho x_{t-1} + u_t,\;\; E(u_t \mid \{x_{t-1}, x_{t-2},...\}) =0,\;x_0 =0$$ For a sample of size T, the estimator is $$\hat \rho = \frac {\sum_{t=1}^T x_{t}x_{t-
27,786
Random walk estimation with AR(1)
This is not really an answer but too long for a comment, so I post this anyway. I was able to get a coefficient greater than 1 two times out of a hundred for a sample size of 100 (using "R"): N=100 # number of trials T=100 # length of time series coef=c() for(i in 1:N){ set.seed(i) x=rnorm(T) # generate T realizations of a standard normal variable y=cumsum(x) # cumulative sum of x produces a random walk y lm1=lm(y[-1]~y[-T]) # regress y on its own first lag, with intercept coef[i]=as.numeric(lm1$coef[1]) } length(which(coef<1))/N # the proportion of estimated coefficients below 1 Realizations 84 and 95 have coefficient above 1, so it is not always below one. However, the tendency is clearly to have a downward-biased estimate. The questions remains, why? Edit: the above regressions included an intercept term which does not seem to belong in the model. Once the intercept is removed, I get many more estimates above 1 (3158 out of 10000) -- but still it is clearly below 50% of all the cases: N=10000 # number of trials T=100 # length of time series coef=c() for(i in 1:N){ set.seed(i) x=rnorm(T) # generate T realizations of a standard normal variable y=cumsum(x) # cumulative sum of x produces a random walk y lm1=lm(y[-1]~-1+y[-T]) # regress y on its own first lag, without intercept coef[i]=as.numeric(lm1$coef[1]) } length(which(coef<1))/N # the proportion of estimated coefficients below 1
Random walk estimation with AR(1)
This is not really an answer but too long for a comment, so I post this anyway. I was able to get a coefficient greater than 1 two times out of a hundred for a sample size of 100 (using "R"): N=100
Random walk estimation with AR(1) This is not really an answer but too long for a comment, so I post this anyway. I was able to get a coefficient greater than 1 two times out of a hundred for a sample size of 100 (using "R"): N=100 # number of trials T=100 # length of time series coef=c() for(i in 1:N){ set.seed(i) x=rnorm(T) # generate T realizations of a standard normal variable y=cumsum(x) # cumulative sum of x produces a random walk y lm1=lm(y[-1]~y[-T]) # regress y on its own first lag, with intercept coef[i]=as.numeric(lm1$coef[1]) } length(which(coef<1))/N # the proportion of estimated coefficients below 1 Realizations 84 and 95 have coefficient above 1, so it is not always below one. However, the tendency is clearly to have a downward-biased estimate. The questions remains, why? Edit: the above regressions included an intercept term which does not seem to belong in the model. Once the intercept is removed, I get many more estimates above 1 (3158 out of 10000) -- but still it is clearly below 50% of all the cases: N=10000 # number of trials T=100 # length of time series coef=c() for(i in 1:N){ set.seed(i) x=rnorm(T) # generate T realizations of a standard normal variable y=cumsum(x) # cumulative sum of x produces a random walk y lm1=lm(y[-1]~-1+y[-T]) # regress y on its own first lag, without intercept coef[i]=as.numeric(lm1$coef[1]) } length(which(coef<1))/N # the proportion of estimated coefficients below 1
Random walk estimation with AR(1) This is not really an answer but too long for a comment, so I post this anyway. I was able to get a coefficient greater than 1 two times out of a hundred for a sample size of 100 (using "R"): N=100
27,787
A random variable that induces a $\sigma$-algebra the same as the one in the sample space
When you chase the definitions, the issues become trivial (although perhaps still unintuitive): $\mathbb{E}(Y\mid X) = \mathbb{E}(Y\mid \mathcal{F}_X)$ by definition. For any subalgebra $\mathcal{G}\subset \mathcal{F}$, $\mathbb{E}(Y\mid \mathcal{G})$ is defined to be any $\mathcal{G}$-measurable function for which $$\int_G \mathbb{E}(Y\mid \mathcal{G})(\omega) \,\mathrm d \mathbb{P}(\omega) = \int_G Y(\omega) \,\mathrm d \mathbb{P}(\omega)$$ for every $G\in \mathcal{G}$. Therefore, whenever $\mathcal{F}_X = \mathcal{F}$, it must be the case that $\mathbb{E}(Y\mid X)$ is $\mathcal{F}$-measurable and $\int_F \mathbb{E}(Y\mid X)(\omega) \,\mathrm d \mathbb{P}(\omega) = \int_F Y(\omega) \,\mathrm d \mathbb{P}(\omega)$ for every $F\in \mathcal{F}$. The equality of the integrals for all measurable sets implies (as is well known and established early in any account of Lebesgue integration) that $\mathbb{E}(Y\mid X)$ must equal $Y$ almost surely (a.s.): they can differ only on a set of measure zero. The second part of the question requests an example. Let's construct a very simple but not entirely trivial one. It concerns a finite binomial process used to model (among other things) changes in prices of a financial asset over time. For simplicity, I have restricted it to a sequence of two times during which the price could go up ($+$) or down ($-$), whence $\Omega$ can be identified with the set $\{++, +-, -+, --\}$. $\mathcal{F}$ consists of all subsets of $\Omega$ (the discrete algebra). $\mathbb{P}$ is determined by its values on the atoms, written $p_{++}=\mathbb{P}(\{++\})$, etc. Let $Y$ be the price of the asset after the first time and $X$ be its price after the second time. (These natural and meaningful descriptions show this is not some pathological construction we're about to review.) The figure displays this model as a binary tree in which the individual (conditional!) probabilities label the branches, the elements of $\Omega$ are the four possible paths from left to right through the tree, and the values of $Y$ and $X$ are indicated at the points where they are determined. Suppose all four prices assigned by $X$ are distinct. Then, since any individual price is measurable in $\mathcal{B}(\mathbb{R})$, $\mathcal{F}_X$ contains all the atoms, whence it consists of $\mathcal{F}$ itself. But $Y$ can assign at most two distinct prices, $Y_{+} = Y(++) = Y(+-)$ and $Y_{-} = Y(-+) = Y(--)$. The inverse images of these two prices then are the sets $+_1=\{++,+-\}$ and $-_1=\{-+,--\}$. They generate a strict subalgebra of $\mathcal{F}$: it has four measurable sets and does not include any of the atoms. It describes what is "known" after the first time but before the second one. The definition of conditional expectation needs to be checked only on a basis for $\mathcal{F}_X$. The set of its atoms is most convenient. Here is an example of a calculation for the atom $\{-+\}$: $$\int_{\{-+\}} \mathbb{E}(Y\mid X)(\omega) \,\mathrm d \mathbb{P}(\omega) = \int_{\{-+\}} Y(\omega) \,\mathrm d \mathbb{P}(\omega) = Y(-+)p_{-+}$$ The parallel calculations for the other atoms make it clear that for all $\omega\in\Omega$, $$Y(\omega) p_\omega = \int_{\omega} \mathbb{E}(Y\mid X)(\omega) = \mathbb{E}(Y\mid X)(\omega) p_\omega,$$ where the second equality computes the integral directly. From this we can construct two interesting examples: Suppose every outcome has nonzero probability. Then we may always divide both sides by $p_\omega$, no matter what $\omega$ may be, and obtain $$\mathbb{E}(Y\mid X)(\omega) = Y(\omega).$$ The conditional expectation of $Y$ is just $Y$ itself. Suppose $p_{++}=p_{+-}=1/2$ and $p_{--}=p_{-+}=0$. (This models a situation where an initial decrease is impossible.) Then we may define $Y_{-}$ to be any value, since it does not matter (due to the impossibility of this event): the defining equality for $\omega={--}$ $$0 = Y_{-} p_{--} = Y(--) p_{--} = \mathbb{E}(Y\mid X)(--) p_{--} = 0$$ and its counterpart for $\omega=-+$ automatically hold. Thus, it is not necessarily the case that $\mathbb{E}(Y|\mathcal{F}) = Y$, but the set of $\omega$ where the two sides differ must have zero probability (and, of course, be measurable with respect to $Y$). Looking back at the tree might supply some intuition: in conditioning $Y$ on $X$, whose values were determined later, we thereby have complete information about $Y$ along any sets of paths having nonzero probability of occurring.
A random variable that induces a $\sigma$-algebra the same as the one in the sample space
When you chase the definitions, the issues become trivial (although perhaps still unintuitive): $\mathbb{E}(Y\mid X) = \mathbb{E}(Y\mid \mathcal{F}_X)$ by definition. For any subalgebra $\mathcal{G}\
A random variable that induces a $\sigma$-algebra the same as the one in the sample space When you chase the definitions, the issues become trivial (although perhaps still unintuitive): $\mathbb{E}(Y\mid X) = \mathbb{E}(Y\mid \mathcal{F}_X)$ by definition. For any subalgebra $\mathcal{G}\subset \mathcal{F}$, $\mathbb{E}(Y\mid \mathcal{G})$ is defined to be any $\mathcal{G}$-measurable function for which $$\int_G \mathbb{E}(Y\mid \mathcal{G})(\omega) \,\mathrm d \mathbb{P}(\omega) = \int_G Y(\omega) \,\mathrm d \mathbb{P}(\omega)$$ for every $G\in \mathcal{G}$. Therefore, whenever $\mathcal{F}_X = \mathcal{F}$, it must be the case that $\mathbb{E}(Y\mid X)$ is $\mathcal{F}$-measurable and $\int_F \mathbb{E}(Y\mid X)(\omega) \,\mathrm d \mathbb{P}(\omega) = \int_F Y(\omega) \,\mathrm d \mathbb{P}(\omega)$ for every $F\in \mathcal{F}$. The equality of the integrals for all measurable sets implies (as is well known and established early in any account of Lebesgue integration) that $\mathbb{E}(Y\mid X)$ must equal $Y$ almost surely (a.s.): they can differ only on a set of measure zero. The second part of the question requests an example. Let's construct a very simple but not entirely trivial one. It concerns a finite binomial process used to model (among other things) changes in prices of a financial asset over time. For simplicity, I have restricted it to a sequence of two times during which the price could go up ($+$) or down ($-$), whence $\Omega$ can be identified with the set $\{++, +-, -+, --\}$. $\mathcal{F}$ consists of all subsets of $\Omega$ (the discrete algebra). $\mathbb{P}$ is determined by its values on the atoms, written $p_{++}=\mathbb{P}(\{++\})$, etc. Let $Y$ be the price of the asset after the first time and $X$ be its price after the second time. (These natural and meaningful descriptions show this is not some pathological construction we're about to review.) The figure displays this model as a binary tree in which the individual (conditional!) probabilities label the branches, the elements of $\Omega$ are the four possible paths from left to right through the tree, and the values of $Y$ and $X$ are indicated at the points where they are determined. Suppose all four prices assigned by $X$ are distinct. Then, since any individual price is measurable in $\mathcal{B}(\mathbb{R})$, $\mathcal{F}_X$ contains all the atoms, whence it consists of $\mathcal{F}$ itself. But $Y$ can assign at most two distinct prices, $Y_{+} = Y(++) = Y(+-)$ and $Y_{-} = Y(-+) = Y(--)$. The inverse images of these two prices then are the sets $+_1=\{++,+-\}$ and $-_1=\{-+,--\}$. They generate a strict subalgebra of $\mathcal{F}$: it has four measurable sets and does not include any of the atoms. It describes what is "known" after the first time but before the second one. The definition of conditional expectation needs to be checked only on a basis for $\mathcal{F}_X$. The set of its atoms is most convenient. Here is an example of a calculation for the atom $\{-+\}$: $$\int_{\{-+\}} \mathbb{E}(Y\mid X)(\omega) \,\mathrm d \mathbb{P}(\omega) = \int_{\{-+\}} Y(\omega) \,\mathrm d \mathbb{P}(\omega) = Y(-+)p_{-+}$$ The parallel calculations for the other atoms make it clear that for all $\omega\in\Omega$, $$Y(\omega) p_\omega = \int_{\omega} \mathbb{E}(Y\mid X)(\omega) = \mathbb{E}(Y\mid X)(\omega) p_\omega,$$ where the second equality computes the integral directly. From this we can construct two interesting examples: Suppose every outcome has nonzero probability. Then we may always divide both sides by $p_\omega$, no matter what $\omega$ may be, and obtain $$\mathbb{E}(Y\mid X)(\omega) = Y(\omega).$$ The conditional expectation of $Y$ is just $Y$ itself. Suppose $p_{++}=p_{+-}=1/2$ and $p_{--}=p_{-+}=0$. (This models a situation where an initial decrease is impossible.) Then we may define $Y_{-}$ to be any value, since it does not matter (due to the impossibility of this event): the defining equality for $\omega={--}$ $$0 = Y_{-} p_{--} = Y(--) p_{--} = \mathbb{E}(Y\mid X)(--) p_{--} = 0$$ and its counterpart for $\omega=-+$ automatically hold. Thus, it is not necessarily the case that $\mathbb{E}(Y|\mathcal{F}) = Y$, but the set of $\omega$ where the two sides differ must have zero probability (and, of course, be measurable with respect to $Y$). Looking back at the tree might supply some intuition: in conditioning $Y$ on $X$, whose values were determined later, we thereby have complete information about $Y$ along any sets of paths having nonzero probability of occurring.
A random variable that induces a $\sigma$-algebra the same as the one in the sample space When you chase the definitions, the issues become trivial (although perhaps still unintuitive): $\mathbb{E}(Y\mid X) = \mathbb{E}(Y\mid \mathcal{F}_X)$ by definition. For any subalgebra $\mathcal{G}\
27,788
A random variable that induces a $\sigma$-algebra the same as the one in the sample space
Two well-known results are that $$E[Y\mid \mathcal F]=Y,\; a.s. \tag{1}$$ and that, denoting $\mathcal F_0 \equiv \{\emptyset, \Omega\}$, $$E[Y\mid \mathcal F_0] = E[Y] \tag{2}$$ In all the books that I am aware of, both are "proven" by the remark "obtains directly from the definition of conditional expectation", which is not particularly illuminating. So what could be the intuition here? Equation $(2)$ is easiest: if "what we know" is that "either the experiment has not been performed, or that if it has been performed, some elementary event has happened among all possible such" (this is what $\mathcal F_0$ represents), really, it is equivalent as knowing nothing at all about the outcome of the experiment. Then the value of this conditional expectation can be nothing else but equal to the unconditional expected value. Let's turn to the, perhaps less intuitive equation $(1)$. How could we verbally describe "condition on the $\sigma$-algebra of the Sample Space"? Here, we are told that "what may have happened is some elementary event, but also some composite event among all possible such". Can we here conclude that the conditional expectation equals the unconditional one? No, because the unconditional expected value measures the elementary events (is defined only over the elements of $\Omega$). So it is obvious that "$E[Y]$" cannot be the correct answer to eq. $(1)$. Let's first establish that $$E[Y\mid \sigma(Y)] = E(Y\mid Y) = Y \tag{3}$$ This seems easier: if what we know is that "$Y$ has happened" (this is what $\sigma(Y)$ reflects, and it is not the same as "$\Omega$ has happened"), then the expected value of $Y$ based only on this information cannot be but equal to $Y$. Then apply the "Tower property" (or Law of Iterated Expectations): Using first $(3)$ and then the fact that $\sigma(Y) \subseteq \mathcal F$, we have $$ E[Y\mid \mathcal F]=E\Big[E[Y\mid \sigma(Y)]\Big | \mathcal F\Big] = E[Y\mid \sigma(Y)] = Y $$ If "everything may have happened", then $Y$ happened, and so again, the expected value given this information is equal to $Y$ itself. The formal justification of course is that $Y$ is $\mathcal F$-measurable, and so we have the more general result $E[Y\mid \mathcal G] = Y$ if $Y$ is $\mathcal G$-measurable, for any $\sigma$-algebra $\mathcal G$.
A random variable that induces a $\sigma$-algebra the same as the one in the sample space
Two well-known results are that $$E[Y\mid \mathcal F]=Y,\; a.s. \tag{1}$$ and that, denoting $\mathcal F_0 \equiv \{\emptyset, \Omega\}$, $$E[Y\mid \mathcal F_0] = E[Y] \tag{2}$$ In all the books t
A random variable that induces a $\sigma$-algebra the same as the one in the sample space Two well-known results are that $$E[Y\mid \mathcal F]=Y,\; a.s. \tag{1}$$ and that, denoting $\mathcal F_0 \equiv \{\emptyset, \Omega\}$, $$E[Y\mid \mathcal F_0] = E[Y] \tag{2}$$ In all the books that I am aware of, both are "proven" by the remark "obtains directly from the definition of conditional expectation", which is not particularly illuminating. So what could be the intuition here? Equation $(2)$ is easiest: if "what we know" is that "either the experiment has not been performed, or that if it has been performed, some elementary event has happened among all possible such" (this is what $\mathcal F_0$ represents), really, it is equivalent as knowing nothing at all about the outcome of the experiment. Then the value of this conditional expectation can be nothing else but equal to the unconditional expected value. Let's turn to the, perhaps less intuitive equation $(1)$. How could we verbally describe "condition on the $\sigma$-algebra of the Sample Space"? Here, we are told that "what may have happened is some elementary event, but also some composite event among all possible such". Can we here conclude that the conditional expectation equals the unconditional one? No, because the unconditional expected value measures the elementary events (is defined only over the elements of $\Omega$). So it is obvious that "$E[Y]$" cannot be the correct answer to eq. $(1)$. Let's first establish that $$E[Y\mid \sigma(Y)] = E(Y\mid Y) = Y \tag{3}$$ This seems easier: if what we know is that "$Y$ has happened" (this is what $\sigma(Y)$ reflects, and it is not the same as "$\Omega$ has happened"), then the expected value of $Y$ based only on this information cannot be but equal to $Y$. Then apply the "Tower property" (or Law of Iterated Expectations): Using first $(3)$ and then the fact that $\sigma(Y) \subseteq \mathcal F$, we have $$ E[Y\mid \mathcal F]=E\Big[E[Y\mid \sigma(Y)]\Big | \mathcal F\Big] = E[Y\mid \sigma(Y)] = Y $$ If "everything may have happened", then $Y$ happened, and so again, the expected value given this information is equal to $Y$ itself. The formal justification of course is that $Y$ is $\mathcal F$-measurable, and so we have the more general result $E[Y\mid \mathcal G] = Y$ if $Y$ is $\mathcal G$-measurable, for any $\sigma$-algebra $\mathcal G$.
A random variable that induces a $\sigma$-algebra the same as the one in the sample space Two well-known results are that $$E[Y\mid \mathcal F]=Y,\; a.s. \tag{1}$$ and that, denoting $\mathcal F_0 \equiv \{\emptyset, \Omega\}$, $$E[Y\mid \mathcal F_0] = E[Y] \tag{2}$$ In all the books t
27,789
Should I exclude random effects from a model if they are not statistically significant?
My recommendation is to include the random effects in the model even if they are not statistically significant, on the grounds that the statistical analysis then more faithfully represents the actual study design. This allows you to write something like this in your Statistical Methods section: Random effects were included for individual and order to control for possible dependence due to repeated measures or order effects. This will probably forestall reviewer comments about dependence assumptions or pseudo-replication. It is just easier to do this than to "explain" why it is okay to drop those terms, even if they seem essentially useless. Also, having those terms in the model is probably not costing you anything. I would be surprised and suspicious if the results changed dramatically when you removed them. Here are some considerations: Pragmatic: Sometimes, the distribution of the data does not allow fitting of the model to the data. This can happen when due to cost, time or effort very few trials are collected on purpose, when the data are too sparse in some way, or when the distribution of the data turn out to be degenerate or too flat. In this case, you may have no way to proceed other than simplifying the model, maybe dramatically. Usually, I try to first drop the effects that are at the finest granularity, since there are usually more of them to be estimated. In the worst case, you might wish to proceed as though the data were collected independently. This may be better than nothing, but significance tests are going to have to be taken with a big grain of salt. The interpretation of the results should be hedged quite a bit. Practical: In some situations, it might be reasonable to pool terms in order to get some information in order to proceed. Here, I am thinking more about experimental design in ongoing research and development, rather than for publication. Lorenzen and Anderson (1993) give "sometimes pooling" rules for the case where it would be helpful to get more precise tests of other factors in the model. A term in the model will be declared negligible and a candidate for removal from the model and EMS column if it is insignificant at the $\alpha=0.25$ level. A term should not be removed from the model if a higher order interaction involving that term is significant at the $0.25$ level. Again, though, this type of rule is more for practical use and not for publication use, in my opinion. Theoretical: Now, it might be that in fact you get essentially "identical" results when you drop those random effects. That is nice but you should be aware that you are now fitting two different models, and the terms might need to be interpreted differently even though they might be "the same". What I would take from that is that the results are robust under various assumptions. That's always a good thing. Dropping terms can also be thought of as part of "model selection", "model building", or "model simplification". There is a variety of methodologies out there for model selection. While "drop the terms with insignificant $p$-values" is one such method, it does not seem to have much support theoretically in general. I am not sure how the various methodologies fare with mixed models. Also, depending on how you want to interpret the results from your model, you may not wish to "simplify" it. Littell et al (2006) has a little discussion (p. 211) about narrow versus wide inference and population-wide versus subject-specific inference in a simple setting. In your case you are probably interested in broad inference, making conclusions that pertain to the entire population rather than to just the individuals in your study. Anyway, in your case, your study was run in a way that introduced potential for dependence based on order and individuals. If you can accurately model the structure of your study then you should. References: Littell, Milliken, Stroup, Wolfinger, and Schabenberger (2006) SAS for Mixed Models. SAS. Lorenzen and Anderson (1993) Design of Experiments: A No-Name Approach. Marcel Dekker, Inc.
Should I exclude random effects from a model if they are not statistically significant?
My recommendation is to include the random effects in the model even if they are not statistically significant, on the grounds that the statistical analysis then more faithfully represents the actual
Should I exclude random effects from a model if they are not statistically significant? My recommendation is to include the random effects in the model even if they are not statistically significant, on the grounds that the statistical analysis then more faithfully represents the actual study design. This allows you to write something like this in your Statistical Methods section: Random effects were included for individual and order to control for possible dependence due to repeated measures or order effects. This will probably forestall reviewer comments about dependence assumptions or pseudo-replication. It is just easier to do this than to "explain" why it is okay to drop those terms, even if they seem essentially useless. Also, having those terms in the model is probably not costing you anything. I would be surprised and suspicious if the results changed dramatically when you removed them. Here are some considerations: Pragmatic: Sometimes, the distribution of the data does not allow fitting of the model to the data. This can happen when due to cost, time or effort very few trials are collected on purpose, when the data are too sparse in some way, or when the distribution of the data turn out to be degenerate or too flat. In this case, you may have no way to proceed other than simplifying the model, maybe dramatically. Usually, I try to first drop the effects that are at the finest granularity, since there are usually more of them to be estimated. In the worst case, you might wish to proceed as though the data were collected independently. This may be better than nothing, but significance tests are going to have to be taken with a big grain of salt. The interpretation of the results should be hedged quite a bit. Practical: In some situations, it might be reasonable to pool terms in order to get some information in order to proceed. Here, I am thinking more about experimental design in ongoing research and development, rather than for publication. Lorenzen and Anderson (1993) give "sometimes pooling" rules for the case where it would be helpful to get more precise tests of other factors in the model. A term in the model will be declared negligible and a candidate for removal from the model and EMS column if it is insignificant at the $\alpha=0.25$ level. A term should not be removed from the model if a higher order interaction involving that term is significant at the $0.25$ level. Again, though, this type of rule is more for practical use and not for publication use, in my opinion. Theoretical: Now, it might be that in fact you get essentially "identical" results when you drop those random effects. That is nice but you should be aware that you are now fitting two different models, and the terms might need to be interpreted differently even though they might be "the same". What I would take from that is that the results are robust under various assumptions. That's always a good thing. Dropping terms can also be thought of as part of "model selection", "model building", or "model simplification". There is a variety of methodologies out there for model selection. While "drop the terms with insignificant $p$-values" is one such method, it does not seem to have much support theoretically in general. I am not sure how the various methodologies fare with mixed models. Also, depending on how you want to interpret the results from your model, you may not wish to "simplify" it. Littell et al (2006) has a little discussion (p. 211) about narrow versus wide inference and population-wide versus subject-specific inference in a simple setting. In your case you are probably interested in broad inference, making conclusions that pertain to the entire population rather than to just the individuals in your study. Anyway, in your case, your study was run in a way that introduced potential for dependence based on order and individuals. If you can accurately model the structure of your study then you should. References: Littell, Milliken, Stroup, Wolfinger, and Schabenberger (2006) SAS for Mixed Models. SAS. Lorenzen and Anderson (1993) Design of Experiments: A No-Name Approach. Marcel Dekker, Inc.
Should I exclude random effects from a model if they are not statistically significant? My recommendation is to include the random effects in the model even if they are not statistically significant, on the grounds that the statistical analysis then more faithfully represents the actual
27,790
Power of a Mann Whitney test compared to a t test
1) The Mann-Whitney test is not guaranteed to be more powerful than a t-test when the assumptions of the t-test are not satisfied, although for the sorts of violations we tend to see in the real world, it is. Consider a standard Normal distribution truncated at +/- 100 and a difference between means of two groups of 0.01; this isn't Normal, but both tests will perform as if it were, since the difference between the two distributions is so small. 2) The t-test is the uniformly most powerful test for difference between means of two Normal variates blah blah blah, so it isn't going to be beaten by the Mann-Whitney on that kind of data no matter what. However, the worst that the Mann-Whitney can ever perform relative to the t-test is about 0.864 in terms of asymptotic relative efficiency, i.e., it would require 1/0.864x as much data to give the same power (asymptotically.) (Hollander and Wolfe, Nonparametric Statistical Methods.) There isn't any bound going the other way. Reproducing some numbers from Hollander and Wolfe, for different distributions we get an A.R.E. of the M-W to the t-test of: Normal: 0.955 Uniform: 1.0 <- also a counterexample to the M-W being better than the t for non-normal dist'ns Logistic: 1.097 Double Exponential: 1.5 Exponential: 3.0 Cauchy (well that's easy): $\infty$ The point of course being that you can't shoot yourself in the foot by using the Mann-Whitney test instead of the t-test, but the converse is not true.
Power of a Mann Whitney test compared to a t test
1) The Mann-Whitney test is not guaranteed to be more powerful than a t-test when the assumptions of the t-test are not satisfied, although for the sorts of violations we tend to see in the real worl
Power of a Mann Whitney test compared to a t test 1) The Mann-Whitney test is not guaranteed to be more powerful than a t-test when the assumptions of the t-test are not satisfied, although for the sorts of violations we tend to see in the real world, it is. Consider a standard Normal distribution truncated at +/- 100 and a difference between means of two groups of 0.01; this isn't Normal, but both tests will perform as if it were, since the difference between the two distributions is so small. 2) The t-test is the uniformly most powerful test for difference between means of two Normal variates blah blah blah, so it isn't going to be beaten by the Mann-Whitney on that kind of data no matter what. However, the worst that the Mann-Whitney can ever perform relative to the t-test is about 0.864 in terms of asymptotic relative efficiency, i.e., it would require 1/0.864x as much data to give the same power (asymptotically.) (Hollander and Wolfe, Nonparametric Statistical Methods.) There isn't any bound going the other way. Reproducing some numbers from Hollander and Wolfe, for different distributions we get an A.R.E. of the M-W to the t-test of: Normal: 0.955 Uniform: 1.0 <- also a counterexample to the M-W being better than the t for non-normal dist'ns Logistic: 1.097 Double Exponential: 1.5 Exponential: 3.0 Cauchy (well that's easy): $\infty$ The point of course being that you can't shoot yourself in the foot by using the Mann-Whitney test instead of the t-test, but the converse is not true.
Power of a Mann Whitney test compared to a t test 1) The Mann-Whitney test is not guaranteed to be more powerful than a t-test when the assumptions of the t-test are not satisfied, although for the sorts of violations we tend to see in the real worl
27,791
Power of a Mann Whitney test compared to a t test
is a Mann Whitney test on data where assumptions aren't satisfied as or almost powerful as a t-test on data where assumptions are satisfied? A phrase like 'as powerful' doesn't really work as a general statement. Power isn't especially comparable across different distributional models. The size of a given effect has different meanings in different parts of the distribution. Imagine you have a distribution that is pretty peaked, but has a heavy tail; by what measure to we say a particular size of deviation is similar to something with a much 'flatter' centre and smaller tail? A small deviation might be about as easy to pick up, but a large deviation might be (relative to the other distributional possibility we're trying to compare power for) harder. With two possible sets of normal distributions, one pair with a large s.d. and one with a small s.d., it's easy to say 'well, power will just scale with standard deviation; if we define our effect size in terms of number of standard deviations, we can relate the two power curves'. But now with differently shaped distributions, there's no obvious scale choice. We must make some choices about how to compare them. What choices we make will determine how they "compare". For example, how do I compare power when the data are Cauchy with power when the data are say a scaled beta(2,2)? What is a comparable effect size? The Cauchy below has more of its distribution between -1 and 1 and less of its distribution between -3 and 3 than the other one. Their interquartile ranges are different, for example. What is our basis for comparison? If you can resolve that conundrum, now consider if one of the distributions is skewed left and the other is bimodal, or any of a myriad number of other possibilities. You can still compute power under any particular set of assumptions, but comparison of one test across different distributional assumptions rather than two tests under a given distributional assumption is conceptually very tricky.
Power of a Mann Whitney test compared to a t test
is a Mann Whitney test on data where assumptions aren't satisfied as or almost powerful as a t-test on data where assumptions are satisfied? A phrase like 'as powerful' doesn't really work as a gener
Power of a Mann Whitney test compared to a t test is a Mann Whitney test on data where assumptions aren't satisfied as or almost powerful as a t-test on data where assumptions are satisfied? A phrase like 'as powerful' doesn't really work as a general statement. Power isn't especially comparable across different distributional models. The size of a given effect has different meanings in different parts of the distribution. Imagine you have a distribution that is pretty peaked, but has a heavy tail; by what measure to we say a particular size of deviation is similar to something with a much 'flatter' centre and smaller tail? A small deviation might be about as easy to pick up, but a large deviation might be (relative to the other distributional possibility we're trying to compare power for) harder. With two possible sets of normal distributions, one pair with a large s.d. and one with a small s.d., it's easy to say 'well, power will just scale with standard deviation; if we define our effect size in terms of number of standard deviations, we can relate the two power curves'. But now with differently shaped distributions, there's no obvious scale choice. We must make some choices about how to compare them. What choices we make will determine how they "compare". For example, how do I compare power when the data are Cauchy with power when the data are say a scaled beta(2,2)? What is a comparable effect size? The Cauchy below has more of its distribution between -1 and 1 and less of its distribution between -3 and 3 than the other one. Their interquartile ranges are different, for example. What is our basis for comparison? If you can resolve that conundrum, now consider if one of the distributions is skewed left and the other is bimodal, or any of a myriad number of other possibilities. You can still compute power under any particular set of assumptions, but comparison of one test across different distributional assumptions rather than two tests under a given distributional assumption is conceptually very tricky.
Power of a Mann Whitney test compared to a t test is a Mann Whitney test on data where assumptions aren't satisfied as or almost powerful as a t-test on data where assumptions are satisfied? A phrase like 'as powerful' doesn't really work as a gener
27,792
Difference between shifted distribution and zero-truncated distribution
1. Shifting and truncation are different things Truncating a Poisson at zero is not the same as shifting a Poisson to the right. Shifting just moves the whole thing left or right. Truncation actually cuts off some of the distribution. As a result the remainder is "scaled up" so that the total probability is still 1. Here's an illustration of the difference between shifting and truncation for normal distributions. The blue is the original in both cases, the gray is the result of either shifting or truncation: 2. Writing down a shifted probability function Actual shifting (by $\delta$, say) is easy to write down, you just "replace" the variable ($x$, say) by $(x-\delta)$ (and the domain is shifted by $+\delta$). Slightly more formally: So consider a random variable $X\sim\text{Poisson}(\lambda)$ $$P(X=x)=\frac{e^{-\lambda}\lambda^x}{x!},\quad x=0,1,2,\ldots$$ Now consider $Y=X+1$; $Y$ is just $X$ shifted 1 to the right. $$P(Y=y)=\frac{e^{-\lambda}\lambda^{y-1}}{(y-1)!},\quad y=1,2,\ldots$$ (The required "0 elsewhere"'s being understood as needed.) 3. Writing down a truncated probability function Since you seem to be looking at left-truncation, I'll discuss that specifically, but right-truncation or truncation at both ends works analogously. Imagine your probability function or density function is $f_X(x),\quad l \leq x\leq u$ but now you have a new variable, $Y$, which is distributed like $X$ but truncated on the left at $t>l$ (i.e. that any values $\leq t$ are not observed*). Then $f_Y(y) = \frac{1}{1-F_X(t)} f_X(y),\quad t< y\leq u$. * If truncation at $t$ instead means values $<t$ are not observed it changes to $\frac{1}{1-F_X(t^-)} f_X(y),$ $t\leq y\leq u$ (where $(t^-)$ is understood in the same sense as $(a-)$ here). Again, consider a Poisson random variable $X\sim\text{Poisson}(\lambda)$ $$P(X=x)=\frac{e^{-\lambda}\lambda^x}{x!},\quad x=0,1,2,\ldots$$ Let $Y$ be like $X$ but truncated at $0$ (which here can only mean that $0$ is truncated; the alternative meaning does nothing). Then $$P(Y=y)=\frac{e^{-\lambda}\lambda^y}{y!(1-e^{-\lambda})},\quad y=1,2,\ldots$$ We can see how these look different by comparing (for a Poisson with $\lambda=1.8$) shifting up by 1 vs truncating 0: Additional discussion of truncation can be found here at Wikipedia.
Difference between shifted distribution and zero-truncated distribution
1. Shifting and truncation are different things Truncating a Poisson at zero is not the same as shifting a Poisson to the right. Shifting just moves the whole thing left or right. Truncation actually
Difference between shifted distribution and zero-truncated distribution 1. Shifting and truncation are different things Truncating a Poisson at zero is not the same as shifting a Poisson to the right. Shifting just moves the whole thing left or right. Truncation actually cuts off some of the distribution. As a result the remainder is "scaled up" so that the total probability is still 1. Here's an illustration of the difference between shifting and truncation for normal distributions. The blue is the original in both cases, the gray is the result of either shifting or truncation: 2. Writing down a shifted probability function Actual shifting (by $\delta$, say) is easy to write down, you just "replace" the variable ($x$, say) by $(x-\delta)$ (and the domain is shifted by $+\delta$). Slightly more formally: So consider a random variable $X\sim\text{Poisson}(\lambda)$ $$P(X=x)=\frac{e^{-\lambda}\lambda^x}{x!},\quad x=0,1,2,\ldots$$ Now consider $Y=X+1$; $Y$ is just $X$ shifted 1 to the right. $$P(Y=y)=\frac{e^{-\lambda}\lambda^{y-1}}{(y-1)!},\quad y=1,2,\ldots$$ (The required "0 elsewhere"'s being understood as needed.) 3. Writing down a truncated probability function Since you seem to be looking at left-truncation, I'll discuss that specifically, but right-truncation or truncation at both ends works analogously. Imagine your probability function or density function is $f_X(x),\quad l \leq x\leq u$ but now you have a new variable, $Y$, which is distributed like $X$ but truncated on the left at $t>l$ (i.e. that any values $\leq t$ are not observed*). Then $f_Y(y) = \frac{1}{1-F_X(t)} f_X(y),\quad t< y\leq u$. * If truncation at $t$ instead means values $<t$ are not observed it changes to $\frac{1}{1-F_X(t^-)} f_X(y),$ $t\leq y\leq u$ (where $(t^-)$ is understood in the same sense as $(a-)$ here). Again, consider a Poisson random variable $X\sim\text{Poisson}(\lambda)$ $$P(X=x)=\frac{e^{-\lambda}\lambda^x}{x!},\quad x=0,1,2,\ldots$$ Let $Y$ be like $X$ but truncated at $0$ (which here can only mean that $0$ is truncated; the alternative meaning does nothing). Then $$P(Y=y)=\frac{e^{-\lambda}\lambda^y}{y!(1-e^{-\lambda})},\quad y=1,2,\ldots$$ We can see how these look different by comparing (for a Poisson with $\lambda=1.8$) shifting up by 1 vs truncating 0: Additional discussion of truncation can be found here at Wikipedia.
Difference between shifted distribution and zero-truncated distribution 1. Shifting and truncation are different things Truncating a Poisson at zero is not the same as shifting a Poisson to the right. Shifting just moves the whole thing left or right. Truncation actually
27,793
Difference between shifted distribution and zero-truncated distribution
If $X$ has a given distribution $f(x)$, then the distribution of $X+a$ is what you call the shifted distribution and is $g(x) = f(x-a)$. For discrete distributions, all the probability masses shift to the right by $a$ as in Glen_b's answer. On the other hand, the truncated distribution is effectively the conditional distribution of $X$ conditioned on the event that $X >b$ or $X \geq b$ (or, if you lop off the top, conditioned on $X < c$ or $X \leq c$). For the case of the conditioning event being $\{X > b\}$, this distribution is given by $$h(x) = \begin{cases}\frac{f(x)}{P\{X > b\}}, & x > b,\\0, & x \leq b, \end{cases}$$ and similarly for the other possible conditioning events. Yet another possibility for truncation is that we have a new random variable $Y$ that is related to $X$ as $$Y = \begin{cases}X, & X > b,\\b, & X \leq b,\end{cases}$$ in which case, $Y$ has a mixed distribution if $X$ is a continuous random variable, with a distribution that has a point mass at $b$ and is continuous to the right of $b$. But, for a discrete random variable $X$, $Y$ is also a discrete random variable and its probability mass function is given by $$p_Y(x) = \begin{cases}p_X(x), & x > b,\\P\{X \leq b\}, & x = b, \\0, & x < b.\end{cases}$$
Difference between shifted distribution and zero-truncated distribution
If $X$ has a given distribution $f(x)$, then the distribution of $X+a$ is what you call the shifted distribution and is $g(x) = f(x-a)$. For discrete distributions, all the probability masses shift
Difference between shifted distribution and zero-truncated distribution If $X$ has a given distribution $f(x)$, then the distribution of $X+a$ is what you call the shifted distribution and is $g(x) = f(x-a)$. For discrete distributions, all the probability masses shift to the right by $a$ as in Glen_b's answer. On the other hand, the truncated distribution is effectively the conditional distribution of $X$ conditioned on the event that $X >b$ or $X \geq b$ (or, if you lop off the top, conditioned on $X < c$ or $X \leq c$). For the case of the conditioning event being $\{X > b\}$, this distribution is given by $$h(x) = \begin{cases}\frac{f(x)}{P\{X > b\}}, & x > b,\\0, & x \leq b, \end{cases}$$ and similarly for the other possible conditioning events. Yet another possibility for truncation is that we have a new random variable $Y$ that is related to $X$ as $$Y = \begin{cases}X, & X > b,\\b, & X \leq b,\end{cases}$$ in which case, $Y$ has a mixed distribution if $X$ is a continuous random variable, with a distribution that has a point mass at $b$ and is continuous to the right of $b$. But, for a discrete random variable $X$, $Y$ is also a discrete random variable and its probability mass function is given by $$p_Y(x) = \begin{cases}p_X(x), & x > b,\\P\{X \leq b\}, & x = b, \\0, & x < b.\end{cases}$$
Difference between shifted distribution and zero-truncated distribution If $X$ has a given distribution $f(x)$, then the distribution of $X+a$ is what you call the shifted distribution and is $g(x) = f(x-a)$. For discrete distributions, all the probability masses shift
27,794
What is the benefit of using permutation tests?
Since the discussion grew long, I've taken my responses to an answer. But I've changed the order. Permutation tests are "exact", rather than asymptotic (compare with, for example, likelihood ratio tests). So, for example, you can do a test of means even without being able to compute the distribution of the difference in means under the null; you don't even need to specify the distributions involved. You can design a test statistic that has good power under a set of assumptions without being as sensitive to them as a fully parametric assumption (you can use a statistic that is robust but has good A.R.E.). Note that the definitions you give (or rather, whoever you're quoting there gives) are not universal; some people would call U a permutation test statistic (what makes a permutation test is not the statistic but how you evaluate the p-value). But once you're doing a permutation test and you have assigned a direction as 'extremes of this are inconsistent with H0', that kind of definition for T above is basically how you work out p-values - it's just the actual proportion of the permutation distribution at least as extreme as the sample under the null (the very definition of a p-value). So for example, if I want to do a (one-tailed, for simplicity) test of means like a two-sample t-test, I could make my statistic the numerator of the t-statistic, or the t-statistic itself, or the sum of the first sample (each of those definitions is monotonic in the others, conditional on the combined sample), or any monotonic transformation of them, and have the same test, since they yield identical p-values. All I need to do is see how far into (in terms of proportion) the permutation distribution of whatever statistic I choose the sample statistic lies. T as defined above is just another statistic, as good as any other I could choose (T as defined there being monotonic in U). T won't be exactly uniform, because that would require continuous distributions and T is necessarily discrete. Because U and therefore T can map more than one permutation to a given statistic, the outcomes aren't equi-probable, but they have a "uniform-like" cdf**, but one where the steps aren't necessarily equal in size. ** ($F(x)\leq x$, and strictly equal to it at the right limit of each jump -- there's probably a name for what that actually is) For reasonable statistics as $n$ goes to infinity the distribution of $T$ approaches uniformity. I think the best way to begin to understand them is really to do them in a variety of situations. Should T(X) be equal to the p-value based on U(X), for any sample X? If I understand correctly, I found it on page 5 of this slides. T is the p-value (for cases where large U indicates deviation from the null and small U is consistent with it). Note that the distribution is conditional on the sample. So its distribution isn't 'for any sample'. So the benefit of using permutation test is to compute the p-value of the original test statistic U without knowing the distribution of X under null? Therefore, the distribution of T(X) can be not necessarily uniform? I've already explained that T isn't uniform. I think I have already explained what I see as the benefits of permutation tests; other people will suggest other advantages (e.g.). Does "T is the p-value (for cases where large U indicates deviation from the null and small U is consistent with it)", mean that the p-value for test statistic U and sample X is T(X)? Why? Is there some reference for explaining that? The sentence you quoted explicitly states that T is a p-value, and when it is. If you can explain what is unclear about it maybe I could say more. As for why, see the definition of p-value (first sentence at the link) - it quite directly follows from that There's a good elementary discussion of permutation tests here. -- Edit: I add here a small permutation test example; this (R) code is only suitable for small samples - you need better algorithms for finding the extreme combinations in moderate samples. Consider a permutation test against a one-tailed alternative: $H_0: \mu_x = \mu_y$ (some people insist on $\mu_x \geq \mu_y$*) $H_1: \mu_x < \mu_y$ * but I usually avoid it because it particularly tends to confuse the issue for students when trying to work out null distributions on the following data: > x;y [1] 25.17 20.57 19.03 [1] 25.88 25.20 23.75 26.99 There are 35 ways of dividing the 7 observations into samples of size 3 and 4: > choose(7,3) [1] 35 As mentioned before, given the 7 data values, the sum of the first sample is monotonic in the difference in means, so let's use that as a test statistic. So the original sample has a test statistic of: > sum(x) [1] 64.77 Now here's the permutation distribution: > sort(apply(combn(c(x,y),3),2,sum)) [1] 63.35 64.77 64.80 65.48 66.59 67.95 67.98 68.66 69.40 69.49 69.52 69.77 [13] 70.08 70.11 70.20 70.94 71.19 71.22 71.31 71.62 71.65 71.90 72.73 72.76 [25] 73.44 74.12 74.80 74.83 75.91 75.94 76.25 76.62 77.36 78.04 78.07 (It's not essential to sort them, I just did that to make it easier to see the test statistic was the second value in from the end.) We can see (in this case by inspection) that $p$ is 2/35, or > 2/35 [1] 0.05714286 (Note that only in the case of no x-y overlap is a p-value below .05 possible here. In this case, $T$ would be discrete uniform because there are no tied values in $U$.) The pink arrows indicate the sample statistic on the x-axis, and the p-value on the y-axis.
What is the benefit of using permutation tests?
Since the discussion grew long, I've taken my responses to an answer. But I've changed the order. Permutation tests are "exact", rather than asymptotic (compare with, for example, likelihood ratio tes
What is the benefit of using permutation tests? Since the discussion grew long, I've taken my responses to an answer. But I've changed the order. Permutation tests are "exact", rather than asymptotic (compare with, for example, likelihood ratio tests). So, for example, you can do a test of means even without being able to compute the distribution of the difference in means under the null; you don't even need to specify the distributions involved. You can design a test statistic that has good power under a set of assumptions without being as sensitive to them as a fully parametric assumption (you can use a statistic that is robust but has good A.R.E.). Note that the definitions you give (or rather, whoever you're quoting there gives) are not universal; some people would call U a permutation test statistic (what makes a permutation test is not the statistic but how you evaluate the p-value). But once you're doing a permutation test and you have assigned a direction as 'extremes of this are inconsistent with H0', that kind of definition for T above is basically how you work out p-values - it's just the actual proportion of the permutation distribution at least as extreme as the sample under the null (the very definition of a p-value). So for example, if I want to do a (one-tailed, for simplicity) test of means like a two-sample t-test, I could make my statistic the numerator of the t-statistic, or the t-statistic itself, or the sum of the first sample (each of those definitions is monotonic in the others, conditional on the combined sample), or any monotonic transformation of them, and have the same test, since they yield identical p-values. All I need to do is see how far into (in terms of proportion) the permutation distribution of whatever statistic I choose the sample statistic lies. T as defined above is just another statistic, as good as any other I could choose (T as defined there being monotonic in U). T won't be exactly uniform, because that would require continuous distributions and T is necessarily discrete. Because U and therefore T can map more than one permutation to a given statistic, the outcomes aren't equi-probable, but they have a "uniform-like" cdf**, but one where the steps aren't necessarily equal in size. ** ($F(x)\leq x$, and strictly equal to it at the right limit of each jump -- there's probably a name for what that actually is) For reasonable statistics as $n$ goes to infinity the distribution of $T$ approaches uniformity. I think the best way to begin to understand them is really to do them in a variety of situations. Should T(X) be equal to the p-value based on U(X), for any sample X? If I understand correctly, I found it on page 5 of this slides. T is the p-value (for cases where large U indicates deviation from the null and small U is consistent with it). Note that the distribution is conditional on the sample. So its distribution isn't 'for any sample'. So the benefit of using permutation test is to compute the p-value of the original test statistic U without knowing the distribution of X under null? Therefore, the distribution of T(X) can be not necessarily uniform? I've already explained that T isn't uniform. I think I have already explained what I see as the benefits of permutation tests; other people will suggest other advantages (e.g.). Does "T is the p-value (for cases where large U indicates deviation from the null and small U is consistent with it)", mean that the p-value for test statistic U and sample X is T(X)? Why? Is there some reference for explaining that? The sentence you quoted explicitly states that T is a p-value, and when it is. If you can explain what is unclear about it maybe I could say more. As for why, see the definition of p-value (first sentence at the link) - it quite directly follows from that There's a good elementary discussion of permutation tests here. -- Edit: I add here a small permutation test example; this (R) code is only suitable for small samples - you need better algorithms for finding the extreme combinations in moderate samples. Consider a permutation test against a one-tailed alternative: $H_0: \mu_x = \mu_y$ (some people insist on $\mu_x \geq \mu_y$*) $H_1: \mu_x < \mu_y$ * but I usually avoid it because it particularly tends to confuse the issue for students when trying to work out null distributions on the following data: > x;y [1] 25.17 20.57 19.03 [1] 25.88 25.20 23.75 26.99 There are 35 ways of dividing the 7 observations into samples of size 3 and 4: > choose(7,3) [1] 35 As mentioned before, given the 7 data values, the sum of the first sample is monotonic in the difference in means, so let's use that as a test statistic. So the original sample has a test statistic of: > sum(x) [1] 64.77 Now here's the permutation distribution: > sort(apply(combn(c(x,y),3),2,sum)) [1] 63.35 64.77 64.80 65.48 66.59 67.95 67.98 68.66 69.40 69.49 69.52 69.77 [13] 70.08 70.11 70.20 70.94 71.19 71.22 71.31 71.62 71.65 71.90 72.73 72.76 [25] 73.44 74.12 74.80 74.83 75.91 75.94 76.25 76.62 77.36 78.04 78.07 (It's not essential to sort them, I just did that to make it easier to see the test statistic was the second value in from the end.) We can see (in this case by inspection) that $p$ is 2/35, or > 2/35 [1] 0.05714286 (Note that only in the case of no x-y overlap is a p-value below .05 possible here. In this case, $T$ would be discrete uniform because there are no tied values in $U$.) The pink arrows indicate the sample statistic on the x-axis, and the p-value on the y-axis.
What is the benefit of using permutation tests? Since the discussion grew long, I've taken my responses to an answer. But I've changed the order. Permutation tests are "exact", rather than asymptotic (compare with, for example, likelihood ratio tes
27,795
How to plot 20 years of daily data in time series
The problem with your data is not that it is extremely detailed: you have no values at weekends, that's why it is plotted with gaps. There are two ways to deal with it: Either try to guess approximate values in weekends with some smoothing methods (smooth.spline, loess, etc.). Code of simple interpolation is below. But in this case you will introduce something "unnatural" and artificial to the data. That's why I prefer second option. currentDate <- min(as.Date(oracle$Date)) dates <- c(currentDate) openValues <- c(oracle$Open[5045]) i <- 5044 while (i > 0) { currentDate <- currentDate + 1; dates <- c(dates, currentDate) if (currentDate == as.Date(oracle$Date[i])) { # just copy value and move openValues <- c(openValues, oracle$Open[i]) i <- i-1 } else { # interpolate value openValues <- c(openValues, mean(oracle$Open[i:i-1])) } } plot(dates, openValues, type="l") You can go from daily basis to a weekly basis, just averaging (for example) five sequential points that belog to one week (in this case you are "killing" some information). Just a quick example of how to do that would be openValues = c(mean(oracle$Open[1:5])); dates = c(as.Date(oracle$Date[1])); for (i in seq(6,5045,5)) { openValues = c(openValues, mean(oracle$Open[i:i+5])); dates = c(dates, as.Date(oracle$Date[i])); } plot(dates, openValues, type="l") Hope it will help.
How to plot 20 years of daily data in time series
The problem with your data is not that it is extremely detailed: you have no values at weekends, that's why it is plotted with gaps. There are two ways to deal with it: Either try to guess approximat
How to plot 20 years of daily data in time series The problem with your data is not that it is extremely detailed: you have no values at weekends, that's why it is plotted with gaps. There are two ways to deal with it: Either try to guess approximate values in weekends with some smoothing methods (smooth.spline, loess, etc.). Code of simple interpolation is below. But in this case you will introduce something "unnatural" and artificial to the data. That's why I prefer second option. currentDate <- min(as.Date(oracle$Date)) dates <- c(currentDate) openValues <- c(oracle$Open[5045]) i <- 5044 while (i > 0) { currentDate <- currentDate + 1; dates <- c(dates, currentDate) if (currentDate == as.Date(oracle$Date[i])) { # just copy value and move openValues <- c(openValues, oracle$Open[i]) i <- i-1 } else { # interpolate value openValues <- c(openValues, mean(oracle$Open[i:i-1])) } } plot(dates, openValues, type="l") You can go from daily basis to a weekly basis, just averaging (for example) five sequential points that belog to one week (in this case you are "killing" some information). Just a quick example of how to do that would be openValues = c(mean(oracle$Open[1:5])); dates = c(as.Date(oracle$Date[1])); for (i in seq(6,5045,5)) { openValues = c(openValues, mean(oracle$Open[i:i+5])); dates = c(dates, as.Date(oracle$Date[i])); } plot(dates, openValues, type="l") Hope it will help.
How to plot 20 years of daily data in time series The problem with your data is not that it is extremely detailed: you have no values at weekends, that's why it is plotted with gaps. There are two ways to deal with it: Either try to guess approximat
27,796
How to plot 20 years of daily data in time series
Because the problem is common to many statistical software environments, let's discuss it here on Cross Validated rather than migrating it to an R-specific forum (such as StackOverflow). The real issue is that Date is treated as a factor--a discrete variable--and so the lines are not being connected properly. (Nor are the points being plotted perfectly accurately in the horizontal direction.) To make the righthand plot, the Date field was converted from a factor to an actual date, each week was identified with a simple calculation (breaking the weeks between Saturday and Sunday) and the lines were interrupted over weekends by looping over the weeks: oracle$date <- as.Date(oracle$Date) oracle$week.num <- (as.integer(oracle$date) + 3) %/% 7 oracle$week <- as.Date(oracle$week.num * 7 - 3, as.Date("1970-01-01", "%Y-%m-%d")) par(mfrow=c(1,2)) plot(as.factor(unclass(oracle$Date[1:120])), oracle$Open[1:120], type="l", main="Original Plot: Inset", xlab="Factor code") plot(oracle$date[1:120], oracle$Open[1:120], type="n", ylab="Price", main="Oracle Opening Prices") tmp <- by(oracle[1:120,], oracle$week[1:120], function(x) lines(x$date, x$Open, lwd=2)) (A date equivalent of each week, giving the Monday of that week, was also stored in the oracle dataframe because it can be useful for plotting weekly aggregated data.) The original intention can be achieved simply by emulating the last line to display all the data. To add some information about seasonal behavior, the following plot varies the color by week throughout each calendar year: par(mfrow=c(1,1)) colors <- terrain.colors(52) plot(oracle$date, oracle$Open, type="n", main="Oracle Opening Prices") tmp <- by(oracle, oracle$week, function(x) lines(x$date, x$Open, col=colors[x$week.num %% 52 + 1]))
How to plot 20 years of daily data in time series
Because the problem is common to many statistical software environments, let's discuss it here on Cross Validated rather than migrating it to an R-specific forum (such as StackOverflow). The real issu
How to plot 20 years of daily data in time series Because the problem is common to many statistical software environments, let's discuss it here on Cross Validated rather than migrating it to an R-specific forum (such as StackOverflow). The real issue is that Date is treated as a factor--a discrete variable--and so the lines are not being connected properly. (Nor are the points being plotted perfectly accurately in the horizontal direction.) To make the righthand plot, the Date field was converted from a factor to an actual date, each week was identified with a simple calculation (breaking the weeks between Saturday and Sunday) and the lines were interrupted over weekends by looping over the weeks: oracle$date <- as.Date(oracle$Date) oracle$week.num <- (as.integer(oracle$date) + 3) %/% 7 oracle$week <- as.Date(oracle$week.num * 7 - 3, as.Date("1970-01-01", "%Y-%m-%d")) par(mfrow=c(1,2)) plot(as.factor(unclass(oracle$Date[1:120])), oracle$Open[1:120], type="l", main="Original Plot: Inset", xlab="Factor code") plot(oracle$date[1:120], oracle$Open[1:120], type="n", ylab="Price", main="Oracle Opening Prices") tmp <- by(oracle[1:120,], oracle$week[1:120], function(x) lines(x$date, x$Open, lwd=2)) (A date equivalent of each week, giving the Monday of that week, was also stored in the oracle dataframe because it can be useful for plotting weekly aggregated data.) The original intention can be achieved simply by emulating the last line to display all the data. To add some information about seasonal behavior, the following plot varies the color by week throughout each calendar year: par(mfrow=c(1,1)) colors <- terrain.colors(52) plot(oracle$date, oracle$Open, type="n", main="Oracle Opening Prices") tmp <- by(oracle, oracle$week, function(x) lines(x$date, x$Open, col=colors[x$week.num %% 52 + 1]))
How to plot 20 years of daily data in time series Because the problem is common to many statistical software environments, let's discuss it here on Cross Validated rather than migrating it to an R-specific forum (such as StackOverflow). The real issu
27,797
How to plot 20 years of daily data in time series
I would not interpolate at the weekends. Very few stock exchanges trade on Saturday and none that I know of on Sunday. You are introducing an estimate for data that never existed so why not instead just remove Saturday and Sunday from the data set? I would do something like the below: require(ggplot2) require(scales) require(gridExtra) require(lubridate) require(reshape) set.seed(12345) # Create data frame from random data daysback <- 1000 # number of days, only a few for this example startdate <- as.Date(format(now()), format = "%Y-%m-%d") - days(daysback) mydf <- data.frame(mydate = seq(as.Date(startdate), by = "day", length.out = daysback), open = runif(daysback, min = 600, max = 800)) # Now that we have a data frame, remove the weekend days mydf <- mydf[!(weekdays(as.Date(mydf$mydate)) %in% c('Saturday','Sunday')),] # remove weekend days # Calculate change, except for the first date mydf$diff <- c(NA, diff(mydf$open)) # Remove first row with no 'diff' value firstdate <- head(mydf$mydate, 1) mydf <- mydf[mydf$mydate > firstdate, ] p <- ggplot(mydf, aes(x = mydate, y = diff)) + geom_bar(data = mydf, stat = "identity", fill = "red") print(p)
How to plot 20 years of daily data in time series
I would not interpolate at the weekends. Very few stock exchanges trade on Saturday and none that I know of on Sunday. You are introducing an estimate for data that never existed so why not instead ju
How to plot 20 years of daily data in time series I would not interpolate at the weekends. Very few stock exchanges trade on Saturday and none that I know of on Sunday. You are introducing an estimate for data that never existed so why not instead just remove Saturday and Sunday from the data set? I would do something like the below: require(ggplot2) require(scales) require(gridExtra) require(lubridate) require(reshape) set.seed(12345) # Create data frame from random data daysback <- 1000 # number of days, only a few for this example startdate <- as.Date(format(now()), format = "%Y-%m-%d") - days(daysback) mydf <- data.frame(mydate = seq(as.Date(startdate), by = "day", length.out = daysback), open = runif(daysback, min = 600, max = 800)) # Now that we have a data frame, remove the weekend days mydf <- mydf[!(weekdays(as.Date(mydf$mydate)) %in% c('Saturday','Sunday')),] # remove weekend days # Calculate change, except for the first date mydf$diff <- c(NA, diff(mydf$open)) # Remove first row with no 'diff' value firstdate <- head(mydf$mydate, 1) mydf <- mydf[mydf$mydate > firstdate, ] p <- ggplot(mydf, aes(x = mydate, y = diff)) + geom_bar(data = mydf, stat = "identity", fill = "red") print(p)
How to plot 20 years of daily data in time series I would not interpolate at the weekends. Very few stock exchanges trade on Saturday and none that I know of on Sunday. You are introducing an estimate for data that never existed so why not instead ju
27,798
How to plot 20 years of daily data in time series
Regarding the look of your plot, I suppose that adding of multiple labels under the x-axis would visually improve it. The look of suggested plot you can see here http://imgur.com/ZTNPniA I do not know how to make such plot, it is just an idea (which I have not seen realized in R)
How to plot 20 years of daily data in time series
Regarding the look of your plot, I suppose that adding of multiple labels under the x-axis would visually improve it. The look of suggested plot you can see here http://imgur.com/ZTNPniA I do not kno
How to plot 20 years of daily data in time series Regarding the look of your plot, I suppose that adding of multiple labels under the x-axis would visually improve it. The look of suggested plot you can see here http://imgur.com/ZTNPniA I do not know how to make such plot, it is just an idea (which I have not seen realized in R)
How to plot 20 years of daily data in time series Regarding the look of your plot, I suppose that adding of multiple labels under the x-axis would visually improve it. The look of suggested plot you can see here http://imgur.com/ZTNPniA I do not kno
27,799
Determining largest contributor in a group
David Harris has provided a great answer, but since the question continues to be edited, perhaps it would help to see the details of his solution. Highlights of the following analysis are: Weighted least squares is probably more appropriate than ordinary least squares. Because the estimates may reflect variation in productivity beyond any individual's control, be cautious about using them to evaluate individual workers. To carry this out, let's create some realistic data using specified formulas so we can evaluate the accuracy of the solution. This is done with R: set.seed(17) n.names <- 1000 groupSize <- 3.5 n.cases <- 5 * n.names # Should exceed n.names cv <- 0.10 # Must be 0 or greater groupSize <- 3.5 # Must be greater than 0 proficiency <- round(rgamma(n.names, 20, scale=5)); hist(proficiency) In these initial steps, we: Set a seed for the random number generator so anybody can exactly reproduce the results. Specify how many workers there are with n.names. Stipulate the expected number of workers per group with groupSize. Specify how many cases (observations) are available with n.cases. (Later a few of these will be eliminated because they correspond, as it happens at random, to none of the workers in our synthetic workforce.) Arrange for the amounts of work to differ randomly from what would be predicted based on the sum of each group's work "proficiencies." The value of cv is a typical proportional variation; E.g., the $0.10$ given here corresponds to a typical 10% variation (which could range beyond 30% in a few cases). Create a workforce of people with varying work proficiencies. The parameters given here for computing proficiency create a range of over 4:1 between the best and worst workers (which in my experience may even be a bit narrow for technology and professional jobs, but perhaps is wide for routine manufacturing jobs). With this synthetic workforce in hand, let's simulate their work. This amounts to creating a group of each workers (schedule) for each observation (eliminating any observations in which no workers at all were involved), summing the proficiencies of the workers in each group, and multiplying that sum by a random value (averaging exactly $1$) to reflect the variations that will inevitably occur. (If there were no variation at all, we would refer this question to the Mathematics site, where respondents could point out this problem is just a set of simultaneous linear equations which could be solved exactly for the proficiencies.) schedule <- matrix(rbinom(n.cases * n.names, 1, groupSize/n.names), nrow=n.cases) schedule <- schedule[apply(schedule, 1, sum) > 0, ] work <- round(schedule %*% proficiency * exp(rnorm(dim(schedule)[1], -cv^2/2, cv))) hist(work) I have found it's convenient to put all the workgroup data into a single data frame for analysis but to keep the work values separate: data <- data.frame(schedule) This is where we would begin with real data: we would have the worker grouping encoded by data (or schedule) and the observed work outputs in the work array. Unfortunately, if some workers are always paired, R's lm procedure simply fails with an error. We should check first for such pairings. One way is to find perfectly correlated workers in the schedule: correlations <- cor(data) outer(names(data), names(data), paste)[which(upper.tri(correlations) & correlations >= 0.999999)] The output will list pairs of always-paired workers: this can be used to combine these workers into groups, because at least we can estimate the productivity of each group, if not the individuals within it. We hope it just spits out character(0). Let's presume it does. One subtle point, implicit in the foregoing explanation, is that the variation in the work performed is multiplicative, not additive. This is realistic: the variation in output of a large group of workers will, on an absolute scale, be greater than the variation in smaller groups. Accordingly, we will get better estimates by using weighted least squares rather than ordinary least squares. The best weights to use in this particular model are the reciprocals of the work amounts. (In the event some work amounts are zero, I fudge this by adding a small amount to avoid dividing by zero.) fit <- lm(work ~ . + 0, data=data, weights=1/(max(work)/10^3+work)) fit.sum <- summary(fit) This should take just one or two seconds. Before going on we ought to perform some diagnostic tests of the fit. Although discussing those would take us too far afield here, one R command to produce useful diagnostics is plot(fit) (This will take a few seconds: it's a large dataset!) Although these few lines of code do all the work, and spit out estimated proficiencies for each worker, we wouldn't want to scan through all 1000 lines of output--at least not right away. Let's use graphics to display the results. fit.coef <- coef(fit.sum) results <- cbind(fit.coef[, c("Estimate", "Std. Error")], Actual=proficiency, Difference=fit.coef[, "Estimate"] - proficiency, Residual=(fit.coef[, "Estimate"] - proficiency)/fit.coef[, "Std. Error"]) hist(results[, "Residual"]) plot(results[, c("Actual", "Estimate")]) The histogram (lower left panel of the figure below) is of the differences between the estimated and actual proficiencies, expressed as multiples of the standard error of estimate. For a good procedure, these values will almost always lie between $-2$ and $2$ and be symmetrically distributed around $0$. With 1000 workers involved, though, we fully expect to see a few of these standardized differences to stretch out $3$ and even $4$ away from $0$. This is exactly the case here: the histogram is as pretty as one could hope for. (One might thing of course it's nice: these are simulated data, after all. But the symmetry confirms the weights are doing their job correctly. Using the wrong weights will tend to create an asymmetric histogram.) The scatterplot (lower right panel of the figure) directly compares estimated proficiencies to actual ones. Of course this would not be available in reality, because we do not know the actual proficiencies: herein lies the power of the computer simulation. Observe: If there had been no random variation in work (set cv=0 and rerun the code to see this), the scatterplot would be a perfect diagonal line. All estimates would be perfectly accurate. Thus, the scatter seen here reflects that variation. Occasionally, an estimated value is pretty far away from the actual value. For instance, there is one point near (110, 160) where the estimated proficiency is about 50% greater than the actual proficiency. This is almost inevitable in any large batch of data. Bear this in mind if the estimates will be used on an individual basis, such as for evaluating workers. On the whole these estimates may be excellent, but to the extent the variation in work productivity is due to causes beyond any individual's control, then for a few of the workers the estimates will be erroneous: some too high, some too low. And there's no way to tell precisely who is affected. Here are the four plots generated during this process. Finally, note that this regression method is easily adapted to controlling for other variables that plausibly might be associated with group productivity. These could include the group size, the duration of each work effort, a time variable, a factor for the manager of each group, and so on. Just include them as additional variables in the regression.
Determining largest contributor in a group
David Harris has provided a great answer, but since the question continues to be edited, perhaps it would help to see the details of his solution. Highlights of the following analysis are: Weighted
Determining largest contributor in a group David Harris has provided a great answer, but since the question continues to be edited, perhaps it would help to see the details of his solution. Highlights of the following analysis are: Weighted least squares is probably more appropriate than ordinary least squares. Because the estimates may reflect variation in productivity beyond any individual's control, be cautious about using them to evaluate individual workers. To carry this out, let's create some realistic data using specified formulas so we can evaluate the accuracy of the solution. This is done with R: set.seed(17) n.names <- 1000 groupSize <- 3.5 n.cases <- 5 * n.names # Should exceed n.names cv <- 0.10 # Must be 0 or greater groupSize <- 3.5 # Must be greater than 0 proficiency <- round(rgamma(n.names, 20, scale=5)); hist(proficiency) In these initial steps, we: Set a seed for the random number generator so anybody can exactly reproduce the results. Specify how many workers there are with n.names. Stipulate the expected number of workers per group with groupSize. Specify how many cases (observations) are available with n.cases. (Later a few of these will be eliminated because they correspond, as it happens at random, to none of the workers in our synthetic workforce.) Arrange for the amounts of work to differ randomly from what would be predicted based on the sum of each group's work "proficiencies." The value of cv is a typical proportional variation; E.g., the $0.10$ given here corresponds to a typical 10% variation (which could range beyond 30% in a few cases). Create a workforce of people with varying work proficiencies. The parameters given here for computing proficiency create a range of over 4:1 between the best and worst workers (which in my experience may even be a bit narrow for technology and professional jobs, but perhaps is wide for routine manufacturing jobs). With this synthetic workforce in hand, let's simulate their work. This amounts to creating a group of each workers (schedule) for each observation (eliminating any observations in which no workers at all were involved), summing the proficiencies of the workers in each group, and multiplying that sum by a random value (averaging exactly $1$) to reflect the variations that will inevitably occur. (If there were no variation at all, we would refer this question to the Mathematics site, where respondents could point out this problem is just a set of simultaneous linear equations which could be solved exactly for the proficiencies.) schedule <- matrix(rbinom(n.cases * n.names, 1, groupSize/n.names), nrow=n.cases) schedule <- schedule[apply(schedule, 1, sum) > 0, ] work <- round(schedule %*% proficiency * exp(rnorm(dim(schedule)[1], -cv^2/2, cv))) hist(work) I have found it's convenient to put all the workgroup data into a single data frame for analysis but to keep the work values separate: data <- data.frame(schedule) This is where we would begin with real data: we would have the worker grouping encoded by data (or schedule) and the observed work outputs in the work array. Unfortunately, if some workers are always paired, R's lm procedure simply fails with an error. We should check first for such pairings. One way is to find perfectly correlated workers in the schedule: correlations <- cor(data) outer(names(data), names(data), paste)[which(upper.tri(correlations) & correlations >= 0.999999)] The output will list pairs of always-paired workers: this can be used to combine these workers into groups, because at least we can estimate the productivity of each group, if not the individuals within it. We hope it just spits out character(0). Let's presume it does. One subtle point, implicit in the foregoing explanation, is that the variation in the work performed is multiplicative, not additive. This is realistic: the variation in output of a large group of workers will, on an absolute scale, be greater than the variation in smaller groups. Accordingly, we will get better estimates by using weighted least squares rather than ordinary least squares. The best weights to use in this particular model are the reciprocals of the work amounts. (In the event some work amounts are zero, I fudge this by adding a small amount to avoid dividing by zero.) fit <- lm(work ~ . + 0, data=data, weights=1/(max(work)/10^3+work)) fit.sum <- summary(fit) This should take just one or two seconds. Before going on we ought to perform some diagnostic tests of the fit. Although discussing those would take us too far afield here, one R command to produce useful diagnostics is plot(fit) (This will take a few seconds: it's a large dataset!) Although these few lines of code do all the work, and spit out estimated proficiencies for each worker, we wouldn't want to scan through all 1000 lines of output--at least not right away. Let's use graphics to display the results. fit.coef <- coef(fit.sum) results <- cbind(fit.coef[, c("Estimate", "Std. Error")], Actual=proficiency, Difference=fit.coef[, "Estimate"] - proficiency, Residual=(fit.coef[, "Estimate"] - proficiency)/fit.coef[, "Std. Error"]) hist(results[, "Residual"]) plot(results[, c("Actual", "Estimate")]) The histogram (lower left panel of the figure below) is of the differences between the estimated and actual proficiencies, expressed as multiples of the standard error of estimate. For a good procedure, these values will almost always lie between $-2$ and $2$ and be symmetrically distributed around $0$. With 1000 workers involved, though, we fully expect to see a few of these standardized differences to stretch out $3$ and even $4$ away from $0$. This is exactly the case here: the histogram is as pretty as one could hope for. (One might thing of course it's nice: these are simulated data, after all. But the symmetry confirms the weights are doing their job correctly. Using the wrong weights will tend to create an asymmetric histogram.) The scatterplot (lower right panel of the figure) directly compares estimated proficiencies to actual ones. Of course this would not be available in reality, because we do not know the actual proficiencies: herein lies the power of the computer simulation. Observe: If there had been no random variation in work (set cv=0 and rerun the code to see this), the scatterplot would be a perfect diagonal line. All estimates would be perfectly accurate. Thus, the scatter seen here reflects that variation. Occasionally, an estimated value is pretty far away from the actual value. For instance, there is one point near (110, 160) where the estimated proficiency is about 50% greater than the actual proficiency. This is almost inevitable in any large batch of data. Bear this in mind if the estimates will be used on an individual basis, such as for evaluating workers. On the whole these estimates may be excellent, but to the extent the variation in work productivity is due to causes beyond any individual's control, then for a few of the workers the estimates will be erroneous: some too high, some too low. And there's no way to tell precisely who is affected. Here are the four plots generated during this process. Finally, note that this regression method is easily adapted to controlling for other variables that plausibly might be associated with group productivity. These could include the group size, the duration of each work effort, a time variable, a factor for the manager of each group, and so on. Just include them as additional variables in the regression.
Determining largest contributor in a group David Harris has provided a great answer, but since the question continues to be edited, perhaps it would help to see the details of his solution. Highlights of the following analysis are: Weighted
27,800
Determining largest contributor in a group
You'd want to set up your data something like this, with 1 indicating that the person was part of the team that did that row's work: work.done Alice Bob Carl Dave Eve Fred Greg Harry Isabel 1.6631071 0 1 1 0 1 0 0 0 0 0.7951651 1 1 0 0 0 0 0 1 0 0.2650049 1 1 1 0 0 0 0 0 0 1.2733771 0 0 0 0 1 0 0 1 1 0.8086390 1 0 1 0 0 0 0 0 1 1.7323428 1 0 0 0 0 0 1 0 1 ... Then, you can just do linear regression (assuming everything is additive, etc., as you mentioned in comments). In R, the command would be lm(work.done ~ . + 0, data = my.data) The "formula" work.done ~ . + 0 says, in English, that the amount of work done depends on all the other columns (that's the ".") and that groups with no workers would do no work (that's the "+ 0"). This will give you the approximate contribution from each worker to the average group output. As discussed in the comments, if you have a pair of workers that are always together, the model won't be distinguish the contributions of the two workers from one another, and one of them will get an "NA".
Determining largest contributor in a group
You'd want to set up your data something like this, with 1 indicating that the person was part of the team that did that row's work: work.done Alice Bob Carl Dave Eve Fred Greg Harry Isabel 1.663107
Determining largest contributor in a group You'd want to set up your data something like this, with 1 indicating that the person was part of the team that did that row's work: work.done Alice Bob Carl Dave Eve Fred Greg Harry Isabel 1.6631071 0 1 1 0 1 0 0 0 0 0.7951651 1 1 0 0 0 0 0 1 0 0.2650049 1 1 1 0 0 0 0 0 0 1.2733771 0 0 0 0 1 0 0 1 1 0.8086390 1 0 1 0 0 0 0 0 1 1.7323428 1 0 0 0 0 0 1 0 1 ... Then, you can just do linear regression (assuming everything is additive, etc., as you mentioned in comments). In R, the command would be lm(work.done ~ . + 0, data = my.data) The "formula" work.done ~ . + 0 says, in English, that the amount of work done depends on all the other columns (that's the ".") and that groups with no workers would do no work (that's the "+ 0"). This will give you the approximate contribution from each worker to the average group output. As discussed in the comments, if you have a pair of workers that are always together, the model won't be distinguish the contributions of the two workers from one another, and one of them will get an "NA".
Determining largest contributor in a group You'd want to set up your data something like this, with 1 indicating that the person was part of the team that did that row's work: work.done Alice Bob Carl Dave Eve Fred Greg Harry Isabel 1.663107