RUВход: одна таблица, четыре вопроса
На потоке 400 студентов. Форма обучения и результат экзамена сведены в таблицу:
| Сдал | Не сдал | Всего |
|---|
| Очники | 210 | 90 | 300 |
| Заочники | 40 | 60 | 100 |
| Всего | 250 | 150 | 400 |
Ответь на четыре вопроса, прежде чем читать дальше: каждый ответ — одно деление.
- Вероятность того, что случайный студент сдал.
- Вероятность того, что студент сдал, если известно, что он очник.
- Вероятность того, что студент очник, если известно, что он сдал.
- Вероятность того, что студент одновременно очник и сдал.
Ответы: $\frac{250}{400} = 0.625$, затем $\frac{210}{300} = 0.7$, затем $\frac{210}{250} = 0.84$ и $\frac{210}{400} = 0.525$.
В трёх последних числитель один и тот же — 210, различаются только знаменатели: 300, 250 и 400. Это и есть вся тема: слово «известно» не добавляет вычислений, оно выбирает знаменатель.
Определение и что оно на самом деле делает
Условная вероятность$$\P(A \mid B) = \frac{\P(A \cap B)}{\P(B)}, \qquad \P(B) > 0$$
Проверим на таблице, что определение не вводит ничего нового. Пусть $A$ — «сдал», $B$ — «очник». Тогда $\P(A \cap B) = \frac{210}{400}$, $\P(B) = \frac{300}{400}$, а их отношение равно $\frac{210}{300}$: общий знаменатель 400 сократился. Отсюда правило скорости: если даны абсолютные числа, делить на размер совокупности бессмысленно — бери отношение двух клеток.
Из той же таблицы виден порядок записи: $\P(A \mid B) = 0.7$, а $\P(B \mid A) = 0.84$. В задачах с редкими событиями такие пары отличаются не на проценты, а в разы.
Что стоит справа от чёрточкиЧитая условие, помечай на полях две вещи: что дано (идёт справа) и что ищется (слева). Маркеры данного: «известно, что», «при условии», «оказалось, что», «выяснилось». Отдельно следи за формой, в которой условие прячут в описании выборки: «наугад выбирают студента среди не сдавших» — то же самое условие, только сказанное иначе.
Умножение вдоль ветки
Определение, переписанное наоборот, даёт рабочую формулу для последовательных опытов:
$$\P(A \cap B) = \P(B) \cdot \P(A \mid B)$$Для цепочки из трёх шагов условие в каждом множителе накапливает всё, что было раньше:
$$\P(A_1 \cap A_2 \cap A_3) = \P(A_1) \cdot \P(A_2 \mid A_1) \cdot \P(A_3 \mid A_1 \cap A_2)$$Пример. Три карты из 36 вынимают без возвращения. Вероятность, что все три — тузы?
$$\P = \frac{4}{36} \cdot \frac{3}{35} \cdot \frac{2}{34} = \frac{1}{1785} \approx 0.00056$$Тот же ответ даёт классическое определение через сочетания: $\frac{\binom{4}{3}}{\binom{36}{3}} = \frac{4}{7140} = \frac{1}{1785}$. Два независимых пути к одному числу — самая дешёвая из проверок, сегодня она работает почти везде.
Где здесь независимость
Разделив вчерашнее равенство $\P(A \cap B) = \P(A)\,\P(B)$ на $\P(B)$, получаем рабочее прочтение: $\P(A \mid B) = \P(A)$, независимость — это когда условие ничего не сообщает.
Независимость против несовместностиДля несовместных $\P(A \mid B) = 0$, для независимых $\P(A \mid B) = \P(A)$. Отсюда следствие: два события с ненулевыми вероятностями не бывают одновременно несовместными и независимыми.
Дерево гипотез и формула полной вероятности
Большинство задач темы двухступенчаты: сначала реализуется один из сценариев, потом внутри него происходит наблюдаемое событие.
Задача. Детали приходят с трёх линий: с первой $50\%$ всей партии, со второй $30\%$, с третьей $20\%$. Доля брака на линиях равна $1\%$, $2\%$ и $5\%$ соответственно. Какова доля брака во всей партии?
Сценарии называются гипотезами $H_1, H_2, H_3$. Требование к ним одно, и проверять его надо явно: гипотезы попарно несовместны и вместе покрывают всё $\Omega$. Здесь это так — деталь пришла ровно с одной линии.
| Ветка | Вес гипотезы | Правдоподобие брака | Произведение |
|---|
| линия 1 | 0.5 | 0.01 | 0.005 |
| линия 2 | 0.3 | 0.02 | 0.006 |
| линия 3 | 0.2 | 0.05 | 0.010 |
Вдоль ветки вероятности перемножаются — это цепное правило. Между ветками складываются — это несовместность гипотез. Значит доля брака равна $0.005 + 0.006 + 0.010 = 0.021$.
Формула полной вероятностиЕсли $H_1, \ldots, H_n$ попарно несовместны и покрывают всё $\Omega$, то для любого события $B$
$$\P(B) = \sum_{i=1}^{n} \P(B \mid H_i)\,\P(H_i)$$Разбей на непересекающиеся сценарии, в каждом посчитай вероятность наблюдения и сложи с весами сценариев. Две бесплатные проверки: сумма весов равна единице, а каждое произведение не больше своего веса.
Разворот условия: формула Байеса
Взятая наугад деталь оказалась бракованной. Какова вероятность, что она с третьей линии? Раньше мы шли от линии к браку, теперь идём от брака к линии — условие развернулось, а математика осталась прежней, работает то же определение:
$$\P(H_3 \mid D) = \frac{\P(H_3 \cap D)}{\P(D)} = \frac{0.010}{0.021} = \frac{10}{21} \approx 0.4762$$Формула Байеса$$\P(H_k \mid B) = \frac{\P(B \mid H_k)\,\P(H_k)}{\sum_i \P(B \mid H_i)\,\P(H_i)}$$Числитель — одна ветка дерева, знаменатель — сумма всех веток, ведущих к наблюдению. Заучивать формулу не нужно: если дерево нарисовано, она собирается за десять секунд.
Терминология из ML: $\P(H)$ — априорная вероятность, $\P(B \mid H)$ — правдоподобие, $\P(H \mid B)$ — апостериорная. Здесь априорная вероятность третьей линии была $0.2$, а после наблюдения выросла до $0.476$.
Проверка направления сдвигаРазделив формулу Байеса на $\P(H_k)$, получаем $\frac{\P(H_k \mid B)}{\P(H_k)} = \frac{\P(B \mid H_k)}{\P(B)}$: апостериорная вероятность растёт ровно у тех гипотез, при которых наблюдение вероятнее среднего. Здесь $0.05 > 0.021$, значит вероятность третьей линии обязана была вырасти; вышло иначе — ищи ошибку.
Поделив формулу Байеса для одной гипотезы на такую же для другой, знаменатель убираем совсем — он у них общий. Остаётся правило, которым две гипотезы считаются в уме.
Правило шансов$$\frac{\P(H_1 \mid B)}{\P(H_2 \mid B)} = \frac{\P(H_1)}{\P(H_2)} \cdot \frac{\P(B \mid H_1)}{\P(B \mid H_2)}$$Апостериорные шансы равны априорным, умноженным на отношение правдоподобий. На деталях: шансы «третья линия против первой» до опыта равны $0.2 : 0.5 = 2 : 5$, правдоподобия относятся как $0.05 : 0.01 = 5 : 1$, значит после наблюдения шансы стали $2 \cdot 5 : 5 \cdot 1 = 2 : 1$. Сходится с посчитанным: $\frac{10}{21}$ против $\frac{5}{21}$. Когда гипотез ровно две, шансы $a : b$ переводятся в вероятность как $\frac{a}{a + b}$, и знаменатель считать не нужно.
Ловушка базовой ставки
Условие. Заболевание встречается у $1\%$ населения. Тест выявляет болезнь у больного с вероятностью $95\%$ и с той же вероятностью даёт отрицательный результат у здорового. Человек получил положительный результат. Какова вероятность, что он болен? Назови число вслух, прежде чем читать дальше: большинство отвечает «около $90\%$».
Больных среди 10 000 человек ровно 100, тест находит 95 из них; здоровых 9900, и тест ошибочно даёт им «плюс» в $5\%$ случаев, то есть 495 раз.
| Тест «+» | Тест «−» | Всего |
|---|
| Больны | 95 | 5 | 100 |
| Здоровы | 495 | 9405 | 9900 |
| Всего | 590 | 9410 | 10000 |
В столбце «Тест +» стоят $95 + 495 = 590$ человек, и лишь 95 из них больны: $\P(\text{болен} \mid +) = \frac{95}{590} \approx 0.1610$. Шестнадцать процентов, не девяносто.
Почему такЗдоровых в сто раз больше, чем больных, и пять процентов ошибок на огромной группе дают больше срабатываний, чем девяносто пять процентов попаданий на крошечной: редкость события перевешивает качество теста. Это и есть ловушка базовой ставки.
Абсолютные числа вместо долей: рабочий режим дня
Половина официальных задач темы приходит таблицей долей. Для них есть три хода, и делать их надо именно в таком порядке.
- Перевести все доли в людей сразу, до того как понял, что спрашивают: умножить долю на размер своей группы.
- Достроить таблицу до конца — недостающие клетки получаются вычитанием из итога строки или столбца.
- Неизвестную долю восстановить из строки «всего» — это одно линейное уравнение.
Строка «всего» — это уравнение$$n_1 p_1 + n_2 p_2 + \cdots + n_k p_k = p\,N$$Слева — сдавшие по группам, справа — сдавшие по всей совокупности: это формула полной вероятности, записанная в людях. Если неизвестна ровно одна доля, уравнение решается в строку.
Пример. В компании 150 разработчиков и 100 сотрудников поддержки, других нет. Сертификат получили $64\%$ всех сотрудников, среди разработчиков — $70\%$. Какова доля сертифицированных в поддержке и какова вероятность, что случайный обладатель сертификата работает в поддержке?
Сертификатов всего $0.64 \cdot 250 = 160$, у разработчиков их $0.7 \cdot 150 = 105$. Значит в поддержке $160 - 105 = 55$, и доля там равна $\frac{55}{100} = 0.55$. Второй вопрос — условная вероятность, прочитанная из тех же двух чисел:
$$\P(\text{поддержка} \mid \text{сертификат}) = \frac{55}{160} = 0.34375 \approx 0.3438$$Почему в людях, а не в долях? Целые числа проверяются сложением: сумма по строке обязана дать размер группы, сумма по столбцу — итог. Ошибка в долях незаметна, ошибка в людях ломает итог.
Условие «хотя бы один»
Отдельный тип условия, на котором стоит самая трудная задача дня. Когда сказано «хотя бы один объект обладает свойством», дополнением считаются обе части дроби.
Пример. Бросили три монеты. Известно, что выпал хотя бы один орёл. Какова вероятность, что все три — орлы? Всего исходов 8, без орлов ровно один, значит знаменатель равен $8 - 1 = 7$. Числитель — один исход. Ответ $\frac17 \approx 0.1429$.
Адресное условие и условие существования«Первый», «старший», «красный», «названный по имени» — условие адресное: оно фиксирует конкретный объект. «Хотя бы один», «среди них есть» — условие существования: объект не назван. Это два разных множества оставшихся исходов, поэтому и ответы разные. Правила «чем адреснее, тем выше вероятность» не существует: условие «старший ребёнок — девочка» адреснее некуда, а вероятность «оба мальчики» падает при нём до нуля. Куда сдвинулся ответ, показывает только пересчёт. Поэтому любую подробность — день недели, цвет, имя — сначала вписывай в $\Omega$ и считай, и лишь потом смотри, что получилось.
Что должно остаться в голове
- Условие не добавляет вычислений, оно выбирает знаменатель.
- $\P(A \mid B) \ne \P(B \mid A)$. Помечай на полях, что дано, а что ищется, до начала счёта.
- Вдоль ветки умножаем условные вероятности, между несовместными ветками складываем.
- Полная вероятность — сумма всех веток, ведущих к наблюдению; сумма весов гипотез равна 1.
- Байес — одна ветка, делённая на эту сумму. Апостериорная растёт там, где правдоподобие выше среднего, а для двух гипотез быстрее правило шансов.
- При редком событии базовая ставка перевешивает качество теста.
- Таблица в целых людях надёжнее формулы, а строка «всего» — это уравнение.
ENOpening: one table, four questions
A class has 400 students. Their study format and exam result are summarized below:
| Passed | Failed | Total |
|---|
| Full-time | 210 | 90 | 300 |
| Part-time | 40 | 60 | 100 |
| Total | 250 | 150 | 400 |
Answer the four questions before reading on; each answer is one division.
- What is the probability that a random student passed?
- What is the probability that a student passed, given that they study full-time?
- What is the probability that a student studies full-time, given that they passed?
- What is the probability that a student is both full-time and a passer?
The answers are $\frac{250}{400}=0.625$, then $\frac{210}{300}=0.7$, then $\frac{210}{250}=0.84$, and $\frac{210}{400}=0.525$.
In the last three, the numerator is the same—210—and only the denominator changes: 300, 250, and 400. That is the whole topic: the word “given” does not add computation; it chooses the denominator.
The definition and what it really does
Conditional probability$$\P(A \mid B) = \frac{\P(A \cap B)}{\P(B)}, \qquad \P(B) > 0$$
Check on the table that the definition introduces nothing new. Let $A$ mean “passed” and $B$ mean “full-time.” Then $\P(A\cap B)=\frac{210}{400}$ and $\P(B)=\frac{300}{400}$, whose ratio is $\frac{210}{300}$: the common denominator 400 cancels. Hence a speed rule: when absolute counts are given, dividing by the population size is pointless—take the ratio of the two cells.
The same table shows why order matters: $\P(A\mid B)=0.7$, while $\P(B\mid A)=0.84$. With rare events, such pairs can differ by a factor of several, not a few percentage points.
What goes to the right of the barAs you read a condition, mark two things in the margin: what is given (on the right) and what is being asked (on the left). Signals for the given condition include “it is known that,” “given that,” “it turned out that,” and “it was found that.” Also watch for sampling language: “choose a student from among those who failed” is the same condition expressed differently.
Multiplying along a branch
Rearranging the definition gives a working rule for sequential experiments:
$$\P(A \cap B) = \P(B) \cdot \P(A \mid B)$$For a three-step chain, each conditional factor accumulates everything that happened earlier:
$$\P(A_1 \cap A_2 \cap A_3) = \P(A_1) \cdot \P(A_2 \mid A_1) \cdot \P(A_3 \mid A_1 \cap A_2)$$Example. Draw three cards without replacement from a 36-card deck. What is the probability that all three are aces?
$$\P = \frac{4}{36} \cdot \frac{3}{35} \cdot \frac{2}{34} = \frac{1}{1785} \approx 0.00056$$The classical definition gives the same result: $\frac{\binom{4}{3}}{\binom{36}{3}}=\frac{4}{7140}=\frac{1}{1785}$. Two independent routes to one number are the cheapest possible check, and they work almost everywhere today.
Where independence fits
Divide yesterday’s identity $\P(A\cap B)=\P(A)\,\P(B)$ by $\P(B)$ to get the practical reading $\P(A\mid B)=\P(A)$: independence means the condition tells you nothing.
Independence versus disjointnessFor disjoint events, $\P(A\mid B)=0$; for independent events, $\P(A\mid B)=\P(A)$. Consequently, two events with nonzero probabilities cannot be disjoint and independent at the same time.
Hypothesis trees and total probability
Most problems in this topic have two stages: first one scenario occurs, then an observed event happens within it.
Problem. Parts come from three production lines: 50% of the entire batch from line 1, 30% from line 2, and 20% from line 3. The defect rates are 1%, 2%, and 5%, respectively. What fraction of the whole batch is defective?
Call the scenarios hypotheses $H_1,H_2,H_3$. There is one requirement, which must be checked explicitly: the hypotheses are pairwise disjoint and together cover all of $\Omega$. Here a part came from exactly one line, so this holds.
| Branch | Hypothesis weight | Defect likelihood | Product |
|---|
| line 1 | 0.5 | 0.01 | 0.005 |
| line 2 | 0.3 | 0.02 | 0.006 |
| line 3 | 0.2 | 0.05 | 0.010 |
Probabilities multiply along a branch—the chain rule. They add across branches because the hypotheses are disjoint. The defect fraction is therefore $0.005+0.006+0.010=0.021$.
Law of total probabilityIf $H_1,\ldots,H_n$ are pairwise disjoint and cover $\Omega$, then for any event $B$
$$\P(B) = \sum_{i=1}^{n} \P(B \mid H_i)\,\P(H_i)$$Split into disjoint scenarios, compute the observation probability inside each, then add with the scenario weights. Two free checks: the weights sum to one, and each product is no larger than its weight.
Reversing the condition: Bayes’ rule
A randomly selected part turned out to be defective. What is the probability that it came from line 3? Before, we moved from line to defect; now we move from defect to line. The condition is reversed, but the mathematics is unchanged:
$$\P(H_3 \mid D) = \frac{\P(H_3 \cap D)}{\P(D)} = \frac{0.010}{0.021} = \frac{10}{21} \approx 0.4762$$Bayes’ rule$$\P(H_k \mid B) = \frac{\P(B \mid H_k)\,\P(H_k)}{\sum_i \P(B \mid H_i)\,\P(H_i)}$$The numerator is one branch of the tree; the denominator is the sum of all branches leading to the observation. Do not memorize the formula: if the tree is drawn, assemble it in ten seconds.
ML terminology: $\P(H)$ is the prior, $\P(B\mid H)$ is the likelihood, and $\P(H\mid B)$ is the posterior. The prior probability of line 3 was $0.2$; after observing a defect it rose to $0.476$.
Check the direction of the shiftDivide Bayes’ rule by $\P(H_k)$ to get $\frac{\P(H_k\mid B)}{\P(H_k)}=\frac{\P(B\mid H_k)}{\P(B)}$: the posterior grows exactly for hypotheses where the observation is more likely than average. Here $0.05>0.021$, so the probability of line 3 had to rise. If it moved the other way, look for an error.
Dividing Bayes’ rule for one hypothesis by the corresponding rule for another cancels the common denominator. The result is a mental shortcut for two hypotheses.
Odds form$$\frac{\P(H_1 \mid B)}{\P(H_2 \mid B)} = \frac{\P(H_1)}{\P(H_2)} \cdot \frac{\P(B \mid H_1)}{\P(B \mid H_2)}$$Posterior odds equal prior odds multiplied by the likelihood ratio. For the parts, the odds “line 3 versus line 1” before observing are $0.2:0.5=2:5$, while the likelihoods are in the ratio $0.05:0.01=5:1$. Afterwards the odds are $2\cdot5:5\cdot1=2:1$, matching $\frac{10}{21}$ versus $\frac{5}{21}$. With exactly two hypotheses, odds $a:b$ convert to probability as $\frac{a}{a+b}$; no denominator tree is needed.
The base-rate trap
Condition. A disease affects 1% of the population. A test detects it in a sick person with probability 95% and gives a negative result to a healthy person with the same probability. Someone tests positive. What is the probability they are sick? Say a number aloud before reading on: most people answer “about 90%.”
Among 10,000 people, exactly 100 are sick and the test finds 95 of them. There are 9,900 healthy people, and a false positive occurs for 5% of them, or 495 people.
| Test “+” | Test “−” | Total |
|---|
| Sick | 95 | 5 | 100 |
| Healthy | 495 | 9405 | 9900 |
| Total | 590 | 9410 | 10000 |
The “+” column contains $95+495=590$ people, only 95 of whom are sick: $\P(\text{sick}\mid +)=\frac{95}{590}\approx0.1610$. Sixteen percent, not ninety.
WhyHealthy people outnumber sick people by a hundred to one. Five percent false positives in the huge group produce more positive tests than 95% true positives in the tiny group. The rarity of the event outweighs the test’s quality: this is the base-rate trap.
Absolute counts instead of proportions: today’s working mode
Half of the official problems in this topic arrive as a table of proportions. Use three moves, in this order.
- Convert every proportion to people immediately, before deciding what the question asks: multiply the proportion by its group size.
- Complete the table—missing cells come from subtracting a row or column total.
- Recover an unknown proportion from the “total” row—this is one linear equation.
The “total” row is an equation$$n_1p_1+n_2p_2+\cdots+n_kp_k=pN$$The left side is the number of passes in each group; the right side is the number of passes in the entire population. This is the law of total probability written in people. If exactly one proportion is unknown, the equation is one line.
Example. A company has 150 developers and 100 support staff, and no one else. Sixty-four percent of all employees hold a certificate; 70% of developers do. What fraction of support staff are certified, and what is the probability that a randomly selected certificate holder works in support?
There are $0.64\cdot250=160$ certificates in all, and $0.7\cdot150=105$ among developers. Support therefore has $160-105=55$, a fraction $\frac{55}{100}=0.55$. The second question is a conditional probability read from the same two counts:
$$\P(\text{support}\mid\text{certificate})=\frac{55}{160}=0.34375\approx0.3438$$Why people rather than proportions? Integers are checked by addition: row totals must equal group sizes and column totals must equal the overall totals. A proportion error can hide; a people-count error breaks the totals.
The condition “at least one”
This special condition underlies the hardest problem of the day. When it says “at least one object has the property,” take the complement in both parts of the fraction.
Example. Toss three coins. It is known that at least one head occurred. What is the probability that all three are heads? There are 8 outcomes; exactly one has no heads, so the denominator is $8-1=7$. The numerator is one outcome. The answer is $\frac17\approx0.1429$.
Address-specific versus existence conditions“The first,” “the oldest,” “the red one,” and “the object named by name” are address-specific: they identify a particular object. “At least one” and “there is one among them” are existence conditions: no object is named. These leave different sets of outcomes, so their answers differ. There is no rule that “the more specific the condition, the higher the probability.” “The oldest child is a girl” is as specific as possible, yet under it the probability that both children are boys drops to zero. Only a recount shows which way the answer moved. Put every detail—day of the week, color, name—into $\Omega$ first, count, and only then interpret the result.
What should stay with you
- A condition does not add computation; it chooses the denominator.
- $\P(A\mid B)\ne\P(B\mid A)$. Mark what is given and what is asked before you calculate.
- Multiply conditional probabilities along a branch; add across disjoint branches.
- Total probability is the sum of all branches leading to the observation; hypothesis weights sum to 1.
- Bayes is one branch divided by that sum. The posterior grows where the likelihood is above average; with two hypotheses, odds are faster.
- When the event is rare, the base rate can outweigh test quality.
- A table in whole people is safer than a table of proportions, and the “total” row is an equation.