RUНаблюдения и неизвестный закон
В дне 4 мы считали среднее по известному закону. Здесь задача обратная: видим наблюдения и хотим восстановить неизвестный параметр закона.
Выборка — набор наблюдений $X_1,\ldots,X_n$. До опыта это случайные величины; после опыта получаем конкретные числа $x_1,\ldots,x_n$. Объём $n$ считает все наблюдения, включая повторяющиеся.
Сокращение i.i.d. означает «независимые и одинаково распределённые». Независимость разрешает перемножать вероятности наблюдений. Одинаковый закон означает, что во всех множителях стоит один и тот же параметр. Ни одно из этих условий не следует из другого.
Параметр — неизвестная постоянная закона, например вероятность успеха $p$. Статистика — функция выборки, которую можно вычислить без знания параметра, например $\bar X=(X_1+\cdots+X_n)/n$.
Оценка параметра — статистика, выбранная для приближения параметра. До наблюдений $\hat p$ случайна: другая выборка даст другое значение. После наблюдений число $\hat p(x_1,\ldots,x_n)$ — результат применения оценки. Удачный ответ для одной выборки ещё не доказывает качество метода.
Правдоподобие из условия
Пусть закон задаётся вероятностями $P_p(X=k)=f(k;p)$. Для независимой выборки вероятность увидеть именно последовательность $x_1,\ldots,x_n$ равна произведению.
$$L(p)=\prod_{i=1}^n f(x_i;p).$$В этом выражении данные уже зафиксированы, а менять будем $p$. Поэтому это функция правдоподобия, а не распределение вероятностей самого параметра. Искать площадь под $L(p)$ или требовать её равной единице не нужно.
Метод максимального правдоподобия, MLE, выбирает допустимое значение параметра, при котором наблюдённые данные наиболее правдоподобны в принятой модели. Сначала строим произведение из данного закона; готовую формулу оценки заранее не угадываем.
Множитель, не зависящий от параметра, можно отбросить при поиске максимума, но не при вычислении самого значения $L$. Если данные записаны по порядку, не добавляйте число перестановок выборки.
Зачем брать логарифм
На положительных числах логарифм строго возрастает: $L(p_1)>L(p_2)$ тогда и только тогда, когда $\ln L(p_1)>\ln L(p_2)$. Место максимума сохраняется. Произведение превращается в сумму, а степень — в множитель.
$$\ell(p)=\ln L(p)=\sum_i\ln f(x_i;p).$$Это упрощает дифференцирование и уменьшает риск потери чисел при умножении многих маленьких вероятностей. Но в точке $L=0$ логарифм не определён; границы проверяют по исходному $L$ или по одностороннему пределу $\ell$.
Геометрический закон: что именно считают?
Если $X$ — число попыток до первого успеха включительно, то $X=1,2,\ldots$. Событие $X=k$ состоит из $k-1$ неудач и одного успеха.
$$P(X=k)=p(1-p)^{k-1},\qquad L(p)=p^n(1-p)^{S-n},\qquad S=\sum_i x_i.$$В выборке всегда $n$ успехов, по одному в конце каждого наблюдения. Неудач всего $S-n$. При $S>n$ логарифм имеет вид $\ell=n\ln p+(S-n)\ln(1-p)$.
$$\ell\prime(p)=\frac np-\frac{S-n}{1-p}=0\quad\Longrightarrow\quad\hat p=\frac nS=\frac1{\bar x}.$$Мы нашли кандидата, а не закончили решение. При $0<p<1$ вторая производная $\ell\prime\prime=-n/p^2-(S-n)/(1-p)^2<0$. Это означает, что наклон строго убывает: до найденной точки он положителен, после — отрицателен. Получен единственный максимум.
Кроме того, $S>n$ даёт $0<n/S<1$, а на концах $L$ стремится к нулю. Все три проверки согласованы: область, характер стационарной точки и границы.
Если все наблюдения равны $1$, то $S=n$, $L(p)=p^n$. Производная внутри области не обнуляется: максимум при $p=1$, если эта граница разрешена. Для открытой области $0<p<1$ максимума нет, хотя значения приближаются к $1$. Поэтому область должна быть в условии и в решении.
Теперь пусть $Y$ считает только неудачи до успеха. Тогда $Y=0,1,\ldots$, $Y=X-1$, и $P(Y=k)=p(1-p)^k$. В выборке неудач уже $T=\sum_i y_i$, поэтому
$$L(p)=p^n(1-p)^T,\qquad\hat p=\frac n{n+T}=\frac1{1+\bar y}.$$Одинаковая фраза «геометрическое распределение» допускает обе договорённости. Защитный приём: перед произведением написать «одно наблюдение = неудачи + успех». При переходе от $X$ к $Y=X-1$ оценка для одних и тех же опытов должна совпасть.
Ожидание оценки и её разброс
Другая задача оценивания: нам уже дали статистику $T$ и спрашивают, насколько она хороша. Считать новое правдоподобие здесь не нужно. Несмещённость означает $\E_\mu T=\mu$ для каждого допустимого $\mu$, а не только для одной выборки.
Если $\E X_i=\mu$, то по линейности $\E(\sum_i a_iX_i)=(\sum_i a_i)\mu$. При произвольном неизвестном среднем достаточный и необходимый критерий несмещённости — сумма весов равна $1$. Независимость для этого не требуется.
Дисперсия определяется как $\Var X=\E[(X-\E X)^2]$. Для $aX+b$ отклонение от среднего равно $a(X-\E X)$; после возведения в квадрат появляется $a^2$. Постоянный сдвиг исчезает.
$$\Var(aX+b)=a^2\Var X.$$У ожидания нет возведения отклонений в квадрат, поэтому там коэффициенты сохраняют знак и степень. У дисперсии квадратуется весь вес: для $T=(X_1+2X_2)/3$ это веса $1/3,2/3$, а не $1,2$ с последующим делением дисперсии на $3$.
Ковариация $\Cov(X,Y)=\E[(X-\E X)(Y-\E Y)]$ измеряет среднее совместное изменение. При раскрытии квадрата суммы возникает смешанное произведение, поэтому для конечных дисперсий
$$\Var\Big(\sum_i a_iX_i\Big)=\sum_i a_i^2\Var X_i+2\sum_{i<j}a_i a_j\Cov(X_i,X_j).$$Независимость обнуляет все ковариации и даёт формулу из вопроса Q11. Но она достаточна, не необходима: нулевых попарных ковариаций тоже достаточно. Для двух величин без весов равенство дисперсий эквивалентно нулевой ковариации. Для нескольких величин смешанные члены могут также взаимно сократиться.
Пример зависимости с нулевой ковариацией: $X$ равномерно на $\{-1,0,1\}$, $Y=X^2$. По $X$ известно $Y$, но $\E X=\E X^3=0$, значит $\Cov(X,Y)=0$. Подробный численный разбор — y1503; он не нужен для механического применения формулы к независимым наблюдениям.
Проверка перед ответом
У MLE проверьте носитель, область параметра и максимум. У взвешенной оценки сначала проверьте среднее, затем дисперсию. Несмещённость сама по себе не обещает малого разброса: отрицательные или неравные веса могут увеличить дисперсию.
Не утверждайте, что MLE автоматически несмещённа. Это разные вопросы: один выбирает параметр для наблюдённых данных, другой усредняет статистику по всем возможным выборкам.
ENObservations and an unknown distribution
In day 4, we calculated a mean from a known distribution. Here we reverse the task: we observe data and want to recover an unknown parameter of the distribution.
A sample is a collection of observations $X_1,\ldots,X_n$. Before the experiment they are random variables; afterward we have the actual numbers $x_1,\ldots,x_n$. The sample size $n$ counts all observations, including repeated values.
i.i.d. means “independent and identically distributed.” Independence permits multiplication of observation probabilities. The common distribution means the same parameter appears in every factor. Neither condition implies the other.
A parameter is an unknown constant describing the distribution, such as the success probability $p$. A statistic is a function of the sample that can be calculated without knowing the parameter, for example $\bar X=(X_1+\cdots+X_n)/n$.
An estimator is a statistic chosen to approximate a parameter. Before observing the data, $\hat p$ is random: another sample would give another value. After observation, the number $\hat p(x_1,\ldots,x_n)$ is the resulting estimate. A good answer on one sample does not establish the quality of the method.
Constructing the likelihood
Suppose the model is given by probabilities $P_p(X=k)=f(k;p)$. For an independent sample, the probability of observing exactly the sequence $x_1,\ldots,x_n$ is a product.
$$L(p)=\prod_{i=1}^n f(x_i;p).$$In this expression the data are fixed, and we vary $p$. This makes it a likelihood function, not a probability distribution for the parameter itself. There is no requirement that the area under $L(p)$ equal one.
Maximum likelihood estimation, or MLE, chooses an allowed parameter value that makes the observed data most likely under the assumed model. First construct the product from the stated distribution; do not guess a ready-made estimator formula.
A factor independent of the parameter can be dropped when locating the maximum, but not when calculating the value of $L$ itself. If observations are recorded in order, do not add a sample-permutation factor.
Why take logarithms?
The logarithm is strictly increasing on positive numbers: $L(p_1)>L(p_2)$ if and only if $\ln L(p_1)>\ln L(p_2)$. The maximizing point is unchanged. Products become sums, and powers become coefficients.
$$\ell(p)=\ln L(p)=\sum_i\ln f(x_i;p).$$This simplifies differentiation and avoids numerical underflow when multiplying many tiny probabilities. However, the logarithm is undefined at $L=0$; check boundaries using the original $L$ or a one-sided limit of $\ell$.
Geometric distribution: what is counted?
If $X$ counts trials up to and including the first success, then $X=1,2,\ldots$. The event $X=k$ consists of $k-1$ failures followed by one success.
$$P(X=k)=p(1-p)^{k-1},\qquad L(p)=p^n(1-p)^{S-n},\qquad S=\sum_i x_i.$$The sample always contains $n$ successes, one at the end of each observation. There are $S-n$ failures in total. When $S>n$, the log-likelihood is $\ell=n\ln p+(S-n)\ln(1-p)$.
$$\ell\prime(p)=\frac np-\frac{S-n}{1-p}=0\quad\Longrightarrow\quad\hat p=\frac nS=\frac1{\bar x}.$$We have found a candidate, not finished the solution. For $0<p<1$, the second derivative is $\ell\prime\prime=-n/p^2-(S-n)/(1-p)^2<0$. Thus the slope is strictly decreasing: it is positive before the candidate and negative afterward. This establishes the unique maximum.
Also, $S>n$ gives $0<n/S<1$, while $L$ tends to zero at the endpoints. The domain, the type of stationary point, and the boundary behavior all agree.
If every observation equals $1$, then $S=n$ and $L(p)=p^n$. Its derivative never vanishes inside the domain: the maximum is at $p=1$ if that boundary is allowed. On the open domain $0<p<1$, there is no maximum, although the likelihood approaches $1$. This is why the domain belongs in both the statement and the solution.
Now let $Y$ count only failures before the success. Then $Y=0,1,\ldots$, $Y=X-1$, and $P(Y=k)=p(1-p)^k$. The sample has $T=\sum_i y_i$ failures, so
$$L(p)=p^n(1-p)^T,\qquad\hat p=\frac n{n+T}=\frac1{1+\bar y}.$$The phrase “geometric distribution” is used for both conventions. Protect yourself by writing “one observation = failures + success” before forming the product. Converting the same trials from $X$ to $Y=X-1$ must leave the estimate unchanged.
An estimator's expectation and spread
Another estimation task gives you a statistic $T$ and asks how it behaves. There is no need to construct another likelihood. Unbiasedness means $\E_\mu T=\mu$ for every allowed $\mu$, not just for one sample.
If $\E X_i=\mu$, linearity gives $\E(\sum_i a_iX_i)=(\sum_i a_i)\mu$. For an arbitrary unknown mean, unbiasedness holds exactly when the weights sum to $1$. Independence is not required here.
Variance is defined as $\Var X=\E[(X-\E X)^2]$. The deviation of $aX+b$ from its mean is $a(X-\E X)$; squaring it produces $a^2$. A constant shift disappears.
$$\Var(aX+b)=a^2\Var X.$$Expectation does not square deviations, so its coefficients keep their signs and powers. Variance squares each complete weight: for $T=(X_1+2X_2)/3$, these weights are $1/3,2/3$, not $1,2$ followed by dividing the variance by $3$.
Covariance, $\Cov(X,Y)=\E[(X-\E X)(Y-\E Y)]$, measures average joint variation. Expanding the square of a sum produces a cross product, so for finite variances
$$\Var\Big(\sum_i a_iX_i\Big)=\sum_i a_i^2\Var X_i+2\sum_{i<j}a_i a_j\Cov(X_i,X_j).$$Independence makes all covariances zero and gives the formula needed in Q11. But it is sufficient, not necessary: zero pairwise covariances also suffice. For two unweighted variables, variance additivity is equivalent to zero covariance. With several variables, cross terms can also cancel one another.
An example of dependence with zero covariance is $X$ uniform on $\{-1,0,1\}$ with $Y=X^2$. Knowing $X$ determines $Y$, but $\E X=\E X^3=0$, so $\Cov(X,Y)=0$. Problem y1503 develops the calculation; it is not a prerequisite for applying the formula to independent observations.
Before submitting
For an MLE, check the support, parameter domain, and maximum. For a weighted estimator, check its expectation first, then its variance. Unbiasedness alone does not promise low spread: negative or unequal weights can increase variance.
Do not claim that an MLE is automatically unbiased. These are different questions: one selects a parameter for observed data; the other averages a statistic over all possible samples.