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 |
|---|---|---|---|---|---|---|
17,201 | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased? | It is true that $\hat{q}$ is a biased estimate of $q$ in the sense that $\text{E}(\hat{q}) \neq q$, but you shouldn't necessarily let this deter you. This exact scenario can be used as a criticism against the idea that we should always use unbiased estimators, because here the bias is more of an artifact of the particular experiment we happen to be doing. The data look exactly as they would if we had chosen the number of samples in advance, so why should our inferences change?
Interestingly, if you were to collect data in this way and then write down the likelihood function under both the binomial (fixed sample size) and negative binomial models, you would find that the two are proportional to one another. This means that $\hat{q}$ is just the ordinary maximum likelihood estimate under the negative binomial model, which of course is a perfectly reasonable estimate. | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased? | It is true that $\hat{q}$ is a biased estimate of $q$ in the sense that $\text{E}(\hat{q}) \neq q$, but you shouldn't necessarily let this deter you. This exact scenario can be used as a criticism ag | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased?
It is true that $\hat{q}$ is a biased estimate of $q$ in the sense that $\text{E}(\hat{q}) \neq q$, but you shouldn't necessarily let this deter you. This exact scenario can be used as a criticism against the idea that we should always use unbiased estimators, because here the bias is more of an artifact of the particular experiment we happen to be doing. The data look exactly as they would if we had chosen the number of samples in advance, so why should our inferences change?
Interestingly, if you were to collect data in this way and then write down the likelihood function under both the binomial (fixed sample size) and negative binomial models, you would find that the two are proportional to one another. This means that $\hat{q}$ is just the ordinary maximum likelihood estimate under the negative binomial model, which of course is a perfectly reasonable estimate. | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased?
It is true that $\hat{q}$ is a biased estimate of $q$ in the sense that $\text{E}(\hat{q}) \neq q$, but you shouldn't necessarily let this deter you. This exact scenario can be used as a criticism ag |
17,202 | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased? | It is not insisting that the last sample is a fail which biases the estimate, it is taking the reciprocal of $N$
So $\mathbb{E}\left[\frac{N}{10}\right] =\frac{1}{q}$ in your example but $\mathbb{E}\left[\frac{10}{N}\right] \not = q$. This is close to comparing the arithmetic mean with the harmonic mean
The bad news is that the bias can increase as $q$ gets smaller, though not by much once $q$ is already small. The good news is that bias decreases as the required number of failures increases. It seems that if you require $f$ failures, then the bias is bounded above by a multiplicative factor of $\frac{f}{f-1}$ for small $q$; you do not want this approach when you stop after the first failure
Stopping after $10$ failures, with $q=0.01$ you will get $\mathbb{E}\left[\frac{N}{10}\right] = 100$ but $\mathbb{E}\left[\frac{10}{N}\right] \approx 0.011097$, while with $q=0.001$ you will get $\mathbb{E}\left[\frac{N}{10}\right] = 1000$ but $\mathbb{E}\left[\frac{10}{N}\right] \approx 0.001111$. A bias of roughly a $\frac{10}{9}$ multiplicative factor | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased? | It is not insisting that the last sample is a fail which biases the estimate, it is taking the reciprocal of $N$
So $\mathbb{E}\left[\frac{N}{10}\right] =\frac{1}{q}$ in your example but $\mathbb{E} | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased?
It is not insisting that the last sample is a fail which biases the estimate, it is taking the reciprocal of $N$
So $\mathbb{E}\left[\frac{N}{10}\right] =\frac{1}{q}$ in your example but $\mathbb{E}\left[\frac{10}{N}\right] \not = q$. This is close to comparing the arithmetic mean with the harmonic mean
The bad news is that the bias can increase as $q$ gets smaller, though not by much once $q$ is already small. The good news is that bias decreases as the required number of failures increases. It seems that if you require $f$ failures, then the bias is bounded above by a multiplicative factor of $\frac{f}{f-1}$ for small $q$; you do not want this approach when you stop after the first failure
Stopping after $10$ failures, with $q=0.01$ you will get $\mathbb{E}\left[\frac{N}{10}\right] = 100$ but $\mathbb{E}\left[\frac{10}{N}\right] \approx 0.011097$, while with $q=0.001$ you will get $\mathbb{E}\left[\frac{N}{10}\right] = 1000$ but $\mathbb{E}\left[\frac{10}{N}\right] \approx 0.001111$. A bias of roughly a $\frac{10}{9}$ multiplicative factor | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased?
It is not insisting that the last sample is a fail which biases the estimate, it is taking the reciprocal of $N$
So $\mathbb{E}\left[\frac{N}{10}\right] =\frac{1}{q}$ in your example but $\mathbb{E} |
17,203 | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased? | As a complement to dsaxton's answer, here are some simulations in R showing the sampling distribution of $\hat{q}$ when $k=10$ and $q_0 = 0.02$:
n_replications <- 10000
k <- 10
failure_prob <- 0.02
n_trials <- k + rnbinom(n_replications, size=k, prob=failure_prob)
all(n_trials >= k) # Sanity check, cannot have 10 failures in < 10 trials
estimated_failure_probability <- k / n_trials
histogram_breaks <- seq(0, max(estimated_failure_probability) + 0.001, 0.001)
## png("estimated_failure_probability.png")
hist(estimated_failure_probability, breaks=histogram_breaks)
abline(v=failure_prob, col="red", lty=2, lwd=2) # True failure probability in red
## dev.off()
mean(estimated_failure_probability) # Around 0.022
sd(estimated_failure_probability)
t.test(x=estimated_failure_probability, mu=failure_prob) # Interval around [0.0220, 0.0223]
It looks like $\mathbb{E}\left[ \hat{q}\right] \approx 0.022$, which is a rather small bias relative to the variability in $\hat{q}$. | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased? | As a complement to dsaxton's answer, here are some simulations in R showing the sampling distribution of $\hat{q}$ when $k=10$ and $q_0 = 0.02$:
n_replications <- 10000
k <- 10
failure_prob <- 0.02
n_ | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased?
As a complement to dsaxton's answer, here are some simulations in R showing the sampling distribution of $\hat{q}$ when $k=10$ and $q_0 = 0.02$:
n_replications <- 10000
k <- 10
failure_prob <- 0.02
n_trials <- k + rnbinom(n_replications, size=k, prob=failure_prob)
all(n_trials >= k) # Sanity check, cannot have 10 failures in < 10 trials
estimated_failure_probability <- k / n_trials
histogram_breaks <- seq(0, max(estimated_failure_probability) + 0.001, 0.001)
## png("estimated_failure_probability.png")
hist(estimated_failure_probability, breaks=histogram_breaks)
abline(v=failure_prob, col="red", lty=2, lwd=2) # True failure probability in red
## dev.off()
mean(estimated_failure_probability) # Around 0.022
sd(estimated_failure_probability)
t.test(x=estimated_failure_probability, mu=failure_prob) # Interval around [0.0220, 0.0223]
It looks like $\mathbb{E}\left[ \hat{q}\right] \approx 0.022$, which is a rather small bias relative to the variability in $\hat{q}$. | Estimating the probability in a Bernoulli process by sampling until 10 failures: is it biased?
As a complement to dsaxton's answer, here are some simulations in R showing the sampling distribution of $\hat{q}$ when $k=10$ and $q_0 = 0.02$:
n_replications <- 10000
k <- 10
failure_prob <- 0.02
n_ |
17,204 | What is the relationship between event and random variable? | Let the experiment be given by $ \DeclareMathOperator{\P}{\mathbb{P}} \DeclareMathOperator{\E}{\mathbb{E}} (\mathbb{X},\mathbb{B}, \P)$ where $\mathbb{X}$ is the sample space, $\mathbb{B}$ is the set of all events (subsets of $\mathbb{X}$ which we assign a probability) and $\P$ is the probability measure. Points of $\mathbb{X}$ are denoted $\omega$, and are the "elementary events" (or "outcomes"). Random variables on this experiment are functions $f \colon \mathbb{X}\mapsto \mathbb{R}$ and are written like $f(\omega)$, meaning that their value are determined by the elementary outcome $\omega$.
Corresponding to the event $A$ is the indicator random variable
$$
I_A(\omega) = \begin{cases} 1 ~\text{if $A$ occurs, that is, $\omega\in A$.} \\
0 ~\text{if $A$ do not occur, that is $\omega \not\in A$.} \end{cases}
$$
In this sense, events can be embedded as a subset of the set of all random variables defined for this experimental setup. Then the probability of $A$ occurring can be written as an expectation
$$
\P(A) = \E I_A.
$$
To the additional question in comments: If $A$ and $B$ are independent (as events), then $I_A$ and $I_B$ are independent (as random variables). "Can we say that $I_A=1$ and $I_B=1$ are independent?" Well, $I_A=1$ is simply the event $A$, so I think you can answer now! | What is the relationship between event and random variable? | Let the experiment be given by $ \DeclareMathOperator{\P}{\mathbb{P}} \DeclareMathOperator{\E}{\mathbb{E}} (\mathbb{X},\mathbb{B}, \P)$ where $\mathbb{X}$ is the sample space, $\mathbb{B}$ is the set | What is the relationship between event and random variable?
Let the experiment be given by $ \DeclareMathOperator{\P}{\mathbb{P}} \DeclareMathOperator{\E}{\mathbb{E}} (\mathbb{X},\mathbb{B}, \P)$ where $\mathbb{X}$ is the sample space, $\mathbb{B}$ is the set of all events (subsets of $\mathbb{X}$ which we assign a probability) and $\P$ is the probability measure. Points of $\mathbb{X}$ are denoted $\omega$, and are the "elementary events" (or "outcomes"). Random variables on this experiment are functions $f \colon \mathbb{X}\mapsto \mathbb{R}$ and are written like $f(\omega)$, meaning that their value are determined by the elementary outcome $\omega$.
Corresponding to the event $A$ is the indicator random variable
$$
I_A(\omega) = \begin{cases} 1 ~\text{if $A$ occurs, that is, $\omega\in A$.} \\
0 ~\text{if $A$ do not occur, that is $\omega \not\in A$.} \end{cases}
$$
In this sense, events can be embedded as a subset of the set of all random variables defined for this experimental setup. Then the probability of $A$ occurring can be written as an expectation
$$
\P(A) = \E I_A.
$$
To the additional question in comments: If $A$ and $B$ are independent (as events), then $I_A$ and $I_B$ are independent (as random variables). "Can we say that $I_A=1$ and $I_B=1$ are independent?" Well, $I_A=1$ is simply the event $A$, so I think you can answer now! | What is the relationship between event and random variable?
Let the experiment be given by $ \DeclareMathOperator{\P}{\mathbb{P}} \DeclareMathOperator{\E}{\mathbb{E}} (\mathbb{X},\mathbb{B}, \P)$ where $\mathbb{X}$ is the sample space, $\mathbb{B}$ is the set |
17,205 | What is the relationship between event and random variable? | Yes, events are like Boolean (you said binary but I take it this is what you mean) random variables or more precisely for every event there is a corresponding Boolean random variable. Different communities use slightly different terminology (indicator function, characteristic function, predicate) for the same thing, and the output type may be $\{0,1\}$ or $\{False, True\}$.
You raised the point:
an event can happen or not whereas a random variable can have multiple
outcomes.
I think probability texts often don't do enough to describe why the axioms of probability are the way they are, so I'll give a very hand-waving go at it:
Suppose you were inventing the foundations of probability theory. Your first stab might be to say there's some set of possible ways the world could be: $X$, and some kind of function which assigns probabilities to each of these possibilities $f: X \to [0,1]$. For example we could say that $X$ is the set of numbers 1 to 6 from a die roll and $f(x) = 1/6$.
Soon you would find this a little restrictive because you want to talk about subsets of possible worlds, i.e. what if the die roll is greater than 3. So you adjust your theory and instead assign probabilities to sets $\mu: \mathcal{P}(X) \to [0,1]$ where $\mathcal{P}$ denotes the set of all subsets. Each one of these subsets you call an event, and when you say an event occured what you really mean is that the real world turned out to be one of the possible worlds in that event. $\mu$ can't just assign probabilities to sets arbitrarily, it should be consistent with $f$ and common sense.
You're almost satisfied but then you realise there are other things you want to model that weren't initially accounted for in $X$. For example you want to talk about the probability that the die bounces three times.
More generally, putting your philosopher hat on, you decide its impossible (or at least very difficult) to talk about the real world, we can only talk about our limited observations of it.
So instead you construct a new object $\Omega$ which represents a richer model of the world (for example maybe it's a very accurate physical simulation of a die rolling, or even of the whole universe) but you are only allowed to talk about it with random variables.
You can now instead define $X$ as random variable (a function $\Omega \to \mathbb{N}$), and many others which each talk about properties of interest.
For every set of outcomes of a random variable (with a single outcome being just a special case) there is always a corresponding set of possible worlds (subset of $\Omega$), the event. | What is the relationship between event and random variable? | Yes, events are like Boolean (you said binary but I take it this is what you mean) random variables or more precisely for every event there is a corresponding Boolean random variable. Different commu | What is the relationship between event and random variable?
Yes, events are like Boolean (you said binary but I take it this is what you mean) random variables or more precisely for every event there is a corresponding Boolean random variable. Different communities use slightly different terminology (indicator function, characteristic function, predicate) for the same thing, and the output type may be $\{0,1\}$ or $\{False, True\}$.
You raised the point:
an event can happen or not whereas a random variable can have multiple
outcomes.
I think probability texts often don't do enough to describe why the axioms of probability are the way they are, so I'll give a very hand-waving go at it:
Suppose you were inventing the foundations of probability theory. Your first stab might be to say there's some set of possible ways the world could be: $X$, and some kind of function which assigns probabilities to each of these possibilities $f: X \to [0,1]$. For example we could say that $X$ is the set of numbers 1 to 6 from a die roll and $f(x) = 1/6$.
Soon you would find this a little restrictive because you want to talk about subsets of possible worlds, i.e. what if the die roll is greater than 3. So you adjust your theory and instead assign probabilities to sets $\mu: \mathcal{P}(X) \to [0,1]$ where $\mathcal{P}$ denotes the set of all subsets. Each one of these subsets you call an event, and when you say an event occured what you really mean is that the real world turned out to be one of the possible worlds in that event. $\mu$ can't just assign probabilities to sets arbitrarily, it should be consistent with $f$ and common sense.
You're almost satisfied but then you realise there are other things you want to model that weren't initially accounted for in $X$. For example you want to talk about the probability that the die bounces three times.
More generally, putting your philosopher hat on, you decide its impossible (or at least very difficult) to talk about the real world, we can only talk about our limited observations of it.
So instead you construct a new object $\Omega$ which represents a richer model of the world (for example maybe it's a very accurate physical simulation of a die rolling, or even of the whole universe) but you are only allowed to talk about it with random variables.
You can now instead define $X$ as random variable (a function $\Omega \to \mathbb{N}$), and many others which each talk about properties of interest.
For every set of outcomes of a random variable (with a single outcome being just a special case) there is always a corresponding set of possible worlds (subset of $\Omega$), the event. | What is the relationship between event and random variable?
Yes, events are like Boolean (you said binary but I take it this is what you mean) random variables or more precisely for every event there is a corresponding Boolean random variable. Different commu |
17,206 | What is the relationship between event and random variable? | For purposes of understanding we will limit ourselves to finite sample spaces.
Firstly in answer to your question, no, the outcome of a random variable is not an event. A random variable takes as its input an element of the sample space and outputs a real number.
For example, suppose we draw a ball from an urn having 3 balls labelled A, B and C. The sample space of all balls in the urn is S = {A, B, C}. There are 8 possible events: {}, {A}, {B}, {C}, {A, B}, {A, C}, {B, C}, {A, B, C}. The event {B, C} means that the ball drawn is either B or C.
A random variable is a real valued function on the sample space. If random variable X assigns 10 to A, 10 to B and 30 to C then if A is drawn the realized value of X is 10, a real number, not an event.
If x is a number then the event corresponding to X = x is the set of sample space elements which are mapped by X to x. In the current example, the event corresponding to X = 10 is {A, B} as both A and B are mapped to 10 and C is not.
The above relationship between random variables and events extends to other concepts. For example, random variables X and Y are independent if for each pair of real numbers x and y the events X = x and Y = y are independent. Similarly X and Y are conditionally independent given Z if the events X = x and Y = y are conditionally independent given the event Z = z.
(I am assuming here that the question is about the relationship between events and random variables and not about the definitions of probability, independence
and conditional independence which we have assumed.) | What is the relationship between event and random variable? | For purposes of understanding we will limit ourselves to finite sample spaces.
Firstly in answer to your question, no, the outcome of a random variable is not an event. A random variable takes as its | What is the relationship between event and random variable?
For purposes of understanding we will limit ourselves to finite sample spaces.
Firstly in answer to your question, no, the outcome of a random variable is not an event. A random variable takes as its input an element of the sample space and outputs a real number.
For example, suppose we draw a ball from an urn having 3 balls labelled A, B and C. The sample space of all balls in the urn is S = {A, B, C}. There are 8 possible events: {}, {A}, {B}, {C}, {A, B}, {A, C}, {B, C}, {A, B, C}. The event {B, C} means that the ball drawn is either B or C.
A random variable is a real valued function on the sample space. If random variable X assigns 10 to A, 10 to B and 30 to C then if A is drawn the realized value of X is 10, a real number, not an event.
If x is a number then the event corresponding to X = x is the set of sample space elements which are mapped by X to x. In the current example, the event corresponding to X = 10 is {A, B} as both A and B are mapped to 10 and C is not.
The above relationship between random variables and events extends to other concepts. For example, random variables X and Y are independent if for each pair of real numbers x and y the events X = x and Y = y are independent. Similarly X and Y are conditionally independent given Z if the events X = x and Y = y are conditionally independent given the event Z = z.
(I am assuming here that the question is about the relationship between events and random variables and not about the definitions of probability, independence
and conditional independence which we have assumed.) | What is the relationship between event and random variable?
For purposes of understanding we will limit ourselves to finite sample spaces.
Firstly in answer to your question, no, the outcome of a random variable is not an event. A random variable takes as its |
17,207 | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence? | Latent Dirichlet Allocation (LDA) is great, but if you want something better that uses neural networks I would strongly suggest doc2vec (https://radimrehurek.com/gensim/models/doc2vec.html).
What it does? It works similarly to Google's word2vec but instead of a single word feature vector you get a feature vector for a paragraph. The method is based on a skip-gram model and neural networks and is considered one of the best methods to extract a feature vector for documents.
Now given that you have this vector you can run k-means clustering (or any other preferable algorithm) and cluster the results.
Finally, to extract the feature vectors you can do it as easy as that:
from gensim.models import Doc2Vec
from gensim.models.doc2vec import LabeledSentence
class LabeledLineSentence(object):
def __init__(self, filename):
self.filename = filename
def __iter__(self):
for uid, line in enumerate(open(self.filename)):
yield LabeledSentence(words=line.split(), labels=['TXT_%s' % uid])
sentences = LabeledLineSentence('your_text.txt')
model = Doc2Vec(alpha=0.025, min_alpha=0.025, size=50, window=5, min_count=5,
dm=1, workers=8, sample=1e-5)
model.build_vocab(sentences)
for epoch in range(500):
try:
print 'epoch %d' % (epoch)
model.train(sentences)
model.alpha *= 0.99
model.min_alpha = model.alpha
except (KeyboardInterrupt, SystemExit):
break | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence? | Latent Dirichlet Allocation (LDA) is great, but if you want something better that uses neural networks I would strongly suggest doc2vec (https://radimrehurek.com/gensim/models/doc2vec.html).
What it d | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence?
Latent Dirichlet Allocation (LDA) is great, but if you want something better that uses neural networks I would strongly suggest doc2vec (https://radimrehurek.com/gensim/models/doc2vec.html).
What it does? It works similarly to Google's word2vec but instead of a single word feature vector you get a feature vector for a paragraph. The method is based on a skip-gram model and neural networks and is considered one of the best methods to extract a feature vector for documents.
Now given that you have this vector you can run k-means clustering (or any other preferable algorithm) and cluster the results.
Finally, to extract the feature vectors you can do it as easy as that:
from gensim.models import Doc2Vec
from gensim.models.doc2vec import LabeledSentence
class LabeledLineSentence(object):
def __init__(self, filename):
self.filename = filename
def __iter__(self):
for uid, line in enumerate(open(self.filename)):
yield LabeledSentence(words=line.split(), labels=['TXT_%s' % uid])
sentences = LabeledLineSentence('your_text.txt')
model = Doc2Vec(alpha=0.025, min_alpha=0.025, size=50, window=5, min_count=5,
dm=1, workers=8, sample=1e-5)
model.build_vocab(sentences)
for epoch in range(500):
try:
print 'epoch %d' % (epoch)
model.train(sentences)
model.alpha *= 0.99
model.min_alpha = model.alpha
except (KeyboardInterrupt, SystemExit):
break | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence?
Latent Dirichlet Allocation (LDA) is great, but if you want something better that uses neural networks I would strongly suggest doc2vec (https://radimrehurek.com/gensim/models/doc2vec.html).
What it d |
17,208 | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence? | Apart from LDA you can use Latent Semantic Analysis with K-Means. It's not neural networks, but rather "classical" clustering, but it works quite well.
Example in sklearn (taken from here):
dataset = fetch_20newsgroups(subset='all', shuffle=True, random_state=42)
labels = dataset.target
true_k = np.unique(labels).shape[0]
vectorizer = TfidfTransformer()
X = vectorizer.fit_transform(dataset.data)
svd = TruncatedSVD(true_k)
lsa = make_pipeline(svd, Normalizer(copy=False))
X = lsa.fit_transform(X)
km = KMeans(n_clusters=true_k, init='k-means++', max_iter=100)
km.fit(X)
Now cluster assignment labels are available in km.labels_
For example, these are the topics extracted from 20 newsgroups with LSA:
Cluster 0: space shuttle alaska edu nasa moon launch orbit henry sci
Cluster 1: edu game team games year ca university players hockey baseball
Cluster 2: sale 00 edu 10 offer new distribution subject lines shipping
Cluster 3: israel israeli jews arab jewish arabs edu jake peace israelis
Cluster 4: cmu andrew org com stratus edu mellon carnegie pittsburgh pa
Cluster 5: god jesus christian bible church christ christians people edu believe
Cluster 6: drive scsi card edu mac disk ide bus pc apple
Cluster 7: com ca hp subject edu lines organization writes article like
Cluster 8: car cars com edu engine ford new dealer just oil
Cluster 9: sun monitor com video edu vga east card monitors microsystems
Cluster 10: nasa gov jpl larc gsfc jsc center fnal article writes
Cluster 11: windows dos file edu ms files program os com use
Cluster 12: netcom com edu cramer fbi sandvik 408 writes article people
Cluster 13: armenian turkish armenians armenia serdar argic turks turkey genocide soviet
Cluster 14: uiuc cso edu illinois urbana uxa university writes news cobb
Cluster 15: edu cs university posting host nntp state subject organization lines
Cluster 16: uk ac window mit server lines subject university com edu
Cluster 17: caltech edu keith gatech technology institute prism morality sgi livesey
Cluster 18: key clipper chip encryption com keys escrow government algorithm des
Cluster 19: people edu gun com government don like think just access
You also can apply Non-Negative Matrix Factorization, which can be interpreted as clustering. All you need to do is to take largest component of each document in the transformed space - and use it as cluster assignment.
In sklearn:
nmf = NMF(n_components=k, random_state=1).fit_transform(X)
labels = nmf.argmax(axis=1) | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence? | Apart from LDA you can use Latent Semantic Analysis with K-Means. It's not neural networks, but rather "classical" clustering, but it works quite well.
Example in sklearn (taken from here):
dataset = | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence?
Apart from LDA you can use Latent Semantic Analysis with K-Means. It's not neural networks, but rather "classical" clustering, but it works quite well.
Example in sklearn (taken from here):
dataset = fetch_20newsgroups(subset='all', shuffle=True, random_state=42)
labels = dataset.target
true_k = np.unique(labels).shape[0]
vectorizer = TfidfTransformer()
X = vectorizer.fit_transform(dataset.data)
svd = TruncatedSVD(true_k)
lsa = make_pipeline(svd, Normalizer(copy=False))
X = lsa.fit_transform(X)
km = KMeans(n_clusters=true_k, init='k-means++', max_iter=100)
km.fit(X)
Now cluster assignment labels are available in km.labels_
For example, these are the topics extracted from 20 newsgroups with LSA:
Cluster 0: space shuttle alaska edu nasa moon launch orbit henry sci
Cluster 1: edu game team games year ca university players hockey baseball
Cluster 2: sale 00 edu 10 offer new distribution subject lines shipping
Cluster 3: israel israeli jews arab jewish arabs edu jake peace israelis
Cluster 4: cmu andrew org com stratus edu mellon carnegie pittsburgh pa
Cluster 5: god jesus christian bible church christ christians people edu believe
Cluster 6: drive scsi card edu mac disk ide bus pc apple
Cluster 7: com ca hp subject edu lines organization writes article like
Cluster 8: car cars com edu engine ford new dealer just oil
Cluster 9: sun monitor com video edu vga east card monitors microsystems
Cluster 10: nasa gov jpl larc gsfc jsc center fnal article writes
Cluster 11: windows dos file edu ms files program os com use
Cluster 12: netcom com edu cramer fbi sandvik 408 writes article people
Cluster 13: armenian turkish armenians armenia serdar argic turks turkey genocide soviet
Cluster 14: uiuc cso edu illinois urbana uxa university writes news cobb
Cluster 15: edu cs university posting host nntp state subject organization lines
Cluster 16: uk ac window mit server lines subject university com edu
Cluster 17: caltech edu keith gatech technology institute prism morality sgi livesey
Cluster 18: key clipper chip encryption com keys escrow government algorithm des
Cluster 19: people edu gun com government don like think just access
You also can apply Non-Negative Matrix Factorization, which can be interpreted as clustering. All you need to do is to take largest component of each document in the transformed space - and use it as cluster assignment.
In sklearn:
nmf = NMF(n_components=k, random_state=1).fit_transform(X)
labels = nmf.argmax(axis=1) | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence?
Apart from LDA you can use Latent Semantic Analysis with K-Means. It's not neural networks, but rather "classical" clustering, but it works quite well.
Example in sklearn (taken from here):
dataset = |
17,209 | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence? | LSA+KMeans works well but you have to input the amount of clusters you are expecting. Moreover the silhouette coefficient of the clusters found is usually low.
Another method with which I get better results is to use DBSCAN example here.
It search for centers of high density and expands to make clusters. In this method it automatically finds the optimal amount of clusters.
I've also found it very important to use a stemmer, such as Snowball for ex, which reduces the errors due to typos.
A good stop words list is also very important if you want to be sure to get rid of some clusters which would have no meaning because of the high occurrence of common words with no significant meaning.
When you build your count matrix, normalisation is also important, it allows to add weigh to a word with a low occurrence on the dataset, but with high occurrence in particular samples. These words are meaningful and you don't want to miss them. It also lowers weights of words with high occurrences in all particular samples (close to stop word but for words which can have a little meaning).
One last thing I noticed was important is not to print the top 10 words of your clusters, but a more extended selection. Usually the quality and relevance of the keywords toward the label you would give to the cluster tend to reduce dramatically after these top 10-20 words. So an extended view of top keywords will help you to analyze if your cluster is really relevant or very polluted by noise. | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence? | LSA+KMeans works well but you have to input the amount of clusters you are expecting. Moreover the silhouette coefficient of the clusters found is usually low.
Another method with which I get better r | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence?
LSA+KMeans works well but you have to input the amount of clusters you are expecting. Moreover the silhouette coefficient of the clusters found is usually low.
Another method with which I get better results is to use DBSCAN example here.
It search for centers of high density and expands to make clusters. In this method it automatically finds the optimal amount of clusters.
I've also found it very important to use a stemmer, such as Snowball for ex, which reduces the errors due to typos.
A good stop words list is also very important if you want to be sure to get rid of some clusters which would have no meaning because of the high occurrence of common words with no significant meaning.
When you build your count matrix, normalisation is also important, it allows to add weigh to a word with a low occurrence on the dataset, but with high occurrence in particular samples. These words are meaningful and you don't want to miss them. It also lowers weights of words with high occurrences in all particular samples (close to stop word but for words which can have a little meaning).
One last thing I noticed was important is not to print the top 10 words of your clusters, but a more extended selection. Usually the quality and relevance of the keywords toward the label you would give to the cluster tend to reduce dramatically after these top 10-20 words. So an extended view of top keywords will help you to analyze if your cluster is really relevant or very polluted by noise. | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence?
LSA+KMeans works well but you have to input the amount of clusters you are expecting. Moreover the silhouette coefficient of the clusters found is usually low.
Another method with which I get better r |
17,210 | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence? | My favorite method is LDA; you can look here for a tutorial using python packages.
You can also look at much simpler methods like this. | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence? | My favorite method is LDA; you can look here for a tutorial using python packages.
You can also look at much simpler methods like this. | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence?
My favorite method is LDA; you can look here for a tutorial using python packages.
You can also look at much simpler methods like this. | Text Mining: how to cluster texts (e.g. news articles) with artificial intelligence?
My favorite method is LDA; you can look here for a tutorial using python packages.
You can also look at much simpler methods like this. |
17,211 | MAD formula for outlier detection | Suppose $x$ follows a standard normal distribution.
The $\mathbf{MAD}$ will converge to the median of the half normal distribution, which is the 75% percentile of a normal distribution, and $\mathbf{N}(0.75) \simeq 0.6745$
Since you are multiplying by $(x-\hat{x})$, this means that, for any normal distribution, your formula will converge to 1 for a large enough sample size. | MAD formula for outlier detection | Suppose $x$ follows a standard normal distribution.
The $\mathbf{MAD}$ will converge to the median of the half normal distribution, which is the 75% percentile of a normal distribution, and $\mathbf{N | MAD formula for outlier detection
Suppose $x$ follows a standard normal distribution.
The $\mathbf{MAD}$ will converge to the median of the half normal distribution, which is the 75% percentile of a normal distribution, and $\mathbf{N}(0.75) \simeq 0.6745$
Since you are multiplying by $(x-\hat{x})$, this means that, for any normal distribution, your formula will converge to 1 for a large enough sample size. | MAD formula for outlier detection
Suppose $x$ follows a standard normal distribution.
The $\mathbf{MAD}$ will converge to the median of the half normal distribution, which is the 75% percentile of a normal distribution, and $\mathbf{N |
17,212 | MAD formula for outlier detection | The formula was given by Iglewicz and Hoaglin$^1$ (reference below).
Let the mad for a vector $x$ of $n$ observations be defined as $m(x) = \text{median}(|x- \text{median}(x)|)$. If $x$ is normally distributed, it can be shown that
$$
\lim_{n\rightarrow \infty}E(m(x)) = \sigma\Phi^{-1}(0.75)
$$
where $\Phi^{-1}(0.75) \approx 0.6745$ is the $0.75^\text{th}$ quantile of the standard normal distribution and is used for consistency. That is, so that
$m(x)/0.6745$ is a consistent estimator of the standard deviation $\sigma$.
If you can't assume normality, you can use the 0.75$^\text{th}$ quantile of any other distribution that is symmetric about some value (not necessarly the mean) standardised to have mean 0 and standard deviation 1. Typically a t-distribution is used if fat-tail are assumed.
Iglewicz and Hoaglin suggest using $\pm3.5$ as cut-off value but this a matter of choice ($\pm3$ is also often used).
$^1$ Boris Iglewicz and David Hoaglin (1993), "Volume 16: How to Detect and Handle Outliers", The ASQC Basic References in Quality Control: Statistical Techniques, Edward F. Mykytka, Ph.D., Editor. | MAD formula for outlier detection | The formula was given by Iglewicz and Hoaglin$^1$ (reference below).
Let the mad for a vector $x$ of $n$ observations be defined as $m(x) = \text{median}(|x- \text{median}(x)|)$. If $x$ is normally d | MAD formula for outlier detection
The formula was given by Iglewicz and Hoaglin$^1$ (reference below).
Let the mad for a vector $x$ of $n$ observations be defined as $m(x) = \text{median}(|x- \text{median}(x)|)$. If $x$ is normally distributed, it can be shown that
$$
\lim_{n\rightarrow \infty}E(m(x)) = \sigma\Phi^{-1}(0.75)
$$
where $\Phi^{-1}(0.75) \approx 0.6745$ is the $0.75^\text{th}$ quantile of the standard normal distribution and is used for consistency. That is, so that
$m(x)/0.6745$ is a consistent estimator of the standard deviation $\sigma$.
If you can't assume normality, you can use the 0.75$^\text{th}$ quantile of any other distribution that is symmetric about some value (not necessarly the mean) standardised to have mean 0 and standard deviation 1. Typically a t-distribution is used if fat-tail are assumed.
Iglewicz and Hoaglin suggest using $\pm3.5$ as cut-off value but this a matter of choice ($\pm3$ is also often used).
$^1$ Boris Iglewicz and David Hoaglin (1993), "Volume 16: How to Detect and Handle Outliers", The ASQC Basic References in Quality Control: Statistical Techniques, Edward F. Mykytka, Ph.D., Editor. | MAD formula for outlier detection
The formula was given by Iglewicz and Hoaglin$^1$ (reference below).
Let the mad for a vector $x$ of $n$ observations be defined as $m(x) = \text{median}(|x- \text{median}(x)|)$. If $x$ is normally d |
17,213 | What are some popular choices for visualizing 4-dimensional data? | If the first three are just spatial coordinates and the data are sparse you can simply do a 3D scatter plot with differently sized or colored points for the value.
Looks something like this:
(source: gatech.edu)
If your data is intended to be continuous in nature and exists on a lattice grid, you can plot several isocontours of the data using Marching Cubes.
Another approach when you have dense 4D data is to display several 2D "slices" of the data embedded in 3D. It will look something like this: | What are some popular choices for visualizing 4-dimensional data? | If the first three are just spatial coordinates and the data are sparse you can simply do a 3D scatter plot with differently sized or colored points for the value.
Looks something like this:
(source: | What are some popular choices for visualizing 4-dimensional data?
If the first three are just spatial coordinates and the data are sparse you can simply do a 3D scatter plot with differently sized or colored points for the value.
Looks something like this:
(source: gatech.edu)
If your data is intended to be continuous in nature and exists on a lattice grid, you can plot several isocontours of the data using Marching Cubes.
Another approach when you have dense 4D data is to display several 2D "slices" of the data embedded in 3D. It will look something like this: | What are some popular choices for visualizing 4-dimensional data?
If the first three are just spatial coordinates and the data are sparse you can simply do a 3D scatter plot with differently sized or colored points for the value.
Looks something like this:
(source: |
17,214 | What are some popular choices for visualizing 4-dimensional data? | Do you have four quantitative variables? If so, try tours, parallel coordinate plots, scatterplot matrices. The tourr (and tourrGui) package in R will run tours, basically rotation in high dimensions, you can choose to project into 1D, 2D or more, and there is a JSS paper that you can read to get started cited in the package. Parallel coordinate plots and scatterplot matrices are in the GGally package, also scatterplot matrices are in the YaleToolkit package. You can also look at the http://www.ggobi.org for videos and more documentation on all of these.
If your data is entirely categorical you should use mosaic plots, or variants. Take a look at the productplots package in R, also vcd has some reasonable functions, or the ggparallel package to do the equivalent of parallel coordinate plots for categorical data. Also, just found the extracat package has some functions for displaying categorical data.
I misread the question, originally, because I stopped at the question, and neglected to read the full description. Similar to the approach below (coloring points in 3D) you can use linked brushing to explore functions defined on high-dimensional spaces. Take a look at the video here which shows doing this for a 3D multivariate normal function. The brush paints points with high density (high function values) and then moves to lower and lower density values (low function values). The locations where the function is sampled are shown in a 3D rotating scatterplot, using the tour, which could be used to look at 4, 5, or higher dimensional domains also. | What are some popular choices for visualizing 4-dimensional data? | Do you have four quantitative variables? If so, try tours, parallel coordinate plots, scatterplot matrices. The tourr (and tourrGui) package in R will run tours, basically rotation in high dimensions, | What are some popular choices for visualizing 4-dimensional data?
Do you have four quantitative variables? If so, try tours, parallel coordinate plots, scatterplot matrices. The tourr (and tourrGui) package in R will run tours, basically rotation in high dimensions, you can choose to project into 1D, 2D or more, and there is a JSS paper that you can read to get started cited in the package. Parallel coordinate plots and scatterplot matrices are in the GGally package, also scatterplot matrices are in the YaleToolkit package. You can also look at the http://www.ggobi.org for videos and more documentation on all of these.
If your data is entirely categorical you should use mosaic plots, or variants. Take a look at the productplots package in R, also vcd has some reasonable functions, or the ggparallel package to do the equivalent of parallel coordinate plots for categorical data. Also, just found the extracat package has some functions for displaying categorical data.
I misread the question, originally, because I stopped at the question, and neglected to read the full description. Similar to the approach below (coloring points in 3D) you can use linked brushing to explore functions defined on high-dimensional spaces. Take a look at the video here which shows doing this for a 3D multivariate normal function. The brush paints points with high density (high function values) and then moves to lower and lower density values (low function values). The locations where the function is sampled are shown in a 3D rotating scatterplot, using the tour, which could be used to look at 4, 5, or higher dimensional domains also. | What are some popular choices for visualizing 4-dimensional data?
Do you have four quantitative variables? If so, try tours, parallel coordinate plots, scatterplot matrices. The tourr (and tourrGui) package in R will run tours, basically rotation in high dimensions, |
17,215 | What are some popular choices for visualizing 4-dimensional data? | Try Chernoff faces. The idea is to attach the variables to facial features. For instance, size of the smile would one variable, roundness of the face is another etc. As ridiculous as it sounds, this may actually work if you find out a smart way to map variables to features.
Another way is to show 2-d projections of the 3-d phase diagram. Say you have x1,x2,x3,x4 your variables. For each value of x4, draw 3-d graph of (x1,x2,x3) points, and connect the points. This works best when x4 is ordered, e.g. it's date or time.
UPDATE:
You can also try bubble plots. Three dimensions would usual cartesian x,y,z, and the 4th dimension would the size of the bubble point.
You can try animation, i.e. use time as fourth dimension.
Also a combination of bubble and animation: x,y, bubble and time.
Also, related to Chernoff is glyph plot, which may look a little more serious. It's stars with length of rays proportional to variable values. | What are some popular choices for visualizing 4-dimensional data? | Try Chernoff faces. The idea is to attach the variables to facial features. For instance, size of the smile would one variable, roundness of the face is another etc. As ridiculous as it sounds, this m | What are some popular choices for visualizing 4-dimensional data?
Try Chernoff faces. The idea is to attach the variables to facial features. For instance, size of the smile would one variable, roundness of the face is another etc. As ridiculous as it sounds, this may actually work if you find out a smart way to map variables to features.
Another way is to show 2-d projections of the 3-d phase diagram. Say you have x1,x2,x3,x4 your variables. For each value of x4, draw 3-d graph of (x1,x2,x3) points, and connect the points. This works best when x4 is ordered, e.g. it's date or time.
UPDATE:
You can also try bubble plots. Three dimensions would usual cartesian x,y,z, and the 4th dimension would the size of the bubble point.
You can try animation, i.e. use time as fourth dimension.
Also a combination of bubble and animation: x,y, bubble and time.
Also, related to Chernoff is glyph plot, which may look a little more serious. It's stars with length of rays proportional to variable values. | What are some popular choices for visualizing 4-dimensional data?
Try Chernoff faces. The idea is to attach the variables to facial features. For instance, size of the smile would one variable, roundness of the face is another etc. As ridiculous as it sounds, this m |
17,216 | Expected value of sample median given the sample mean | Let $X$ denote the original sample and $Z$ the random vector with entries $Z_k=X_k-\bar X$. Then $Z$ is normal centered (but its entries are not independent, as can be seen from the fact that their sum is zero with full probability). As a linear functional of $X$, the vector $(Z,\bar X)$ is normal hence the computation of its covariance matrix suffices to show that $Z$ is independent of $\bar X$.
Turning to $Y$, one sees that $Y=\bar X+T$ where $T$ is the median of $Z$. In particular, $T$ depends on $Z$ only hence $T$ is independent of $\bar X$, and the distribution of $Z$ is symmetric hence $T$ is centered.
Finally, $$E(Y\mid\bar X)=\bar X+E(T\mid\bar X)=\bar X+E(T)=\bar X.$$ | Expected value of sample median given the sample mean | Let $X$ denote the original sample and $Z$ the random vector with entries $Z_k=X_k-\bar X$. Then $Z$ is normal centered (but its entries are not independent, as can be seen from the fact that their su | Expected value of sample median given the sample mean
Let $X$ denote the original sample and $Z$ the random vector with entries $Z_k=X_k-\bar X$. Then $Z$ is normal centered (but its entries are not independent, as can be seen from the fact that their sum is zero with full probability). As a linear functional of $X$, the vector $(Z,\bar X)$ is normal hence the computation of its covariance matrix suffices to show that $Z$ is independent of $\bar X$.
Turning to $Y$, one sees that $Y=\bar X+T$ where $T$ is the median of $Z$. In particular, $T$ depends on $Z$ only hence $T$ is independent of $\bar X$, and the distribution of $Z$ is symmetric hence $T$ is centered.
Finally, $$E(Y\mid\bar X)=\bar X+E(T\mid\bar X)=\bar X+E(T)=\bar X.$$ | Expected value of sample median given the sample mean
Let $X$ denote the original sample and $Z$ the random vector with entries $Z_k=X_k-\bar X$. Then $Z$ is normal centered (but its entries are not independent, as can be seen from the fact that their su |
17,217 | Expected value of sample median given the sample mean | The sample median is an order statistic and has a non-normal distribution, so the joint finite-sample distribution of sample median and sample mean (which has a normal distribution) would not be bivariate normal. Resorting to approximations, asymptotically the following holds (see my answer here):
$$\sqrt n\Big [\left (\begin{matrix} \bar X_n \\ Y_n \end{matrix}\right) - \left (\begin{matrix} \mu \\ \mathbb v \end{matrix}\right)\Big ] \rightarrow_{\mathbf L}\; N\Big [\left (\begin{matrix} 0 \\ 0 \end{matrix}\right) , \Sigma \Big]$$
with
$$\Sigma = \left (\begin{matrix} \sigma^2 & E\left( |X-\mathbb v|\right)\left[2f(\mathbb v)\right]^{-1} \\ E\left(|X-\mathbb v|\right)\left[2f(\mathbb v)\right]^{-1} & \left[2f(\mathbb v)\right]^{-2} \end{matrix}\right)$$
where $\bar X_n$ is the sample mean and $\mu$ the population mean, $Y_n$ is the sample median and $\mathbb v$ the population median, $f()$ is the probability density of the random variables involved and $\sigma^2$ is the variance.
So approximately for large samples, their joint distribution is bivariate normal, so we have that
$$E(Y_n \mid \bar X_n=\bar x) = \mathbb v + \rho\frac {\sigma_{\mathbb v}}{\sigma_{\bar X}}(\bar x -\mu)$$
where $\rho$ is the correlation coefficient.
Manipulating the asymptotic distribution to become the approximate large-sample joint distribution of sample mean and sample median (and not of the standardized quantities), we have
$$\rho = \frac {\frac 1nE\left(|X-\mathbb v|\right)\left[2f(\mathbb v)\right]^{-1}}{\frac 1n \sigma \left[2f(\mathbb v)\right]^{-1}} = \frac {E\left(|X-\mathbb v|\right)}{\sigma }$$
So
$$E(Y_n \mid \bar X_n=\bar x) = \mathbb v + \frac {E\left(|X-\mathbb v|\right)}{\sigma }\frac {\left[2f(\mathbb v)\right]^{-1}}{\sigma}(\bar x -\mu)$$
We have that $2f(\mathbb v) = 2/\sigma\sqrt{2\pi}$ due to the symmetry of the normal density so we arrive at
$$E(Y_n \mid \bar X_n=\bar x) = \mathbb v + \sqrt{\frac {\pi}{2}}E\left(\left|\frac {X-\mu}{\sigma}\right|\right)(\bar x -\mu)$$
where we have used $\mathbb v = \mu$. Now the standardized variable is a standard normal, so its absolute value is a half-normal distribution with expected value equal to $\sqrt{2/\pi}$ (since the underlying variance is unity). So
$$E(Y_n \mid \bar X_n=\bar x) = \mathbb v + \sqrt{\frac {\pi}{2}}\sqrt{\frac {2}{\pi}}(\bar x -\mu) = \mathbb v + \bar x -\mu = \bar x$$ | Expected value of sample median given the sample mean | The sample median is an order statistic and has a non-normal distribution, so the joint finite-sample distribution of sample median and sample mean (which has a normal distribution) would not be bivar | Expected value of sample median given the sample mean
The sample median is an order statistic and has a non-normal distribution, so the joint finite-sample distribution of sample median and sample mean (which has a normal distribution) would not be bivariate normal. Resorting to approximations, asymptotically the following holds (see my answer here):
$$\sqrt n\Big [\left (\begin{matrix} \bar X_n \\ Y_n \end{matrix}\right) - \left (\begin{matrix} \mu \\ \mathbb v \end{matrix}\right)\Big ] \rightarrow_{\mathbf L}\; N\Big [\left (\begin{matrix} 0 \\ 0 \end{matrix}\right) , \Sigma \Big]$$
with
$$\Sigma = \left (\begin{matrix} \sigma^2 & E\left( |X-\mathbb v|\right)\left[2f(\mathbb v)\right]^{-1} \\ E\left(|X-\mathbb v|\right)\left[2f(\mathbb v)\right]^{-1} & \left[2f(\mathbb v)\right]^{-2} \end{matrix}\right)$$
where $\bar X_n$ is the sample mean and $\mu$ the population mean, $Y_n$ is the sample median and $\mathbb v$ the population median, $f()$ is the probability density of the random variables involved and $\sigma^2$ is the variance.
So approximately for large samples, their joint distribution is bivariate normal, so we have that
$$E(Y_n \mid \bar X_n=\bar x) = \mathbb v + \rho\frac {\sigma_{\mathbb v}}{\sigma_{\bar X}}(\bar x -\mu)$$
where $\rho$ is the correlation coefficient.
Manipulating the asymptotic distribution to become the approximate large-sample joint distribution of sample mean and sample median (and not of the standardized quantities), we have
$$\rho = \frac {\frac 1nE\left(|X-\mathbb v|\right)\left[2f(\mathbb v)\right]^{-1}}{\frac 1n \sigma \left[2f(\mathbb v)\right]^{-1}} = \frac {E\left(|X-\mathbb v|\right)}{\sigma }$$
So
$$E(Y_n \mid \bar X_n=\bar x) = \mathbb v + \frac {E\left(|X-\mathbb v|\right)}{\sigma }\frac {\left[2f(\mathbb v)\right]^{-1}}{\sigma}(\bar x -\mu)$$
We have that $2f(\mathbb v) = 2/\sigma\sqrt{2\pi}$ due to the symmetry of the normal density so we arrive at
$$E(Y_n \mid \bar X_n=\bar x) = \mathbb v + \sqrt{\frac {\pi}{2}}E\left(\left|\frac {X-\mu}{\sigma}\right|\right)(\bar x -\mu)$$
where we have used $\mathbb v = \mu$. Now the standardized variable is a standard normal, so its absolute value is a half-normal distribution with expected value equal to $\sqrt{2/\pi}$ (since the underlying variance is unity). So
$$E(Y_n \mid \bar X_n=\bar x) = \mathbb v + \sqrt{\frac {\pi}{2}}\sqrt{\frac {2}{\pi}}(\bar x -\mu) = \mathbb v + \bar x -\mu = \bar x$$ | Expected value of sample median given the sample mean
The sample median is an order statistic and has a non-normal distribution, so the joint finite-sample distribution of sample median and sample mean (which has a normal distribution) would not be bivar |
17,218 | Expected value of sample median given the sample mean | The answer is $\bar{x}$.
Let $x = (x_1, x_2, \ldots, x_n)$ have a multivariate distribution $F$ for which all the marginals are symmetric about a common value $\mu$. (It does not matter whether they are independent or even are identically distributed.) Define $\bar{x}$ to be the arithmetic mean of the $x_i,$ $\bar{x} = (x_1+x_2+\cdots+x_n)/n$ and write $x-\bar{x} = (x_1-\bar{x}, x_2-\bar{x}, \ldots, x_n-\bar{x})$ for the vector of residuals. The symmetry assumption on $F$ implies the distribution of $x - \bar{x}$ is symmetric about $0$; that is, when $E\subset\mathbb{R}^n$ is any event,
$${\Pr}_F(x - \bar{x}\in E) = {\Pr}_F(x - \bar{x}\in -E).$$
Applying the generalized result at https://stats.stackexchange.com/a/83887 shows that the median of $x-\bar{x}$ has a symmetric distribution about $0$. Assuming its expectation exists (which is certainly the case when the marginal distributions of the $x_i$ are Normal), that expectation has to be $0$ (because the symmetry implies it equals its own negative).
Now since subtracting the same value $\bar{x}$ from each of a set of values does not change their order, $Y$ (the median of the $x_i$) equals $\bar{x}$ plus the median of $x-\bar{x}$. Consequently its expectation conditional on $\bar{x}$ equals the expectation of $x-\bar{x}$ conditional on $\bar{x}$, plus $E(\bar{x}\ |\ \bar{x})$. The latter obviously is $\bar{x}$ whereas the former is $0$ because the unconditional expectation is $0$. Their sum is $\bar{x},$ QED. | Expected value of sample median given the sample mean | The answer is $\bar{x}$.
Let $x = (x_1, x_2, \ldots, x_n)$ have a multivariate distribution $F$ for which all the marginals are symmetric about a common value $\mu$. (It does not matter whether they | Expected value of sample median given the sample mean
The answer is $\bar{x}$.
Let $x = (x_1, x_2, \ldots, x_n)$ have a multivariate distribution $F$ for which all the marginals are symmetric about a common value $\mu$. (It does not matter whether they are independent or even are identically distributed.) Define $\bar{x}$ to be the arithmetic mean of the $x_i,$ $\bar{x} = (x_1+x_2+\cdots+x_n)/n$ and write $x-\bar{x} = (x_1-\bar{x}, x_2-\bar{x}, \ldots, x_n-\bar{x})$ for the vector of residuals. The symmetry assumption on $F$ implies the distribution of $x - \bar{x}$ is symmetric about $0$; that is, when $E\subset\mathbb{R}^n$ is any event,
$${\Pr}_F(x - \bar{x}\in E) = {\Pr}_F(x - \bar{x}\in -E).$$
Applying the generalized result at https://stats.stackexchange.com/a/83887 shows that the median of $x-\bar{x}$ has a symmetric distribution about $0$. Assuming its expectation exists (which is certainly the case when the marginal distributions of the $x_i$ are Normal), that expectation has to be $0$ (because the symmetry implies it equals its own negative).
Now since subtracting the same value $\bar{x}$ from each of a set of values does not change their order, $Y$ (the median of the $x_i$) equals $\bar{x}$ plus the median of $x-\bar{x}$. Consequently its expectation conditional on $\bar{x}$ equals the expectation of $x-\bar{x}$ conditional on $\bar{x}$, plus $E(\bar{x}\ |\ \bar{x})$. The latter obviously is $\bar{x}$ whereas the former is $0$ because the unconditional expectation is $0$. Their sum is $\bar{x},$ QED. | Expected value of sample median given the sample mean
The answer is $\bar{x}$.
Let $x = (x_1, x_2, \ldots, x_n)$ have a multivariate distribution $F$ for which all the marginals are symmetric about a common value $\mu$. (It does not matter whether they |
17,219 | Expected value of sample median given the sample mean | This is simpler than the above answers make it. The sample mean is a complete and sufficient statistic (when the variance is known, but our results do not depend on the variance, hence will be valid also in the situation when the variance is unknown). Then the Rao-Blackwell together with the Lehmann-Scheffe theorems (see wikipedia ...) will imply that the conditional expectation of the median, given the arithmetic mean, is the unique minimum variance unbiased estimator of the expectation $\mu$. But we know that is the arithmetic mean, hence the result follows.
We did also use that the median is an unbiased estimator, which follows from symmetry. | Expected value of sample median given the sample mean | This is simpler than the above answers make it. The sample mean is a complete and sufficient statistic (when the variance is known, but our results do not depend on the variance, hence will be valid | Expected value of sample median given the sample mean
This is simpler than the above answers make it. The sample mean is a complete and sufficient statistic (when the variance is known, but our results do not depend on the variance, hence will be valid also in the situation when the variance is unknown). Then the Rao-Blackwell together with the Lehmann-Scheffe theorems (see wikipedia ...) will imply that the conditional expectation of the median, given the arithmetic mean, is the unique minimum variance unbiased estimator of the expectation $\mu$. But we know that is the arithmetic mean, hence the result follows.
We did also use that the median is an unbiased estimator, which follows from symmetry. | Expected value of sample median given the sample mean
This is simpler than the above answers make it. The sample mean is a complete and sufficient statistic (when the variance is known, but our results do not depend on the variance, hence will be valid |
17,220 | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant? | I agree with Glen_b on this. Maybe I can add a few words to make the point even clearer. If data come from a normal distribution (iid situation) with an unknown variance the t statistic is the pivotal quantity used to generate confidence intervals and do hypothesis testing. The only thing that matters for that inference is its distribution under the null hypothesis (for determining the critical value) and under the alternative (to determine power and sample). Those are the central and noncentral t distributions, respectively. Now considering for a moment the one sample problem, the t test even has optimal properties as a test for the mean of a normal distribution. Now the sample variance is an unbiased estimator of the population variance but its square root is a BIASED estimator of the population standard deviation. It doesn't matter that this BIASED estimator enters in the denominator of the pivotal quantity. Now it does play a role in that it is a consistent estimator. That is what allows the t distribution to approach the standard normal as the sample size goes to infinity. But being biased for any fixed $n$ does not affect the nice properties of the test.
In my opinion unbiasedness is overemphasized in introductory statistics classes. Accuracy and consistency of estimators are the real properties that deserve emphasis.
For other problems where parametric or nonparametric methods are applied, an estimate of standard deviation does not even enter into the formula. | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant? | I agree with Glen_b on this. Maybe I can add a few words to make the point even clearer. If data come from a normal distribution (iid situation) with an unknown variance the t statistic is the pivota | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant?
I agree with Glen_b on this. Maybe I can add a few words to make the point even clearer. If data come from a normal distribution (iid situation) with an unknown variance the t statistic is the pivotal quantity used to generate confidence intervals and do hypothesis testing. The only thing that matters for that inference is its distribution under the null hypothesis (for determining the critical value) and under the alternative (to determine power and sample). Those are the central and noncentral t distributions, respectively. Now considering for a moment the one sample problem, the t test even has optimal properties as a test for the mean of a normal distribution. Now the sample variance is an unbiased estimator of the population variance but its square root is a BIASED estimator of the population standard deviation. It doesn't matter that this BIASED estimator enters in the denominator of the pivotal quantity. Now it does play a role in that it is a consistent estimator. That is what allows the t distribution to approach the standard normal as the sample size goes to infinity. But being biased for any fixed $n$ does not affect the nice properties of the test.
In my opinion unbiasedness is overemphasized in introductory statistics classes. Accuracy and consistency of estimators are the real properties that deserve emphasis.
For other problems where parametric or nonparametric methods are applied, an estimate of standard deviation does not even enter into the formula. | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant?
I agree with Glen_b on this. Maybe I can add a few words to make the point even clearer. If data come from a normal distribution (iid situation) with an unknown variance the t statistic is the pivota |
17,221 | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant? | Consider an interval calculated on the basis of a pivotal quantity, like a t-statistic. The mean value of the estimator for standard deviation doesn't really come into it - the interval is based on the distribution of the statistic. So the statement is right as far as that goes. | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant? | Consider an interval calculated on the basis of a pivotal quantity, like a t-statistic. The mean value of the estimator for standard deviation doesn't really come into it - the interval is based on th | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant?
Consider an interval calculated on the basis of a pivotal quantity, like a t-statistic. The mean value of the estimator for standard deviation doesn't really come into it - the interval is based on the distribution of the statistic. So the statement is right as far as that goes. | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant?
Consider an interval calculated on the basis of a pivotal quantity, like a t-statistic. The mean value of the estimator for standard deviation doesn't really come into it - the interval is based on th |
17,222 | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant? | Interpretation is always part speculation, but I think the implied meaning is that often you can get the result you want without estimating the standard deviation explicitly. In other words, I think the author is referring to situations where you would use no estimate of the standard deviation, rather than a biased estimate.
For instance, if you can construct an estimate of the whole distribution of a statistic, you can compute confidence intervals without using the standard deviation. In fact, for many (non-normal) distributions the standard deviation itself (and the mean) is not sufficient to compute an estimate of the confidence interval. In other cases, such as a sign test, you do not need an estimate for the standard deviation either.
(Of course, it is non-trivial to construct an unbiased estimate of a full distribution, and in Bayesian statistics it is actually quite common to introduce bias explicitly through the prior.) | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant? | Interpretation is always part speculation, but I think the implied meaning is that often you can get the result you want without estimating the standard deviation explicitly. In other words, I think t | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant?
Interpretation is always part speculation, but I think the implied meaning is that often you can get the result you want without estimating the standard deviation explicitly. In other words, I think the author is referring to situations where you would use no estimate of the standard deviation, rather than a biased estimate.
For instance, if you can construct an estimate of the whole distribution of a statistic, you can compute confidence intervals without using the standard deviation. In fact, for many (non-normal) distributions the standard deviation itself (and the mean) is not sufficient to compute an estimate of the confidence interval. In other cases, such as a sign test, you do not need an estimate for the standard deviation either.
(Of course, it is non-trivial to construct an unbiased estimate of a full distribution, and in Bayesian statistics it is actually quite common to introduce bias explicitly through the prior.) | Why does this excerpt say that unbiased estimation of standard deviation usually isn't relevant?
Interpretation is always part speculation, but I think the implied meaning is that often you can get the result you want without estimating the standard deviation explicitly. In other words, I think t |
17,223 | Measures of residuals heteroscedasticity | This problem has an exploratory feel to it. John Tukey describes many procedures for exploring heteroscedasticity in his classic, Exploratory Data Analysis (Addison-Wesley 1977). Perhaps the most directly useful is a variant of his "wandering schematic plot." This slices one variable (such as the predicted value) into bins and uses m-letter summaries (generalizations of boxplots) to show the location, spread, and shape of the other variable for each bin. The m-letter statistics are further smoothed in order to emphasize overall patterns rather than chance deviations.
A quick version can be cooked up by exploiting the boxplot procedure in R. We illustrate with simulated strongly heteroscedastic data:
set.seed(17)
n <- 500
x <- rgamma(n, shape=6, scale=1/2)
e <- rnorm(length(x), sd=abs(sin(x)))
y <- x + e
Let's obtain the predicted values and residuals from the OLS regression:
fit <- lm(y ~ x)
res <- residuals(fit)
pred <- predict(fit)
Here, then, is the wandering schematic plot using equal-count bins for the predicted values. I use lowess for a quick-and-dirty smooth.
n.bins <- 17
bins <- cut(pred, quantile(pred,
probs = seq(0, 1, 1/n.bins)))
b <- boxplot(res ~ bins, boxwex=1/2,
main="Residuals vs. Predicted",
xlab="Predicted", ylab="Residual")
colors <- hsv(seq(2/6, 1, 1/6))
temp <- sapply(1:5, function(i) lines(lowess(1:n.bins,
b$stats[i,], f=.25),
col=colors[i], lwd=2))
The blue curve smooths the medians. Its horizontal tendency indicates the regression is generally a good fit. The other curves smooth the box ends (quartiles) and fences (which are typically extreme values). Their strong convergence and subsequent separation testify to the heteroscedasticity--and help us characterize and quantify it.
(Notice the nonlinear scale on the horizontal axis, reflecting the distribution of predicted values. With a bit more work this axis could be linearized, which sometimes is useful.) | Measures of residuals heteroscedasticity | This problem has an exploratory feel to it. John Tukey describes many procedures for exploring heteroscedasticity in his classic, Exploratory Data Analysis (Addison-Wesley 1977). Perhaps the most di | Measures of residuals heteroscedasticity
This problem has an exploratory feel to it. John Tukey describes many procedures for exploring heteroscedasticity in his classic, Exploratory Data Analysis (Addison-Wesley 1977). Perhaps the most directly useful is a variant of his "wandering schematic plot." This slices one variable (such as the predicted value) into bins and uses m-letter summaries (generalizations of boxplots) to show the location, spread, and shape of the other variable for each bin. The m-letter statistics are further smoothed in order to emphasize overall patterns rather than chance deviations.
A quick version can be cooked up by exploiting the boxplot procedure in R. We illustrate with simulated strongly heteroscedastic data:
set.seed(17)
n <- 500
x <- rgamma(n, shape=6, scale=1/2)
e <- rnorm(length(x), sd=abs(sin(x)))
y <- x + e
Let's obtain the predicted values and residuals from the OLS regression:
fit <- lm(y ~ x)
res <- residuals(fit)
pred <- predict(fit)
Here, then, is the wandering schematic plot using equal-count bins for the predicted values. I use lowess for a quick-and-dirty smooth.
n.bins <- 17
bins <- cut(pred, quantile(pred,
probs = seq(0, 1, 1/n.bins)))
b <- boxplot(res ~ bins, boxwex=1/2,
main="Residuals vs. Predicted",
xlab="Predicted", ylab="Residual")
colors <- hsv(seq(2/6, 1, 1/6))
temp <- sapply(1:5, function(i) lines(lowess(1:n.bins,
b$stats[i,], f=.25),
col=colors[i], lwd=2))
The blue curve smooths the medians. Its horizontal tendency indicates the regression is generally a good fit. The other curves smooth the box ends (quartiles) and fences (which are typically extreme values). Their strong convergence and subsequent separation testify to the heteroscedasticity--and help us characterize and quantify it.
(Notice the nonlinear scale on the horizontal axis, reflecting the distribution of predicted values. With a bit more work this axis could be linearized, which sometimes is useful.) | Measures of residuals heteroscedasticity
This problem has an exploratory feel to it. John Tukey describes many procedures for exploring heteroscedasticity in his classic, Exploratory Data Analysis (Addison-Wesley 1977). Perhaps the most di |
17,224 | Measures of residuals heteroscedasticity | Typically, heteroskedasticity is modeled using a Breusch-Pagan approach. The residuals from your linear regression are then squared and regressed onto the variables in your original linear model. The latter regression is called an auxiliary regression.
$nR^2_a$, where $n$ is the number of observations and $R^2_a$ is the $R^2$ from the auxiliary regression serves as a test statistic for the null hypothesis of homoskedasticity.
For your purposes, you could focus on the individual coefficients from this model to see which variables are most predictive of high or low variance outcomes. | Measures of residuals heteroscedasticity | Typically, heteroskedasticity is modeled using a Breusch-Pagan approach. The residuals from your linear regression are then squared and regressed onto the variables in your original linear model. The | Measures of residuals heteroscedasticity
Typically, heteroskedasticity is modeled using a Breusch-Pagan approach. The residuals from your linear regression are then squared and regressed onto the variables in your original linear model. The latter regression is called an auxiliary regression.
$nR^2_a$, where $n$ is the number of observations and $R^2_a$ is the $R^2$ from the auxiliary regression serves as a test statistic for the null hypothesis of homoskedasticity.
For your purposes, you could focus on the individual coefficients from this model to see which variables are most predictive of high or low variance outcomes. | Measures of residuals heteroscedasticity
Typically, heteroskedasticity is modeled using a Breusch-Pagan approach. The residuals from your linear regression are then squared and regressed onto the variables in your original linear model. The |
17,225 | Looking for a step through an example of a factor analysis on dichotomous data (binary variables) using R | I take it the focus of the question is less on the theoretical side, and more on the practical side, i.e., how to implement a factor analysis of dichotomous data in R.
First, let's simulate 200 observations from 6 variables, coming from 2 orthogonal factors. I'll take a couple of intermediate steps and start with multivariate normal continuous data that I later dichotomize. That way, we can compare Pearson correlations with polychoric correlations, and compare factor loadings from continuous data with that from dichotomous data and the true loadings.
set.seed(1.234)
N <- 200 # number of observations
P <- 6 # number of variables
Q <- 2 # number of factors
# true P x Q loading matrix -> variable-factor correlations
Lambda <- matrix(c(0.7,-0.4, 0.8,0, -0.2,0.9, -0.3,0.4, 0.3,0.7, -0.8,0.1),
nrow=P, ncol=Q, byrow=TRUE)
Now simulate the actual data from the model $x = \Lambda f + e$, with $x$ being the observed variable values of a person, $\Lambda$ the true loadings matrix, $f$ the latent factor score, and $e$ iid, mean 0, normal errors.
library(mvtnorm) # for rmvnorm()
FF <- rmvnorm(N, mean=c(5, 15), sigma=diag(Q)) # factor scores (uncorrelated factors)
E <- rmvnorm(N, rep(0, P), diag(P)) # matrix with iid, mean 0, normal errors
X <- FF %*% t(Lambda) + E # matrix with variable values
Xdf <- data.frame(X) # data also as a data frame
Do the factor analysis for the continuous data. The estimated loadings are similar to the true ones when ignoring the irrelevant sign.
> library(psych) # for fa(), fa.poly(), factor.plot(), fa.diagram(), fa.parallel.poly, vss()
> fa(X, nfactors=2, rotate="varimax")$loadings # factor analysis continuous data
Loadings:
MR2 MR1
[1,] -0.602 -0.125
[2,] -0.450 0.102
[3,] 0.341 0.386
[4,] 0.443 0.251
[5,] -0.156 0.985
[6,] 0.590
Now let's dichotomize the data. We'll keep the data in two formats: as a data frame with ordered factors, and as a numeric matrix. hetcor() from package polycor gives us the polychoric correlation matrix we'll later use for the FA.
# dichotomize variables into a list of ordered factors
Xdi <- lapply(Xdf, function(x) cut(x, breaks=c(-Inf, median(x), Inf), ordered=TRUE))
Xdidf <- do.call("data.frame", Xdi) # combine list into a data frame
XdiNum <- data.matrix(Xdidf) # dichotomized data as a numeric matrix
library(polycor) # for hetcor()
pc <- hetcor(Xdidf, ML=TRUE) # polychoric corr matrix -> component correlations
Now use the polychoric correlation matrix to do a regular FA. Note that the estimated loadings are fairly similar to the ones from the continuous data.
> faPC <- fa(r=pc$correlations, nfactors=2, n.obs=N, rotate="varimax")
> faPC$loadings
Loadings:
MR2 MR1
X1 -0.706 -0.150
X2 -0.278 0.167
X3 0.482 0.182
X4 0.598 0.226
X5 0.143 0.987
X6 0.571
You can skip the step of calculating the polychoric correlation matrix yourself, and directly use fa.poly() from package psych, which does the same thing in the end. This function accepts the raw dichotomous data as a numeric matrix.
faPCdirect <- fa.poly(XdiNum, nfactors=2, rotate="varimax") # polychoric FA
faPCdirect$fa$loadings # loadings are the same as above ...
EDIT: For factor scores, look at package ltm which has a factor.scores() function specifically for polytomous outcome data. An example is provided on this page -> "Factor Scores - Ability Estimates".
You can visualize the loadings from the factor analysis using factor.plot() and fa.diagram(), both from package psych. For some reason, factor.plot() accepts only the $fa component of the result from fa.poly(), not the full object.
factor.plot(faPCdirect$fa, cut=0.5)
fa.diagram(faPCdirect)
Parallel analysis and a "very simple structure" analysis provide help in selecting the number of factors. Again, package psych has the required functions. vss() takes the polychoric correlation matrix as an argument.
fa.parallel.poly(XdiNum) # parallel analysis for dichotomous data
vss(pc$correlations, n.obs=N, rotate="varimax") # very simple structure
Parallel analysis for polychoric FA is also provided by the package random.polychor.pa.
library(random.polychor.pa) # for random.polychor.pa()
random.polychor.pa(data.matrix=XdiNum, nrep=5, q.eigen=0.99)
Note that the functions fa() and fa.poly() provide many many more options to set up the FA. In addition, I edited out some of the output which gives goodness of fit tests etc. The documentation for these functions (and package psych in general) is excellent. This example here is just intended to get you started. | Looking for a step through an example of a factor analysis on dichotomous data (binary variables) us | I take it the focus of the question is less on the theoretical side, and more on the practical side, i.e., how to implement a factor analysis of dichotomous data in R.
First, let's simulate 200 observ | Looking for a step through an example of a factor analysis on dichotomous data (binary variables) using R
I take it the focus of the question is less on the theoretical side, and more on the practical side, i.e., how to implement a factor analysis of dichotomous data in R.
First, let's simulate 200 observations from 6 variables, coming from 2 orthogonal factors. I'll take a couple of intermediate steps and start with multivariate normal continuous data that I later dichotomize. That way, we can compare Pearson correlations with polychoric correlations, and compare factor loadings from continuous data with that from dichotomous data and the true loadings.
set.seed(1.234)
N <- 200 # number of observations
P <- 6 # number of variables
Q <- 2 # number of factors
# true P x Q loading matrix -> variable-factor correlations
Lambda <- matrix(c(0.7,-0.4, 0.8,0, -0.2,0.9, -0.3,0.4, 0.3,0.7, -0.8,0.1),
nrow=P, ncol=Q, byrow=TRUE)
Now simulate the actual data from the model $x = \Lambda f + e$, with $x$ being the observed variable values of a person, $\Lambda$ the true loadings matrix, $f$ the latent factor score, and $e$ iid, mean 0, normal errors.
library(mvtnorm) # for rmvnorm()
FF <- rmvnorm(N, mean=c(5, 15), sigma=diag(Q)) # factor scores (uncorrelated factors)
E <- rmvnorm(N, rep(0, P), diag(P)) # matrix with iid, mean 0, normal errors
X <- FF %*% t(Lambda) + E # matrix with variable values
Xdf <- data.frame(X) # data also as a data frame
Do the factor analysis for the continuous data. The estimated loadings are similar to the true ones when ignoring the irrelevant sign.
> library(psych) # for fa(), fa.poly(), factor.plot(), fa.diagram(), fa.parallel.poly, vss()
> fa(X, nfactors=2, rotate="varimax")$loadings # factor analysis continuous data
Loadings:
MR2 MR1
[1,] -0.602 -0.125
[2,] -0.450 0.102
[3,] 0.341 0.386
[4,] 0.443 0.251
[5,] -0.156 0.985
[6,] 0.590
Now let's dichotomize the data. We'll keep the data in two formats: as a data frame with ordered factors, and as a numeric matrix. hetcor() from package polycor gives us the polychoric correlation matrix we'll later use for the FA.
# dichotomize variables into a list of ordered factors
Xdi <- lapply(Xdf, function(x) cut(x, breaks=c(-Inf, median(x), Inf), ordered=TRUE))
Xdidf <- do.call("data.frame", Xdi) # combine list into a data frame
XdiNum <- data.matrix(Xdidf) # dichotomized data as a numeric matrix
library(polycor) # for hetcor()
pc <- hetcor(Xdidf, ML=TRUE) # polychoric corr matrix -> component correlations
Now use the polychoric correlation matrix to do a regular FA. Note that the estimated loadings are fairly similar to the ones from the continuous data.
> faPC <- fa(r=pc$correlations, nfactors=2, n.obs=N, rotate="varimax")
> faPC$loadings
Loadings:
MR2 MR1
X1 -0.706 -0.150
X2 -0.278 0.167
X3 0.482 0.182
X4 0.598 0.226
X5 0.143 0.987
X6 0.571
You can skip the step of calculating the polychoric correlation matrix yourself, and directly use fa.poly() from package psych, which does the same thing in the end. This function accepts the raw dichotomous data as a numeric matrix.
faPCdirect <- fa.poly(XdiNum, nfactors=2, rotate="varimax") # polychoric FA
faPCdirect$fa$loadings # loadings are the same as above ...
EDIT: For factor scores, look at package ltm which has a factor.scores() function specifically for polytomous outcome data. An example is provided on this page -> "Factor Scores - Ability Estimates".
You can visualize the loadings from the factor analysis using factor.plot() and fa.diagram(), both from package psych. For some reason, factor.plot() accepts only the $fa component of the result from fa.poly(), not the full object.
factor.plot(faPCdirect$fa, cut=0.5)
fa.diagram(faPCdirect)
Parallel analysis and a "very simple structure" analysis provide help in selecting the number of factors. Again, package psych has the required functions. vss() takes the polychoric correlation matrix as an argument.
fa.parallel.poly(XdiNum) # parallel analysis for dichotomous data
vss(pc$correlations, n.obs=N, rotate="varimax") # very simple structure
Parallel analysis for polychoric FA is also provided by the package random.polychor.pa.
library(random.polychor.pa) # for random.polychor.pa()
random.polychor.pa(data.matrix=XdiNum, nrep=5, q.eigen=0.99)
Note that the functions fa() and fa.poly() provide many many more options to set up the FA. In addition, I edited out some of the output which gives goodness of fit tests etc. The documentation for these functions (and package psych in general) is excellent. This example here is just intended to get you started. | Looking for a step through an example of a factor analysis on dichotomous data (binary variables) us
I take it the focus of the question is less on the theoretical side, and more on the practical side, i.e., how to implement a factor analysis of dichotomous data in R.
First, let's simulate 200 observ |
17,226 | Do you reject the null hypothesis when $p < \alpha$ or $p \leq \alpha$? | Relying on Lehmann and Romano, Testing Statistical Hypotheses, $\leq$. Defining $S_1$ as the region of rejection and $\Omega_H$ as the null hypothesis region, loosely speaking, we have the following statement, p. 57 in my copy:
Thus one selects a number $\alpha$ between 0 and 1, called the level
of significance, and imposes the condition that:
... $P_\theta\{X \in S_1\} \leq \alpha \text{ for all } \theta \in
\Omega_H$
Since it is possible that $P_\theta\{X \in S_1\} = \alpha$, it follows that you'd reject for p-values $\leq \alpha$.
On a more intuitive level, imagine a test on a discrete parameter space, and a best (most powerful) rejection region with a probability of exactly 0.05 under the null hypothesis. Assume the next largest (in terms of probability) best rejection region had a probability of 0.001 under the null hypothesis. It would be kind of difficult to justify, again intuitively speaking, saying that the first region was not equivalent to an "at the 95% level of confidence..." decision but that you had to use the second region to reach the 95% level of confidence. | Do you reject the null hypothesis when $p < \alpha$ or $p \leq \alpha$? | Relying on Lehmann and Romano, Testing Statistical Hypotheses, $\leq$. Defining $S_1$ as the region of rejection and $\Omega_H$ as the null hypothesis region, loosely speaking, we have the following | Do you reject the null hypothesis when $p < \alpha$ or $p \leq \alpha$?
Relying on Lehmann and Romano, Testing Statistical Hypotheses, $\leq$. Defining $S_1$ as the region of rejection and $\Omega_H$ as the null hypothesis region, loosely speaking, we have the following statement, p. 57 in my copy:
Thus one selects a number $\alpha$ between 0 and 1, called the level
of significance, and imposes the condition that:
... $P_\theta\{X \in S_1\} \leq \alpha \text{ for all } \theta \in
\Omega_H$
Since it is possible that $P_\theta\{X \in S_1\} = \alpha$, it follows that you'd reject for p-values $\leq \alpha$.
On a more intuitive level, imagine a test on a discrete parameter space, and a best (most powerful) rejection region with a probability of exactly 0.05 under the null hypothesis. Assume the next largest (in terms of probability) best rejection region had a probability of 0.001 under the null hypothesis. It would be kind of difficult to justify, again intuitively speaking, saying that the first region was not equivalent to an "at the 95% level of confidence..." decision but that you had to use the second region to reach the 95% level of confidence. | Do you reject the null hypothesis when $p < \alpha$ or $p \leq \alpha$?
Relying on Lehmann and Romano, Testing Statistical Hypotheses, $\leq$. Defining $S_1$ as the region of rejection and $\Omega_H$ as the null hypothesis region, loosely speaking, we have the following |
17,227 | Do you reject the null hypothesis when $p < \alpha$ or $p \leq \alpha$? | You've touched on an interesting and somewhat controversial issue. This can be humorously summarized by this image (found on Andrew Gelman's blog but originally courtesy of Dan Goldstein):
First of all, there is nothing magical about .05. As long as you pick your threshold beforehand, a threshold of .1 or .01 could make just as much sense. To that end, either choosing that you want to use a cutoff of $<.05$ or $\leq.05$ would be equally justifiable, provided that you did not cheat by changing your cutoff after having observed your p-value.
If you want to look at this in the strictest sense then, if you beforehand chose a cutoff of $<.05$ (which I believe to be more "standard") and you observe p to be exactly equal to .05, technically you'd be cheating under standard frequentist techniques. But therein lies part of the problem with this whole approach. We are making a binary problem "statistically significant or not" out of something that is not really a binary problem at all. As Andrew Gelman and Hal Stern aptly put it, "The difference between 'significant' and 'not significant' is not itself statistically significant." | Do you reject the null hypothesis when $p < \alpha$ or $p \leq \alpha$? | You've touched on an interesting and somewhat controversial issue. This can be humorously summarized by this image (found on Andrew Gelman's blog but originally courtesy of Dan Goldstein):
First of | Do you reject the null hypothesis when $p < \alpha$ or $p \leq \alpha$?
You've touched on an interesting and somewhat controversial issue. This can be humorously summarized by this image (found on Andrew Gelman's blog but originally courtesy of Dan Goldstein):
First of all, there is nothing magical about .05. As long as you pick your threshold beforehand, a threshold of .1 or .01 could make just as much sense. To that end, either choosing that you want to use a cutoff of $<.05$ or $\leq.05$ would be equally justifiable, provided that you did not cheat by changing your cutoff after having observed your p-value.
If you want to look at this in the strictest sense then, if you beforehand chose a cutoff of $<.05$ (which I believe to be more "standard") and you observe p to be exactly equal to .05, technically you'd be cheating under standard frequentist techniques. But therein lies part of the problem with this whole approach. We are making a binary problem "statistically significant or not" out of something that is not really a binary problem at all. As Andrew Gelman and Hal Stern aptly put it, "The difference between 'significant' and 'not significant' is not itself statistically significant." | Do you reject the null hypothesis when $p < \alpha$ or $p \leq \alpha$?
You've touched on an interesting and somewhat controversial issue. This can be humorously summarized by this image (found on Andrew Gelman's blog but originally courtesy of Dan Goldstein):
First of |
17,228 | Where to find a large text corpus? [closed] | Do not the Wikileaks texts suit you? | Where to find a large text corpus? [closed] | Do not the Wikileaks texts suit you? | Where to find a large text corpus? [closed]
Do not the Wikileaks texts suit you? | Where to find a large text corpus? [closed]
Do not the Wikileaks texts suit you? |
17,229 | Where to find a large text corpus? [closed] | What about wikinews? Here's the latest database dump I could find: http://dumps.wikimedia.org/enwikinews/20111120/
You probably want the "All pages, current versions only."-version. | Where to find a large text corpus? [closed] | What about wikinews? Here's the latest database dump I could find: http://dumps.wikimedia.org/enwikinews/20111120/
You probably want the "All pages, current versions only."-version. | Where to find a large text corpus? [closed]
What about wikinews? Here's the latest database dump I could find: http://dumps.wikimedia.org/enwikinews/20111120/
You probably want the "All pages, current versions only."-version. | Where to find a large text corpus? [closed]
What about wikinews? Here's the latest database dump I could find: http://dumps.wikimedia.org/enwikinews/20111120/
You probably want the "All pages, current versions only."-version. |
17,230 | Where to find a large text corpus? [closed] | The reuters text corpus is a classic in the field, and can be found here | Where to find a large text corpus? [closed] | The reuters text corpus is a classic in the field, and can be found here | Where to find a large text corpus? [closed]
The reuters text corpus is a classic in the field, and can be found here | Where to find a large text corpus? [closed]
The reuters text corpus is a classic in the field, and can be found here |
17,231 | Where to find a large text corpus? [closed] | http://endb-consolidated.aihit.com/datasets.htm contains 10K companies with textual descriptions | Where to find a large text corpus? [closed] | http://endb-consolidated.aihit.com/datasets.htm contains 10K companies with textual descriptions | Where to find a large text corpus? [closed]
http://endb-consolidated.aihit.com/datasets.htm contains 10K companies with textual descriptions | Where to find a large text corpus? [closed]
http://endb-consolidated.aihit.com/datasets.htm contains 10K companies with textual descriptions |
17,232 | Where to find a large text corpus? [closed] | If recency is not an issue, you can try
http://www.infochimps.com/datasets/20-newsgroups-dataset-de-duped-version
and there are other many more similar dataset in infochimp depending on your budget.
Regards,
Andy. | Where to find a large text corpus? [closed] | If recency is not an issue, you can try
http://www.infochimps.com/datasets/20-newsgroups-dataset-de-duped-version
and there are other many more similar dataset in infochimp depending on your budget.
| Where to find a large text corpus? [closed]
If recency is not an issue, you can try
http://www.infochimps.com/datasets/20-newsgroups-dataset-de-duped-version
and there are other many more similar dataset in infochimp depending on your budget.
Regards,
Andy. | Where to find a large text corpus? [closed]
If recency is not an issue, you can try
http://www.infochimps.com/datasets/20-newsgroups-dataset-de-duped-version
and there are other many more similar dataset in infochimp depending on your budget.
|
17,233 | Where to find a large text corpus? [closed] | If you want precomputed n-grams, you could try the google books archive:
http://books.google.com/ngrams/datasets | Where to find a large text corpus? [closed] | If you want precomputed n-grams, you could try the google books archive:
http://books.google.com/ngrams/datasets | Where to find a large text corpus? [closed]
If you want precomputed n-grams, you could try the google books archive:
http://books.google.com/ngrams/datasets | Where to find a large text corpus? [closed]
If you want precomputed n-grams, you could try the google books archive:
http://books.google.com/ngrams/datasets |
17,234 | How to put values over bars in barplot in R [closed] | To add text to a plot, just use the text command. From @chl's answer to your previous question:
##Create data
x = replicate(2, sample(letters[1:2], 100, rep=T))
apply(x, 2, table)
##Create plot
barplot(matrix(c(5, 3, 8, 9), nr=2), beside=TRUE,
col=c("aquamarine3", "coral"),
names.arg=LETTERS[1:2],
ylim=range(0,12)))
##Add text at coordinates: x=2, y=6
##Use trial and error to place them
text(2, 6, "A label")
text(5, 10, "Another label") | How to put values over bars in barplot in R [closed] | To add text to a plot, just use the text command. From @chl's answer to your previous question:
##Create data
x = replicate(2, sample(letters[1:2], 100, rep=T))
apply(x, 2, table)
##Create plot
barpl | How to put values over bars in barplot in R [closed]
To add text to a plot, just use the text command. From @chl's answer to your previous question:
##Create data
x = replicate(2, sample(letters[1:2], 100, rep=T))
apply(x, 2, table)
##Create plot
barplot(matrix(c(5, 3, 8, 9), nr=2), beside=TRUE,
col=c("aquamarine3", "coral"),
names.arg=LETTERS[1:2],
ylim=range(0,12)))
##Add text at coordinates: x=2, y=6
##Use trial and error to place them
text(2, 6, "A label")
text(5, 10, "Another label") | How to put values over bars in barplot in R [closed]
To add text to a plot, just use the text command. From @chl's answer to your previous question:
##Create data
x = replicate(2, sample(letters[1:2], 100, rep=T))
apply(x, 2, table)
##Create plot
barpl |
17,235 | How to put values over bars in barplot in R [closed] | Another example of the use of text command
u <- c(3.2,6.6,11.7,16.3,16.6,15.4,14.6,12.7,11.4,10.2,9.8,9.1,9.1,9.0,8.8,8.4,7.7)
p <-c(3737,3761,3784,3802,3825,3839,3850,3862,3878,3890,3901,3909,3918,3926,3935,3948)
-c(385,394,401,409,422,430,434,437,437,435,436,437,439,442,447,452)
e <- c(2504,2375,2206,2071,2054,2099,2127,2170,2222,2296,2335,2367,2372,2365,2365,2401)
par(mar=c(2,3,1,2),las=1,mgp=c(2.2,1,0))
x <- barplot(u,names.arg=1990:2006,col="palegreen4",space=.3,ylim=c(0,20),
ylab="%",xaxs="r",xlim=c(.8,21.6))
text(x,u+.4,format(u,T))
lines(x[-17],100*e/p-55,lwd=2)
points(x[-17],100*e/p-55,lwd=2,cex=1.5,pch=1)
axis(4,seq(0,20,5),seq(55,75,5))
text(c(x[1]+1,x[5],x[16]+1),c(100*e/p-55)[c(1,5,16)]+c(0,-1,0),
format(c(100*e/p)[c(1,5,16)],T,di=3))
box() | How to put values over bars in barplot in R [closed] | Another example of the use of text command
u <- c(3.2,6.6,11.7,16.3,16.6,15.4,14.6,12.7,11.4,10.2,9.8,9.1,9.1,9.0,8.8,8.4,7.7)
p <-c(3737,3761,3784,3802,3825,3839,3850,3862,3878,3890,3901,3909,3918,39 | How to put values over bars in barplot in R [closed]
Another example of the use of text command
u <- c(3.2,6.6,11.7,16.3,16.6,15.4,14.6,12.7,11.4,10.2,9.8,9.1,9.1,9.0,8.8,8.4,7.7)
p <-c(3737,3761,3784,3802,3825,3839,3850,3862,3878,3890,3901,3909,3918,3926,3935,3948)
-c(385,394,401,409,422,430,434,437,437,435,436,437,439,442,447,452)
e <- c(2504,2375,2206,2071,2054,2099,2127,2170,2222,2296,2335,2367,2372,2365,2365,2401)
par(mar=c(2,3,1,2),las=1,mgp=c(2.2,1,0))
x <- barplot(u,names.arg=1990:2006,col="palegreen4",space=.3,ylim=c(0,20),
ylab="%",xaxs="r",xlim=c(.8,21.6))
text(x,u+.4,format(u,T))
lines(x[-17],100*e/p-55,lwd=2)
points(x[-17],100*e/p-55,lwd=2,cex=1.5,pch=1)
axis(4,seq(0,20,5),seq(55,75,5))
text(c(x[1]+1,x[5],x[16]+1),c(100*e/p-55)[c(1,5,16)]+c(0,-1,0),
format(c(100*e/p)[c(1,5,16)],T,di=3))
box() | How to put values over bars in barplot in R [closed]
Another example of the use of text command
u <- c(3.2,6.6,11.7,16.3,16.6,15.4,14.6,12.7,11.4,10.2,9.8,9.1,9.1,9.0,8.8,8.4,7.7)
p <-c(3737,3761,3784,3802,3825,3839,3850,3862,3878,3890,3901,3909,3918,39 |
17,236 | How to put values over bars in barplot in R [closed] | If you're learning to plot in R you might look at the R graph gallery (original here).
All the graphs there are posted with the code used to build them. Its a good resource. | How to put values over bars in barplot in R [closed] | If you're learning to plot in R you might look at the R graph gallery (original here).
All the graphs there are posted with the code used to build them. Its a good resource. | How to put values over bars in barplot in R [closed]
If you're learning to plot in R you might look at the R graph gallery (original here).
All the graphs there are posted with the code used to build them. Its a good resource. | How to put values over bars in barplot in R [closed]
If you're learning to plot in R you might look at the R graph gallery (original here).
All the graphs there are posted with the code used to build them. Its a good resource. |
17,237 | For neural networks, is mini-batching done purely because of memory constraints? | There is evidence that supports the proposition that it is best to use the biggest batch size your machine can handle. See e.g. Goyal et al. (2018).
However, that paper (and another) reveal optimization difficulties with extremely large batch sizes. There is concern that large-batch optimization converges to "sharp" minima that generalize less well. Goyal et al. present some strategies to avoid those optimization difficulties (e.g. low-training-rate warmup phase, how to adjust learning rate dependent on batch size, training data shuffling each epoch). | For neural networks, is mini-batching done purely because of memory constraints? | There is evidence that supports the proposition that it is best to use the biggest batch size your machine can handle. See e.g. Goyal et al. (2018).
However, that paper (and another) reveal optimizati | For neural networks, is mini-batching done purely because of memory constraints?
There is evidence that supports the proposition that it is best to use the biggest batch size your machine can handle. See e.g. Goyal et al. (2018).
However, that paper (and another) reveal optimization difficulties with extremely large batch sizes. There is concern that large-batch optimization converges to "sharp" minima that generalize less well. Goyal et al. present some strategies to avoid those optimization difficulties (e.g. low-training-rate warmup phase, how to adjust learning rate dependent on batch size, training data shuffling each epoch). | For neural networks, is mini-batching done purely because of memory constraints?
There is evidence that supports the proposition that it is best to use the biggest batch size your machine can handle. See e.g. Goyal et al. (2018).
However, that paper (and another) reveal optimizati |
17,238 | For neural networks, is mini-batching done purely because of memory constraints? | It's complicated. We're trying to balance multiple effects. Yes, you are right in your reasoning as far as it goes, but there are other considerations as well.
GPU utilization favors larger batches, up to a point. Larger batches allow us to parallelize the computation -- up until you max out the capacity of your GPU. GPUs are designed to do many copies of the same computation in parallel. So, a mini-batch of only one sample is usually wasteful: it doesn't use the full capacity of your GPU. Depending on your GPU and the network, there will be some number of copies of the neural network it can run in parallel. It can be beneficial to set a batch size around that number. For instance, suppose your GPU can support a batch size of up to 64. Then using a batch size of 32 will only use 50% of the capacity of your GPU, wasting its power and causing training to take 2x longer than necessary; using a batch size of 64 will use its full capability and make training time the fastest possible; and using a batch size larger than 64 won't offer any further speedups.
Mathematical optimization favors larger batches, in some sense. One way to view training a neural network is as solving a mathematical optimization problem: namely, we're trying to find network weights that minimize the training loss. Gradient descent gives you some kind of approximation to the optimal solution. From that perspective, yes, if you fix the number of iterations of gradient descent, then the larger the batch size, the better the quality of the solution gradient descent finds (the lower the training loss). So, yes, from this perspective, what you write is absolutely correct.
Generalization favors smaller batches. It turns out there is another, subtler issue: generalization. It turns out that if you try as hard as you possibly can to find the optimal solution to the learning optimization problem (and in particular, run gradient descent for as long as you can stand to), neural networks tend to overfit to the training data and thus generalize poorly to other data. This is bad. There are various methods for combating overfitting, but one of the most fundamental methods used in neural networks is "early stopping": namely, we stop gradient descent early, before it has reached an optimal solution to the optimization problem. This is bit counter-intuitive, because it means that we are deliberately accepting a poorer solution to the optimization problem. It is surprising that it is beneficial to do so, but it turns out that early stopping acts as a form of regularization and helps the neural network generalize better. As far as I know it is an open question exactly why early stopping helps, but it does.
And, as a result, using very large batches is in tension with early stopping. My understanding is that using very large batches has a somewhat similar effect to running gradient descent for a long time, and thus may cause overfitting. Intuitively, running for 1000 iterations of gradient descent with a batch size of 128 is vaguely comparable to 2000 iterations with a batch size of 64, so you can perhaps see why, for a fixed number of iterations of gradient descent, larger batch sizes pose a greater risk of overfitting.
Just to add to the complications, in practice we don't hold the number of iterations fixed. Instead, we hold fixed the batch size * the number of iterations. This is typically measured in terms of the number of epochs, which is measured as the batch size * the number of iterations / the size of the training set. For a fixed number of epochs, it turns out that using a smaller batch size gives a slightly better solution to the optimization problem, so we have some incentives to use smaller batch sizes. This effect might be relatively minor, for the ranges of batch sizes used in practice, but if you tried to put the entire training set in one batch, this might potentially lead to a degradation in the effectiveness of the learned model. (The number of iterations determines how long it takes to train the model on a single GPU, in wall-clock time; the number of epochs determines how much energy or computation it takes to train the model, in total.)
Summary. We are dealing with competing concerns. From the perspective of generalization and overfitting, it might be best to use a batch size of 1, or small batches. But this would make very inefficient use of GPUs, and would make training take prohibitively long. From the perspective of using your GPU fully and making training complete in a reasonable amount of time, we are incentivized to use a batch size large enough to fully utilize all of the GPU's parallel computing units. So, in practice, it's common to choose batch sizes somewhere around there. | For neural networks, is mini-batching done purely because of memory constraints? | It's complicated. We're trying to balance multiple effects. Yes, you are right in your reasoning as far as it goes, but there are other considerations as well.
GPU utilization favors larger batches, | For neural networks, is mini-batching done purely because of memory constraints?
It's complicated. We're trying to balance multiple effects. Yes, you are right in your reasoning as far as it goes, but there are other considerations as well.
GPU utilization favors larger batches, up to a point. Larger batches allow us to parallelize the computation -- up until you max out the capacity of your GPU. GPUs are designed to do many copies of the same computation in parallel. So, a mini-batch of only one sample is usually wasteful: it doesn't use the full capacity of your GPU. Depending on your GPU and the network, there will be some number of copies of the neural network it can run in parallel. It can be beneficial to set a batch size around that number. For instance, suppose your GPU can support a batch size of up to 64. Then using a batch size of 32 will only use 50% of the capacity of your GPU, wasting its power and causing training to take 2x longer than necessary; using a batch size of 64 will use its full capability and make training time the fastest possible; and using a batch size larger than 64 won't offer any further speedups.
Mathematical optimization favors larger batches, in some sense. One way to view training a neural network is as solving a mathematical optimization problem: namely, we're trying to find network weights that minimize the training loss. Gradient descent gives you some kind of approximation to the optimal solution. From that perspective, yes, if you fix the number of iterations of gradient descent, then the larger the batch size, the better the quality of the solution gradient descent finds (the lower the training loss). So, yes, from this perspective, what you write is absolutely correct.
Generalization favors smaller batches. It turns out there is another, subtler issue: generalization. It turns out that if you try as hard as you possibly can to find the optimal solution to the learning optimization problem (and in particular, run gradient descent for as long as you can stand to), neural networks tend to overfit to the training data and thus generalize poorly to other data. This is bad. There are various methods for combating overfitting, but one of the most fundamental methods used in neural networks is "early stopping": namely, we stop gradient descent early, before it has reached an optimal solution to the optimization problem. This is bit counter-intuitive, because it means that we are deliberately accepting a poorer solution to the optimization problem. It is surprising that it is beneficial to do so, but it turns out that early stopping acts as a form of regularization and helps the neural network generalize better. As far as I know it is an open question exactly why early stopping helps, but it does.
And, as a result, using very large batches is in tension with early stopping. My understanding is that using very large batches has a somewhat similar effect to running gradient descent for a long time, and thus may cause overfitting. Intuitively, running for 1000 iterations of gradient descent with a batch size of 128 is vaguely comparable to 2000 iterations with a batch size of 64, so you can perhaps see why, for a fixed number of iterations of gradient descent, larger batch sizes pose a greater risk of overfitting.
Just to add to the complications, in practice we don't hold the number of iterations fixed. Instead, we hold fixed the batch size * the number of iterations. This is typically measured in terms of the number of epochs, which is measured as the batch size * the number of iterations / the size of the training set. For a fixed number of epochs, it turns out that using a smaller batch size gives a slightly better solution to the optimization problem, so we have some incentives to use smaller batch sizes. This effect might be relatively minor, for the ranges of batch sizes used in practice, but if you tried to put the entire training set in one batch, this might potentially lead to a degradation in the effectiveness of the learned model. (The number of iterations determines how long it takes to train the model on a single GPU, in wall-clock time; the number of epochs determines how much energy or computation it takes to train the model, in total.)
Summary. We are dealing with competing concerns. From the perspective of generalization and overfitting, it might be best to use a batch size of 1, or small batches. But this would make very inefficient use of GPUs, and would make training take prohibitively long. From the perspective of using your GPU fully and making training complete in a reasonable amount of time, we are incentivized to use a batch size large enough to fully utilize all of the GPU's parallel computing units. So, in practice, it's common to choose batch sizes somewhere around there. | For neural networks, is mini-batching done purely because of memory constraints?
It's complicated. We're trying to balance multiple effects. Yes, you are right in your reasoning as far as it goes, but there are other considerations as well.
GPU utilization favors larger batches, |
17,239 | For neural networks, is mini-batching done purely because of memory constraints? | so you have to understand that neural networks are used as 'computation-bound' statistical models. ie they are solving the problem how accurate can I get with a budget of X compute-hours.
reasoning with a mental model of modelling in under an hour will lead you astray.
minibatch is a tradeoff of stochasticity and iteration speed vs accuracy.
you will be able to achieve more iterations in the same time if you have a smaller minibatch - iteration speed
(batch) gradient descent will get stuck in local minima. so some stochasticity is beneficial.
stochastic gradient descent (ie updating after each sample) will be too noisy (ie the single sample gradient is too far from the batch gradient)
somewhere in between is therefore beneficial. the law of large numbers would suggest that accuracy of the estimate only scales with square root of the number of samples - halving the error requires 4 times the samples, quartering the error requires 16 times the samples (and therefore corresponding computation time...) | For neural networks, is mini-batching done purely because of memory constraints? | so you have to understand that neural networks are used as 'computation-bound' statistical models. ie they are solving the problem how accurate can I get with a budget of X compute-hours.
reasoning wi | For neural networks, is mini-batching done purely because of memory constraints?
so you have to understand that neural networks are used as 'computation-bound' statistical models. ie they are solving the problem how accurate can I get with a budget of X compute-hours.
reasoning with a mental model of modelling in under an hour will lead you astray.
minibatch is a tradeoff of stochasticity and iteration speed vs accuracy.
you will be able to achieve more iterations in the same time if you have a smaller minibatch - iteration speed
(batch) gradient descent will get stuck in local minima. so some stochasticity is beneficial.
stochastic gradient descent (ie updating after each sample) will be too noisy (ie the single sample gradient is too far from the batch gradient)
somewhere in between is therefore beneficial. the law of large numbers would suggest that accuracy of the estimate only scales with square root of the number of samples - halving the error requires 4 times the samples, quartering the error requires 16 times the samples (and therefore corresponding computation time...) | For neural networks, is mini-batching done purely because of memory constraints?
so you have to understand that neural networks are used as 'computation-bound' statistical models. ie they are solving the problem how accurate can I get with a budget of X compute-hours.
reasoning wi |
17,240 | For neural networks, is mini-batching done purely because of memory constraints? | It might be useful to consider the extreme cases of mini-batch sizes: using a single sample vs taking all $N$ samples in one go. These are sometimes also referred to as on-line and batch learning, respectively.
For on-line learning (single sample), we could list the following properties (I am probably ignoring a lot here):
The gradient will depend on the sample we consider. This makes the update process stochastic, which is believed to benefit generalisation.
The updates have to be applied sequentially, since there is no possibility for parallellisation across samples. We first have to apply the update due to the current sample, before we can move to the next.
After one pass through the dataset, we will have made $N$ updates.
For batch learning ($N$ samples), on the other hand, we have
The gradient is always going to be the same. This is because we are computing the true gradient for the training data, which is deterministic. Of course, this also means that only the training error is guaranteed to go down.
The computations can be massively parallellised. We can compute the gradient for each sample at the same time and we only have to accumulate them in the end.
After one pass through the dataset, we will have made $1$ update.
Conceptually, the on-line learning scenario is arguably more attractive.
After all, we get much more updates out of a single pass through the data and generalisation performance should be better.
The batch learning scenario, on the other hand, looks more promising in practice, because it can benefit from parallellisation, reducing run/waiting times.
However, modern datasets can be so large that it has become impossible to use all data at once, which obviously cripples this argument.
In the end, the size of your mini-batches seems to be a trade-off between how long you want to wait for computations and how good you want your model to generalise. At least for small datasets.
If you are working with huge datasets, you will probably end up with mini-batches that consist of a collection of single samples for a subset of all possible classes. As a result, the gradients will be stochastic enough to provide generalisation benefits. Moreover, you might have to wait weeks instead of days if you don't take a sufficiently large batch size to finish a single pass through the data. Also, some architectures rely on a sufficiently large batch size to work properly (e.g. batchnorm, CLIP, ...)
TL;DR: it's a trade-off that probably depends on the size of the data.
Wait a minute... Who said that more updates is better?
That turns out to depend on how you do the updates.
If the gradient for a single sample, $(\boldsymbol{x}_i, \boldsymbol{y}_i),$ would be $$\nabla_\theta L(g(\boldsymbol{x}_i \mathbin{;} \theta), \boldsymbol{y}_i)$$ (with $\theta$ the set of parameters and $L$ some loss function), the gradient for the entire dataset should equal $$\sum_{i=1}^N \nabla_\theta L(g(\boldsymbol{x}_i \mathbin{;} \theta), \boldsymbol{y}_i).$$
If we use each sample exactly once in the on-line setting the $N$ updates should be roughly equivalent to the single update from the full-batch setting.
Especially if the learning rate is small enough (i.e. the individual updates do not change the weights too much).
The figure below illustrates the learning curves when trained on the sum of errors.
Note that performance does not depend on the number of updates (but it does depend on the number of passes through the data).
However, instead of optimising the sum of errors, it is actually more common to optimise the average error. This means that the update in the online setting remains the same, whereas the update for the full batch is reduced by a factor $N$:
$$\frac{1}{N} \sum_{i=1}^N \nabla_\theta L(g(\boldsymbol{x}_i \mathbin{;} \theta), \boldsymbol{y}_i).$$
In this case, the update in the full batch setting is much smaller (in the same scale as a single update in the online setting, if you want).
This also means that more updates leads to better performance.
The figure below illustrates the learning curves when trained on the average error. Note that the performance depends on the number of updates (and not on the number of passes through the data). | For neural networks, is mini-batching done purely because of memory constraints? | It might be useful to consider the extreme cases of mini-batch sizes: using a single sample vs taking all $N$ samples in one go. These are sometimes also referred to as on-line and batch learning, res | For neural networks, is mini-batching done purely because of memory constraints?
It might be useful to consider the extreme cases of mini-batch sizes: using a single sample vs taking all $N$ samples in one go. These are sometimes also referred to as on-line and batch learning, respectively.
For on-line learning (single sample), we could list the following properties (I am probably ignoring a lot here):
The gradient will depend on the sample we consider. This makes the update process stochastic, which is believed to benefit generalisation.
The updates have to be applied sequentially, since there is no possibility for parallellisation across samples. We first have to apply the update due to the current sample, before we can move to the next.
After one pass through the dataset, we will have made $N$ updates.
For batch learning ($N$ samples), on the other hand, we have
The gradient is always going to be the same. This is because we are computing the true gradient for the training data, which is deterministic. Of course, this also means that only the training error is guaranteed to go down.
The computations can be massively parallellised. We can compute the gradient for each sample at the same time and we only have to accumulate them in the end.
After one pass through the dataset, we will have made $1$ update.
Conceptually, the on-line learning scenario is arguably more attractive.
After all, we get much more updates out of a single pass through the data and generalisation performance should be better.
The batch learning scenario, on the other hand, looks more promising in practice, because it can benefit from parallellisation, reducing run/waiting times.
However, modern datasets can be so large that it has become impossible to use all data at once, which obviously cripples this argument.
In the end, the size of your mini-batches seems to be a trade-off between how long you want to wait for computations and how good you want your model to generalise. At least for small datasets.
If you are working with huge datasets, you will probably end up with mini-batches that consist of a collection of single samples for a subset of all possible classes. As a result, the gradients will be stochastic enough to provide generalisation benefits. Moreover, you might have to wait weeks instead of days if you don't take a sufficiently large batch size to finish a single pass through the data. Also, some architectures rely on a sufficiently large batch size to work properly (e.g. batchnorm, CLIP, ...)
TL;DR: it's a trade-off that probably depends on the size of the data.
Wait a minute... Who said that more updates is better?
That turns out to depend on how you do the updates.
If the gradient for a single sample, $(\boldsymbol{x}_i, \boldsymbol{y}_i),$ would be $$\nabla_\theta L(g(\boldsymbol{x}_i \mathbin{;} \theta), \boldsymbol{y}_i)$$ (with $\theta$ the set of parameters and $L$ some loss function), the gradient for the entire dataset should equal $$\sum_{i=1}^N \nabla_\theta L(g(\boldsymbol{x}_i \mathbin{;} \theta), \boldsymbol{y}_i).$$
If we use each sample exactly once in the on-line setting the $N$ updates should be roughly equivalent to the single update from the full-batch setting.
Especially if the learning rate is small enough (i.e. the individual updates do not change the weights too much).
The figure below illustrates the learning curves when trained on the sum of errors.
Note that performance does not depend on the number of updates (but it does depend on the number of passes through the data).
However, instead of optimising the sum of errors, it is actually more common to optimise the average error. This means that the update in the online setting remains the same, whereas the update for the full batch is reduced by a factor $N$:
$$\frac{1}{N} \sum_{i=1}^N \nabla_\theta L(g(\boldsymbol{x}_i \mathbin{;} \theta), \boldsymbol{y}_i).$$
In this case, the update in the full batch setting is much smaller (in the same scale as a single update in the online setting, if you want).
This also means that more updates leads to better performance.
The figure below illustrates the learning curves when trained on the average error. Note that the performance depends on the number of updates (and not on the number of passes through the data). | For neural networks, is mini-batching done purely because of memory constraints?
It might be useful to consider the extreme cases of mini-batch sizes: using a single sample vs taking all $N$ samples in one go. These are sometimes also referred to as on-line and batch learning, res |
17,241 | For neural networks, is mini-batching done purely because of memory constraints? | It is difficult to prove anything and many results assume some network architectures, unless you can use fit everything into 1 batch.
But from my experience, for small batch sizes relative to the dataset, you want smaller learning rate than when using larger batch sizes (intuitively, you want the general direction to be the sum of many small vectors). Problem is nobody knows what is small enough or large enough is, but we have general idea for some network architectures.
Furthermore, with many training algorithms, the learning rates can adapt and it can get really complex to prove anything.
To improve your training speed, do make batch size as large as possible unless you can fit your entire data into one batch, then breaking it down to mini batches may help you break out of the first local minimum you encounter. There is nothing, however, that guarantees that the other minimums are better than your first local minimum. It is an empirical result really... | For neural networks, is mini-batching done purely because of memory constraints? | It is difficult to prove anything and many results assume some network architectures, unless you can use fit everything into 1 batch.
But from my experience, for small batch sizes relative to the data | For neural networks, is mini-batching done purely because of memory constraints?
It is difficult to prove anything and many results assume some network architectures, unless you can use fit everything into 1 batch.
But from my experience, for small batch sizes relative to the dataset, you want smaller learning rate than when using larger batch sizes (intuitively, you want the general direction to be the sum of many small vectors). Problem is nobody knows what is small enough or large enough is, but we have general idea for some network architectures.
Furthermore, with many training algorithms, the learning rates can adapt and it can get really complex to prove anything.
To improve your training speed, do make batch size as large as possible unless you can fit your entire data into one batch, then breaking it down to mini batches may help you break out of the first local minimum you encounter. There is nothing, however, that guarantees that the other minimums are better than your first local minimum. It is an empirical result really... | For neural networks, is mini-batching done purely because of memory constraints?
It is difficult to prove anything and many results assume some network architectures, unless you can use fit everything into 1 batch.
But from my experience, for small batch sizes relative to the data |
17,242 | Why does this algorithm generate a standard normal distribution? | I was wondering how anyone would come up with this idea.
You observe, correctly, that the $Y_i$ have exponential distributions. They were easy to generate from a standard uniform number generator. The question could be put like this:
Find a simple way to exploit your ability to generate $(Y_1,Y_2)$ to draw values $Z$ following any continuous distribution with positive support.
Such a distribution is one with a density function proportional to $e^{g(z)}$ for a function $g$ defined on the positive numbers.
The key terms "simple" and "proportional to" suggest trying a rejection sampling method. That leads to the algorithm in the question in the following generalized form:
Generate $(Y_1,Y_2)$ and keep $Y_1$ provided $Y_2 \gt f(Y_1)$ for some function $f$ to be determined.
Although it might feel more natural to reject when $Y_2\le f(Y_1),$ as we will see this equivalent formulation leads to a simple calculation.
The result of this sampling procedure evidently produces values of $Y_1$ conditional on the event $Y_2 \gt f(Y_1).$ To find its distribution function, apply the (elementary) definition of conditional probability to the event $Y_1 \le z$ for an arbitrary positive number $z.$ It states
$$\Pr(Y_1\le z \mid Y_2 \gt f(Y_1)) \ \propto\ \Pr(Y_1\le z\text{ and }Y_2 \gt f(Y_1)).$$
We needn't be concerned about the constant of proportionality because we can work it out at the very end, knowing the result has to evaluate to $1$ as $z\to\infty$ (by the axiom of Total Probability).
Because $(Y_1,Y_2)$ is independent, their joint density is exponential. Thus, assuming $f(z) \ge 0$ for all $z\gt 0,$
$$\begin{aligned}
\int_0^z e^{g(y_1)}\,\mathrm{d}y_1 &= \Pr(Y_1\le z\text{ and }Y_2 \gt f(Y_1)) \\
&\propto \int_0^z e^{-y_1}\int_{f(y_1)}^\infty e^{-y_2}\,\mathrm{d}y_2\mathrm{d}y_1\\
&= \int_0^z e^{-y_1 - f(y_1)}\,\mathrm{d}y_1.
\end{aligned}$$
Equality will hold for all $z$ provided the two integrands are equal. Solving for $f$ gives
$$f(z) = -z - g(z) + C$$
where the number $C$ accounts for the neglected proportionality constant $e^C.$
Consider the Half Normal distribution where $g(z) = -z^2/2.$ We find
$$f(z) = -z + z^2/2 + C = (1 - z)^2/2 + C - 1/2.$$
We will need $C \ge 1/2$ to assure $f(z)$ is nonnegative. Larger values of $C$ work, too, but cause more rejections and are thereby less efficient.
Clearly, step (3) in the question converts any positive variable (like a Half Normal variable) into a variable symmetrically distributed around $0.$
Applications
For this method to succeed, we need $f$ to attain a minimum that is not too negative. This implies the target distribution must not be too heavy-tailed. One example is the generalized Gamma distribution with density proportional to $\exp(-z^3/3)$ on the positive numbers.
Here are histograms based on a million draws of $(Y_1,Y_2)$ for the Half Normal and Generalized Gamma problems. The red curves plot the target densities to demonstrate the correctness of this algorithm. The (empirical) acceptance rates show how efficient it is.
This R code produced these plots.
set.seed(17)
n <- 1e6
Y <- matrix(-log(runif(2*n)), ncol = 2) # Step (1): obtain iid exponential variates
#
# The function `f`. The constant can be any non-negative value, with 0 being the
# most efficient.
#
Dists <- list(`Half Normal` = function(z, C = 0) (1 - z)^2/2 + C,
`Generalized Gamma` = function(z, C = 0) -z + z^3/3 + 2/3 + C)
pars <- par(mfrow = c(1, length(Dists)))
for(D in names(Dists)) {
f <- Dists[[D]]
z <- Y[Y[, 2] > f(Y[, 1]), 1] # Step (2) of the rejection sampling
rate <- length(z) / nrow(Y)
hist(z, freq = FALSE, main = D,
sub = bquote(paste("Acceptance rate is ", .(signif(rate, 2)))))
g <- function(x) exp(-x - f(x))
A <- integrate(g, 0, Inf)$value # The constant of integration
curve(g(x) / A, add = TRUE, col = "Red", lwd = 2)
}
par(pars) | Why does this algorithm generate a standard normal distribution? | I was wondering how anyone would come up with this idea.
You observe, correctly, that the $Y_i$ have exponential distributions. They were easy to generate from a standard uniform number generator. T | Why does this algorithm generate a standard normal distribution?
I was wondering how anyone would come up with this idea.
You observe, correctly, that the $Y_i$ have exponential distributions. They were easy to generate from a standard uniform number generator. The question could be put like this:
Find a simple way to exploit your ability to generate $(Y_1,Y_2)$ to draw values $Z$ following any continuous distribution with positive support.
Such a distribution is one with a density function proportional to $e^{g(z)}$ for a function $g$ defined on the positive numbers.
The key terms "simple" and "proportional to" suggest trying a rejection sampling method. That leads to the algorithm in the question in the following generalized form:
Generate $(Y_1,Y_2)$ and keep $Y_1$ provided $Y_2 \gt f(Y_1)$ for some function $f$ to be determined.
Although it might feel more natural to reject when $Y_2\le f(Y_1),$ as we will see this equivalent formulation leads to a simple calculation.
The result of this sampling procedure evidently produces values of $Y_1$ conditional on the event $Y_2 \gt f(Y_1).$ To find its distribution function, apply the (elementary) definition of conditional probability to the event $Y_1 \le z$ for an arbitrary positive number $z.$ It states
$$\Pr(Y_1\le z \mid Y_2 \gt f(Y_1)) \ \propto\ \Pr(Y_1\le z\text{ and }Y_2 \gt f(Y_1)).$$
We needn't be concerned about the constant of proportionality because we can work it out at the very end, knowing the result has to evaluate to $1$ as $z\to\infty$ (by the axiom of Total Probability).
Because $(Y_1,Y_2)$ is independent, their joint density is exponential. Thus, assuming $f(z) \ge 0$ for all $z\gt 0,$
$$\begin{aligned}
\int_0^z e^{g(y_1)}\,\mathrm{d}y_1 &= \Pr(Y_1\le z\text{ and }Y_2 \gt f(Y_1)) \\
&\propto \int_0^z e^{-y_1}\int_{f(y_1)}^\infty e^{-y_2}\,\mathrm{d}y_2\mathrm{d}y_1\\
&= \int_0^z e^{-y_1 - f(y_1)}\,\mathrm{d}y_1.
\end{aligned}$$
Equality will hold for all $z$ provided the two integrands are equal. Solving for $f$ gives
$$f(z) = -z - g(z) + C$$
where the number $C$ accounts for the neglected proportionality constant $e^C.$
Consider the Half Normal distribution where $g(z) = -z^2/2.$ We find
$$f(z) = -z + z^2/2 + C = (1 - z)^2/2 + C - 1/2.$$
We will need $C \ge 1/2$ to assure $f(z)$ is nonnegative. Larger values of $C$ work, too, but cause more rejections and are thereby less efficient.
Clearly, step (3) in the question converts any positive variable (like a Half Normal variable) into a variable symmetrically distributed around $0.$
Applications
For this method to succeed, we need $f$ to attain a minimum that is not too negative. This implies the target distribution must not be too heavy-tailed. One example is the generalized Gamma distribution with density proportional to $\exp(-z^3/3)$ on the positive numbers.
Here are histograms based on a million draws of $(Y_1,Y_2)$ for the Half Normal and Generalized Gamma problems. The red curves plot the target densities to demonstrate the correctness of this algorithm. The (empirical) acceptance rates show how efficient it is.
This R code produced these plots.
set.seed(17)
n <- 1e6
Y <- matrix(-log(runif(2*n)), ncol = 2) # Step (1): obtain iid exponential variates
#
# The function `f`. The constant can be any non-negative value, with 0 being the
# most efficient.
#
Dists <- list(`Half Normal` = function(z, C = 0) (1 - z)^2/2 + C,
`Generalized Gamma` = function(z, C = 0) -z + z^3/3 + 2/3 + C)
pars <- par(mfrow = c(1, length(Dists)))
for(D in names(Dists)) {
f <- Dists[[D]]
z <- Y[Y[, 2] > f(Y[, 1]), 1] # Step (2) of the rejection sampling
rate <- length(z) / nrow(Y)
hist(z, freq = FALSE, main = D,
sub = bquote(paste("Acceptance rate is ", .(signif(rate, 2)))))
g <- function(x) exp(-x - f(x))
A <- integrate(g, 0, Inf)$value # The constant of integration
curve(g(x) / A, add = TRUE, col = "Red", lwd = 2)
}
par(pars) | Why does this algorithm generate a standard normal distribution?
I was wondering how anyone would come up with this idea.
You observe, correctly, that the $Y_i$ have exponential distributions. They were easy to generate from a standard uniform number generator. T |
17,243 | Why does this algorithm generate a standard normal distribution? | To draw a comparison between this Normal generator (that I will consider as von Neumann's) and the Box-Müller polar generator,
#Box-Müller
bm=function(N){
a=sqrt(-2*log(runif(N/2)))
b=2*pi*runif(N/2)
return(c(a*sin(b),a*cos(b)))
}
#vonNeumann
vn=function(N){
u=-log(runif(2.64*N))
v=-2*log(runif(2.64*N))>(u-1)^2
w=(runif(2.64*N)<.5)-2
return((w*u)[v])
}
here are the relative computing times
> system.time(bm(1e8))
utilisateur système écoulé
7.015 0.649 7.674
> system.time(vn(1e8))
utilisateur système écoulé
42.483 5.713 48.222 | Why does this algorithm generate a standard normal distribution? | To draw a comparison between this Normal generator (that I will consider as von Neumann's) and the Box-Müller polar generator,
#Box-Müller
bm=function(N){
a=sqrt(-2*log(runif(N/2)))
b=2*pi*runif(N | Why does this algorithm generate a standard normal distribution?
To draw a comparison between this Normal generator (that I will consider as von Neumann's) and the Box-Müller polar generator,
#Box-Müller
bm=function(N){
a=sqrt(-2*log(runif(N/2)))
b=2*pi*runif(N/2)
return(c(a*sin(b),a*cos(b)))
}
#vonNeumann
vn=function(N){
u=-log(runif(2.64*N))
v=-2*log(runif(2.64*N))>(u-1)^2
w=(runif(2.64*N)<.5)-2
return((w*u)[v])
}
here are the relative computing times
> system.time(bm(1e8))
utilisateur système écoulé
7.015 0.649 7.674
> system.time(vn(1e8))
utilisateur système écoulé
42.483 5.713 48.222 | Why does this algorithm generate a standard normal distribution?
To draw a comparison between this Normal generator (that I will consider as von Neumann's) and the Box-Müller polar generator,
#Box-Müller
bm=function(N){
a=sqrt(-2*log(runif(N/2)))
b=2*pi*runif(N |
17,244 | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B? | After 10 throws, A and B are in the exact same position. The chance that A has more heads is p, the chance that B has more heads is also p (we don't know p), and the chance for same number of heads is the remainder, 1-2p.
After the 11th throw for A only, A has more heads if he had more heads after 10 throws, or the number of heads was the same after 10 throws, and he throws head. We add the probabilities: p + (1 - 2p) / 2 = p + (0.5 - p) = 0.5. | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B? | After 10 throws, A and B are in the exact same position. The chance that A has more heads is p, the chance that B has more heads is also p (we don't know p), and the chance for same number of heads is | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B?
After 10 throws, A and B are in the exact same position. The chance that A has more heads is p, the chance that B has more heads is also p (we don't know p), and the chance for same number of heads is the remainder, 1-2p.
After the 11th throw for A only, A has more heads if he had more heads after 10 throws, or the number of heads was the same after 10 throws, and he throws head. We add the probabilities: p + (1 - 2p) / 2 = p + (0.5 - p) = 0.5. | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B?
After 10 throws, A and B are in the exact same position. The chance that A has more heads is p, the chance that B has more heads is also p (we don't know p), and the chance for same number of heads is |
17,245 | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B? | Your "naive first thought" is the clever (standard) solution.
To make it rigorous, let $\mathscr E_0$ be the event "A and B are tied after each has tossed 10 times;" let $\mathscr E_A$ and $\mathscr E_B$ be the events "A has more heads than B after 10 tosses each" and "B has more heads than A after 10 tosses each," respectively. Let $\mathscr F$ designate the event "A has more heads than B after all tosses are made."
Notice:
$\mathscr E_0,$ $\mathscr E_A,$ and $\mathscr E_B$ are mutually exclusive: no two have any outcomes in common and collectively they include all the possibilities. Therefore $$\Pr(\mathscr E_0) + \Pr(\mathscr E_A) + \Pr(\mathscr E_B)=1.$$
$\Pr(\mathscr F\mid \mathscr E_A) = 1$ (A has won by the first 10 tosses); $\Pr(\mathscr F\mid \mathscr E_B) = 0$ (A is behind after 10 tosses and therefore cannot win with the last toss); and $\Pr(\mathscr F\mid \mathscr E_0) = 1/2$ (if both are tied after 10 tosses, A's 11th toss is the tiebreaker).
$\Pr(\mathscr E_A) = \Pr(\mathscr{E_B})$ (after 10 tosses the game is symmetric -- both players are equally situated -- and therefore they have equal chances of being ahead at that point).
By the law of total probability,
$$\begin{aligned}
\Pr(\mathscr F) &= \Pr(\mathscr F\mid \mathscr E_0)\Pr(\mathscr E_0) + \Pr(\mathscr F\mid \mathscr E_A)\Pr(\mathscr E_A) + \Pr(\mathscr F\mid \mathscr E_B)\Pr(\mathscr E_B)\\
& = \Pr(\mathscr E_0)\left(\frac{1}{2}\right) + \Pr(\mathscr E_A)(1) + \Pr(\mathscr E_B)(0)\\
&= \frac{1}{2}\left(\Pr(\mathscr E_0) + \Pr(\mathscr E_A) + \Pr(\mathscr E_A)\right)\\
&= \frac{1}{2}\left(\Pr(\mathscr E_0) + \Pr(\mathscr E_A) + \Pr(\mathscr E_B)\right)\\
& = \frac{1}{2}\left(1\right) = \frac{1}{2}.
\end{aligned} $$
As an alternative approach, you wish to evaluate the double sum
$$\sum_{a \gt b} \binom{11}{a}\binom{10}{b} = \sum_{a \gt b} \binom{11}{11-a}\binom{10}{10-b} = \sum_{a^\prime \le b^\prime} \binom{11}{a^\prime}\binom{10}{b^\prime}.$$
(In case the algebra isn't obvious, the first equality exploits the Binomial coefficient symmetry and the second is the change of variable $a^\prime = 11-a,$ $b^\prime = 10-b.$ We can be a vague about the endpoints of the summations because whenever $a$ or $a^\prime$ is not in the range from $0$ through $11$ or $b$ or $b^\prime$ is not in the range from $0$ through $10$ the Binomial coefficients are zero.)
Because the indexes in the two sums on the left and right sides (1) never overlap and (2) cover all the possibilities (since either $a\gt b$ or $a\le b$ but never both), together they give the total probability, which is $1.$ Consequently, since those sums are equal, each is $1/2,$ QED.
This figure shows the rotational symmetry of the distribution under the mapping $(a,b)\to(11-a,10-b).$ The blue circles are rotated around the yellow dot into red triangles of exactly the same probability. The desired sum is the total of the blue circles, which therefore must be $1/2.$ | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B? | Your "naive first thought" is the clever (standard) solution.
To make it rigorous, let $\mathscr E_0$ be the event "A and B are tied after each has tossed 10 times;" let $\mathscr E_A$ and $\mathscr E | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B?
Your "naive first thought" is the clever (standard) solution.
To make it rigorous, let $\mathscr E_0$ be the event "A and B are tied after each has tossed 10 times;" let $\mathscr E_A$ and $\mathscr E_B$ be the events "A has more heads than B after 10 tosses each" and "B has more heads than A after 10 tosses each," respectively. Let $\mathscr F$ designate the event "A has more heads than B after all tosses are made."
Notice:
$\mathscr E_0,$ $\mathscr E_A,$ and $\mathscr E_B$ are mutually exclusive: no two have any outcomes in common and collectively they include all the possibilities. Therefore $$\Pr(\mathscr E_0) + \Pr(\mathscr E_A) + \Pr(\mathscr E_B)=1.$$
$\Pr(\mathscr F\mid \mathscr E_A) = 1$ (A has won by the first 10 tosses); $\Pr(\mathscr F\mid \mathscr E_B) = 0$ (A is behind after 10 tosses and therefore cannot win with the last toss); and $\Pr(\mathscr F\mid \mathscr E_0) = 1/2$ (if both are tied after 10 tosses, A's 11th toss is the tiebreaker).
$\Pr(\mathscr E_A) = \Pr(\mathscr{E_B})$ (after 10 tosses the game is symmetric -- both players are equally situated -- and therefore they have equal chances of being ahead at that point).
By the law of total probability,
$$\begin{aligned}
\Pr(\mathscr F) &= \Pr(\mathscr F\mid \mathscr E_0)\Pr(\mathscr E_0) + \Pr(\mathscr F\mid \mathscr E_A)\Pr(\mathscr E_A) + \Pr(\mathscr F\mid \mathscr E_B)\Pr(\mathscr E_B)\\
& = \Pr(\mathscr E_0)\left(\frac{1}{2}\right) + \Pr(\mathscr E_A)(1) + \Pr(\mathscr E_B)(0)\\
&= \frac{1}{2}\left(\Pr(\mathscr E_0) + \Pr(\mathscr E_A) + \Pr(\mathscr E_A)\right)\\
&= \frac{1}{2}\left(\Pr(\mathscr E_0) + \Pr(\mathscr E_A) + \Pr(\mathscr E_B)\right)\\
& = \frac{1}{2}\left(1\right) = \frac{1}{2}.
\end{aligned} $$
As an alternative approach, you wish to evaluate the double sum
$$\sum_{a \gt b} \binom{11}{a}\binom{10}{b} = \sum_{a \gt b} \binom{11}{11-a}\binom{10}{10-b} = \sum_{a^\prime \le b^\prime} \binom{11}{a^\prime}\binom{10}{b^\prime}.$$
(In case the algebra isn't obvious, the first equality exploits the Binomial coefficient symmetry and the second is the change of variable $a^\prime = 11-a,$ $b^\prime = 10-b.$ We can be a vague about the endpoints of the summations because whenever $a$ or $a^\prime$ is not in the range from $0$ through $11$ or $b$ or $b^\prime$ is not in the range from $0$ through $10$ the Binomial coefficients are zero.)
Because the indexes in the two sums on the left and right sides (1) never overlap and (2) cover all the possibilities (since either $a\gt b$ or $a\le b$ but never both), together they give the total probability, which is $1.$ Consequently, since those sums are equal, each is $1/2,$ QED.
This figure shows the rotational symmetry of the distribution under the mapping $(a,b)\to(11-a,10-b).$ The blue circles are rotated around the yellow dot into red triangles of exactly the same probability. The desired sum is the total of the blue circles, which therefore must be $1/2.$ | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B?
Your "naive first thought" is the clever (standard) solution.
To make it rigorous, let $\mathscr E_0$ be the event "A and B are tied after each has tossed 10 times;" let $\mathscr E_A$ and $\mathscr E |
17,246 | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B? | I like your first approach, it's neat.
Here's how I often approach this kind of 'probability that player A scores more than player B' problem (which I first came up with when dealing with similar questions involving dice, many years ago). It's not clever, but it generalizes in various ways and does reduce the calculations involved. I'll try to explain in fair bit of detail but in practice the whole process takes a few moments of thought before a simplified calculation in this case involving no summing or combinatorics at all.
Let's score each head '1' and each tail '0' and sum the scores (this is just counting but emphasizes the fact that we're summing outcomes). Let $X_A$ be the score for $A$ and similarly for $B$ ($X_B$).
Now consider a different game where player B counted tails instead of heads, and call that variable $Y_B$. The probabilities of interest with fair coins are unchanged, so we would get the same answer if we responded to this question (i.e. if we computed $P(X_A>Y_B)$). Now for this new game, player B's score $Y_B=10-X_B$. Consequently:
$P(X_A>X_B) = P(X_A>Y_B) = P(X_A>10-X_B) = P(X_A+X_B>10)$
Now $X_A+X_B$ is just the number of heads in 21 tosses of a fair coin, which has expectation 10.5.
By symmetry the probability that this total exceeds 10 is $\frac12$. $\qquad\square$
Note that this strategy works for other questions like "Player A tosses 12 times and player B tosses 9 times, what's the probability player A beats player B by more than 3?".
In that case $P(X_A>X_B+3) = P(X_A>(9-X_B)+3) = P(X_A+X_B>12)$. This is a straight binomial problem, though we can use symmetry to simplify it further to calculating just two adjacent binomial probabilities.
With sums of dice, you take one more than the number of faces to flip it around. e.g. for a six-sided die, it's equivalent to subtracting a six-sided die from 7. This lets you put B's rolls on A's side of the probability again, reducing comparing two sums of dice to comparing a single sum (with more dice) to a constant number, reducing it to a straight convolution, which is easy to automate calculations for. | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B? | I like your first approach, it's neat.
Here's how I often approach this kind of 'probability that player A scores more than player B' problem (which I first came up with when dealing with similar ques | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B?
I like your first approach, it's neat.
Here's how I often approach this kind of 'probability that player A scores more than player B' problem (which I first came up with when dealing with similar questions involving dice, many years ago). It's not clever, but it generalizes in various ways and does reduce the calculations involved. I'll try to explain in fair bit of detail but in practice the whole process takes a few moments of thought before a simplified calculation in this case involving no summing or combinatorics at all.
Let's score each head '1' and each tail '0' and sum the scores (this is just counting but emphasizes the fact that we're summing outcomes). Let $X_A$ be the score for $A$ and similarly for $B$ ($X_B$).
Now consider a different game where player B counted tails instead of heads, and call that variable $Y_B$. The probabilities of interest with fair coins are unchanged, so we would get the same answer if we responded to this question (i.e. if we computed $P(X_A>Y_B)$). Now for this new game, player B's score $Y_B=10-X_B$. Consequently:
$P(X_A>X_B) = P(X_A>Y_B) = P(X_A>10-X_B) = P(X_A+X_B>10)$
Now $X_A+X_B$ is just the number of heads in 21 tosses of a fair coin, which has expectation 10.5.
By symmetry the probability that this total exceeds 10 is $\frac12$. $\qquad\square$
Note that this strategy works for other questions like "Player A tosses 12 times and player B tosses 9 times, what's the probability player A beats player B by more than 3?".
In that case $P(X_A>X_B+3) = P(X_A>(9-X_B)+3) = P(X_A+X_B>12)$. This is a straight binomial problem, though we can use symmetry to simplify it further to calculating just two adjacent binomial probabilities.
With sums of dice, you take one more than the number of faces to flip it around. e.g. for a six-sided die, it's equivalent to subtracting a six-sided die from 7. This lets you put B's rolls on A's side of the probability again, reducing comparing two sums of dice to comparing a single sum (with more dice) to a constant number, reducing it to a straight convolution, which is easy to automate calculations for. | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B?
I like your first approach, it's neat.
Here's how I often approach this kind of 'probability that player A scores more than player B' problem (which I first came up with when dealing with similar ques |
17,247 | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B? | This is not really an answer but purely involves your "naive first thought".
You base that on the fact that A and B have the same expected value of heads if only the first $10$ times are taken into account.
This is not correct.
Imagine a game where A throws $5$ coins and $B$ throws $4$ coins.
The first coin of A has probability $1$ on resulting in head, and the second, third and fourth have probability $\frac13$ on resulting in head and finally the fifth has probability $\frac12$ on heads.
The first coin of B has probability $0$ on resulting in head, and the second, third and fourth have probability $\frac23$ on resulting in head.
Then for both the expected number of heads gained in the first $4$ throws is $2$.
However the probability that A throws in total more heads than B in the whole game appears to be $\frac{706}{1458}<0.5$.
It would be correct to base it on the fact that A and B have the same probability of winning if only the first $10$ times are taken into account.
Think about it like this: A and B want to play a fair game ($10$ flips for each) but foreseeing that the game can end in a draw (which they want to prevent) they make the following agreement:
If the game ends in a draw then A throws a coin. If it is a head then A is declared to be the winner and otherwise B is declared to be the winner. Also if the game does not end in a draw A throws a coin but then evidently its result has no real impact on the question who wins.
Then evidently this game is fair and gives both players a chance of 50% to win.
Further it is true that A wins iff he throws more heads than B. | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B? | This is not really an answer but purely involves your "naive first thought".
You base that on the fact that A and B have the same expected value of heads if only the first $10$ times are taken into ac | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B?
This is not really an answer but purely involves your "naive first thought".
You base that on the fact that A and B have the same expected value of heads if only the first $10$ times are taken into account.
This is not correct.
Imagine a game where A throws $5$ coins and $B$ throws $4$ coins.
The first coin of A has probability $1$ on resulting in head, and the second, third and fourth have probability $\frac13$ on resulting in head and finally the fifth has probability $\frac12$ on heads.
The first coin of B has probability $0$ on resulting in head, and the second, third and fourth have probability $\frac23$ on resulting in head.
Then for both the expected number of heads gained in the first $4$ throws is $2$.
However the probability that A throws in total more heads than B in the whole game appears to be $\frac{706}{1458}<0.5$.
It would be correct to base it on the fact that A and B have the same probability of winning if only the first $10$ times are taken into account.
Think about it like this: A and B want to play a fair game ($10$ flips for each) but foreseeing that the game can end in a draw (which they want to prevent) they make the following agreement:
If the game ends in a draw then A throws a coin. If it is a head then A is declared to be the winner and otherwise B is declared to be the winner. Also if the game does not end in a draw A throws a coin but then evidently its result has no real impact on the question who wins.
Then evidently this game is fair and gives both players a chance of 50% to win.
Further it is true that A wins iff he throws more heads than B. | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B?
This is not really an answer but purely involves your "naive first thought".
You base that on the fact that A and B have the same expected value of heads if only the first $10$ times are taken into ac |
17,248 | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B? | An approximation. The coin flipping experiment is a binomial distribution, the binomial distribution can be approximated using a normal distribution (under certain conditions), the result then is the convolution of the two approximated normal distributions, which has a simple analytical solution.
If $X \sim \mathcal{B}(n,p)$ then $X \sim \mathcal{N}(np,\sqrt{(np(1-p)})$, if $np \geq 5$ and $n(1-p) \geq 5$ (rule of thumb).
For your specific case (R code)
ap=0.5
an=11
bp=0.5
bn=10
pnorm(
0,
(ap*an-bp*bn)/2,
sqrt((an*ap*(1-ap)+bn*bp*(1-bp))/2),
lower.tail=F
)
[1] 0.5613147 | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B? | An approximation. The coin flipping experiment is a binomial distribution, the binomial distribution can be approximated using a normal distribution (under certain conditions), the result then is the | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B?
An approximation. The coin flipping experiment is a binomial distribution, the binomial distribution can be approximated using a normal distribution (under certain conditions), the result then is the convolution of the two approximated normal distributions, which has a simple analytical solution.
If $X \sim \mathcal{B}(n,p)$ then $X \sim \mathcal{N}(np,\sqrt{(np(1-p)})$, if $np \geq 5$ and $n(1-p) \geq 5$ (rule of thumb).
For your specific case (R code)
ap=0.5
an=11
bp=0.5
bn=10
pnorm(
0,
(ap*an-bp*bn)/2,
sqrt((an*ap*(1-ap)+bn*bp*(1-bp))/2),
lower.tail=F
)
[1] 0.5613147 | A flips a fair coin 11 times, B 10 times: what is the probability A gets more heads than B?
An approximation. The coin flipping experiment is a binomial distribution, the binomial distribution can be approximated using a normal distribution (under certain conditions), the result then is the |
17,249 | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | Two techniques: penalty and variable transformation.
penalty
build one model with these three outputs, then modify/customize the loss function during its estimation by adding the penalty for violation of the assumption. this will not guarantee the inequalities but will make them very unlikely.
You can simply add $-\lambda[\min(y_2-y_1,0)+\min(y_3-y_2,0)]$ where $\lambda$ is a hyper parameter reflecting how badly you want to enforce the conditions, and $y_1,y_2,y_3$ are you min, mean and max outputs. I’m using ReLU function here, but you can use any strictly positive function.
variable transformation
I use this technique in similar situations. Here's how it goes. Create new variables: $$y'_1=y_2\\y'_2=\ln(y_2-y_1)\\y'_3=\ln(y_3-y_2)$$
Now you can fit the unconstrained model to new variables, then reconstruct the outputs as
$$y_2=y'_2\\y_1=y_2-e^{y'_2}\\y_3=y_2+e^{y'_3}$$
The outputs will be guaranteed to have the required conditions.
There are variations, e.g. you can transform min, mean and max into mean, range and mean/range etc which can be more stable. You can replace exponent with any strictly positive function such as ReLU, as it is noted in a comments.
This may look like a better technique, but it has its own issues. The main one is that fitting to logarithm can produce very wild forecasts. It's one reason why you should not transform the mean itself, and only min and max are transformed to distances from the mean. This way at least we may get reasonable mean forecast, and maybe crazy min and max, which are expected to be lousy anyways.
related issue
Another thing to be aware of is that usually mean forecast should be expected to have lower variance than min and max. Therefore, you may make some accommodations in your loss function to allow min and max have larger forecast error than mean. | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | Two techniques: penalty and variable transformation.
penalty
build one model with these three outputs, then modify/customize the loss function during its estimation by adding the penalty for violation | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
Two techniques: penalty and variable transformation.
penalty
build one model with these three outputs, then modify/customize the loss function during its estimation by adding the penalty for violation of the assumption. this will not guarantee the inequalities but will make them very unlikely.
You can simply add $-\lambda[\min(y_2-y_1,0)+\min(y_3-y_2,0)]$ where $\lambda$ is a hyper parameter reflecting how badly you want to enforce the conditions, and $y_1,y_2,y_3$ are you min, mean and max outputs. I’m using ReLU function here, but you can use any strictly positive function.
variable transformation
I use this technique in similar situations. Here's how it goes. Create new variables: $$y'_1=y_2\\y'_2=\ln(y_2-y_1)\\y'_3=\ln(y_3-y_2)$$
Now you can fit the unconstrained model to new variables, then reconstruct the outputs as
$$y_2=y'_2\\y_1=y_2-e^{y'_2}\\y_3=y_2+e^{y'_3}$$
The outputs will be guaranteed to have the required conditions.
There are variations, e.g. you can transform min, mean and max into mean, range and mean/range etc which can be more stable. You can replace exponent with any strictly positive function such as ReLU, as it is noted in a comments.
This may look like a better technique, but it has its own issues. The main one is that fitting to logarithm can produce very wild forecasts. It's one reason why you should not transform the mean itself, and only min and max are transformed to distances from the mean. This way at least we may get reasonable mean forecast, and maybe crazy min and max, which are expected to be lousy anyways.
related issue
Another thing to be aware of is that usually mean forecast should be expected to have lower variance than min and max. Therefore, you may make some accommodations in your loss function to allow min and max have larger forecast error than mean. | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
Two techniques: penalty and variable transformation.
penalty
build one model with these three outputs, then modify/customize the loss function during its estimation by adding the penalty for violation |
17,250 | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | It may be infeasible to formally check the KKT conditions for your optimization problem, however you can still try encoding your inequality constraints as if the conditions hold. Then it is a matter of checking whether the training behaves nicely in practice.
If you're unfamiliar with encoding constraints into an objective function in the way that KKT states, see Lagrange multipliers for a first example with equality constraints. Then I recommend you look at encoding inequality constraints (see example) in a similar fashion.
Once you have the mathematical expression in hand, you'll need to implement it in Tensorflow. You can build your own loss function class by inheriting from the tf.keras.losses.Loss base class. | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | It may be infeasible to formally check the KKT conditions for your optimization problem, however you can still try encoding your inequality constraints as if the conditions hold. Then it is a matter o | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
It may be infeasible to formally check the KKT conditions for your optimization problem, however you can still try encoding your inequality constraints as if the conditions hold. Then it is a matter of checking whether the training behaves nicely in practice.
If you're unfamiliar with encoding constraints into an objective function in the way that KKT states, see Lagrange multipliers for a first example with equality constraints. Then I recommend you look at encoding inequality constraints (see example) in a similar fashion.
Once you have the mathematical expression in hand, you'll need to implement it in Tensorflow. You can build your own loss function class by inheriting from the tf.keras.losses.Loss base class. | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
It may be infeasible to formally check the KKT conditions for your optimization problem, however you can still try encoding your inequality constraints as if the conditions hold. Then it is a matter o |
17,251 | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | As mentioned in above discussion with @Galen:
Conjecture This might be achieved with custom recurrent layer. We could provide a box plot values as an output, i.e., Five number summary as a monotonic output. Though, internals of recurrent layer is a design choice, see Define custom LSTM Cell in Keras?. Here, output of LSTM cell will be our monotonic summary function. This approach guarantees the inequality. | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | As mentioned in above discussion with @Galen:
Conjecture This might be achieved with custom recurrent layer. We could provide a box plot values as an output, i.e., Five number summary as a monotonic o | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
As mentioned in above discussion with @Galen:
Conjecture This might be achieved with custom recurrent layer. We could provide a box plot values as an output, i.e., Five number summary as a monotonic output. Though, internals of recurrent layer is a design choice, see Define custom LSTM Cell in Keras?. Here, output of LSTM cell will be our monotonic summary function. This approach guarantees the inequality. | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
As mentioned in above discussion with @Galen:
Conjecture This might be achieved with custom recurrent layer. We could provide a box plot values as an output, i.e., Five number summary as a monotonic o |
17,252 | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | I would suggest you are better off investigating quantile regression.
see eg
https://towardsdatascience.com/deep-quantile-regression-in-tensorflow-1dbc792fe597.
What I believe you want is to predict the mean and limits of your distribution. at each x value. using the minimum and maximum as targets will not give you what you want. instead you will have the expected value of the minimum/maximum at each input (this is what MSE produces).
eg input is x
id
x
y_mean
y_max
1
1
1
1
2
1
1
3
3
1
1
5
then the prediction for y_max for input x=1 will be 3, not 5.
if instead you predict the quantiles you will get eg 10 percentile, 50 percentile and 90 percentile of your distribution.
(an alternative simpler way is to continue with mse,but predict the mean and squared error. that gives you the variance and you can eg estimate the percentiles making a normal approximation) | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | I would suggest you are better off investigating quantile regression.
see eg
https://towardsdatascience.com/deep-quantile-regression-in-tensorflow-1dbc792fe597.
What I believe you want is to predict t | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
I would suggest you are better off investigating quantile regression.
see eg
https://towardsdatascience.com/deep-quantile-regression-in-tensorflow-1dbc792fe597.
What I believe you want is to predict the mean and limits of your distribution. at each x value. using the minimum and maximum as targets will not give you what you want. instead you will have the expected value of the minimum/maximum at each input (this is what MSE produces).
eg input is x
id
x
y_mean
y_max
1
1
1
1
2
1
1
3
3
1
1
5
then the prediction for y_max for input x=1 will be 3, not 5.
if instead you predict the quantiles you will get eg 10 percentile, 50 percentile and 90 percentile of your distribution.
(an alternative simpler way is to continue with mse,but predict the mean and squared error. that gives you the variance and you can eg estimate the percentiles making a normal approximation) | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
I would suggest you are better off investigating quantile regression.
see eg
https://towardsdatascience.com/deep-quantile-regression-in-tensorflow-1dbc792fe597.
What I believe you want is to predict t |
17,253 | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | Unless I have misunderstood the question, here's a simple approach.
For outputs a b and c, you could enforce positive values for the second and third outputs via a suitable activation function, and then train to find values a b and c, such that a is the min, a + b is the mean, and a + b + c is the max value. | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | Unless I have misunderstood the question, here's a simple approach.
For outputs a b and c, you could enforce positive values for the second and third outputs via a suitable activation function, and th | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
Unless I have misunderstood the question, here's a simple approach.
For outputs a b and c, you could enforce positive values for the second and third outputs via a suitable activation function, and then train to find values a b and c, such that a is the min, a + b is the mean, and a + b + c is the max value. | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
Unless I have misunderstood the question, here's a simple approach.
For outputs a b and c, you could enforce positive values for the second and third outputs via a suitable activation function, and th |
17,254 | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | Why not applying cumsum layer at the very end of your model?
By doing that, the model will predict the difference between t-1 and t on the layer n-1.
Something like:
tf.math.cumsum(y_features, axis=time_series_axis_index)` | Can I enforce monotonically increasing neural net outputs (min, mean, max)? | Why not applying cumsum layer at the very end of your model?
By doing that, the model will predict the difference between t-1 and t on the layer n-1.
Something like:
tf.math.cumsum(y_features, axis=ti | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
Why not applying cumsum layer at the very end of your model?
By doing that, the model will predict the difference between t-1 and t on the layer n-1.
Something like:
tf.math.cumsum(y_features, axis=time_series_axis_index)` | Can I enforce monotonically increasing neural net outputs (min, mean, max)?
Why not applying cumsum layer at the very end of your model?
By doing that, the model will predict the difference between t-1 and t on the layer n-1.
Something like:
tf.math.cumsum(y_features, axis=ti |
17,255 | Skewness of the logarithm of a gamma random variable | The moment generating function $M(t)$ of $Y=\ln X$ is helpful in this case, since it has a simple algebraic form. By the definition of m.g.f., we have $$\begin{aligned}M(t)&=\operatorname{E}[e^{t\ln X}]=\operatorname{E}[X^t]\\
&=\frac{1}{\Gamma(\alpha)\theta^\alpha}\int_0^\infty x^{\alpha+t-1}e^{-x/\theta}\,dx\\
&=\frac{\theta^{t}}{\Gamma(\alpha)}\int_0^\infty y^{\alpha+t-1}e^{-y}\,dy\\
&=\frac{\theta^t\Gamma(\alpha+t)}{\Gamma(\alpha)}.\end{aligned}$$
Let's verify the expectation and the variance you gave. Taking derivatives, we have $$M'(t)=\frac{\Gamma'(\alpha+t)}{\Gamma(\alpha)}\theta^t+\frac{\Gamma(\alpha+t)}{\Gamma(\alpha)}\theta^t\ln(\theta)$$ and $$M''(t)=\frac{\Gamma''(\alpha+t)}{\Gamma(\alpha)}\theta^t+\frac{2\Gamma'(\alpha+t)}{\Gamma(\alpha)}\theta^t\ln(\theta)+\frac{\Gamma(\alpha+t)}{\Gamma(\alpha)}\theta^t\ln^2(\theta).$$ Hence, $$\operatorname{E}[Y]=\psi^{(0)}(\alpha)+\ln(\theta),\qquad\operatorname{E}[Y^2]=\frac{\Gamma''(\alpha)}{\Gamma(\alpha)}+2\psi^{(0)}(\alpha)\ln(\theta)+\ln^2(\theta).$$ It follows then $$\operatorname{Var}(Y)=\operatorname{E}[Y^2]-\operatorname{E}[Y]^2=\frac{\Gamma''(\alpha)}{\Gamma(\alpha)}-\left(\frac{\Gamma'(\alpha)}{\Gamma(\alpha)}\right)^2=\psi^{(1)}(\alpha).$$
To find the skewness, note the cumulant generating function (thanks @probabilityislogic for the tip) is $$K(t)=\ln M(t)=t\ln\theta+\ln\Gamma(\alpha+t)-\ln\Gamma(\alpha).$$ The first cumulant is thus simply $K'(0)=\psi^{(0)}(\alpha)+\ln(\theta)$. Recall that $\psi^{(n)}(x)=d^{n+1}\ln\Gamma(x)/dx^{n+1}$, so the subsequent cumulants are $K^{(n)}(0)=\psi^{(n-1)}(\alpha)$, $n\geq2$. The skewness is therefore $$\frac{\operatorname{E}[(Y-\operatorname{E}[Y])^3]}{\operatorname{Var}(Y)^{3/2}}=\frac{\psi^{(2)}(\alpha)}{[\psi^{(1)}(\alpha)]^{3/2}}.$$
As a side note, this particular distribution appeared to have been thoroughly studied by A. C. Olshen in his Transformations of the Pearson Type III Distribution, Johnson et al.'s Continuous Univariate Distributions also has a small piece about it. Check those out. | Skewness of the logarithm of a gamma random variable | The moment generating function $M(t)$ of $Y=\ln X$ is helpful in this case, since it has a simple algebraic form. By the definition of m.g.f., we have $$\begin{aligned}M(t)&=\operatorname{E}[e^{t\ln X | Skewness of the logarithm of a gamma random variable
The moment generating function $M(t)$ of $Y=\ln X$ is helpful in this case, since it has a simple algebraic form. By the definition of m.g.f., we have $$\begin{aligned}M(t)&=\operatorname{E}[e^{t\ln X}]=\operatorname{E}[X^t]\\
&=\frac{1}{\Gamma(\alpha)\theta^\alpha}\int_0^\infty x^{\alpha+t-1}e^{-x/\theta}\,dx\\
&=\frac{\theta^{t}}{\Gamma(\alpha)}\int_0^\infty y^{\alpha+t-1}e^{-y}\,dy\\
&=\frac{\theta^t\Gamma(\alpha+t)}{\Gamma(\alpha)}.\end{aligned}$$
Let's verify the expectation and the variance you gave. Taking derivatives, we have $$M'(t)=\frac{\Gamma'(\alpha+t)}{\Gamma(\alpha)}\theta^t+\frac{\Gamma(\alpha+t)}{\Gamma(\alpha)}\theta^t\ln(\theta)$$ and $$M''(t)=\frac{\Gamma''(\alpha+t)}{\Gamma(\alpha)}\theta^t+\frac{2\Gamma'(\alpha+t)}{\Gamma(\alpha)}\theta^t\ln(\theta)+\frac{\Gamma(\alpha+t)}{\Gamma(\alpha)}\theta^t\ln^2(\theta).$$ Hence, $$\operatorname{E}[Y]=\psi^{(0)}(\alpha)+\ln(\theta),\qquad\operatorname{E}[Y^2]=\frac{\Gamma''(\alpha)}{\Gamma(\alpha)}+2\psi^{(0)}(\alpha)\ln(\theta)+\ln^2(\theta).$$ It follows then $$\operatorname{Var}(Y)=\operatorname{E}[Y^2]-\operatorname{E}[Y]^2=\frac{\Gamma''(\alpha)}{\Gamma(\alpha)}-\left(\frac{\Gamma'(\alpha)}{\Gamma(\alpha)}\right)^2=\psi^{(1)}(\alpha).$$
To find the skewness, note the cumulant generating function (thanks @probabilityislogic for the tip) is $$K(t)=\ln M(t)=t\ln\theta+\ln\Gamma(\alpha+t)-\ln\Gamma(\alpha).$$ The first cumulant is thus simply $K'(0)=\psi^{(0)}(\alpha)+\ln(\theta)$. Recall that $\psi^{(n)}(x)=d^{n+1}\ln\Gamma(x)/dx^{n+1}$, so the subsequent cumulants are $K^{(n)}(0)=\psi^{(n-1)}(\alpha)$, $n\geq2$. The skewness is therefore $$\frac{\operatorname{E}[(Y-\operatorname{E}[Y])^3]}{\operatorname{Var}(Y)^{3/2}}=\frac{\psi^{(2)}(\alpha)}{[\psi^{(1)}(\alpha)]^{3/2}}.$$
As a side note, this particular distribution appeared to have been thoroughly studied by A. C. Olshen in his Transformations of the Pearson Type III Distribution, Johnson et al.'s Continuous Univariate Distributions also has a small piece about it. Check those out. | Skewness of the logarithm of a gamma random variable
The moment generating function $M(t)$ of $Y=\ln X$ is helpful in this case, since it has a simple algebraic form. By the definition of m.g.f., we have $$\begin{aligned}M(t)&=\operatorname{E}[e^{t\ln X |
17,256 | Skewness of the logarithm of a gamma random variable | I. Direct computation
Gradshteyn & Ryzhik [1] (sect 4.358, 7th ed) list explicit closed forms for $$\int_0^\infty x^{\nu-1}e^{-\mu x}(\ln x)^p dx$$ for $p=2,3,4$ while the $p=1$ case is done in 4.352 (assuming you regard expressions in $\Gamma, \psi$ and $\zeta$ functions as closed form) -- from which it is definitely doable up to kurtosis; they give the integral for all $p$ as a derivative of a gamma function so presumably it's feasible to go higher. So skewness is certainly doable but not especially "neat".
Details of the derivation of the formulas in 4.358 are in [2]. I'll quote the formulas given there since they're slightly more succinctly stated and put 4.352.1 in the same form.
Let $\delta= \psi(a)-\ln \mu$. Then:
\begin{align}
\int_0^\infty x^{a-1} e^{-\mu x} \ln x \,dx
&=\frac{\Gamma(a)}{\mu^a}\left\{ \delta \right\} \\
\int_0^\infty x^{a-1} e^{-\mu x} \ln^2\!x \,dx
&=\frac{\Gamma(a)}{\mu^a}\left\{ \delta^2+\zeta(2,a) \right\} \\
\int_0^\infty x^{a-1} e^{-\mu x} \ln^3\!x \,dx
&=\frac{\Gamma(a)}{\mu^a}\left\{ \delta^3+3\zeta(2,a)\delta-2\zeta(3,a) \right\} \\
\int_0^\infty x^{a-1} e^{-\mu x} \ln^4\!x \,dx
&=\frac{\Gamma(a)}{\mu^a}\left\{ \delta^4+6\zeta(2,a)\delta^2-8\zeta(3,a)\delta + 3\zeta^2(2,a)+6\zeta(4,a)) \right\}
\end{align}
where $\zeta(z,q)=\sum_{n=0}^\infty \frac{1}{(n+q)^z}$ is the Hurwitz zeta function (the Riemann zeta function is the special case $q=1$).
Now on to the moments of the log of a gamma random variable.
Noting firstly that on the log scale the scale or rate parameter of the gamma density is merely a shift-parameter, so it has no impact on the central moments; we may take whichever one we're using to be 1.
If $X\sim \text{Gamma}(\alpha,1)$ then $$E(\log^{p}\!X) = \frac{1}{\Gamma(\alpha)}\int_0^\infty \log^{p}\!x\, x^{\alpha-1} e^{-x} \,dx.$$
We can set $\mu=1$ in the above integral formulas, which gives us raw moments; we have $E(Y)$, $E(Y^2)$, $E(Y^3)$, $E(Y^4)$.
Since we have eliminated $\mu$ from the above, without fear of confusion we're now free to re-use $\mu_k$ to represent the $k$-th central moment in the usual fashion. We may then obtain the central moments from the raw moments via the usual formulas.
Then we can obtain the skewness and kurtosis as $\frac{\mu_3}{\mu_2^{3/2}}$ and $\frac{\mu_4}{\mu_2^{2}}$.
A note on terminology
It looks like Wolfram's reference pages write the moments of this distribution (they call it ExpGamma distribution) in terms of the polygamma function.
By contrast, Chan (see below) calls this the log-gamma distribution.
II. Chan's formulas via MGF
Chan (1993) [3] gives the mgf as the very neat $\Gamma(\alpha+t)/\Gamma(\alpha)$.
(A very nice derivation for this is given in Francis' answer, using the simple fact that the mgf of $\log(X)$ is just $E(X^t)$.)
Consequently the moments have fairly simple forms. Chan gives:
$$E(Y)=\psi(\alpha)$$
and the central moments as
\begin{align}
E(Y-\mu_Y)^2 &= \psi'(\alpha) \\
E(Y-\mu_Y)^3 &= \psi''(\alpha) \\
E(Y-\mu_Y)^4 &= \psi'''(\alpha)
\end{align}
and so the skewness is $\psi''(\alpha)/(\psi'(\alpha)^{3/2})$ and kurtosis is $\psi'''(\alpha)/(\psi'(\alpha)^{2})$. Presumably the earlier formulas I have above should simplify to these.
Conveniently, R offers digamma ($\psi$) and trigamma ($\psi'$) functions as well as the more general polygamma function where you select the order of the derivative. (A number of other programs offer similarly convenient functions.)
Consequently we can compute the skewness and kurtosis quite directly in R:
skew.eg <- function(a) psigamma(a,2)/psigamma(a,1)^(3/2)
kurt.eg <- function(a) psigamma(a,3)/psigamma(a,1)^2
Trying a few values of a ($\alpha$ in the above), we reproduce the first few rows of the table at the end of Sec 2.2 in Chan [3], except that the kurtosis values in that table are supposed to be excess kurtosis, but I just calculated kurtosis by the formulas given above by Chan; these should differ by 3.
(E.g. for the log of an exponential, the table says the excess kurtosis is 2.4, but the formula for $\beta_2$ is $\psi'''(1)/\psi'(1)^2$ ... and that is 2.4.)
Simulation confirms that as we increase sample size, the kurtosis of a log of an exponential is converging to around 5.4 not 2.4. It appears that the thesis possibly has an error.
Consequently, Chan's formulas for central moments appear to actually be the formulas for the cumulants (see the derivation in Francis' answer). This would then mean that the skewness formula was correct as is; because the second and third cumulants are equal to the second and third central moments.
Nevertheless these are particularly convenient formulas as long as we keep in mind that kurt.eg is giving excess kurtosis.
References
[1] Gradshteyn, I.S. & Ryzhik I.M. (2007),
Table of Integrals, Series, and Products, 7th ed.
Academic Press, Inc.
[2] Victor H. Moll (2007)
The integrals in Gradshteyn and Ryzhik, Part 4: The gamma function
SCIENTIA Series A: Mathematical Sciences, Vol. 15, 37–46
Universidad Técnica Federico Santa María, Valparaíso, Chile
http://129.81.170.14/~vhm/FORM-PROOFS_html/final4.pdf
[3] Chan, P.S. (1993),
A statistical study of log-gamma distribution,
McMaster University (Ph.D. thesis)
https://macsphere.mcmaster.ca/bitstream/11375/6816/1/fulltext.pdf | Skewness of the logarithm of a gamma random variable | I. Direct computation
Gradshteyn & Ryzhik [1] (sect 4.358, 7th ed) list explicit closed forms for $$\int_0^\infty x^{\nu-1}e^{-\mu x}(\ln x)^p dx$$ for $p=2,3,4$ while the $p=1$ case is done in 4.352 | Skewness of the logarithm of a gamma random variable
I. Direct computation
Gradshteyn & Ryzhik [1] (sect 4.358, 7th ed) list explicit closed forms for $$\int_0^\infty x^{\nu-1}e^{-\mu x}(\ln x)^p dx$$ for $p=2,3,4$ while the $p=1$ case is done in 4.352 (assuming you regard expressions in $\Gamma, \psi$ and $\zeta$ functions as closed form) -- from which it is definitely doable up to kurtosis; they give the integral for all $p$ as a derivative of a gamma function so presumably it's feasible to go higher. So skewness is certainly doable but not especially "neat".
Details of the derivation of the formulas in 4.358 are in [2]. I'll quote the formulas given there since they're slightly more succinctly stated and put 4.352.1 in the same form.
Let $\delta= \psi(a)-\ln \mu$. Then:
\begin{align}
\int_0^\infty x^{a-1} e^{-\mu x} \ln x \,dx
&=\frac{\Gamma(a)}{\mu^a}\left\{ \delta \right\} \\
\int_0^\infty x^{a-1} e^{-\mu x} \ln^2\!x \,dx
&=\frac{\Gamma(a)}{\mu^a}\left\{ \delta^2+\zeta(2,a) \right\} \\
\int_0^\infty x^{a-1} e^{-\mu x} \ln^3\!x \,dx
&=\frac{\Gamma(a)}{\mu^a}\left\{ \delta^3+3\zeta(2,a)\delta-2\zeta(3,a) \right\} \\
\int_0^\infty x^{a-1} e^{-\mu x} \ln^4\!x \,dx
&=\frac{\Gamma(a)}{\mu^a}\left\{ \delta^4+6\zeta(2,a)\delta^2-8\zeta(3,a)\delta + 3\zeta^2(2,a)+6\zeta(4,a)) \right\}
\end{align}
where $\zeta(z,q)=\sum_{n=0}^\infty \frac{1}{(n+q)^z}$ is the Hurwitz zeta function (the Riemann zeta function is the special case $q=1$).
Now on to the moments of the log of a gamma random variable.
Noting firstly that on the log scale the scale or rate parameter of the gamma density is merely a shift-parameter, so it has no impact on the central moments; we may take whichever one we're using to be 1.
If $X\sim \text{Gamma}(\alpha,1)$ then $$E(\log^{p}\!X) = \frac{1}{\Gamma(\alpha)}\int_0^\infty \log^{p}\!x\, x^{\alpha-1} e^{-x} \,dx.$$
We can set $\mu=1$ in the above integral formulas, which gives us raw moments; we have $E(Y)$, $E(Y^2)$, $E(Y^3)$, $E(Y^4)$.
Since we have eliminated $\mu$ from the above, without fear of confusion we're now free to re-use $\mu_k$ to represent the $k$-th central moment in the usual fashion. We may then obtain the central moments from the raw moments via the usual formulas.
Then we can obtain the skewness and kurtosis as $\frac{\mu_3}{\mu_2^{3/2}}$ and $\frac{\mu_4}{\mu_2^{2}}$.
A note on terminology
It looks like Wolfram's reference pages write the moments of this distribution (they call it ExpGamma distribution) in terms of the polygamma function.
By contrast, Chan (see below) calls this the log-gamma distribution.
II. Chan's formulas via MGF
Chan (1993) [3] gives the mgf as the very neat $\Gamma(\alpha+t)/\Gamma(\alpha)$.
(A very nice derivation for this is given in Francis' answer, using the simple fact that the mgf of $\log(X)$ is just $E(X^t)$.)
Consequently the moments have fairly simple forms. Chan gives:
$$E(Y)=\psi(\alpha)$$
and the central moments as
\begin{align}
E(Y-\mu_Y)^2 &= \psi'(\alpha) \\
E(Y-\mu_Y)^3 &= \psi''(\alpha) \\
E(Y-\mu_Y)^4 &= \psi'''(\alpha)
\end{align}
and so the skewness is $\psi''(\alpha)/(\psi'(\alpha)^{3/2})$ and kurtosis is $\psi'''(\alpha)/(\psi'(\alpha)^{2})$. Presumably the earlier formulas I have above should simplify to these.
Conveniently, R offers digamma ($\psi$) and trigamma ($\psi'$) functions as well as the more general polygamma function where you select the order of the derivative. (A number of other programs offer similarly convenient functions.)
Consequently we can compute the skewness and kurtosis quite directly in R:
skew.eg <- function(a) psigamma(a,2)/psigamma(a,1)^(3/2)
kurt.eg <- function(a) psigamma(a,3)/psigamma(a,1)^2
Trying a few values of a ($\alpha$ in the above), we reproduce the first few rows of the table at the end of Sec 2.2 in Chan [3], except that the kurtosis values in that table are supposed to be excess kurtosis, but I just calculated kurtosis by the formulas given above by Chan; these should differ by 3.
(E.g. for the log of an exponential, the table says the excess kurtosis is 2.4, but the formula for $\beta_2$ is $\psi'''(1)/\psi'(1)^2$ ... and that is 2.4.)
Simulation confirms that as we increase sample size, the kurtosis of a log of an exponential is converging to around 5.4 not 2.4. It appears that the thesis possibly has an error.
Consequently, Chan's formulas for central moments appear to actually be the formulas for the cumulants (see the derivation in Francis' answer). This would then mean that the skewness formula was correct as is; because the second and third cumulants are equal to the second and third central moments.
Nevertheless these are particularly convenient formulas as long as we keep in mind that kurt.eg is giving excess kurtosis.
References
[1] Gradshteyn, I.S. & Ryzhik I.M. (2007),
Table of Integrals, Series, and Products, 7th ed.
Academic Press, Inc.
[2] Victor H. Moll (2007)
The integrals in Gradshteyn and Ryzhik, Part 4: The gamma function
SCIENTIA Series A: Mathematical Sciences, Vol. 15, 37–46
Universidad Técnica Federico Santa María, Valparaíso, Chile
http://129.81.170.14/~vhm/FORM-PROOFS_html/final4.pdf
[3] Chan, P.S. (1993),
A statistical study of log-gamma distribution,
McMaster University (Ph.D. thesis)
https://macsphere.mcmaster.ca/bitstream/11375/6816/1/fulltext.pdf | Skewness of the logarithm of a gamma random variable
I. Direct computation
Gradshteyn & Ryzhik [1] (sect 4.358, 7th ed) list explicit closed forms for $$\int_0^\infty x^{\nu-1}e^{-\mu x}(\ln x)^p dx$$ for $p=2,3,4$ while the $p=1$ case is done in 4.352 |
17,257 | When to use mixed effect model? | I'm afraid I might have the nuanced and perhaps unsatisfying answer that it is a subjective choice by the researcher or data analyst. As mentioned elsewhere in this thread, it isn't enough to simply say the data have a "nested structure." To be fair, though, this is how many books describe when to use multilevel models. For example, I just pulled Joop Hox's book Multilevel Analysis off of my bookshelf, which gives this definition:
A multilevel problem concerns a population with a hierarchical structure.
Even in a pretty good textbook, the initial definition seems to be circular. I think this is partially due to the subjectivity of determining when to use what kind of model (including a multilevel model).
Another book, West, Welch, & Galecki's Linear Mixed Models says these models are for:
outcome variables in which the residuals are normally distributed but may not be independent or have constant variance. Study designs leading to data sets that may be appropriately analyzed using LMMs include (1) studies with clustered data, such as students in classrooms, or experimental designs with random blocks, such as batches of raw material for an industrial process, and (2) longitudinal or repeated-measures studies, in which subjects are measured repeatedly over time or under different conditions.
Finch, Bolin, & Kelley's Multilevel Modeling in R also talks about violating the iid assumption and correlated residuals:
Of particular importance in the context of multilevel modeling is the assumption [in standard regression] of independently distributed error terms for the individual observations within a sample. This assumption essentially means that there are no relationships among individuals in the sample for the dependent variable once the independent variables in the analysis are accounted for.
I believe that a multilevel model makes sense when there is reason to believe that observations are not necessarily independent of one another. Whatever "cluster" accounts for this non-independence can be modeled.
An obvious example would be children in classrooms—they are all interacting with one another, which might lead their test scores to be non-independent. What if one classroom has someone that asks a question that leads to material being covered in that class that isn't covered in other classes? What if the teacher is more awake for some classes than others? In this case, there would be some non-independence of data; in multilevel words, we could expect some variance in the dependent variable to be due to the cluster (i.e., class).
Your example of a dog versus an elephant depends on the independent and dependent variables of interest, I think. For example, let's say we are asking if there is an effect of caffeine on activity level. Animals from all over the zoo are randomly assigned to either get a caffeinated drink or a control drink.
If we are a researcher that is interested in caffeine, we might specify a multilevel model, because we really care about the effect of caffeine. This model would be specified as:
activity ~ condition + (1+condition|species)
This is particularly helpful if there are a large number of species we are testing this hypothesis over. However, a researcher might be interested in the species-specific effects of caffeine. In that case, they could specify species as a fixed effect:
activity ~ condition + species + condition*species
This obviously is a problem if there are, say, 30 species, creating an unwieldy 2 x 30 design. However, you can get pretty creative with how one models these relationships.
For example, some researchers are arguing for an even wider use of multilevel modeling. Gelman, Hill, & Yajima (2012) argue that multilevel modeling could be used as a correction for multiple comparisons—even in experimental research where the structure of the data is not obviously hierarchical in nature:
Harder problems arise when modeling multiple comparisons that have more structure. For example, suppose we have five outcome measures, three varieties of treatments, and subgroups classified by two sexes and four racial groups. We would not want to model this 2 × 3 × 4 × 5 structure as 120 exchangeable groups. Even in these more complex situations, we think multilevel modeling should and will eventually take the place of classical multiple comparisons procedures.
Problems can be modeled in various ways, and in ambiguous cases, multiple approaches might seem appealing. I think our job is to choose a reasonable, informed approach and do so transparently. | When to use mixed effect model? | I'm afraid I might have the nuanced and perhaps unsatisfying answer that it is a subjective choice by the researcher or data analyst. As mentioned elsewhere in this thread, it isn't enough to simply s | When to use mixed effect model?
I'm afraid I might have the nuanced and perhaps unsatisfying answer that it is a subjective choice by the researcher or data analyst. As mentioned elsewhere in this thread, it isn't enough to simply say the data have a "nested structure." To be fair, though, this is how many books describe when to use multilevel models. For example, I just pulled Joop Hox's book Multilevel Analysis off of my bookshelf, which gives this definition:
A multilevel problem concerns a population with a hierarchical structure.
Even in a pretty good textbook, the initial definition seems to be circular. I think this is partially due to the subjectivity of determining when to use what kind of model (including a multilevel model).
Another book, West, Welch, & Galecki's Linear Mixed Models says these models are for:
outcome variables in which the residuals are normally distributed but may not be independent or have constant variance. Study designs leading to data sets that may be appropriately analyzed using LMMs include (1) studies with clustered data, such as students in classrooms, or experimental designs with random blocks, such as batches of raw material for an industrial process, and (2) longitudinal or repeated-measures studies, in which subjects are measured repeatedly over time or under different conditions.
Finch, Bolin, & Kelley's Multilevel Modeling in R also talks about violating the iid assumption and correlated residuals:
Of particular importance in the context of multilevel modeling is the assumption [in standard regression] of independently distributed error terms for the individual observations within a sample. This assumption essentially means that there are no relationships among individuals in the sample for the dependent variable once the independent variables in the analysis are accounted for.
I believe that a multilevel model makes sense when there is reason to believe that observations are not necessarily independent of one another. Whatever "cluster" accounts for this non-independence can be modeled.
An obvious example would be children in classrooms—they are all interacting with one another, which might lead their test scores to be non-independent. What if one classroom has someone that asks a question that leads to material being covered in that class that isn't covered in other classes? What if the teacher is more awake for some classes than others? In this case, there would be some non-independence of data; in multilevel words, we could expect some variance in the dependent variable to be due to the cluster (i.e., class).
Your example of a dog versus an elephant depends on the independent and dependent variables of interest, I think. For example, let's say we are asking if there is an effect of caffeine on activity level. Animals from all over the zoo are randomly assigned to either get a caffeinated drink or a control drink.
If we are a researcher that is interested in caffeine, we might specify a multilevel model, because we really care about the effect of caffeine. This model would be specified as:
activity ~ condition + (1+condition|species)
This is particularly helpful if there are a large number of species we are testing this hypothesis over. However, a researcher might be interested in the species-specific effects of caffeine. In that case, they could specify species as a fixed effect:
activity ~ condition + species + condition*species
This obviously is a problem if there are, say, 30 species, creating an unwieldy 2 x 30 design. However, you can get pretty creative with how one models these relationships.
For example, some researchers are arguing for an even wider use of multilevel modeling. Gelman, Hill, & Yajima (2012) argue that multilevel modeling could be used as a correction for multiple comparisons—even in experimental research where the structure of the data is not obviously hierarchical in nature:
Harder problems arise when modeling multiple comparisons that have more structure. For example, suppose we have five outcome measures, three varieties of treatments, and subgroups classified by two sexes and four racial groups. We would not want to model this 2 × 3 × 4 × 5 structure as 120 exchangeable groups. Even in these more complex situations, we think multilevel modeling should and will eventually take the place of classical multiple comparisons procedures.
Problems can be modeled in various ways, and in ambiguous cases, multiple approaches might seem appealing. I think our job is to choose a reasonable, informed approach and do so transparently. | When to use mixed effect model?
I'm afraid I might have the nuanced and perhaps unsatisfying answer that it is a subjective choice by the researcher or data analyst. As mentioned elsewhere in this thread, it isn't enough to simply s |
17,258 | When to use mixed effect model? | In mixed effects models, you add random (error) terms to your model, so you "mix" fixed and random effects. So, another approach to consider when to use mixed effects models, might be to look at what a "random effect" is. Thus, in addition to the previously given answers, I also find the distinction between the terms "fixed" and "random" effects from Bates (2010) instructive, section 1.1 (esp. page 2).
Parameters associated with the particular levels of a covariate are
sometimes called the “effects” of the levels. If the set of possible
levels of the covariate is fixed and reproducible we model the
covariate using fixed-effects parameters. If the levels that we
observed represent a random sample from the set of all possible levels
we incorporate random effects in the model. There are two things to
notice about this distinction between fixed-effects parameters and
random effects. First, the names are misleading because the
distinction between fixed and random is more a property of the levels
of the categorical covariate than a property of the effects associated
with them.
This definition often applies to some hierachical structure like countries, or classrooms, because you always have a "random" sample of countries or classrooms - data has not been collected from all possible countries or classrooms.
Sex, however, is fixed (or at least treated as being fixed). If you have male or female persons, there are no other sex-levels left (there might be some gender-exceptions, but this is mostly ignored).
Or say educational level: If you ask whether people are of lower, middle or higher education, there are no levels left, so you have not taken a "random" sample of all possible educational levels (hence, this is a fixed effect). | When to use mixed effect model? | In mixed effects models, you add random (error) terms to your model, so you "mix" fixed and random effects. So, another approach to consider when to use mixed effects models, might be to look at what | When to use mixed effect model?
In mixed effects models, you add random (error) terms to your model, so you "mix" fixed and random effects. So, another approach to consider when to use mixed effects models, might be to look at what a "random effect" is. Thus, in addition to the previously given answers, I also find the distinction between the terms "fixed" and "random" effects from Bates (2010) instructive, section 1.1 (esp. page 2).
Parameters associated with the particular levels of a covariate are
sometimes called the “effects” of the levels. If the set of possible
levels of the covariate is fixed and reproducible we model the
covariate using fixed-effects parameters. If the levels that we
observed represent a random sample from the set of all possible levels
we incorporate random effects in the model. There are two things to
notice about this distinction between fixed-effects parameters and
random effects. First, the names are misleading because the
distinction between fixed and random is more a property of the levels
of the categorical covariate than a property of the effects associated
with them.
This definition often applies to some hierachical structure like countries, or classrooms, because you always have a "random" sample of countries or classrooms - data has not been collected from all possible countries or classrooms.
Sex, however, is fixed (or at least treated as being fixed). If you have male or female persons, there are no other sex-levels left (there might be some gender-exceptions, but this is mostly ignored).
Or say educational level: If you ask whether people are of lower, middle or higher education, there are no levels left, so you have not taken a "random" sample of all possible educational levels (hence, this is a fixed effect). | When to use mixed effect model?
In mixed effects models, you add random (error) terms to your model, so you "mix" fixed and random effects. So, another approach to consider when to use mixed effects models, might be to look at what |
17,259 | When to use mixed effect model? | You could of course build a model for each different group, there is nothing wrong with that. However, you'd require larger sample size and need to manage multiple models.
By using mixed model, you pool (and share) the data together and thus require smaller sample size.
In doing so, we are sharing statistical strength. The idea here is that something we can infer well in one group of data can help us with something we cannot infer well in another.
Mixed models also prevents over-sampled groups from unfairly dominating inference.
My point is if you want to model the underlying latern hierarchical structure, you should add random effects to your model. Otherwise, if you don't care in your model intrepretation you don't use it.
https://www.dropbox.com/s/rzi2rsou6h817zz/Datascience%20Presentation.pdf?dl=0
gives relevant discussion. The author discussed why he didn't want to run separate regression models. | When to use mixed effect model? | You could of course build a model for each different group, there is nothing wrong with that. However, you'd require larger sample size and need to manage multiple models.
By using mixed model, you po | When to use mixed effect model?
You could of course build a model for each different group, there is nothing wrong with that. However, you'd require larger sample size and need to manage multiple models.
By using mixed model, you pool (and share) the data together and thus require smaller sample size.
In doing so, we are sharing statistical strength. The idea here is that something we can infer well in one group of data can help us with something we cannot infer well in another.
Mixed models also prevents over-sampled groups from unfairly dominating inference.
My point is if you want to model the underlying latern hierarchical structure, you should add random effects to your model. Otherwise, if you don't care in your model intrepretation you don't use it.
https://www.dropbox.com/s/rzi2rsou6h817zz/Datascience%20Presentation.pdf?dl=0
gives relevant discussion. The author discussed why he didn't want to run separate regression models. | When to use mixed effect model?
You could of course build a model for each different group, there is nothing wrong with that. However, you'd require larger sample size and need to manage multiple models.
By using mixed model, you po |
17,260 | When to use mixed effect model? | You use mixed models when some reasonable assumptions can be made, based on the study design, about the nature of correlation between observations and inference is desired on individual level or conditional effects. Mixed models allow for specifications of random effects, which are a convenient representation of correlation structures that arise naturally in the collection of data.
The most common type of mixed model is a random intercepts model which estimates a latent distribution of common constants having a 0-mean, finite variance normal distribution within clusters of individuals identified in the dataset. This approach accounts for potentially hundreds of confounding factors common to groups of observations, or clusters, but varying between clusters.
A second common type of mixed model is a random slopes model which, akin to the random intercepts model, estimates a latent distribution of time-predictor interactions which again comes from a 0-mean, finite variance normal distribution within a panel study, or clusters of observations measured prospectively or in a longitudinal fashion.
These results are roughly similar to the results obtained from using generalized least squares and the EM-algorithm to iteratively estimate model parameters and the covariance between these dependent observations (or more precisely, their residuals). Weighted least squares is more efficient than least squares when the covariance between observations is known. While the covariance is rarely known, it can be assumed to take a particular structure and be estimated iteratively. The random intercepts model gives similar inference and likelihoods to a weighted least squares having an exchangeable correlation structure where $cor(Y_1, Y_2) = \rho$ if $Y_1, Y_2$ are in the same cluster, and 0 otherwise. The random slopes model gives similar inference and likelihoods to a weighted least squares having an autoregressive 1 correlation structure where $cor(Y_t, Y_s) = \rho^{|t-s|}$ if $Y_t, Y_s$ are observations on the same sample at different times $t, s$ and 0 otherwise. The results are not identical, because the random intercept forces observations within clusters to be positively associated which is almost always a reasonable assumption.
Individual level or conditional effects can be contrasted with population level or marginal effects. Marginal effects represent the effect in a population from an intervention or screening. As an example, an intervention to increase compliance in substance abuse rehabilitation may look at attendance over 3 months in a panel of patients admitted for various conditions. Duration of usage may vary between patients and strongly predict compliance with the workshop with longer using participants having greater addictive tendencies and avoidance. An individual level analysis may reveal that the study is effective despite the fact that participants with longer addiction did not attend prior to receiving the intervention and continued not to attend after receiving the intervention. The inference may be problematic if in the population most eligible people have a long duration of addiction.
Marginal effects has less precise inference due to ignoring homogeneity between clusters in time or space. They can be estimated with generalized estimating equations or by marginalizing the mixed models. | When to use mixed effect model? | You use mixed models when some reasonable assumptions can be made, based on the study design, about the nature of correlation between observations and inference is desired on individual level or condi | When to use mixed effect model?
You use mixed models when some reasonable assumptions can be made, based on the study design, about the nature of correlation between observations and inference is desired on individual level or conditional effects. Mixed models allow for specifications of random effects, which are a convenient representation of correlation structures that arise naturally in the collection of data.
The most common type of mixed model is a random intercepts model which estimates a latent distribution of common constants having a 0-mean, finite variance normal distribution within clusters of individuals identified in the dataset. This approach accounts for potentially hundreds of confounding factors common to groups of observations, or clusters, but varying between clusters.
A second common type of mixed model is a random slopes model which, akin to the random intercepts model, estimates a latent distribution of time-predictor interactions which again comes from a 0-mean, finite variance normal distribution within a panel study, or clusters of observations measured prospectively or in a longitudinal fashion.
These results are roughly similar to the results obtained from using generalized least squares and the EM-algorithm to iteratively estimate model parameters and the covariance between these dependent observations (or more precisely, their residuals). Weighted least squares is more efficient than least squares when the covariance between observations is known. While the covariance is rarely known, it can be assumed to take a particular structure and be estimated iteratively. The random intercepts model gives similar inference and likelihoods to a weighted least squares having an exchangeable correlation structure where $cor(Y_1, Y_2) = \rho$ if $Y_1, Y_2$ are in the same cluster, and 0 otherwise. The random slopes model gives similar inference and likelihoods to a weighted least squares having an autoregressive 1 correlation structure where $cor(Y_t, Y_s) = \rho^{|t-s|}$ if $Y_t, Y_s$ are observations on the same sample at different times $t, s$ and 0 otherwise. The results are not identical, because the random intercept forces observations within clusters to be positively associated which is almost always a reasonable assumption.
Individual level or conditional effects can be contrasted with population level or marginal effects. Marginal effects represent the effect in a population from an intervention or screening. As an example, an intervention to increase compliance in substance abuse rehabilitation may look at attendance over 3 months in a panel of patients admitted for various conditions. Duration of usage may vary between patients and strongly predict compliance with the workshop with longer using participants having greater addictive tendencies and avoidance. An individual level analysis may reveal that the study is effective despite the fact that participants with longer addiction did not attend prior to receiving the intervention and continued not to attend after receiving the intervention. The inference may be problematic if in the population most eligible people have a long duration of addiction.
Marginal effects has less precise inference due to ignoring homogeneity between clusters in time or space. They can be estimated with generalized estimating equations or by marginalizing the mixed models. | When to use mixed effect model?
You use mixed models when some reasonable assumptions can be made, based on the study design, about the nature of correlation between observations and inference is desired on individual level or condi |
17,261 | When to use mixed effect model? | Mixed-effects should be used when data have a nested or hierarchical structure. This actually violates the assumption of independence of measurements, because all measurements within the same group/level are correlated.
In case of
"If different group/species are really similar. Say a female dog and a male dog. I think we may want use gender as a categorical variable in the model."
gender would be factor variable and fixed-effect, whereas variability of dog sizes within gender is a random-effect. My model would be
response ~ sex + (1|size), data=data
Intuitively, rabits, dogs and cates should be modeled separately as sizes of dog and cat are not correlated, however size of two dogs is a kind of "within-species" variability. | When to use mixed effect model? | Mixed-effects should be used when data have a nested or hierarchical structure. This actually violates the assumption of independence of measurements, because all measurements within the same group/le | When to use mixed effect model?
Mixed-effects should be used when data have a nested or hierarchical structure. This actually violates the assumption of independence of measurements, because all measurements within the same group/level are correlated.
In case of
"If different group/species are really similar. Say a female dog and a male dog. I think we may want use gender as a categorical variable in the model."
gender would be factor variable and fixed-effect, whereas variability of dog sizes within gender is a random-effect. My model would be
response ~ sex + (1|size), data=data
Intuitively, rabits, dogs and cates should be modeled separately as sizes of dog and cat are not correlated, however size of two dogs is a kind of "within-species" variability. | When to use mixed effect model?
Mixed-effects should be used when data have a nested or hierarchical structure. This actually violates the assumption of independence of measurements, because all measurements within the same group/le |
17,262 | What is the difference between least square and pseudo-inverse techniques for Linear Regression? | In the context of linear regression, 'least squares' means that we want to find the coefficients that minimize the squared error. It doesn't specify how this minimization should be performed, and there are many possibilities. Multiplying the response vector by the Moore-Penrose pseudoinverse of the regressor matrix is one way to do it, and is therefore one approach to least squares linear regression (as others have pointed out).
Differences between methods can arise when the regressor matrix does not have full rank. This can happen, for example, when the number of variables exceeds the number of data points. In this case, there are infinitely many choices of optimal coefficients. Methods differ in how they choose one solution out of this infinite set. The distinguishing characteristic of the pseudoinverse method in this situation is that it returns the solution with minimum $\ell_2$ norm. | What is the difference between least square and pseudo-inverse techniques for Linear Regression? | In the context of linear regression, 'least squares' means that we want to find the coefficients that minimize the squared error. It doesn't specify how this minimization should be performed, and ther | What is the difference between least square and pseudo-inverse techniques for Linear Regression?
In the context of linear regression, 'least squares' means that we want to find the coefficients that minimize the squared error. It doesn't specify how this minimization should be performed, and there are many possibilities. Multiplying the response vector by the Moore-Penrose pseudoinverse of the regressor matrix is one way to do it, and is therefore one approach to least squares linear regression (as others have pointed out).
Differences between methods can arise when the regressor matrix does not have full rank. This can happen, for example, when the number of variables exceeds the number of data points. In this case, there are infinitely many choices of optimal coefficients. Methods differ in how they choose one solution out of this infinite set. The distinguishing characteristic of the pseudoinverse method in this situation is that it returns the solution with minimum $\ell_2$ norm. | What is the difference between least square and pseudo-inverse techniques for Linear Regression?
In the context of linear regression, 'least squares' means that we want to find the coefficients that minimize the squared error. It doesn't specify how this minimization should be performed, and ther |
17,263 | What is the difference between least square and pseudo-inverse techniques for Linear Regression? | It depends on, what you mean by "differentiation techniques". There are two methods, that I could understand by that:
Use differentiation to derive the gradient, then perform gradient descent on the error surface. However, this would be rather unusual for linear regression (but not for other types of regression).
Use differentiation to derive the gradient, then use that to analytically determine a minimum by setting the gradient to zero.
The first method is very different from the pseudo-inverse. The second is not. If you perform the differentiation and solve the equation resulting from setting the gradient to zero, you will get exactly the pseudo-inverse as a general solution.
If you think about this, it makes a lot of sense. If different techniques would lead to different coefficients, it would be hard to tell, which ones are correct. If they generate the same coefficients, it should also be the case, that you can derive the equations used for one method from the other. | What is the difference between least square and pseudo-inverse techniques for Linear Regression? | It depends on, what you mean by "differentiation techniques". There are two methods, that I could understand by that:
Use differentiation to derive the gradient, then perform gradient descent on the | What is the difference between least square and pseudo-inverse techniques for Linear Regression?
It depends on, what you mean by "differentiation techniques". There are two methods, that I could understand by that:
Use differentiation to derive the gradient, then perform gradient descent on the error surface. However, this would be rather unusual for linear regression (but not for other types of regression).
Use differentiation to derive the gradient, then use that to analytically determine a minimum by setting the gradient to zero.
The first method is very different from the pseudo-inverse. The second is not. If you perform the differentiation and solve the equation resulting from setting the gradient to zero, you will get exactly the pseudo-inverse as a general solution.
If you think about this, it makes a lot of sense. If different techniques would lead to different coefficients, it would be hard to tell, which ones are correct. If they generate the same coefficients, it should also be the case, that you can derive the equations used for one method from the other. | What is the difference between least square and pseudo-inverse techniques for Linear Regression?
It depends on, what you mean by "differentiation techniques". There are two methods, that I could understand by that:
Use differentiation to derive the gradient, then perform gradient descent on the |
17,264 | What is the difference between least square and pseudo-inverse techniques for Linear Regression? | As has been pointed out in the other answers, multiplying by the pseudoinverse is one of the ways of obtaining a least squares solution.
It is easy to see why. Let us say you have $k$ points in $n-$dimensional space:
$$X =
\begin{bmatrix}
1 & x_{11} & x_{12} & x_{13} & \dots & x_{1n} \\
1 & x_{21} & x_{22} & x_{23} & \dots & x_{2n} \\
\vdots & \vdots & \vdots & \vdots & \ddots & \vdots \\
1 & x_{k1} & x_{k2} & x_{k3} & \dots & x_{kn}
\end{bmatrix}$$
Let each corresponding point have a value in $Y$:
$$Y =
\begin{bmatrix}
y_1 \\
y_2 \\
\vdots \\
y_k
\end{bmatrix}$$
You want to find a set of weights
$$W =
\begin{bmatrix}
w_1 \\
w_2 \\
\vdots \\
w_n
\end{bmatrix}$$
such that the squared error between $XW$ and $Y$ is minimized, that is the least squares solution:
$min_Wf(W)$, where $f(W) = (Y-XW)^T(Y-XW)$ (you can easily see that $f(W)$ is the sum of squared errors).
We do that by finding the derivative of $f(W)$ by $W$ and setting it to $0$:
$$\frac{\delta f}{\delta W} = \frac{\delta (Y-XW)^T(Y-XW)}{\delta W} = \frac{\delta (Y^TY - W^TX^TY - Y^TXW + W^TX^TXW)}{\delta W} = \frac{\delta (Y^TY - 2Y^TXW - Y^TXW + W^TX^TXW)}{\delta W} = \frac{\delta Y^TY - 2Y^TXW + W^TX^TXW}{\delta W} = -2Y^TX + 2W^TX^TX$$
Setting the derivative to $0$:
$$2W^TX^TX = 2Y^TX$$
$$X^TXW = X^TY$$
$$(X^TX)^{-1}X^TXW = (X^TX)^{-1}X^TY$$
$$W = (X^TX)^{-1}X^TY$$
So this way we can derive the pseudo-inverse matrix as the solution to the least squares problem. | What is the difference between least square and pseudo-inverse techniques for Linear Regression? | As has been pointed out in the other answers, multiplying by the pseudoinverse is one of the ways of obtaining a least squares solution.
It is easy to see why. Let us say you have $k$ points in $n-$di | What is the difference between least square and pseudo-inverse techniques for Linear Regression?
As has been pointed out in the other answers, multiplying by the pseudoinverse is one of the ways of obtaining a least squares solution.
It is easy to see why. Let us say you have $k$ points in $n-$dimensional space:
$$X =
\begin{bmatrix}
1 & x_{11} & x_{12} & x_{13} & \dots & x_{1n} \\
1 & x_{21} & x_{22} & x_{23} & \dots & x_{2n} \\
\vdots & \vdots & \vdots & \vdots & \ddots & \vdots \\
1 & x_{k1} & x_{k2} & x_{k3} & \dots & x_{kn}
\end{bmatrix}$$
Let each corresponding point have a value in $Y$:
$$Y =
\begin{bmatrix}
y_1 \\
y_2 \\
\vdots \\
y_k
\end{bmatrix}$$
You want to find a set of weights
$$W =
\begin{bmatrix}
w_1 \\
w_2 \\
\vdots \\
w_n
\end{bmatrix}$$
such that the squared error between $XW$ and $Y$ is minimized, that is the least squares solution:
$min_Wf(W)$, where $f(W) = (Y-XW)^T(Y-XW)$ (you can easily see that $f(W)$ is the sum of squared errors).
We do that by finding the derivative of $f(W)$ by $W$ and setting it to $0$:
$$\frac{\delta f}{\delta W} = \frac{\delta (Y-XW)^T(Y-XW)}{\delta W} = \frac{\delta (Y^TY - W^TX^TY - Y^TXW + W^TX^TXW)}{\delta W} = \frac{\delta (Y^TY - 2Y^TXW - Y^TXW + W^TX^TXW)}{\delta W} = \frac{\delta Y^TY - 2Y^TXW + W^TX^TXW}{\delta W} = -2Y^TX + 2W^TX^TX$$
Setting the derivative to $0$:
$$2W^TX^TX = 2Y^TX$$
$$X^TXW = X^TY$$
$$(X^TX)^{-1}X^TXW = (X^TX)^{-1}X^TY$$
$$W = (X^TX)^{-1}X^TY$$
So this way we can derive the pseudo-inverse matrix as the solution to the least squares problem. | What is the difference between least square and pseudo-inverse techniques for Linear Regression?
As has been pointed out in the other answers, multiplying by the pseudoinverse is one of the ways of obtaining a least squares solution.
It is easy to see why. Let us say you have $k$ points in $n-$di |
17,265 | What is the difference between least square and pseudo-inverse techniques for Linear Regression? | Pseudo inverse solution is based on least square error, as Łukasz Grad pointed out. That is, you are actually solving the minimization problem of,
$E(W) =\frac{1}{2}\sum \left(y^{(i)}-W ^Tx^{(i)}\right)^2$
by differentiating the error w.r.t $W$. Then you get the solution: $W = \left(X^TX\right)^{-1}X^TY$. (Note pseudo-inverse is not inverse. So you cannot interpret the solution as equal to $X^{-1}Y$, which may seem like a solution from $XW = Y$ directly with matrix manipulation. It is another topic how to find the pseudo-inverse.)
If you are asking about the covariance-based solution $W = \frac{cov(X, Y)}{var(X)}$, it can be interpreted as a direct solution based on the linear relation between $X$ and $Y$. Actually this solution is also strictly deduced from least square error, and the difference is nonessential from the pseudo-inverse one. This is still the pseudo-inverse solution but knowing that your line will definitely go through the point of mean values $(\bar{X},\bar{Y})$. So the error measure can be rewritten as,
$E(W) =\frac{1}{2}\sum \left((y^{(i)}-\bar{y})-W ^T(x^{(i)}-\bar{x})\right)^2$
When you use $x-\bar{x}$ to represent $x$ and $y-\bar{y}$ to represent $y$, your solution with pseudo-inverse is the same as the one with covariance. The difference is, now you have to compute the intercept separately, because, by subtracing the mean values of $x$ and $y$, you virtually center the coordinates at $(\bar{x}, \bar{y})$ and your line passes it, hence the intercept is zero. You have map the new coordinate system back the original one by computing the intercept with $w_{0} = \bar{y} -W^{T}\bar{x}$. | What is the difference between least square and pseudo-inverse techniques for Linear Regression? | Pseudo inverse solution is based on least square error, as Łukasz Grad pointed out. That is, you are actually solving the minimization problem of,
$E(W) =\frac{1}{2}\sum \left(y^{(i)}-W ^Tx^{(i)}\righ | What is the difference between least square and pseudo-inverse techniques for Linear Regression?
Pseudo inverse solution is based on least square error, as Łukasz Grad pointed out. That is, you are actually solving the minimization problem of,
$E(W) =\frac{1}{2}\sum \left(y^{(i)}-W ^Tx^{(i)}\right)^2$
by differentiating the error w.r.t $W$. Then you get the solution: $W = \left(X^TX\right)^{-1}X^TY$. (Note pseudo-inverse is not inverse. So you cannot interpret the solution as equal to $X^{-1}Y$, which may seem like a solution from $XW = Y$ directly with matrix manipulation. It is another topic how to find the pseudo-inverse.)
If you are asking about the covariance-based solution $W = \frac{cov(X, Y)}{var(X)}$, it can be interpreted as a direct solution based on the linear relation between $X$ and $Y$. Actually this solution is also strictly deduced from least square error, and the difference is nonessential from the pseudo-inverse one. This is still the pseudo-inverse solution but knowing that your line will definitely go through the point of mean values $(\bar{X},\bar{Y})$. So the error measure can be rewritten as,
$E(W) =\frac{1}{2}\sum \left((y^{(i)}-\bar{y})-W ^T(x^{(i)}-\bar{x})\right)^2$
When you use $x-\bar{x}$ to represent $x$ and $y-\bar{y}$ to represent $y$, your solution with pseudo-inverse is the same as the one with covariance. The difference is, now you have to compute the intercept separately, because, by subtracing the mean values of $x$ and $y$, you virtually center the coordinates at $(\bar{x}, \bar{y})$ and your line passes it, hence the intercept is zero. You have map the new coordinate system back the original one by computing the intercept with $w_{0} = \bar{y} -W^{T}\bar{x}$. | What is the difference between least square and pseudo-inverse techniques for Linear Regression?
Pseudo inverse solution is based on least square error, as Łukasz Grad pointed out. That is, you are actually solving the minimization problem of,
$E(W) =\frac{1}{2}\sum \left(y^{(i)}-W ^Tx^{(i)}\righ |
17,266 | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $? | I agree with @whuber that the root of the confusion seems to be replacing the summation asymptotic in CLT with some sort of division in your argument. In CLT we get the fixed distribution $f(x,\lambda)$ then draw $n$ numbers $x_i$ from it and calculate the sum $\bar x_n=\frac{1}{n}\sum_{i=1}^nx_i$. If we keep increasing $n$ then an interesting thing happens:
$$\sqrt n (\bar x_n-\mu)\rightarrow\mathcal{N}(0,\sigma^2)$$
where $\mu,\sigma^2$ are mean and the variance of the distribution $f(x)$.
What you're suggesting to do with Poisson is somewhat backwards: instead of summing the variables from a fixed distribution, you want to divide the fixed distribution into ever changing parts. In other words you take a variable $x$ from a fixed distribution $f(x,\lambda)$ then divide it into $x_i$ so that $$\sum_{i=1}^nx_i\equiv x$$
What does CLT say about this process? Nothing. Note, how in CLT we have ever changing $\sqrt n(\bar x_n-\mu)$, and its changing distribution $f_n(x)$ that converges to a fixed distribution $\mathcal{N}(0,\sigma^2)$
In your setup neither the sum $x$ nor its distribution $f(x,\lambda)$ are changing! They're fixed. They're not changing, they're not converging to anything. So, CLT has nothing to say about them.
Also, CLT doesn't say anything about the number of elements in the sum. You can have a sum of 1000 variables from Poisson(0.001) and CLT won't say anything about the sum. All it does say is that if you keep increasing N then at some point this sum will start looking like a normal distribution $\frac{1}{N}\sum_{i=1}^N x_i, x_i\sim Poisson(0.001)$. In fact if N=1,000,000 you'll get the close approximation of normal distribution.
Your intuition is right only about the number of elements in the sum, i.e. than more the starting distribution is different from normal, then more elements you need to sum to get to normal. The more formal (but still informal) way would be by looking at the characteristic function of Poisson: $$\exp(\lambda (\exp(it)-1))$$
If you $\lambda>>1$, you get with the Taylor expansion (wrt $t$) of the nested exponent:
$$\approx\exp(i\lambda t-\lambda/2t^2)$$
This is the characteristic function of the normal distribution $\mathcal{N}(\lambda,\lambda^2)$
However, your intuition is not applied correctly: your displacing the summation in CLT with some kind of division messes things up, and renders CLT inapplicable. | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $? | I agree with @whuber that the root of the confusion seems to be replacing the summation asymptotic in CLT with some sort of division in your argument. In CLT we get the fixed distribution $f(x,\lambda | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $?
I agree with @whuber that the root of the confusion seems to be replacing the summation asymptotic in CLT with some sort of division in your argument. In CLT we get the fixed distribution $f(x,\lambda)$ then draw $n$ numbers $x_i$ from it and calculate the sum $\bar x_n=\frac{1}{n}\sum_{i=1}^nx_i$. If we keep increasing $n$ then an interesting thing happens:
$$\sqrt n (\bar x_n-\mu)\rightarrow\mathcal{N}(0,\sigma^2)$$
where $\mu,\sigma^2$ are mean and the variance of the distribution $f(x)$.
What you're suggesting to do with Poisson is somewhat backwards: instead of summing the variables from a fixed distribution, you want to divide the fixed distribution into ever changing parts. In other words you take a variable $x$ from a fixed distribution $f(x,\lambda)$ then divide it into $x_i$ so that $$\sum_{i=1}^nx_i\equiv x$$
What does CLT say about this process? Nothing. Note, how in CLT we have ever changing $\sqrt n(\bar x_n-\mu)$, and its changing distribution $f_n(x)$ that converges to a fixed distribution $\mathcal{N}(0,\sigma^2)$
In your setup neither the sum $x$ nor its distribution $f(x,\lambda)$ are changing! They're fixed. They're not changing, they're not converging to anything. So, CLT has nothing to say about them.
Also, CLT doesn't say anything about the number of elements in the sum. You can have a sum of 1000 variables from Poisson(0.001) and CLT won't say anything about the sum. All it does say is that if you keep increasing N then at some point this sum will start looking like a normal distribution $\frac{1}{N}\sum_{i=1}^N x_i, x_i\sim Poisson(0.001)$. In fact if N=1,000,000 you'll get the close approximation of normal distribution.
Your intuition is right only about the number of elements in the sum, i.e. than more the starting distribution is different from normal, then more elements you need to sum to get to normal. The more formal (but still informal) way would be by looking at the characteristic function of Poisson: $$\exp(\lambda (\exp(it)-1))$$
If you $\lambda>>1$, you get with the Taylor expansion (wrt $t$) of the nested exponent:
$$\approx\exp(i\lambda t-\lambda/2t^2)$$
This is the characteristic function of the normal distribution $\mathcal{N}(\lambda,\lambda^2)$
However, your intuition is not applied correctly: your displacing the summation in CLT with some kind of division messes things up, and renders CLT inapplicable. | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $?
I agree with @whuber that the root of the confusion seems to be replacing the summation asymptotic in CLT with some sort of division in your argument. In CLT we get the fixed distribution $f(x,\lambda |
17,267 | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $? | The problem with your example is that you are allowing the parameters to change as $n$ changes. The CLT tells you that for a fixed distribution with a finite mean and sd, as $n \rightarrow \infty$,
$\frac {\sum x - \mu} {\sqrt n} \rightarrow_d N(0, \sigma)$,
where $\mu$ and $\sigma$ are from the mean and sd of the distribution of $x$.
Of course, for different distributions (i.e. higher skewed for example), larger $n$'s are required before the approximation derived from this theorem become reasonable. In your example, for $\lambda_m = 1/m$, an $n >> m$ is required before the normal approximation is reasonable.
EDIT
There is discussion about how the CLT does not apply to sums, but rather to standardized sums (i.e. $\sum x_i / \sqrt n$ not $\sum x_i$). In theory, this is of course true: the unstandardized sum will have an undefined distribution in most cases.
However, in practice, you certainly can apply the approximation justified by the CLT to sums! If $F_{\bar x}$ can be approximated by a normal CDF for large $n$, then certainly $F_{\sum x}$ can too, as multiplying by a scalar preserves normality. And you can see this right away in this problem: recall that if $X_i \sim Pois(\lambda)$, then $Y = \sum_{i = 1}^n X_i \sim Pois(n\lambda)$. And we all learned in our upper division probability course that for large $\lambda$, the CDF of a $Pois(\lambda)$ can be approximated quite well by a normal with $\mu = \lambda$, $\sigma^2 = \lambda$. So for any fixed $\lambda$, we can approximate the CDF of $Y \sim Pois(n\lambda)$ fairly well with $\Phi( \frac{y - n\lambda}{\sqrt{n\lambda} })$ for a large enough $n$ if $\lambda > 0$ (approximation can trivially be applied if $\lambda = 0$, but not the calculation of the CDF as I have written it).
While the CLT does not readily apply to sums, the approximation based on the CLT certainly does. I believe this is what the OP was referring to when discussing applying the CLT to the sum. | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $? | The problem with your example is that you are allowing the parameters to change as $n$ changes. The CLT tells you that for a fixed distribution with a finite mean and sd, as $n \rightarrow \infty$,
$ | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $?
The problem with your example is that you are allowing the parameters to change as $n$ changes. The CLT tells you that for a fixed distribution with a finite mean and sd, as $n \rightarrow \infty$,
$\frac {\sum x - \mu} {\sqrt n} \rightarrow_d N(0, \sigma)$,
where $\mu$ and $\sigma$ are from the mean and sd of the distribution of $x$.
Of course, for different distributions (i.e. higher skewed for example), larger $n$'s are required before the approximation derived from this theorem become reasonable. In your example, for $\lambda_m = 1/m$, an $n >> m$ is required before the normal approximation is reasonable.
EDIT
There is discussion about how the CLT does not apply to sums, but rather to standardized sums (i.e. $\sum x_i / \sqrt n$ not $\sum x_i$). In theory, this is of course true: the unstandardized sum will have an undefined distribution in most cases.
However, in practice, you certainly can apply the approximation justified by the CLT to sums! If $F_{\bar x}$ can be approximated by a normal CDF for large $n$, then certainly $F_{\sum x}$ can too, as multiplying by a scalar preserves normality. And you can see this right away in this problem: recall that if $X_i \sim Pois(\lambda)$, then $Y = \sum_{i = 1}^n X_i \sim Pois(n\lambda)$. And we all learned in our upper division probability course that for large $\lambda$, the CDF of a $Pois(\lambda)$ can be approximated quite well by a normal with $\mu = \lambda$, $\sigma^2 = \lambda$. So for any fixed $\lambda$, we can approximate the CDF of $Y \sim Pois(n\lambda)$ fairly well with $\Phi( \frac{y - n\lambda}{\sqrt{n\lambda} })$ for a large enough $n$ if $\lambda > 0$ (approximation can trivially be applied if $\lambda = 0$, but not the calculation of the CDF as I have written it).
While the CLT does not readily apply to sums, the approximation based on the CLT certainly does. I believe this is what the OP was referring to when discussing applying the CLT to the sum. | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $?
The problem with your example is that you are allowing the parameters to change as $n$ changes. The CLT tells you that for a fixed distribution with a finite mean and sd, as $n \rightarrow \infty$,
$ |
17,268 | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $? | The question is, I argue, more interesting if thought about more generally, letting the distribution of the parent Poisson depend on $n$, say with parameter $\lambda_n$ and $\lambda_n = 1$ as a special case. I think it's perfectly reasonable to ask why, and how we can understand that, a central limit theorem does not hold for the sum $S_n = \sum_{i=1}^n X_{i,n}$. After all, it's common to apply a CLT even in problems where the distributions of the components of the sum depend on $n$. It's also common to decompose Poisson distributions as the distribution of a sum of Poisson variables, and then apply a CLT.
The key issue as I see it is that your construction implies the distribution of $X_{i, n}$ depends on $n$ in such a way that the parameter of the distribution of $S_n$ does not grow in $n$. If you would instead have taken, for example, $S_n \sim Poi(n)$ and made the same decomposition, the standard CLT would apply. In fact, one can think of many decompositions of a $Poi(\lambda_n)$ distribution that allows for application of a CLT.
The Lindeberg-Feller Central Limit Theorem for triangular arrays is often used to examine convergence of such sums. As you point out, $S_n \sim Poi(1)$ for all $n$, so $S_n$ cannot be asymptotically normal. Still, examining the Lindeberg-Feller condition sheds some light on when decomposing a Poisson into a sum may lead to progress.
A version of the theorem may be found in these notes by Hunter. Let $s_n^2 = \mathrm{Var(S_n)}$. The Lindeberg-Feller condition is that, $\forall \epsilon >0$:
$$
\frac{1}{s_n^2}\sum_{i=1}^n\mathbb E[X_{i,n} - 1/n]^2I(\vert X_{i,n} - 1/n \vert >\epsilon s_n) \to 0,n\to\infty
$$
Now, for the case at hand, the variance of the terms in the sum is dying off so quickly in $n$ that $s_n = 1$ for every $n$. For fixed $n$, we also have that the $X_{i,n}$ are iid. Thus, the condition is equivalent to $$
n\mathbb E[X_{1,n} - 1/n]^2I(\vert X_{1,n} - 1/n \vert >\epsilon) \to 0.
$$
But, for small $\epsilon$ and large $n$,
\begin{align}
n\mathbb E[X_{1,n} - 1/n]^2I(\vert X_{1,n} - 1/n \vert >\epsilon) &>n\epsilon^2P(X_{1,n}>0) \\
&=\epsilon^2n[1 - e^{-1/n}] \\
&= \epsilon^2n[1-(1 - 1/n + o(1/n))] \\
&= \epsilon^2 + o(1),
\end{align}
which does not approach zero. Thus, the condition fails to hold. Again, this is as expected since we already know the exact distribution of $S_n$ for every $n$, but going through these calculations gives some indications of why it fails: if the variance didn't die off as quickly in $n$ you could have the condition hold. | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $? | The question is, I argue, more interesting if thought about more generally, letting the distribution of the parent Poisson depend on $n$, say with parameter $\lambda_n$ and $\lambda_n = 1$ as a specia | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $?
The question is, I argue, more interesting if thought about more generally, letting the distribution of the parent Poisson depend on $n$, say with parameter $\lambda_n$ and $\lambda_n = 1$ as a special case. I think it's perfectly reasonable to ask why, and how we can understand that, a central limit theorem does not hold for the sum $S_n = \sum_{i=1}^n X_{i,n}$. After all, it's common to apply a CLT even in problems where the distributions of the components of the sum depend on $n$. It's also common to decompose Poisson distributions as the distribution of a sum of Poisson variables, and then apply a CLT.
The key issue as I see it is that your construction implies the distribution of $X_{i, n}$ depends on $n$ in such a way that the parameter of the distribution of $S_n$ does not grow in $n$. If you would instead have taken, for example, $S_n \sim Poi(n)$ and made the same decomposition, the standard CLT would apply. In fact, one can think of many decompositions of a $Poi(\lambda_n)$ distribution that allows for application of a CLT.
The Lindeberg-Feller Central Limit Theorem for triangular arrays is often used to examine convergence of such sums. As you point out, $S_n \sim Poi(1)$ for all $n$, so $S_n$ cannot be asymptotically normal. Still, examining the Lindeberg-Feller condition sheds some light on when decomposing a Poisson into a sum may lead to progress.
A version of the theorem may be found in these notes by Hunter. Let $s_n^2 = \mathrm{Var(S_n)}$. The Lindeberg-Feller condition is that, $\forall \epsilon >0$:
$$
\frac{1}{s_n^2}\sum_{i=1}^n\mathbb E[X_{i,n} - 1/n]^2I(\vert X_{i,n} - 1/n \vert >\epsilon s_n) \to 0,n\to\infty
$$
Now, for the case at hand, the variance of the terms in the sum is dying off so quickly in $n$ that $s_n = 1$ for every $n$. For fixed $n$, we also have that the $X_{i,n}$ are iid. Thus, the condition is equivalent to $$
n\mathbb E[X_{1,n} - 1/n]^2I(\vert X_{1,n} - 1/n \vert >\epsilon) \to 0.
$$
But, for small $\epsilon$ and large $n$,
\begin{align}
n\mathbb E[X_{1,n} - 1/n]^2I(\vert X_{1,n} - 1/n \vert >\epsilon) &>n\epsilon^2P(X_{1,n}>0) \\
&=\epsilon^2n[1 - e^{-1/n}] \\
&= \epsilon^2n[1-(1 - 1/n + o(1/n))] \\
&= \epsilon^2 + o(1),
\end{align}
which does not approach zero. Thus, the condition fails to hold. Again, this is as expected since we already know the exact distribution of $S_n$ for every $n$, but going through these calculations gives some indications of why it fails: if the variance didn't die off as quickly in $n$ you could have the condition hold. | Why doesn't the CLT work for $x \sim poisson(\lambda = 1) $?
The question is, I argue, more interesting if thought about more generally, letting the distribution of the parent Poisson depend on $n$, say with parameter $\lambda_n$ and $\lambda_n = 1$ as a specia |
17,269 | Cross validation with test data set | Let's look at three different approaches
In the simplest scenario one would collect one dataset and train your model via cross-validation to create your best model. Then you would collect another completely independent dataset and test your model. However, this scenario is not possible for many researchers given time or cost limitations.
If you have a sufficiently large dataset, you would want to take a split of your data and leave it to the side (completely untouched by the training). This is to simulate it as a completely independent dataset set even though it comes from the same dataset but the model training won't take any information from those samples. You would then build your model on the remaining training samples and then test on these left-out samples.
If you have a smaller dataset, you may not be able to afford to simply ignore a chunk of your data for model building. As such, the validation is performed on every fold (k-fold CV?) and your validation metric would be aggregated across each validation.
To more directly answer your question, yes you can just do cross-validation on your full dataset. You can then use your predicted and actual classes to evaluate your models performance by whatever metric you prefer (Accuracy, AUC, etc.)
That said, you still probably want to look in to repeated cross-validation to evaluate the stability of your model. Some good answers regarding this are here on internal vs. external CV and here on the # of repeats | Cross validation with test data set | Let's look at three different approaches
In the simplest scenario one would collect one dataset and train your model via cross-validation to create your best model. Then you would collect another co | Cross validation with test data set
Let's look at three different approaches
In the simplest scenario one would collect one dataset and train your model via cross-validation to create your best model. Then you would collect another completely independent dataset and test your model. However, this scenario is not possible for many researchers given time or cost limitations.
If you have a sufficiently large dataset, you would want to take a split of your data and leave it to the side (completely untouched by the training). This is to simulate it as a completely independent dataset set even though it comes from the same dataset but the model training won't take any information from those samples. You would then build your model on the remaining training samples and then test on these left-out samples.
If you have a smaller dataset, you may not be able to afford to simply ignore a chunk of your data for model building. As such, the validation is performed on every fold (k-fold CV?) and your validation metric would be aggregated across each validation.
To more directly answer your question, yes you can just do cross-validation on your full dataset. You can then use your predicted and actual classes to evaluate your models performance by whatever metric you prefer (Accuracy, AUC, etc.)
That said, you still probably want to look in to repeated cross-validation to evaluate the stability of your model. Some good answers regarding this are here on internal vs. external CV and here on the # of repeats | Cross validation with test data set
Let's look at three different approaches
In the simplest scenario one would collect one dataset and train your model via cross-validation to create your best model. Then you would collect another co |
17,270 | Are sampling distributions legitimate for inference? | Typically you'd carry out inference conditional on the actual sample size $n$, because it's ancillary to the parameters of interest; i.e. it contains no information about their true values, only affecting the precision with which you can measure them. Cox (1958), "Some Problems Connected with Statistical Inference", Ann. Math. Statist. 29, 2 is usually cited as first explicating what's sometimes known as the Conditionality Principle, though it was implicit in much earlier work, harking back to Fisher's idea of "relevant subsets".
If your researcher's funding was cut off because results so far were disappointing, then of course $n$ isn't ancillary. Perhaps the simplest illustration of the problem is estimation of a Bernoulli probability from either a binomial (fixed no. of trials) or negative binomial (fixed no. successes) sampling scheme. The sufficient statistic is the same under either, but its distribution differs. How would you analyze an experiment where you didn't know which was followed? Berger & Wolpert (1988), The Likelihood Principle discuss the implications of this & other stopping rules for inference.
You might want to think about what happens if you don't take any sampling distribution into account. Armitage (1961), "Comment on 'Consistency in Statistical Inference and Decision' by Smith", JRSS B, 23,1 pointed out that if you sample $x$ from a normal distribution until $\sqrt{n} \bar{x} \leq k$, the likelihood ratio for testing that the mean $\mu=0$ vs $\mu\neq0$ is $\frac{L(0)}{L(\bar{x})}\leq \mathrm{e}^{-k^2/2}$, so the researcher can set a bound on this in advance by an appropriate choice of $k$. Only a frequentist analysis can take the distribution of the likelihood ratio under this rather unfair-seeming sampling scheme into account. See the responses of Kerridge (1963), "Bounds for the frequency of misleading Bayes inferences", Ann. Math. Stat., 34, Cornfield (1966), "Sequential trials, sequential analysis, and the likelihood principle", The American Statistician, 20, 2, & Kadane (1996), "Reasoning to a foregone conclusion", JASA, 91, 435
Pointing out the dependence of frequentist inference on a researcher's intentions is a handy dig at people (if there still are any) who get on their high horse about the "subjectivity" of Bayesian inference. Personally, I can live with it; the performance of a procedure over a long series of repetitions is always going to be something more or less notional, which doesn't detract from its being a useful thing to consider ("a calibration of the likelihood" was how Cox described p-values). From the dates of the references you might have noticed that these issues aren't very new; attempts to settle them by a priori argumentation have largely died down (except on the Internet, always behind the times except in trivial matters) & been replaced by acknowledgement that neither Bayesian nor frequentist statistics are going to collapse under the weight of their internal contradictions, & that there's more than one useful way to apply probability theory to inference from noisy data.
PS: Thinking to add a counter-balance to Berger & Wolpert I happened upon Cox & Mayo (2010), "Objectivity and Conditionality in Frequentist Inference" in Error and Inference. There's quite likely an element of wishful thinking in my assertion that the debate has died down, but it's striking how little new there is to be said on the matter after half a century or so. (All the same, this is a concise & eloquent defence of frequentist ideas.) | Are sampling distributions legitimate for inference? | Typically you'd carry out inference conditional on the actual sample size $n$, because it's ancillary to the parameters of interest; i.e. it contains no information about their true values, only affec | Are sampling distributions legitimate for inference?
Typically you'd carry out inference conditional on the actual sample size $n$, because it's ancillary to the parameters of interest; i.e. it contains no information about their true values, only affecting the precision with which you can measure them. Cox (1958), "Some Problems Connected with Statistical Inference", Ann. Math. Statist. 29, 2 is usually cited as first explicating what's sometimes known as the Conditionality Principle, though it was implicit in much earlier work, harking back to Fisher's idea of "relevant subsets".
If your researcher's funding was cut off because results so far were disappointing, then of course $n$ isn't ancillary. Perhaps the simplest illustration of the problem is estimation of a Bernoulli probability from either a binomial (fixed no. of trials) or negative binomial (fixed no. successes) sampling scheme. The sufficient statistic is the same under either, but its distribution differs. How would you analyze an experiment where you didn't know which was followed? Berger & Wolpert (1988), The Likelihood Principle discuss the implications of this & other stopping rules for inference.
You might want to think about what happens if you don't take any sampling distribution into account. Armitage (1961), "Comment on 'Consistency in Statistical Inference and Decision' by Smith", JRSS B, 23,1 pointed out that if you sample $x$ from a normal distribution until $\sqrt{n} \bar{x} \leq k$, the likelihood ratio for testing that the mean $\mu=0$ vs $\mu\neq0$ is $\frac{L(0)}{L(\bar{x})}\leq \mathrm{e}^{-k^2/2}$, so the researcher can set a bound on this in advance by an appropriate choice of $k$. Only a frequentist analysis can take the distribution of the likelihood ratio under this rather unfair-seeming sampling scheme into account. See the responses of Kerridge (1963), "Bounds for the frequency of misleading Bayes inferences", Ann. Math. Stat., 34, Cornfield (1966), "Sequential trials, sequential analysis, and the likelihood principle", The American Statistician, 20, 2, & Kadane (1996), "Reasoning to a foregone conclusion", JASA, 91, 435
Pointing out the dependence of frequentist inference on a researcher's intentions is a handy dig at people (if there still are any) who get on their high horse about the "subjectivity" of Bayesian inference. Personally, I can live with it; the performance of a procedure over a long series of repetitions is always going to be something more or less notional, which doesn't detract from its being a useful thing to consider ("a calibration of the likelihood" was how Cox described p-values). From the dates of the references you might have noticed that these issues aren't very new; attempts to settle them by a priori argumentation have largely died down (except on the Internet, always behind the times except in trivial matters) & been replaced by acknowledgement that neither Bayesian nor frequentist statistics are going to collapse under the weight of their internal contradictions, & that there's more than one useful way to apply probability theory to inference from noisy data.
PS: Thinking to add a counter-balance to Berger & Wolpert I happened upon Cox & Mayo (2010), "Objectivity and Conditionality in Frequentist Inference" in Error and Inference. There's quite likely an element of wishful thinking in my assertion that the debate has died down, but it's striking how little new there is to be said on the matter after half a century or so. (All the same, this is a concise & eloquent defence of frequentist ideas.) | Are sampling distributions legitimate for inference?
Typically you'd carry out inference conditional on the actual sample size $n$, because it's ancillary to the parameters of interest; i.e. it contains no information about their true values, only affec |
17,271 | Are sampling distributions legitimate for inference? | The short answer to your question is: it depends who you ask ;-) Die-hard Bayesians will declare victory over, or at least parity with, frequentist methodology. Die-hard frequentists will default to "This can't be answered". The other 99% of statisticians will use whatever methods have been shown to be reliable under inerrupted experiments.
I know that the sensitivity of the sampling distribution to the intentions of the researcher can be troubling, and there is really no good solution to that problem. Bayesians and frequentists alike must use some subjectivity and judgement in deciding how to form an inference. However, I think you are taking an example from an area that is generally controversial and laying the problems solely at the feet of frequentist inference. The sequential and/or stopped experiments are classic examples of the subjective nature of inference ... and to which there is no absolutely objective and agreed upon answer.
What about regular inference, where you actually collect the sample you intended to get? Here, I think the frequentists have the upper hand, as CI's and p-values are well calibrated wrt their repeated sampling properties, whereas Bayesian inference retains its personal and subjective nature.
If you want a more theoretical exposition of the Bayesian response, I would read about "conditional inference" with key researchers being Nancy Reid and Lehmann. | Are sampling distributions legitimate for inference? | The short answer to your question is: it depends who you ask ;-) Die-hard Bayesians will declare victory over, or at least parity with, frequentist methodology. Die-hard frequentists will default to " | Are sampling distributions legitimate for inference?
The short answer to your question is: it depends who you ask ;-) Die-hard Bayesians will declare victory over, or at least parity with, frequentist methodology. Die-hard frequentists will default to "This can't be answered". The other 99% of statisticians will use whatever methods have been shown to be reliable under inerrupted experiments.
I know that the sensitivity of the sampling distribution to the intentions of the researcher can be troubling, and there is really no good solution to that problem. Bayesians and frequentists alike must use some subjectivity and judgement in deciding how to form an inference. However, I think you are taking an example from an area that is generally controversial and laying the problems solely at the feet of frequentist inference. The sequential and/or stopped experiments are classic examples of the subjective nature of inference ... and to which there is no absolutely objective and agreed upon answer.
What about regular inference, where you actually collect the sample you intended to get? Here, I think the frequentists have the upper hand, as CI's and p-values are well calibrated wrt their repeated sampling properties, whereas Bayesian inference retains its personal and subjective nature.
If you want a more theoretical exposition of the Bayesian response, I would read about "conditional inference" with key researchers being Nancy Reid and Lehmann. | Are sampling distributions legitimate for inference?
The short answer to your question is: it depends who you ask ;-) Die-hard Bayesians will declare victory over, or at least parity with, frequentist methodology. Die-hard frequentists will default to " |
17,272 | How do you decide the sample size when polling a large population? | Sample size doesn't much depend on the population size, which is counter-intuitive to many.
Most polling companies use 400 or 1000 people in their samples.
There is a reason for this:
A sample size of 400 will give you a confidence interval of +/-5% 19 times out of 20 (95%)
A sample size of 1000 will give you a confidence interval of +/-3% 19 times out of 20 (95%)
When you are measuring a proportion near 50% anyways.
This calculator isn't bad:
http://www.raosoft.com/samplesize.html | How do you decide the sample size when polling a large population? | Sample size doesn't much depend on the population size, which is counter-intuitive to many.
Most polling companies use 400 or 1000 people in their samples.
There is a reason for this:
A sample size of | How do you decide the sample size when polling a large population?
Sample size doesn't much depend on the population size, which is counter-intuitive to many.
Most polling companies use 400 or 1000 people in their samples.
There is a reason for this:
A sample size of 400 will give you a confidence interval of +/-5% 19 times out of 20 (95%)
A sample size of 1000 will give you a confidence interval of +/-3% 19 times out of 20 (95%)
When you are measuring a proportion near 50% anyways.
This calculator isn't bad:
http://www.raosoft.com/samplesize.html | How do you decide the sample size when polling a large population?
Sample size doesn't much depend on the population size, which is counter-intuitive to many.
Most polling companies use 400 or 1000 people in their samples.
There is a reason for this:
A sample size of |
17,273 | How do you decide the sample size when polling a large population? | Suppose that you want to know what percentage of people would vote for a particular candidate (say, $\pi$, note that by definition $\pi$ is between 0 and 100). You sample $N$ voters at random to find out how they would vote and your survey of these $N$ voters tells you that the percentage is $p$. So, you would like to establish a confidence interval for the true percentage.
If you assume that $p$ is normally distributed (an assumption that may or may not be justified depending on how 'big' $N$ is) then your confidence interval for $\pi$ would be of the following form:
$$
CI = [ p - k * sd(p),~~ p + k * sd(p)]
$$
where $k$ is a constant that depends on the extent of confidence you want (i.e., 95% or 99% etc).
From a polling perspective, you want the width of your confidence interval to be 'low'. Usually, pollsters work with the margin of error which is basically one-half of the CI. In other words, $\text{MoE} = k * sd(p)$.
Here is how we would go about calculating $sd(p)$: By definition, $p = \sum X_i / N$ where, $X_i = 1$ if voter $i$ votes for candidate and $0$ otherwise.
Since, we sampled the voters at random, we could assume that $X_i$ is a i.i.d Bernoulli random variable. Therefore,
$$
Var(P) = V\left( \sum\frac{X_i}{N}\right) = \frac{\sum V(X_i)}{N^2} = \frac{N \pi (1-\pi)}{N^2} = \frac{\pi (1-\pi)}{N}.
$$
Thus,
$$
sd(p) = \sqrt{\frac{\pi * (1-\pi)}{N}}
$$
Now to estimate margin of error we need to know $\pi$ which we do not know obviously. But, an inspection of the numerator suggests that the 'worst' estimate for $sd(p)$ in the sense that we get the 'largest' standard deviation is when $\pi = 0.5$. Therefore, the worst possible standard deviation is:
$$
sd(p) = \sqrt{0.5 * 0.5 / N } = 0.5 / \sqrt{N}
$$
So, you see that the margin of error falls off exponentially with $N$ and thus you really do not need very big samples to reduce your margin of error, or in other words $N$ need not be very large for you to obtain a narrow confidence interval.
For example, for a 95 % confidence interval (i.e., $k= 1.96$) and $N = 1000$, the confidence interval is:
$$
\left[p - 1.96 \frac{0.5}{\sqrt{1000}},~~ p + 1.96 \frac{0.5}{\sqrt{1000}}\right] = [p - 0.03,~~ p + 0.03]
$$
As we increase $N$ the costs of polling go up linearly but the gains go down exponentially. That is the reason why pollsters usually cap $N$ at 1000 as that gives them a reasonable error of margin under the worst possible assumption of $\pi = 50\%$. | How do you decide the sample size when polling a large population? | Suppose that you want to know what percentage of people would vote for a particular candidate (say, $\pi$, note that by definition $\pi$ is between 0 and 100). You sample $N$ voters at random to find | How do you decide the sample size when polling a large population?
Suppose that you want to know what percentage of people would vote for a particular candidate (say, $\pi$, note that by definition $\pi$ is between 0 and 100). You sample $N$ voters at random to find out how they would vote and your survey of these $N$ voters tells you that the percentage is $p$. So, you would like to establish a confidence interval for the true percentage.
If you assume that $p$ is normally distributed (an assumption that may or may not be justified depending on how 'big' $N$ is) then your confidence interval for $\pi$ would be of the following form:
$$
CI = [ p - k * sd(p),~~ p + k * sd(p)]
$$
where $k$ is a constant that depends on the extent of confidence you want (i.e., 95% or 99% etc).
From a polling perspective, you want the width of your confidence interval to be 'low'. Usually, pollsters work with the margin of error which is basically one-half of the CI. In other words, $\text{MoE} = k * sd(p)$.
Here is how we would go about calculating $sd(p)$: By definition, $p = \sum X_i / N$ where, $X_i = 1$ if voter $i$ votes for candidate and $0$ otherwise.
Since, we sampled the voters at random, we could assume that $X_i$ is a i.i.d Bernoulli random variable. Therefore,
$$
Var(P) = V\left( \sum\frac{X_i}{N}\right) = \frac{\sum V(X_i)}{N^2} = \frac{N \pi (1-\pi)}{N^2} = \frac{\pi (1-\pi)}{N}.
$$
Thus,
$$
sd(p) = \sqrt{\frac{\pi * (1-\pi)}{N}}
$$
Now to estimate margin of error we need to know $\pi$ which we do not know obviously. But, an inspection of the numerator suggests that the 'worst' estimate for $sd(p)$ in the sense that we get the 'largest' standard deviation is when $\pi = 0.5$. Therefore, the worst possible standard deviation is:
$$
sd(p) = \sqrt{0.5 * 0.5 / N } = 0.5 / \sqrt{N}
$$
So, you see that the margin of error falls off exponentially with $N$ and thus you really do not need very big samples to reduce your margin of error, or in other words $N$ need not be very large for you to obtain a narrow confidence interval.
For example, for a 95 % confidence interval (i.e., $k= 1.96$) and $N = 1000$, the confidence interval is:
$$
\left[p - 1.96 \frac{0.5}{\sqrt{1000}},~~ p + 1.96 \frac{0.5}{\sqrt{1000}}\right] = [p - 0.03,~~ p + 0.03]
$$
As we increase $N$ the costs of polling go up linearly but the gains go down exponentially. That is the reason why pollsters usually cap $N$ at 1000 as that gives them a reasonable error of margin under the worst possible assumption of $\pi = 50\%$. | How do you decide the sample size when polling a large population?
Suppose that you want to know what percentage of people would vote for a particular candidate (say, $\pi$, note that by definition $\pi$ is between 0 and 100). You sample $N$ voters at random to find |
17,274 | How do you decide the sample size when polling a large population? | As a rough generalization, any time you sample a fraction of the people in a population, you're going to get a different answer than if you sample the same number again (but possibly different people).
So if you want to find out how many people in Australia are >= 30 years old, and if the true fraction (God told us) just happened to be precisely 0.4, and if we ask 100 people, the average number we can expect to say they are >= 30 is 100 x 0.4 = 40, and the standard deviation of that number is +/- sqrt(100 * 0.4 * 0.6) = sqrt(24) ~ 4.9 or 4.9% (Binomial distribution).
Since that square root is in there, when the sample size goes up by 100 times, the standard deviation goes down by 10 times. So in general, to reduce the uncertainty of a measurement like this by a factor of 10, you need to sample 100 times as many people. So if you ask 100 x 100 = 10000 people, the standard deviation would go up to 49 or, as a percent, down to 0.49%. | How do you decide the sample size when polling a large population? | As a rough generalization, any time you sample a fraction of the people in a population, you're going to get a different answer than if you sample the same number again (but possibly different people) | How do you decide the sample size when polling a large population?
As a rough generalization, any time you sample a fraction of the people in a population, you're going to get a different answer than if you sample the same number again (but possibly different people).
So if you want to find out how many people in Australia are >= 30 years old, and if the true fraction (God told us) just happened to be precisely 0.4, and if we ask 100 people, the average number we can expect to say they are >= 30 is 100 x 0.4 = 40, and the standard deviation of that number is +/- sqrt(100 * 0.4 * 0.6) = sqrt(24) ~ 4.9 or 4.9% (Binomial distribution).
Since that square root is in there, when the sample size goes up by 100 times, the standard deviation goes down by 10 times. So in general, to reduce the uncertainty of a measurement like this by a factor of 10, you need to sample 100 times as many people. So if you ask 100 x 100 = 10000 people, the standard deviation would go up to 49 or, as a percent, down to 0.49%. | How do you decide the sample size when polling a large population?
As a rough generalization, any time you sample a fraction of the people in a population, you're going to get a different answer than if you sample the same number again (but possibly different people) |
17,275 | State space representation of ARMA(p,q) from Hamilton | Hamilton shows that this is a correct representation in the book, but the approach may seem a bit counterintuitive. Let me therefore first give a high-level answer that motivates his modeling choice and then elaborate a bit on his derivation.
Motivation:
As should become clear from reading Chapter 13, there are many ways to write a dynamic model in state space form. We should therefore ask why Hamilton chose this particular representation. The reason is that that this representation keeps the dimensionality of the state vector low. Intuitively, you would think (or at least I would) that the state vector for an ARMA($p$,$q$) needs to be at least of dimension $p+q$. After all, just from observing say $y_{t-1}$, we cannot infer the value of $\epsilon_{t-1}$. Yet he shows that we can define the state-space representation in a clever way that leaves the state vector of dimension of at most $r = \max\{p, q + 1 \}$. Keeping the state dimensionality low may be important for the computational implementation, I guess. It turns out that his state-space representation also offers a nice interpretation of an ARMA process: the unobserved state is an AR($p$), while the MA($q$) part arises due to measurement error.
Derivation:
Now for the derivation. First note that, using lag operator notation, the ARMA(p,q) is defined as:
$$
(1-\phi_1L - \ldots - \phi_rL^r)(y_t - \mu) =(1 + \theta_1L + \ldots + \theta_{r-1}L^{r-1})\epsilon_t
$$
where we let $\phi_j = 0$ for $j>p$, and $\theta_j = 0$ for $j>q$ and we omit $\theta_r$ since $r$ is at least $q+1$. So all we need to show is that his state and observation equations imply the equation above. Let the state vector be
$$
\mathbf{\xi}_t = \{\xi_{1,t}, \xi_{2,t},\ldots,\xi_{r,t}\}^\top
$$
Now look at the state equation. You can check that equations $2$ to $r$ simply move the entries $\xi_{i,t}$ to $\xi_{i-1,t+1}$ one period ahead and discard $\xi_{r,t}$ in the state vector at $t+1$. The first equation, defining $\xi_{i,t+1}$ is therefore the relevant one. Writing it out:
$$
\xi_{1,t+1} = \phi_1 \xi_{1,t} + \phi_2 \xi_{2,t} + \ldots + \phi_r \xi_{r,t} + \epsilon_{t+1}
$$
Since the second element of $\mathbf{\xi_{t}}$ is the first element of $\mathbf{\xi_{t-1}}$ and the third element of the $\mathbf{\xi_{t}}$ is the first element of $\mathbf{\xi_{t-2}}$ and so on, we can rewrite this, using lag operator notation and moving the lag polynomial to the left hand side (equation 13.1.24 in H.):
$$
(1-\phi_1L - \ldots - \phi_rL^r)\xi_{1,t+1} = \epsilon_{t+1}
$$
So the hidden state follows an autoregressive process. Similarly, the observation equation is
$$
y_t = \mu + \xi_{1,t} + \theta_1\xi_{2,t} + \ldots + \theta_{r-1}\xi_{r-1,t}
$$
or
$$
y_t - \mu = (1 + \theta_1L + \ldots + \theta_{r-1}L^{r-1})\xi_{1,t}
$$
This does not look much like an ARMA so far, but now comes the nice part: multiply the last equation by $(1-\phi_1L - \ldots - \phi_rL^r)$:
$$
(1-\phi_1L - \ldots - \phi_rL^r)(y_t - \mu) = (1 + \theta_1L + \ldots + \theta_{r-1}L^{r-1})(1-\phi_1L - \ldots - \phi_rL^r)y_t
$$
But from the state equation (lagged by one period), we have $(1-\phi_1L - \ldots - \phi_rL^r)\xi_{1,t} = \epsilon_{t}$! So the above is equivalent to
$$
(1-\phi_1L - \ldots - \phi_rL^r)(y_t - \mu) = (1 + \theta_1L + \ldots + \theta_{r-1}L^{r-1})\epsilon_{t}
$$
which is exactly what we needed to show! So the state-observation system correctly represents the ARMA(p,q). I was really just paraphrasing Hamilton, but I hope that this is useful anyway. | State space representation of ARMA(p,q) from Hamilton | Hamilton shows that this is a correct representation in the book, but the approach may seem a bit counterintuitive. Let me therefore first give a high-level answer that motivates his modeling choice a | State space representation of ARMA(p,q) from Hamilton
Hamilton shows that this is a correct representation in the book, but the approach may seem a bit counterintuitive. Let me therefore first give a high-level answer that motivates his modeling choice and then elaborate a bit on his derivation.
Motivation:
As should become clear from reading Chapter 13, there are many ways to write a dynamic model in state space form. We should therefore ask why Hamilton chose this particular representation. The reason is that that this representation keeps the dimensionality of the state vector low. Intuitively, you would think (or at least I would) that the state vector for an ARMA($p$,$q$) needs to be at least of dimension $p+q$. After all, just from observing say $y_{t-1}$, we cannot infer the value of $\epsilon_{t-1}$. Yet he shows that we can define the state-space representation in a clever way that leaves the state vector of dimension of at most $r = \max\{p, q + 1 \}$. Keeping the state dimensionality low may be important for the computational implementation, I guess. It turns out that his state-space representation also offers a nice interpretation of an ARMA process: the unobserved state is an AR($p$), while the MA($q$) part arises due to measurement error.
Derivation:
Now for the derivation. First note that, using lag operator notation, the ARMA(p,q) is defined as:
$$
(1-\phi_1L - \ldots - \phi_rL^r)(y_t - \mu) =(1 + \theta_1L + \ldots + \theta_{r-1}L^{r-1})\epsilon_t
$$
where we let $\phi_j = 0$ for $j>p$, and $\theta_j = 0$ for $j>q$ and we omit $\theta_r$ since $r$ is at least $q+1$. So all we need to show is that his state and observation equations imply the equation above. Let the state vector be
$$
\mathbf{\xi}_t = \{\xi_{1,t}, \xi_{2,t},\ldots,\xi_{r,t}\}^\top
$$
Now look at the state equation. You can check that equations $2$ to $r$ simply move the entries $\xi_{i,t}$ to $\xi_{i-1,t+1}$ one period ahead and discard $\xi_{r,t}$ in the state vector at $t+1$. The first equation, defining $\xi_{i,t+1}$ is therefore the relevant one. Writing it out:
$$
\xi_{1,t+1} = \phi_1 \xi_{1,t} + \phi_2 \xi_{2,t} + \ldots + \phi_r \xi_{r,t} + \epsilon_{t+1}
$$
Since the second element of $\mathbf{\xi_{t}}$ is the first element of $\mathbf{\xi_{t-1}}$ and the third element of the $\mathbf{\xi_{t}}$ is the first element of $\mathbf{\xi_{t-2}}$ and so on, we can rewrite this, using lag operator notation and moving the lag polynomial to the left hand side (equation 13.1.24 in H.):
$$
(1-\phi_1L - \ldots - \phi_rL^r)\xi_{1,t+1} = \epsilon_{t+1}
$$
So the hidden state follows an autoregressive process. Similarly, the observation equation is
$$
y_t = \mu + \xi_{1,t} + \theta_1\xi_{2,t} + \ldots + \theta_{r-1}\xi_{r-1,t}
$$
or
$$
y_t - \mu = (1 + \theta_1L + \ldots + \theta_{r-1}L^{r-1})\xi_{1,t}
$$
This does not look much like an ARMA so far, but now comes the nice part: multiply the last equation by $(1-\phi_1L - \ldots - \phi_rL^r)$:
$$
(1-\phi_1L - \ldots - \phi_rL^r)(y_t - \mu) = (1 + \theta_1L + \ldots + \theta_{r-1}L^{r-1})(1-\phi_1L - \ldots - \phi_rL^r)y_t
$$
But from the state equation (lagged by one period), we have $(1-\phi_1L - \ldots - \phi_rL^r)\xi_{1,t} = \epsilon_{t}$! So the above is equivalent to
$$
(1-\phi_1L - \ldots - \phi_rL^r)(y_t - \mu) = (1 + \theta_1L + \ldots + \theta_{r-1}L^{r-1})\epsilon_{t}
$$
which is exactly what we needed to show! So the state-observation system correctly represents the ARMA(p,q). I was really just paraphrasing Hamilton, but I hope that this is useful anyway. | State space representation of ARMA(p,q) from Hamilton
Hamilton shows that this is a correct representation in the book, but the approach may seem a bit counterintuitive. Let me therefore first give a high-level answer that motivates his modeling choice a |
17,276 | State space representation of ARMA(p,q) from Hamilton | This is the same as above, but I thought I would provide a shorter, more concise answer. Again, this is Hamilton's representation for a causal ARMA($p$,$q$) process, where $r=\max(p,q+1)$. This $r$ number will be the dimension of the state vector $ (\xi_t, \xi_{t-1},\ldots, \xi_{t-r+1})'$, and it is needed to make the number of rows of the state match up with the number of columns of the observation matrix. That means we also have to set coefficients to zero whenever the index is too big.
Observation Equation
\begin{align*}
&\phi(B)(y_t - \mu) = \theta(B)\epsilon_t \\
\iff &(y_t - \mu) = \phi^{-1}(B)\theta(B)\epsilon_t \tag{causality}\\
\iff &y_t = \mu + \phi^{-1}(B)\theta(B)\epsilon_t \\
\iff &y_t = \mu + \theta(B)\phi^{-1}(B)\epsilon_t \\
\iff &y_t = \mu + \theta(B)\xi_t \tag{letting $\xi_t = \phi^{-1}(B)\epsilon_t$}\\
\iff &y_t = \mu +
\left[\begin{array}{ccccc}1 & \theta_1 & \theta_2 & \ldots & \theta_{r-1} \end{array}\right]
\underbrace{\left[\begin{array}{c}
\xi_t \\
\xi_{t-1} \\
\vdots \\
\xi_{t-r+1}
\end{array}\right]}_{\text{the state vector}} + 0\tag{this is where we need $r$}.
\end{align*}
State Equation
\begin{align*}
&\xi_t = \phi^{-1}(B)\epsilon_t \\
\iff &\phi(B)\xi_t = \epsilon_t \\
\iff &(1 - \phi_1 B - \cdots - \phi_rB^r) \xi_t = \epsilon_t \\
\iff &\xi_t = \phi_1 \xi_{t-1} + \cdots + \phi_r \xi_{t-r} + \epsilon_t \\
\iff &
\left[\begin{array}{c}
\xi_t \\
\xi_{t-1} \\
\xi_{t-2} \\
\vdots \\
\xi_{t-r+1}
\end{array}\right] =
\left[ \begin{array}{ccccc}
\phi_1 & \phi_2 & \phi_3 & \cdots & \phi_r \\
1 & 0 & 0 & \cdots & 0 \\
0 & 1 & 0 & \cdots & 0 \\
\vdots & \vdots & \ddots & \cdots & 0 \\
0 & 0 &\cdots & 1 & 0
\end{array}\right]
\left[ \begin{array}{c}
\xi_{t-1} \\
\xi_{t-2} \\
\vdots \\
\xi_{t-r}
\end{array}\right]
+
\left[ \begin{array}{c}
\epsilon_t \\
0 \\
\vdots \\
0
\end{array}\right].
\end{align*} | State space representation of ARMA(p,q) from Hamilton | This is the same as above, but I thought I would provide a shorter, more concise answer. Again, this is Hamilton's representation for a causal ARMA($p$,$q$) process, where $r=\max(p,q+1)$. This $r$ nu | State space representation of ARMA(p,q) from Hamilton
This is the same as above, but I thought I would provide a shorter, more concise answer. Again, this is Hamilton's representation for a causal ARMA($p$,$q$) process, where $r=\max(p,q+1)$. This $r$ number will be the dimension of the state vector $ (\xi_t, \xi_{t-1},\ldots, \xi_{t-r+1})'$, and it is needed to make the number of rows of the state match up with the number of columns of the observation matrix. That means we also have to set coefficients to zero whenever the index is too big.
Observation Equation
\begin{align*}
&\phi(B)(y_t - \mu) = \theta(B)\epsilon_t \\
\iff &(y_t - \mu) = \phi^{-1}(B)\theta(B)\epsilon_t \tag{causality}\\
\iff &y_t = \mu + \phi^{-1}(B)\theta(B)\epsilon_t \\
\iff &y_t = \mu + \theta(B)\phi^{-1}(B)\epsilon_t \\
\iff &y_t = \mu + \theta(B)\xi_t \tag{letting $\xi_t = \phi^{-1}(B)\epsilon_t$}\\
\iff &y_t = \mu +
\left[\begin{array}{ccccc}1 & \theta_1 & \theta_2 & \ldots & \theta_{r-1} \end{array}\right]
\underbrace{\left[\begin{array}{c}
\xi_t \\
\xi_{t-1} \\
\vdots \\
\xi_{t-r+1}
\end{array}\right]}_{\text{the state vector}} + 0\tag{this is where we need $r$}.
\end{align*}
State Equation
\begin{align*}
&\xi_t = \phi^{-1}(B)\epsilon_t \\
\iff &\phi(B)\xi_t = \epsilon_t \\
\iff &(1 - \phi_1 B - \cdots - \phi_rB^r) \xi_t = \epsilon_t \\
\iff &\xi_t = \phi_1 \xi_{t-1} + \cdots + \phi_r \xi_{t-r} + \epsilon_t \\
\iff &
\left[\begin{array}{c}
\xi_t \\
\xi_{t-1} \\
\xi_{t-2} \\
\vdots \\
\xi_{t-r+1}
\end{array}\right] =
\left[ \begin{array}{ccccc}
\phi_1 & \phi_2 & \phi_3 & \cdots & \phi_r \\
1 & 0 & 0 & \cdots & 0 \\
0 & 1 & 0 & \cdots & 0 \\
\vdots & \vdots & \ddots & \cdots & 0 \\
0 & 0 &\cdots & 1 & 0
\end{array}\right]
\left[ \begin{array}{c}
\xi_{t-1} \\
\xi_{t-2} \\
\vdots \\
\xi_{t-r}
\end{array}\right]
+
\left[ \begin{array}{c}
\epsilon_t \\
0 \\
\vdots \\
0
\end{array}\right].
\end{align*} | State space representation of ARMA(p,q) from Hamilton
This is the same as above, but I thought I would provide a shorter, more concise answer. Again, this is Hamilton's representation for a causal ARMA($p$,$q$) process, where $r=\max(p,q+1)$. This $r$ nu |
17,277 | Variance in estimating p for a binomial distribution | If $X$ is $\text{Binomial}(n, p)$ then MLE of $p$ is $\hat{p} = X/n$.
A binomial variable can be thought of as the sum of $n$ Bernoulli random variables. $X = \sum_{i=1}^n Y_i$ where $Y_i\sim\text{Bernoulli}(p)$.
so we can calculate the variance of the MLE $\hat{p}$ as
$$\begin{align*}
\text{Var}[\hat{p}] &= \text{Var}\left[\dfrac{1}{n}\sum_{i=1}^n Y_i\right]\\
&= \dfrac{1}{n^2}\sum_{i=1}^n Var[Y_i]\\
&= \dfrac{1}{n^2}\sum_{i=1}^n p(1-p)\\
&= \dfrac{p(1-p)}{n}
\end{align*}$$
So you can see that the variance of the MLE gets smaller for large $n$, and also it is smaller for $p$ close to 0 or 1. In terms of $p$ it is maximized when $p=0.5$.
For some confidence intervals you can check out Binomial Confidence Intervals | Variance in estimating p for a binomial distribution | If $X$ is $\text{Binomial}(n, p)$ then MLE of $p$ is $\hat{p} = X/n$.
A binomial variable can be thought of as the sum of $n$ Bernoulli random variables. $X = \sum_{i=1}^n Y_i$ where $Y_i\sim\text{Be | Variance in estimating p for a binomial distribution
If $X$ is $\text{Binomial}(n, p)$ then MLE of $p$ is $\hat{p} = X/n$.
A binomial variable can be thought of as the sum of $n$ Bernoulli random variables. $X = \sum_{i=1}^n Y_i$ where $Y_i\sim\text{Bernoulli}(p)$.
so we can calculate the variance of the MLE $\hat{p}$ as
$$\begin{align*}
\text{Var}[\hat{p}] &= \text{Var}\left[\dfrac{1}{n}\sum_{i=1}^n Y_i\right]\\
&= \dfrac{1}{n^2}\sum_{i=1}^n Var[Y_i]\\
&= \dfrac{1}{n^2}\sum_{i=1}^n p(1-p)\\
&= \dfrac{p(1-p)}{n}
\end{align*}$$
So you can see that the variance of the MLE gets smaller for large $n$, and also it is smaller for $p$ close to 0 or 1. In terms of $p$ it is maximized when $p=0.5$.
For some confidence intervals you can check out Binomial Confidence Intervals | Variance in estimating p for a binomial distribution
If $X$ is $\text{Binomial}(n, p)$ then MLE of $p$ is $\hat{p} = X/n$.
A binomial variable can be thought of as the sum of $n$ Bernoulli random variables. $X = \sum_{i=1}^n Y_i$ where $Y_i\sim\text{Be |
17,278 | Bootstrapping confidence interval from a regression prediction | Bootstrapping refers to resample your data with replacement. That is, instead of fitting your model to the original X and y, you fit your model to resampled versions of X and y for multiple times.
Thus, you get n slightly different models which you can use to create a confidence interval. Here is a visual example of such an interval.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# Create toy data
x = np.linspace(0, 10, 20)
y = x + (np.random.rand(len(x)) * 10)
# Extend x data to contain another row vector of 1s
X = np.vstack([x, np.ones(len(x))]).T
plt.figure(figsize=(12,8))
for i in range(0, 500):
sample_index = np.random.choice(range(0, len(y)), len(y))
X_samples = X[sample_index]
y_samples = y[sample_index]
lr = LinearRegression()
lr.fit(X_samples, y_samples)
plt.plot(x, lr.predict(X), color='grey', alpha=0.2, zorder=1)
plt.scatter(x,y, marker='o', color='orange', zorder=4)
lr = LinearRegression()
lr.fit(X, y)
plt.plot(x, lr.predict(X), color='red', zorder=5) | Bootstrapping confidence interval from a regression prediction | Bootstrapping refers to resample your data with replacement. That is, instead of fitting your model to the original X and y, you fit your model to resampled versions of X and y for multiple times.
Thu | Bootstrapping confidence interval from a regression prediction
Bootstrapping refers to resample your data with replacement. That is, instead of fitting your model to the original X and y, you fit your model to resampled versions of X and y for multiple times.
Thus, you get n slightly different models which you can use to create a confidence interval. Here is a visual example of such an interval.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# Create toy data
x = np.linspace(0, 10, 20)
y = x + (np.random.rand(len(x)) * 10)
# Extend x data to contain another row vector of 1s
X = np.vstack([x, np.ones(len(x))]).T
plt.figure(figsize=(12,8))
for i in range(0, 500):
sample_index = np.random.choice(range(0, len(y)), len(y))
X_samples = X[sample_index]
y_samples = y[sample_index]
lr = LinearRegression()
lr.fit(X_samples, y_samples)
plt.plot(x, lr.predict(X), color='grey', alpha=0.2, zorder=1)
plt.scatter(x,y, marker='o', color='orange', zorder=4)
lr = LinearRegression()
lr.fit(X, y)
plt.plot(x, lr.predict(X), color='red', zorder=5) | Bootstrapping confidence interval from a regression prediction
Bootstrapping refers to resample your data with replacement. That is, instead of fitting your model to the original X and y, you fit your model to resampled versions of X and y for multiple times.
Thu |
17,279 | Bootstrapping confidence interval from a regression prediction | If you want to use scikit's API for the bootstrap part of the code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import BaggingRegressor
# Create toy data
x = np.linspace(0, 10, 20)
y = x + (np.random.rand(len(x)) * 10)
# Extend x data to contain another row vector of 1s
X = np.vstack([x, np.ones(len(x))]).T
n_estimators = 50
model = BaggingRegressor(LinearRegression(),
n_estimators=n_estimators,
bootstrap=True)
model.fit(X, y)
plt.figure(figsize=(12,8))
# Accessing each base_estimator (already fitted)
for m in model.estimators_:
plt.plot(x, m.predict(X), color='grey', alpha=0.2, zorder=1)
plt.scatter(x,y, marker='o', color='orange', zorder=4)
# "Bagging model" prediction
plt.plot(x, model.predict(X), color='red', zorder=5) | Bootstrapping confidence interval from a regression prediction | If you want to use scikit's API for the bootstrap part of the code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import Ba | Bootstrapping confidence interval from a regression prediction
If you want to use scikit's API for the bootstrap part of the code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import BaggingRegressor
# Create toy data
x = np.linspace(0, 10, 20)
y = x + (np.random.rand(len(x)) * 10)
# Extend x data to contain another row vector of 1s
X = np.vstack([x, np.ones(len(x))]).T
n_estimators = 50
model = BaggingRegressor(LinearRegression(),
n_estimators=n_estimators,
bootstrap=True)
model.fit(X, y)
plt.figure(figsize=(12,8))
# Accessing each base_estimator (already fitted)
for m in model.estimators_:
plt.plot(x, m.predict(X), color='grey', alpha=0.2, zorder=1)
plt.scatter(x,y, marker='o', color='orange', zorder=4)
# "Bagging model" prediction
plt.plot(x, model.predict(X), color='red', zorder=5) | Bootstrapping confidence interval from a regression prediction
If you want to use scikit's API for the bootstrap part of the code:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import Ba |
17,280 | What is meant by categorical distribution? | The categorical distribution is the generalization of the Bernoulli distribution to a fixed number $2 \le k$ of outcomes.
Equivalently, it is the special case of the multinomial distribution where the number of "choices" $n$ is fixed at one.
Therefore, it has pdf:
$$\prod_{i=1}^k p_i^{x_i}
\qquad\text{(where
$0\le p_i$
and
$\sum_i p_i = 1$)}$$
over the support
$$x_i \in \{0,1\}$$
where
$$n \triangleq \sum_{i=1}^k x_i = 1.$$
In summary, Bernoulli has $k=2, n=1$, binomial has $k=2, n\ge 1$, multinomial has $k\ge2, n\ge1$, and categorical has $k\ge2, n=1$. | What is meant by categorical distribution? | The categorical distribution is the generalization of the Bernoulli distribution to a fixed number $2 \le k$ of outcomes.
Equivalently, it is the special case of the multinomial distribution where the | What is meant by categorical distribution?
The categorical distribution is the generalization of the Bernoulli distribution to a fixed number $2 \le k$ of outcomes.
Equivalently, it is the special case of the multinomial distribution where the number of "choices" $n$ is fixed at one.
Therefore, it has pdf:
$$\prod_{i=1}^k p_i^{x_i}
\qquad\text{(where
$0\le p_i$
and
$\sum_i p_i = 1$)}$$
over the support
$$x_i \in \{0,1\}$$
where
$$n \triangleq \sum_{i=1}^k x_i = 1.$$
In summary, Bernoulli has $k=2, n=1$, binomial has $k=2, n\ge 1$, multinomial has $k\ge2, n\ge1$, and categorical has $k\ge2, n=1$. | What is meant by categorical distribution?
The categorical distribution is the generalization of the Bernoulli distribution to a fixed number $2 \le k$ of outcomes.
Equivalently, it is the special case of the multinomial distribution where the |
17,281 | What is meant by categorical distribution? | Categorical variables have finite sets of discrete values. Examples include sex (male/female), country, planet, etc. Contrast this with continuous variables, which can take an infinite number of different values. Examples include weight, longitude, distance, etc.
Note that similar information can sometimes be expressed in categorical and continuous ways; e.g., planet = earth could be expressed as distance to sun = 1 astronomical unit ≈ 150 million kilometers. However, there's not really any way to express 200 million kilometers from the sun in terms of planets, because there's no planet there (Mars is 228 million km from the sun). Same for 201 million km, 202, etc. All you could say about these distances in terms of planets is planet = none; you couldn't say planet = 4/3×earth or .88×Mars, because there's no meaningful way to multiply a planet or any other categorical variable. In terms of planets, these distances would be indistinguishable, but of course they make sense as distinct distances from the sun when expressed as such – as a continuous variable.
One can also express continuous variables with arbitrary precision (e.g., one astronomical unit is 149,597,871 km, not exactly 150 million km). Conversely, there is no way to express planet = earth more precisely; Earth is exactly earth, no more nor less. Furthermore, it would not make sense to say any other planet is "more" or "less" than Earth if planet is a nominal variable. It could be coded as an ordered (ordinal) variable though – planets are ordered in terms of distance to the sun, volume, number of moons, etc. These numbers are all continuous in their own terms (or at least counts, which are discrete but not categorical), but not in terms of planets. E.g., if planets are ordered by distance from the sun or by number of moons, mars > earth > venus. If planets are ordered by volume, earth > venus > mars. It is not necessary to order categorical variables, and maybe some cannot be ordered, but adding order does not make them any less categorical.
As Wikipedia says, categorical distributions are generalizations of the Bernoulli distribution to more than two possible values (the Bernoulli distribution is strictly binary). The Bernoulli distribution is also a special case of the binomial distribution, but I wouldn't call the binomial distribution categorical (it's discrete, but a count variable, so distances between values are defined). Multinomial distributions may be conflated with categorical distributions, but Wikipedia cautions against this. | What is meant by categorical distribution? | Categorical variables have finite sets of discrete values. Examples include sex (male/female), country, planet, etc. Contrast this with continuous variables, which can take an infinite number of diffe | What is meant by categorical distribution?
Categorical variables have finite sets of discrete values. Examples include sex (male/female), country, planet, etc. Contrast this with continuous variables, which can take an infinite number of different values. Examples include weight, longitude, distance, etc.
Note that similar information can sometimes be expressed in categorical and continuous ways; e.g., planet = earth could be expressed as distance to sun = 1 astronomical unit ≈ 150 million kilometers. However, there's not really any way to express 200 million kilometers from the sun in terms of planets, because there's no planet there (Mars is 228 million km from the sun). Same for 201 million km, 202, etc. All you could say about these distances in terms of planets is planet = none; you couldn't say planet = 4/3×earth or .88×Mars, because there's no meaningful way to multiply a planet or any other categorical variable. In terms of planets, these distances would be indistinguishable, but of course they make sense as distinct distances from the sun when expressed as such – as a continuous variable.
One can also express continuous variables with arbitrary precision (e.g., one astronomical unit is 149,597,871 km, not exactly 150 million km). Conversely, there is no way to express planet = earth more precisely; Earth is exactly earth, no more nor less. Furthermore, it would not make sense to say any other planet is "more" or "less" than Earth if planet is a nominal variable. It could be coded as an ordered (ordinal) variable though – planets are ordered in terms of distance to the sun, volume, number of moons, etc. These numbers are all continuous in their own terms (or at least counts, which are discrete but not categorical), but not in terms of planets. E.g., if planets are ordered by distance from the sun or by number of moons, mars > earth > venus. If planets are ordered by volume, earth > venus > mars. It is not necessary to order categorical variables, and maybe some cannot be ordered, but adding order does not make them any less categorical.
As Wikipedia says, categorical distributions are generalizations of the Bernoulli distribution to more than two possible values (the Bernoulli distribution is strictly binary). The Bernoulli distribution is also a special case of the binomial distribution, but I wouldn't call the binomial distribution categorical (it's discrete, but a count variable, so distances between values are defined). Multinomial distributions may be conflated with categorical distributions, but Wikipedia cautions against this. | What is meant by categorical distribution?
Categorical variables have finite sets of discrete values. Examples include sex (male/female), country, planet, etc. Contrast this with continuous variables, which can take an infinite number of diffe |
17,282 | What is the maximum entropy probability density function for a positive continuous variable of given mean and standard deviation? | One may simply use the theorem of Boltzmann's that is in the very Wikipedia article you point to.
Note that specifying the mean and variance is equivalent to specifying the first two raw moments - each determines the other (it's not actually necessary to invoke this, since we may apply the theorem directly to the mean and variance, it's just a little simpler this way).
The theorem then establishes that the density must be of the form:
$$f(x)=c \exp\left(\lambda_1 x + \lambda_2 x^2 \right)\quad \mbox{ for all } x \geq 0$$
Integrability over the positive real line will restrict $\lambda_2$ to be $\leq 0$, and I think places some restrictions on the relationships between the $\lambda$s (which will presumably be satisfied automatically when starting from the specified mean and variance rather than the raw moments).
To my surprise (since I wouldn't have expected it when I started this answer), this appears to leave us with a truncated normal distribution.
As it happens, I don't think I've used this theorem before, so criticisms or helpful suggestions on anything I haven't considered or have left out would be welcome. | What is the maximum entropy probability density function for a positive continuous variable of given | One may simply use the theorem of Boltzmann's that is in the very Wikipedia article you point to.
Note that specifying the mean and variance is equivalent to specifying the first two raw moments - eac | What is the maximum entropy probability density function for a positive continuous variable of given mean and standard deviation?
One may simply use the theorem of Boltzmann's that is in the very Wikipedia article you point to.
Note that specifying the mean and variance is equivalent to specifying the first two raw moments - each determines the other (it's not actually necessary to invoke this, since we may apply the theorem directly to the mean and variance, it's just a little simpler this way).
The theorem then establishes that the density must be of the form:
$$f(x)=c \exp\left(\lambda_1 x + \lambda_2 x^2 \right)\quad \mbox{ for all } x \geq 0$$
Integrability over the positive real line will restrict $\lambda_2$ to be $\leq 0$, and I think places some restrictions on the relationships between the $\lambda$s (which will presumably be satisfied automatically when starting from the specified mean and variance rather than the raw moments).
To my surprise (since I wouldn't have expected it when I started this answer), this appears to leave us with a truncated normal distribution.
As it happens, I don't think I've used this theorem before, so criticisms or helpful suggestions on anything I haven't considered or have left out would be welcome. | What is the maximum entropy probability density function for a positive continuous variable of given
One may simply use the theorem of Boltzmann's that is in the very Wikipedia article you point to.
Note that specifying the mean and variance is equivalent to specifying the first two raw moments - eac |
17,283 | What is the maximum entropy probability density function for a positive continuous variable of given mean and standard deviation? | I want to make @Glen_b's answer more explicit, here is an extra answer just because it wouldn't fit as a comment.
The formalism etc. is well explained in Chapter 11 and 12 of Jaynes' book.
Taking the uniform distribution as the base measure, the general solution, as @Glen_b already said, is a Gaussian
$$
f(x) \propto \mathcal{N}(x | -1/2 \lambda_1/\lambda_2, -1/(2\lambda_2))
$$
For the unbounded variable, you can explicitly solve for the Lagrange multipliers $\lambda_1$ and $\lambda_2$ in terms of the constraint values ($a_1, a_2$ in the Wikipedia article). With $a_1=\mu, a_2=\mu^2 + \sigma^2$, you then get $\lambda_1=\mu/\sigma^2, \lambda_2=-0.5 \sigma^2$, so the standard Gaussian $\mathcal{N}(x|\mu, \sigma^2)$.
For the bounded variable $x>x_{min}$, I (and mathematica) cannot solve for $\lambda_{1,2}$ explicitly anymore because of the error function term that appears when computing the partition function ($1/c$ in wikipedia). This means that that the $\mu$ and $\sigma^2$ parameters of the truncated Gaussian are not the mean and variance of the continuous variable you started with. It can even happen that for $x_{min}=0$, the mode of the Gaussian is negative! Of course the numbers all agree again when you take $x_{min} \to -\infty$.
If you have concrete values for $a_1, a_2$, you can still solve for $\lambda_{1,2}$ numerically and plug in the solutions into the general equation and you are done! The values of $\lambda_{1,2}$ from the unbounded case may be a good starting point for the numerical solver.
This question is a duplicate of https://math.stackexchange.com/questions/598608/what-is-the-maximum-entropy-distribution-for-a-continuous-random-variable-on-0 | What is the maximum entropy probability density function for a positive continuous variable of given | I want to make @Glen_b's answer more explicit, here is an extra answer just because it wouldn't fit as a comment.
The formalism etc. is well explained in Chapter 11 and 12 of Jaynes' book.
Taking the | What is the maximum entropy probability density function for a positive continuous variable of given mean and standard deviation?
I want to make @Glen_b's answer more explicit, here is an extra answer just because it wouldn't fit as a comment.
The formalism etc. is well explained in Chapter 11 and 12 of Jaynes' book.
Taking the uniform distribution as the base measure, the general solution, as @Glen_b already said, is a Gaussian
$$
f(x) \propto \mathcal{N}(x | -1/2 \lambda_1/\lambda_2, -1/(2\lambda_2))
$$
For the unbounded variable, you can explicitly solve for the Lagrange multipliers $\lambda_1$ and $\lambda_2$ in terms of the constraint values ($a_1, a_2$ in the Wikipedia article). With $a_1=\mu, a_2=\mu^2 + \sigma^2$, you then get $\lambda_1=\mu/\sigma^2, \lambda_2=-0.5 \sigma^2$, so the standard Gaussian $\mathcal{N}(x|\mu, \sigma^2)$.
For the bounded variable $x>x_{min}$, I (and mathematica) cannot solve for $\lambda_{1,2}$ explicitly anymore because of the error function term that appears when computing the partition function ($1/c$ in wikipedia). This means that that the $\mu$ and $\sigma^2$ parameters of the truncated Gaussian are not the mean and variance of the continuous variable you started with. It can even happen that for $x_{min}=0$, the mode of the Gaussian is negative! Of course the numbers all agree again when you take $x_{min} \to -\infty$.
If you have concrete values for $a_1, a_2$, you can still solve for $\lambda_{1,2}$ numerically and plug in the solutions into the general equation and you are done! The values of $\lambda_{1,2}$ from the unbounded case may be a good starting point for the numerical solver.
This question is a duplicate of https://math.stackexchange.com/questions/598608/what-is-the-maximum-entropy-distribution-for-a-continuous-random-variable-on-0 | What is the maximum entropy probability density function for a positive continuous variable of given
I want to make @Glen_b's answer more explicit, here is an extra answer just because it wouldn't fit as a comment.
The formalism etc. is well explained in Chapter 11 and 12 of Jaynes' book.
Taking the |
17,284 | How to draw random samples from a non-parametric estimated distribution? | A kernel density estimate is a mixture distribution; for every observation, there's a kernel. If the kernel is a scaled density, this leads to a simple algorithm for sampling from the kernel density estimate:
repeat nsim times:
sample (with replacement) a random observation from the data
sample from the kernel, and add the previously sampled random observation
If (for example) you used a Gaussian kernel, your density estimate is a mixture of 100 normals, each centred at one of your sample points and all having standard deviation $h$ equal to the estimated bandwidth. To draw a sample you can just sample with replacement one of your sample points (say $x_i$) and then sample from a $N(\mu = x_i, \sigma = h)$. In R:
# Original distribution is exp(rate = 5)
N = 1000
x <- rexp(N, rate = 5)
hist(x, prob = TRUE)
lines(density(x))
# Store the bandwith of the estimated KDE
bw <- density(x)$bw
# Draw from the sample and then from the kernel
means <- sample(x, N, replace = TRUE)
hist(rnorm(N, mean = means, sd = bw), prob = TRUE)
Strictly speaking, given that the mixture's components are equally weighted, you could avoid the sampling with replacement part and simply draw a sample a size $M$ from each components of the mixture:
M = 10
hist(rnorm(N * M, mean = x, sd = bw))
If for some reason you can't draw from your kernel (ex. your kernel is not a density), you can try with importance sampling or MCMC. For example, using importance sampling:
# Draw from proposal distribution which is normal(mu, sd = 1)
sam <- rnorm(N, mean(x), 1)
# Weight the sample using ratio of target and proposal densities
w <- sapply(sam, function(input) sum(dnorm(input, mean = x, sd = bw)) /
dnorm(input, mean(x), 1))
# Resample according to the weights to obtain an un-weighted sample
finalSample <- sample(sam, N, replace = TRUE, prob = w)
hist(finalSample, prob = TRUE)
P.S. With my thanks to Glen_b who contributed to the answer. | How to draw random samples from a non-parametric estimated distribution? | A kernel density estimate is a mixture distribution; for every observation, there's a kernel. If the kernel is a scaled density, this leads to a simple algorithm for sampling from the kernel density e | How to draw random samples from a non-parametric estimated distribution?
A kernel density estimate is a mixture distribution; for every observation, there's a kernel. If the kernel is a scaled density, this leads to a simple algorithm for sampling from the kernel density estimate:
repeat nsim times:
sample (with replacement) a random observation from the data
sample from the kernel, and add the previously sampled random observation
If (for example) you used a Gaussian kernel, your density estimate is a mixture of 100 normals, each centred at one of your sample points and all having standard deviation $h$ equal to the estimated bandwidth. To draw a sample you can just sample with replacement one of your sample points (say $x_i$) and then sample from a $N(\mu = x_i, \sigma = h)$. In R:
# Original distribution is exp(rate = 5)
N = 1000
x <- rexp(N, rate = 5)
hist(x, prob = TRUE)
lines(density(x))
# Store the bandwith of the estimated KDE
bw <- density(x)$bw
# Draw from the sample and then from the kernel
means <- sample(x, N, replace = TRUE)
hist(rnorm(N, mean = means, sd = bw), prob = TRUE)
Strictly speaking, given that the mixture's components are equally weighted, you could avoid the sampling with replacement part and simply draw a sample a size $M$ from each components of the mixture:
M = 10
hist(rnorm(N * M, mean = x, sd = bw))
If for some reason you can't draw from your kernel (ex. your kernel is not a density), you can try with importance sampling or MCMC. For example, using importance sampling:
# Draw from proposal distribution which is normal(mu, sd = 1)
sam <- rnorm(N, mean(x), 1)
# Weight the sample using ratio of target and proposal densities
w <- sapply(sam, function(input) sum(dnorm(input, mean = x, sd = bw)) /
dnorm(input, mean(x), 1))
# Resample according to the weights to obtain an un-weighted sample
finalSample <- sample(sam, N, replace = TRUE, prob = w)
hist(finalSample, prob = TRUE)
P.S. With my thanks to Glen_b who contributed to the answer. | How to draw random samples from a non-parametric estimated distribution?
A kernel density estimate is a mixture distribution; for every observation, there's a kernel. If the kernel is a scaled density, this leads to a simple algorithm for sampling from the kernel density e |
17,285 | Finding inflection points in R from smoothed data | From the perspective of using R to find the inflections in the smoothed curve, you just need to find those places in the smoothed y values where the change in y switches sign.
infl <- c(FALSE, diff(diff(out)>0)!=0)
Then you can add points to the graph where these inflections occur.
points(xl[infl ], out[infl ], col="blue")
From the perspective of finding statistically meaningful inflection points, I agree with @nico that you should look into change-point analysis, sometimes also referred to as segmented regression. | Finding inflection points in R from smoothed data | From the perspective of using R to find the inflections in the smoothed curve, you just need to find those places in the smoothed y values where the change in y switches sign.
infl <- c(FALSE, diff(di | Finding inflection points in R from smoothed data
From the perspective of using R to find the inflections in the smoothed curve, you just need to find those places in the smoothed y values where the change in y switches sign.
infl <- c(FALSE, diff(diff(out)>0)!=0)
Then you can add points to the graph where these inflections occur.
points(xl[infl ], out[infl ], col="blue")
From the perspective of finding statistically meaningful inflection points, I agree with @nico that you should look into change-point analysis, sometimes also referred to as segmented regression. | Finding inflection points in R from smoothed data
From the perspective of using R to find the inflections in the smoothed curve, you just need to find those places in the smoothed y values where the change in y switches sign.
infl <- c(FALSE, diff(di |
17,286 | Finding inflection points in R from smoothed data | There are problems on several levels here.
First off, loess just happens to be one smoother and there are many, many to choose from. Optimists argue that just about any reasonable smoother will find a real pattern and that just about all reasonable smoothers agree on real patterns. Pessimists argue that this is the problem and that "reasonable smoothers" and "real patterns" are here defined in terms of each other. To the point, why loess and why do you think that a good choice here? The choice is not just of a single smoother or a single implementation of a smoother (not all that goes under the name of loess or lowess is identical across software), but also of a single degree of smoothing (even if that is chosen by the routine for you). You do mention this point but that is not addressing it.
More specifically, as your toy example shows, basic features like turning points may easily not be preserved by loess (not to single out loess, either). Your first local minimum disappears and your second local minimum is displaced by the particular smooth you show. Inflexions being defined by zeros of the second derivative rather than the first can be expected to be even more fickle. | Finding inflection points in R from smoothed data | There are problems on several levels here.
First off, loess just happens to be one smoother and there are many, many to choose from. Optimists argue that just about any reasonable smoother will find | Finding inflection points in R from smoothed data
There are problems on several levels here.
First off, loess just happens to be one smoother and there are many, many to choose from. Optimists argue that just about any reasonable smoother will find a real pattern and that just about all reasonable smoothers agree on real patterns. Pessimists argue that this is the problem and that "reasonable smoothers" and "real patterns" are here defined in terms of each other. To the point, why loess and why do you think that a good choice here? The choice is not just of a single smoother or a single implementation of a smoother (not all that goes under the name of loess or lowess is identical across software), but also of a single degree of smoothing (even if that is chosen by the routine for you). You do mention this point but that is not addressing it.
More specifically, as your toy example shows, basic features like turning points may easily not be preserved by loess (not to single out loess, either). Your first local minimum disappears and your second local minimum is displaced by the particular smooth you show. Inflexions being defined by zeros of the second derivative rather than the first can be expected to be even more fickle. | Finding inflection points in R from smoothed data
There are problems on several levels here.
First off, loess just happens to be one smoother and there are many, many to choose from. Optimists argue that just about any reasonable smoother will find |
17,287 | Finding inflection points in R from smoothed data | There are a bunch of great approaches to this issue. Some include.
(1) - changepoint- package
(2) - segmented - package. But you are required to choose the number of changepoints.
(3) MARS as implemented in the -earth- package
Depending on your bias/variance tradeoff, all will give you slightly different information. -segmented- is well worth a look. Different number of changepoints models can be compared with AIC/BIC | Finding inflection points in R from smoothed data | There are a bunch of great approaches to this issue. Some include.
(1) - changepoint- package
(2) - segmented - package. But you are required to choose the number of changepoints.
(3) MARS as implem | Finding inflection points in R from smoothed data
There are a bunch of great approaches to this issue. Some include.
(1) - changepoint- package
(2) - segmented - package. But you are required to choose the number of changepoints.
(3) MARS as implemented in the -earth- package
Depending on your bias/variance tradeoff, all will give you slightly different information. -segmented- is well worth a look. Different number of changepoints models can be compared with AIC/BIC | Finding inflection points in R from smoothed data
There are a bunch of great approaches to this issue. Some include.
(1) - changepoint- package
(2) - segmented - package. But you are required to choose the number of changepoints.
(3) MARS as implem |
17,288 | Finding inflection points in R from smoothed data | You could perhaps use the fda library, and once you have estimated an appropriate continuous function, you can easily find the places where the second derivative is zero.
FDA CRAN
FDA Intro | Finding inflection points in R from smoothed data | You could perhaps use the fda library, and once you have estimated an appropriate continuous function, you can easily find the places where the second derivative is zero.
FDA CRAN
FDA Intro | Finding inflection points in R from smoothed data
You could perhaps use the fda library, and once you have estimated an appropriate continuous function, you can easily find the places where the second derivative is zero.
FDA CRAN
FDA Intro | Finding inflection points in R from smoothed data
You could perhaps use the fda library, and once you have estimated an appropriate continuous function, you can easily find the places where the second derivative is zero.
FDA CRAN
FDA Intro |
17,289 | Finding inflection points in R from smoothed data | I have received many visits to the blog about the changepoint package (>650 as of 11 Nov 2014), so here is an updated post using CausalImpact.
http://r-datameister.blogspot.com/2014/11/causality-in-time-series-look-at-2-r.html | Finding inflection points in R from smoothed data | I have received many visits to the blog about the changepoint package (>650 as of 11 Nov 2014), so here is an updated post using CausalImpact.
http://r-datameister.blogspot.com/2014/11/causality-in-ti | Finding inflection points in R from smoothed data
I have received many visits to the blog about the changepoint package (>650 as of 11 Nov 2014), so here is an updated post using CausalImpact.
http://r-datameister.blogspot.com/2014/11/causality-in-time-series-look-at-2-r.html | Finding inflection points in R from smoothed data
I have received many visits to the blog about the changepoint package (>650 as of 11 Nov 2014), so here is an updated post using CausalImpact.
http://r-datameister.blogspot.com/2014/11/causality-in-ti |
17,290 | Finding inflection points in R from smoothed data | see https://play128.shinyapps.io/inflection_points/
this will show your data in plot and you can download as pdf or svg | Finding inflection points in R from smoothed data | see https://play128.shinyapps.io/inflection_points/
this will show your data in plot and you can download as pdf or svg | Finding inflection points in R from smoothed data
see https://play128.shinyapps.io/inflection_points/
this will show your data in plot and you can download as pdf or svg | Finding inflection points in R from smoothed data
see https://play128.shinyapps.io/inflection_points/
this will show your data in plot and you can download as pdf or svg |
17,291 | Questions on parametric and non-parametric bootstrap | The answer given by miura is not entirely accurate so I am answering this old question for posterity:
(2). These are very different things. The empirical cdf is an estimate of the CDF (distribution) which generated the data. Precisely, it is the discrete CDF which assigns probability $1/n$ to each observed data point, $\hat{F}(x) = \frac{1}{n}\sum_{i=1}^n I(X_i\leq x)$, for each $x$. This estimator converges to the true cdf: $\hat{F}(x) \to F(x) = P(X_i\leq x)$ almost surely for each $x$ (in fact uniformly).
The sampling distribution of a statistic $T$ is instead the distribution of the statistic you would expect to see under repeated experimentation. That is, you perform your experiment once and collect data ${X_1,\ldots,X_n}$. $T$ is a function of your data: $T = T(X_1,\ldots,X_n)$. Now, suppose you repeat the experiment, and collect data ${X'_1,\ldots,X'_n}$. Recalculating T on the new sample gives $T' = T({X'_1,\ldots,X'_n})$. If we collected 100 samples we would have 100 estimates of $T$. These observations of $T$ form the sampling distribution of $T$. It is a true distribution. As the number of experiments goes to infinity its mean converges to $E(T)$ and its variance to $Var(T)$.
In general of course we don't repeat experiments like this, we only ever see one instance of $T$. Figuring out what the variance of $T$ is from a single observation is very difficult if you don't know the underlying probability function of $T$ a priori. Bootstrapping is a way to estimate that sampling distribution of $T$ by artificially running "new experiments" on which to calculate new instances of $T$. Each new sample is actually just a resample from the original data. That this provides you with more information than you have in the original data is mysterious and totally awesome.
(1). You are correct--you would not do this. The author is trying to motivate the parametric bootstrap by describing it as doing "what you would do if you knew the distribution" but substituting a very good estimator of the distribution function--the empirical cdf.
For example, suppose you know that your test statistic $T$ is normally distributed with mean zero, variance one. How would you estimate the sampling distribution of $T$? Well, since you know the distribution, a silly and redundant way to estimate the sampling distribution is to use R to generate 10,000 or so standard normal random variables, then take their sample mean and variance, and use these as our estimates of the mean and variance of the sampling distribution of $T$.
If we don't know a priori the parameters of $T$, but we do know that it's normally distributed, what we can do instead is generate 10,000 or so samples from the empirical cdf, calculate $T$ on each of them, then take the sample mean and variance of these 10,000 $T$s, and use them as our estimates of the expected value and variance of $T$. Since the empirical cdf is a good estimator of the true cdf, the sample parameters should converge to the true parameters. This is the parametric bootstrap: you posit a model on the statistic you want to estimate. The model is indexed by a parameter, e.g. $(\mu, \sigma)$, which you estimate from repeated sampling from the ecdf.
(3). The nonparametric bootstrap doesn't even require you to know a priori that $T$ is normally distributed. Instead, you simply draw repeated samples from the ecdf, and calculate $T$ on each one. After you've drawn 10,000 or so samples and calculated 10,000 $T$s, you can plot a histogram of your estimates. This is a visualization of the sampling distribution of $T$. The nonparametric bootstrap won't tell you that the sampling distribution is normal, or gamma, or so on, but it allows you to estimate the sampling distribution (usually) as precisely as needed. It makes fewer assumptions and provides less information than the parametric bootstrap. It is less precise when the parametric assumption is true but more accurate when it is false. Which one you use in each situation you encounter depends entirely on context. Admittedly more people are familiar with the nonparametric bootstrap but frequently a weak parametric assumption makes a completely intractable model amenable to estimation, which is lovely. | Questions on parametric and non-parametric bootstrap | The answer given by miura is not entirely accurate so I am answering this old question for posterity:
(2). These are very different things. The empirical cdf is an estimate of the CDF (distribution) | Questions on parametric and non-parametric bootstrap
The answer given by miura is not entirely accurate so I am answering this old question for posterity:
(2). These are very different things. The empirical cdf is an estimate of the CDF (distribution) which generated the data. Precisely, it is the discrete CDF which assigns probability $1/n$ to each observed data point, $\hat{F}(x) = \frac{1}{n}\sum_{i=1}^n I(X_i\leq x)$, for each $x$. This estimator converges to the true cdf: $\hat{F}(x) \to F(x) = P(X_i\leq x)$ almost surely for each $x$ (in fact uniformly).
The sampling distribution of a statistic $T$ is instead the distribution of the statistic you would expect to see under repeated experimentation. That is, you perform your experiment once and collect data ${X_1,\ldots,X_n}$. $T$ is a function of your data: $T = T(X_1,\ldots,X_n)$. Now, suppose you repeat the experiment, and collect data ${X'_1,\ldots,X'_n}$. Recalculating T on the new sample gives $T' = T({X'_1,\ldots,X'_n})$. If we collected 100 samples we would have 100 estimates of $T$. These observations of $T$ form the sampling distribution of $T$. It is a true distribution. As the number of experiments goes to infinity its mean converges to $E(T)$ and its variance to $Var(T)$.
In general of course we don't repeat experiments like this, we only ever see one instance of $T$. Figuring out what the variance of $T$ is from a single observation is very difficult if you don't know the underlying probability function of $T$ a priori. Bootstrapping is a way to estimate that sampling distribution of $T$ by artificially running "new experiments" on which to calculate new instances of $T$. Each new sample is actually just a resample from the original data. That this provides you with more information than you have in the original data is mysterious and totally awesome.
(1). You are correct--you would not do this. The author is trying to motivate the parametric bootstrap by describing it as doing "what you would do if you knew the distribution" but substituting a very good estimator of the distribution function--the empirical cdf.
For example, suppose you know that your test statistic $T$ is normally distributed with mean zero, variance one. How would you estimate the sampling distribution of $T$? Well, since you know the distribution, a silly and redundant way to estimate the sampling distribution is to use R to generate 10,000 or so standard normal random variables, then take their sample mean and variance, and use these as our estimates of the mean and variance of the sampling distribution of $T$.
If we don't know a priori the parameters of $T$, but we do know that it's normally distributed, what we can do instead is generate 10,000 or so samples from the empirical cdf, calculate $T$ on each of them, then take the sample mean and variance of these 10,000 $T$s, and use them as our estimates of the expected value and variance of $T$. Since the empirical cdf is a good estimator of the true cdf, the sample parameters should converge to the true parameters. This is the parametric bootstrap: you posit a model on the statistic you want to estimate. The model is indexed by a parameter, e.g. $(\mu, \sigma)$, which you estimate from repeated sampling from the ecdf.
(3). The nonparametric bootstrap doesn't even require you to know a priori that $T$ is normally distributed. Instead, you simply draw repeated samples from the ecdf, and calculate $T$ on each one. After you've drawn 10,000 or so samples and calculated 10,000 $T$s, you can plot a histogram of your estimates. This is a visualization of the sampling distribution of $T$. The nonparametric bootstrap won't tell you that the sampling distribution is normal, or gamma, or so on, but it allows you to estimate the sampling distribution (usually) as precisely as needed. It makes fewer assumptions and provides less information than the parametric bootstrap. It is less precise when the parametric assumption is true but more accurate when it is false. Which one you use in each situation you encounter depends entirely on context. Admittedly more people are familiar with the nonparametric bootstrap but frequently a weak parametric assumption makes a completely intractable model amenable to estimation, which is lovely. | Questions on parametric and non-parametric bootstrap
The answer given by miura is not entirely accurate so I am answering this old question for posterity:
(2). These are very different things. The empirical cdf is an estimate of the CDF (distribution) |
17,292 | Questions on parametric and non-parametric bootstrap | I really appreciate the effort contributed by guest47, but I don't quite agree with his answer, in some minor aspects. I wouldn't directly pose my disagreements, but rather reflect them in this answer.
In many cases, it is redundant to compute $\hat\theta s$ when we already know the true underlying parameter $\theta*$. However, it is still useful when we want to look at the accuracy and precision of $\hat\theta s$ in estimating $\theta*$. Besides, the first paragraph in your quoted passage will make it easier for you to understand the notion of "parametric bootstrap", which I will touch upon shortly after.
Guest47 gives good answer. No need to elaborate more.
In parametric bootstrapping, what you have is the observed data D. You come up with a parametric model to fit the data, and use estimators $\hat\theta$ (which is a function of data D) for the true parameters $\theta*$. Then you generate thousands of datasets from the parametric model with $\hat\theta$, and estimate $\hat\theta s$ for these models. In nonparametric bootstrapping, you directly use D, sample (for thousands of times) exactly from D, instead of from generated data. | Questions on parametric and non-parametric bootstrap | I really appreciate the effort contributed by guest47, but I don't quite agree with his answer, in some minor aspects. I wouldn't directly pose my disagreements, but rather reflect them in this answer | Questions on parametric and non-parametric bootstrap
I really appreciate the effort contributed by guest47, but I don't quite agree with his answer, in some minor aspects. I wouldn't directly pose my disagreements, but rather reflect them in this answer.
In many cases, it is redundant to compute $\hat\theta s$ when we already know the true underlying parameter $\theta*$. However, it is still useful when we want to look at the accuracy and precision of $\hat\theta s$ in estimating $\theta*$. Besides, the first paragraph in your quoted passage will make it easier for you to understand the notion of "parametric bootstrap", which I will touch upon shortly after.
Guest47 gives good answer. No need to elaborate more.
In parametric bootstrapping, what you have is the observed data D. You come up with a parametric model to fit the data, and use estimators $\hat\theta$ (which is a function of data D) for the true parameters $\theta*$. Then you generate thousands of datasets from the parametric model with $\hat\theta$, and estimate $\hat\theta s$ for these models. In nonparametric bootstrapping, you directly use D, sample (for thousands of times) exactly from D, instead of from generated data. | Questions on parametric and non-parametric bootstrap
I really appreciate the effort contributed by guest47, but I don't quite agree with his answer, in some minor aspects. I wouldn't directly pose my disagreements, but rather reflect them in this answer |
17,293 | Questions on parametric and non-parametric bootstrap | I'm no expert, but for what it's worth:
Because you're interested in the sampling distribution, as mentioned in the first sentence of your quotation.
The empirical distribution is the distribution you see in your finite number of samples. The sampling distribution is what you would see were you to take an infinite number of samples.
I can't answer 3.
I always understood what is described here as nonparametric bootstrap as "the" bootstrap.
If you have not already fully grasped the concept of the sampling distribution, there is a really nice thread here that features very illustrative R code. | Questions on parametric and non-parametric bootstrap | I'm no expert, but for what it's worth:
Because you're interested in the sampling distribution, as mentioned in the first sentence of your quotation.
The empirical distribution is the distribution yo | Questions on parametric and non-parametric bootstrap
I'm no expert, but for what it's worth:
Because you're interested in the sampling distribution, as mentioned in the first sentence of your quotation.
The empirical distribution is the distribution you see in your finite number of samples. The sampling distribution is what you would see were you to take an infinite number of samples.
I can't answer 3.
I always understood what is described here as nonparametric bootstrap as "the" bootstrap.
If you have not already fully grasped the concept of the sampling distribution, there is a really nice thread here that features very illustrative R code. | Questions on parametric and non-parametric bootstrap
I'm no expert, but for what it's worth:
Because you're interested in the sampling distribution, as mentioned in the first sentence of your quotation.
The empirical distribution is the distribution yo |
17,294 | What is the normal approximation of the multinomial distribution? | You can approximate it with the multivariate normal distribution in the same way that binomial distribution is approximated by univariate normal distribution. Check Elements of Distribution Theory and Multinomial Distribution pages 15-16-17.
Let $P=(p_1,...,p_k)$ be the vector of your probabilities. Then the mean vector of the multivariate normal distribution is $ np=(np_1,np_2,...,np_k)$. The covariance matrix is a $k \times k$ symmetric matrix. The diagonal elements are actually the variance of $X_i$'s; i.e.$ np_i(1-p_i)$, $i=1,2...,k$. The off-diagonal element in the ith row and jth column is $\text{Cov}(X_i,X_j)=-np_ip_j$, where $i$ is not equal to $j$. | What is the normal approximation of the multinomial distribution? | You can approximate it with the multivariate normal distribution in the same way that binomial distribution is approximated by univariate normal distribution. Check Elements of Distribution Theory an | What is the normal approximation of the multinomial distribution?
You can approximate it with the multivariate normal distribution in the same way that binomial distribution is approximated by univariate normal distribution. Check Elements of Distribution Theory and Multinomial Distribution pages 15-16-17.
Let $P=(p_1,...,p_k)$ be the vector of your probabilities. Then the mean vector of the multivariate normal distribution is $ np=(np_1,np_2,...,np_k)$. The covariance matrix is a $k \times k$ symmetric matrix. The diagonal elements are actually the variance of $X_i$'s; i.e.$ np_i(1-p_i)$, $i=1,2...,k$. The off-diagonal element in the ith row and jth column is $\text{Cov}(X_i,X_j)=-np_ip_j$, where $i$ is not equal to $j$. | What is the normal approximation of the multinomial distribution?
You can approximate it with the multivariate normal distribution in the same way that binomial distribution is approximated by univariate normal distribution. Check Elements of Distribution Theory an |
17,295 | What is the normal approximation of the multinomial distribution? | The density given in this answer is degenerate, and so I used the following to calculate the density that results from the normal approximation:
There's a theorem that says given a random variable $X = [X_1, \ldots, X_m]^T \sim \text{Multinom}(n, p)$, for an $m$-dimensional vector $p$ with $\sum_i p_i = 1$ and $\sum_i X_i = n$, that;
$$
X
\xrightarrow{d} \sqrt{n} \, \text{diag}(u) \, Q
\begin{bmatrix}
Z_1 \\ \vdots \\ Z_{m-1} \\ 0
\end{bmatrix} +
\begin{bmatrix} n p_1 \\ \vdots \\ n p_m \end{bmatrix},
$$
for large $n$, given;
a vector $u$ with $u_i = \sqrt{p_i}$;
random variables $Z_i \sim N(0,1)$ for $i = 1, \ldots, m-1$, and;
an orthogonal matrix $Q$ with final column $u$.
That is to say, with some rearrangement, we can work out an $m-1$ dimensional multivariate normal distribution for the first $m-1$ components of $X$ (which are the only interesting components because $X_m$ is the sum of the others).
A suitable value of the matrix $Q$ is $I - 2 v v^T$ with $v_i = (\delta_{im} - u_i) / \sqrt{2(1 - u_m)}$ - i.e. a particular Householder transformation.
If we restrict the left-hand side to the first $m-1$ rows, and restrict $Q$ to its first $m-1$ rows and $m-1$ columns (denote these $\hat{X}$ and $\hat{Q}$ respectively) then:
$$
\hat{X}
\xrightarrow{d} \sqrt{n} \text{diag}(\hat{u}) \hat{Q}
\begin{bmatrix}
Z_1 \\ \vdots \\ Z_{m-1}
\end{bmatrix} +
\begin{bmatrix} n p_1 \\ \vdots \\ n p_{m-1} \end{bmatrix}
\sim
\mathcal{N} \left( \mu, n \Sigma \right),
$$
for large $n$, where;
$\hat{u}$ denotes the first $m-1$ terms of $u$;
the mean is $\mu = [ n p_1, \ldots, n p_{m-1}]^T$, and;
the covariance matrix $n \Sigma = n A A^T$ with $A = \text{diag}( \hat{u} ) \hat{Q}$.
The right hand side of that final equation is the non-degenerate density used in calculation.
As expected, when you plug everything in, you get the following covariance matrix:
$$ (n\Sigma)_{ij} = n \sqrt{p_i p_j} (\delta_{ij} - \sqrt{p_i p_j}) $$
for $i,j = 1, \ldots, m-1$, which is exactly the covariance matrix in the original answer restricted to its first $m-1$ rows and $m-1$ columns.
This blog entry was my starting point. | What is the normal approximation of the multinomial distribution? | The density given in this answer is degenerate, and so I used the following to calculate the density that results from the normal approximation:
There's a theorem that says given a random variable $X | What is the normal approximation of the multinomial distribution?
The density given in this answer is degenerate, and so I used the following to calculate the density that results from the normal approximation:
There's a theorem that says given a random variable $X = [X_1, \ldots, X_m]^T \sim \text{Multinom}(n, p)$, for an $m$-dimensional vector $p$ with $\sum_i p_i = 1$ and $\sum_i X_i = n$, that;
$$
X
\xrightarrow{d} \sqrt{n} \, \text{diag}(u) \, Q
\begin{bmatrix}
Z_1 \\ \vdots \\ Z_{m-1} \\ 0
\end{bmatrix} +
\begin{bmatrix} n p_1 \\ \vdots \\ n p_m \end{bmatrix},
$$
for large $n$, given;
a vector $u$ with $u_i = \sqrt{p_i}$;
random variables $Z_i \sim N(0,1)$ for $i = 1, \ldots, m-1$, and;
an orthogonal matrix $Q$ with final column $u$.
That is to say, with some rearrangement, we can work out an $m-1$ dimensional multivariate normal distribution for the first $m-1$ components of $X$ (which are the only interesting components because $X_m$ is the sum of the others).
A suitable value of the matrix $Q$ is $I - 2 v v^T$ with $v_i = (\delta_{im} - u_i) / \sqrt{2(1 - u_m)}$ - i.e. a particular Householder transformation.
If we restrict the left-hand side to the first $m-1$ rows, and restrict $Q$ to its first $m-1$ rows and $m-1$ columns (denote these $\hat{X}$ and $\hat{Q}$ respectively) then:
$$
\hat{X}
\xrightarrow{d} \sqrt{n} \text{diag}(\hat{u}) \hat{Q}
\begin{bmatrix}
Z_1 \\ \vdots \\ Z_{m-1}
\end{bmatrix} +
\begin{bmatrix} n p_1 \\ \vdots \\ n p_{m-1} \end{bmatrix}
\sim
\mathcal{N} \left( \mu, n \Sigma \right),
$$
for large $n$, where;
$\hat{u}$ denotes the first $m-1$ terms of $u$;
the mean is $\mu = [ n p_1, \ldots, n p_{m-1}]^T$, and;
the covariance matrix $n \Sigma = n A A^T$ with $A = \text{diag}( \hat{u} ) \hat{Q}$.
The right hand side of that final equation is the non-degenerate density used in calculation.
As expected, when you plug everything in, you get the following covariance matrix:
$$ (n\Sigma)_{ij} = n \sqrt{p_i p_j} (\delta_{ij} - \sqrt{p_i p_j}) $$
for $i,j = 1, \ldots, m-1$, which is exactly the covariance matrix in the original answer restricted to its first $m-1$ rows and $m-1$ columns.
This blog entry was my starting point. | What is the normal approximation of the multinomial distribution?
The density given in this answer is degenerate, and so I used the following to calculate the density that results from the normal approximation:
There's a theorem that says given a random variable $X |
17,296 | Automated procedure for selecting subset of data points w/ strongest correlation? | I would say that your method fits into the general category described in this wikipedia article which also has other references if you need something more than just wikipedia. Some of the links within that article would also apply.
Other terms that could apply (if you want to do some more searching) include "Data Dredging" and "Torturing the data until it confesses".
Note that you can always get a correlation of 1 if you just choose 2 points that don't have identical x or y values. There was an article in Chance magazine a few years back that showed when you have an x and y variable with essentially no correlation you can find a way to bin the x's and average the y's within the bins to show either an increasing or decreasing trend (Chance 2006, Visual Revelations: Finding What Is Not There through the Unfortunate binning of Results: The Mendel Effect, pp. 49-52). Also with a full dataset showing a moderate positive correlation it is possible to choose a subset that shows a negative correlation. Given these, even if you have a legitimate reason for doing what you propose, you are giving any skeptics a lot of arguments to use against any conclusions that you come up with. | Automated procedure for selecting subset of data points w/ strongest correlation? | I would say that your method fits into the general category described in this wikipedia article which also has other references if you need something more than just wikipedia. Some of the links withi | Automated procedure for selecting subset of data points w/ strongest correlation?
I would say that your method fits into the general category described in this wikipedia article which also has other references if you need something more than just wikipedia. Some of the links within that article would also apply.
Other terms that could apply (if you want to do some more searching) include "Data Dredging" and "Torturing the data until it confesses".
Note that you can always get a correlation of 1 if you just choose 2 points that don't have identical x or y values. There was an article in Chance magazine a few years back that showed when you have an x and y variable with essentially no correlation you can find a way to bin the x's and average the y's within the bins to show either an increasing or decreasing trend (Chance 2006, Visual Revelations: Finding What Is Not There through the Unfortunate binning of Results: The Mendel Effect, pp. 49-52). Also with a full dataset showing a moderate positive correlation it is possible to choose a subset that shows a negative correlation. Given these, even if you have a legitimate reason for doing what you propose, you are giving any skeptics a lot of arguments to use against any conclusions that you come up with. | Automated procedure for selecting subset of data points w/ strongest correlation?
I would say that your method fits into the general category described in this wikipedia article which also has other references if you need something more than just wikipedia. Some of the links withi |
17,297 | Automated procedure for selecting subset of data points w/ strongest correlation? | The RANSAC algorithm sounds like what you want. Basically, it assumes your data consists of a mix of inliers and outliers, and tries to identify the inliers by repeatedly sampling subsets of the data, fitting a model to it, then trying to fit every other data point to the model. Here's the wikipedia article about it.
In your case, you can just keep repeating the algorithm while saving the current best model that fits at least 40 points, so it won't guarantee you the absolute best correlation, but it should get close. | Automated procedure for selecting subset of data points w/ strongest correlation? | The RANSAC algorithm sounds like what you want. Basically, it assumes your data consists of a mix of inliers and outliers, and tries to identify the inliers by repeatedly sampling subsets of the data, | Automated procedure for selecting subset of data points w/ strongest correlation?
The RANSAC algorithm sounds like what you want. Basically, it assumes your data consists of a mix of inliers and outliers, and tries to identify the inliers by repeatedly sampling subsets of the data, fitting a model to it, then trying to fit every other data point to the model. Here's the wikipedia article about it.
In your case, you can just keep repeating the algorithm while saving the current best model that fits at least 40 points, so it won't guarantee you the absolute best correlation, but it should get close. | Automated procedure for selecting subset of data points w/ strongest correlation?
The RANSAC algorithm sounds like what you want. Basically, it assumes your data consists of a mix of inliers and outliers, and tries to identify the inliers by repeatedly sampling subsets of the data, |
17,298 | Automated procedure for selecting subset of data points w/ strongest correlation? | I have a hard time imagining a context in which this would be good practice, but lets assume for a moment that you indeed have a good reason for doing this.
A brute force algorithm could be something like this:
You calculate all possible sub-samples of n out of your overall sample of N. Most statistical packages have functions for calculating combinations without replacements that will do this for you.
You estimate the correlation between x and y for each one of the sub-samples and select the maximum out of that set.
I just saw the original poster's comment regarding a reference for this procedure. I am not sure that someone has a specific name for this procedure after all you are simply generating an empirical distribution of all possible correlation in your dataset and selecting the maximum. Similar approaches are used when doing bootstraping, but in that case you are interested in the empirical variability, you DO NOT use them to pick a specific sub-sample associated with the max. | Automated procedure for selecting subset of data points w/ strongest correlation? | I have a hard time imagining a context in which this would be good practice, but lets assume for a moment that you indeed have a good reason for doing this.
A brute force algorithm could be something | Automated procedure for selecting subset of data points w/ strongest correlation?
I have a hard time imagining a context in which this would be good practice, but lets assume for a moment that you indeed have a good reason for doing this.
A brute force algorithm could be something like this:
You calculate all possible sub-samples of n out of your overall sample of N. Most statistical packages have functions for calculating combinations without replacements that will do this for you.
You estimate the correlation between x and y for each one of the sub-samples and select the maximum out of that set.
I just saw the original poster's comment regarding a reference for this procedure. I am not sure that someone has a specific name for this procedure after all you are simply generating an empirical distribution of all possible correlation in your dataset and selecting the maximum. Similar approaches are used when doing bootstraping, but in that case you are interested in the empirical variability, you DO NOT use them to pick a specific sub-sample associated with the max. | Automated procedure for selecting subset of data points w/ strongest correlation?
I have a hard time imagining a context in which this would be good practice, but lets assume for a moment that you indeed have a good reason for doing this.
A brute force algorithm could be something |
17,299 | Confidence intervals for regression parameters: Bayesian vs. classical | The 'problem' is in the prior on sigma. Try a less informative setting
tau ~ dgamma(1.0E-3,1.0E-3)
sigma <- pow(tau, -1/2)
in your jags file. Then update a bunch
update(10000)
grab the parameters, and summarise your quantity of interest. It should line up reasonably well with the classic version.
Clarification: The updating is just to make sure you get where you're going whatever choice of prior you decide on, although chains for models like this one with diffuse priors and random starting values do take longer to converge. In real problems you'd check convergence before summarising anything, but convergence is not the main issue in your example I don't think. | Confidence intervals for regression parameters: Bayesian vs. classical | The 'problem' is in the prior on sigma. Try a less informative setting
tau ~ dgamma(1.0E-3,1.0E-3)
sigma <- pow(tau, -1/2)
in your jags file. Then update a bunch
update(10000)
grab the parameters, | Confidence intervals for regression parameters: Bayesian vs. classical
The 'problem' is in the prior on sigma. Try a less informative setting
tau ~ dgamma(1.0E-3,1.0E-3)
sigma <- pow(tau, -1/2)
in your jags file. Then update a bunch
update(10000)
grab the parameters, and summarise your quantity of interest. It should line up reasonably well with the classic version.
Clarification: The updating is just to make sure you get where you're going whatever choice of prior you decide on, although chains for models like this one with diffuse priors and random starting values do take longer to converge. In real problems you'd check convergence before summarising anything, but convergence is not the main issue in your example I don't think. | Confidence intervals for regression parameters: Bayesian vs. classical
The 'problem' is in the prior on sigma. Try a less informative setting
tau ~ dgamma(1.0E-3,1.0E-3)
sigma <- pow(tau, -1/2)
in your jags file. Then update a bunch
update(10000)
grab the parameters, |
17,300 | Confidence intervals for regression parameters: Bayesian vs. classical | If you sample from the posterior of b | y and calculate lims (as you define) it should be same as (b - delta, b + delta). Specifically, if you calculate the posterior distribution of b | y under a flat prior, it is same as the classical sampling distribution of b.
For more details refer to: Gelman et al. (2003). Bayesian Data Analysis. CRC Press. Section 3.6
Edit:
Ringold, the behavior observed by you is consistent with the Bayesian idea. The Bayesian Credible Interval (CI) is generally wider than the classical ones. And the reason is, as you correctly guessed, the hyperpriors taken into account the variability because of the unknown parameters.
For simple scenarios like these (NOT IN GENERAL):
Baysian CI > Empirical Bayesian CI > Classical CI ; > == wider | Confidence intervals for regression parameters: Bayesian vs. classical | If you sample from the posterior of b | y and calculate lims (as you define) it should be same as (b - delta, b + delta). Specifically, if you calculate the posterior distribution of b | y under a fla | Confidence intervals for regression parameters: Bayesian vs. classical
If you sample from the posterior of b | y and calculate lims (as you define) it should be same as (b - delta, b + delta). Specifically, if you calculate the posterior distribution of b | y under a flat prior, it is same as the classical sampling distribution of b.
For more details refer to: Gelman et al. (2003). Bayesian Data Analysis. CRC Press. Section 3.6
Edit:
Ringold, the behavior observed by you is consistent with the Bayesian idea. The Bayesian Credible Interval (CI) is generally wider than the classical ones. And the reason is, as you correctly guessed, the hyperpriors taken into account the variability because of the unknown parameters.
For simple scenarios like these (NOT IN GENERAL):
Baysian CI > Empirical Bayesian CI > Classical CI ; > == wider | Confidence intervals for regression parameters: Bayesian vs. classical
If you sample from the posterior of b | y and calculate lims (as you define) it should be same as (b - delta, b + delta). Specifically, if you calculate the posterior distribution of b | y under a fla |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.