Optional
Sensor: probability and prefix completion
Fit a Markov model to synthetic records. Check normalization, bits per symbol and completion of a given prefix. No downloads or third-party libraries.
- Version
- v2
- Minutes
- ~20
- Evidence
- Self-check in the notebook
Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.
Download the notebook and run it locally. Its environment requirements are listed inside.
Notebook contents
Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.
A sensor model: probability and prefix completion / Модель датчика
Activity version / версия: 2. Python standard library only, no downloads. Только стандартная библиотека Python, без скачиваний.
Fit a three-parameter first-order Markov model to synthetic 12-step binary records. Check a small chain by exact enumeration, then fit transitions, measure held-out bits per symbol and sample continuations. This optional notebook does not gate topic mastery or certificates.
Обучим марковскую модель первого порядка с тремя параметрами на синтетических бинарных записях по 12 шагов. Сначала проверим маленькую цепочку точным перебором, затем оценим переходы, биты на символ на отложенных данных и продолжения. Ноутбук необязателен и не влияет на освоение или сертификаты.
Origin / происхождение. The synthetic model, code and observations were authored for Fedor Pakhurov's project with Codex assistance. The fitted sensor experiment below embeds the reviewed FP function from generative-practice.py at 67f4698. The English note and Russian note explain the scientific context. The three-step rational example, explanations and structural-mask checks here are new additions. The FP assertion that this default fixture beats one bit per symbol is relaxed to positive bits per symbol so that changing the generator remains a valid experiment. No external data, weights, images or notebook outputs are imported.
Данные, код и результаты подготовлены для проекта Фёдора Пахурова с помощью Codex. Функция эксперимента с датчиком взята из проверенной ревизии FP по ссылке. Проверка выигрыша над одним битом заменена на положительное значение bpd, чтобы можно было менять генератор; здесь добавлены трёхшаговый пример с точными дробями, пояснения и проверка путей маски. Чужих данных, весов, изображений или результатов ноутбуков нет.
1. Multiply the right branches / Выбрать правильные ветви
Let p(x1=1)=0.4. The second-one probability is 0.2 after zero and 0.7 after one; the third-one probability is 0.1 after zero and 0.8 after one. A zero outcome uses the complement. Enumerate the eight records with exact rational arithmetic.
Пусть p(x1=1)=0.4. Вероятность второй единицы — 0.2 после нуля и 0.7 после единицы; вероятность третьей — 0.1 после нуля и 0.8 после единицы. Нулевой исход использует дополнение. Переберём восемь записей с точными дробями.
Predict the most likely record before running. Why does summing the last conditional remove that factor? / До запуска предположите, какая запись наиболее вероятна. Почему сумма по последнему условному распределению убирает его множитель?
from fractions import Fraction
import itertools
import math
def toy_probability(row):
x1, x2, x3 = row
one_probabilities = [Fraction(2, 5),
Fraction(7, 10) if x1 else Fraction(1, 5),
Fraction(4, 5) if x2 else Fraction(1, 10)]
factors = [p if x else 1 - p for x, p in zip(row, one_probabilities)]
probability = math.prod(factors)
assert math.isclose(math.log(float(probability)),
sum(math.log(float(p)) for p in factors), abs_tol=1e-12)
return probability
records = list(itertools.product((0, 1), repeat=3))
for row in records:
print(''.join(map(str, row)), f'{float(toy_probability(row)):.3f}')
mass = sum(toy_probability(row) for row in records)
assert mass == 1
print('exact probability mass:', mass)2. Fit, then evaluate separate records / Обучение и отложенные записи
Generator: 12 binary values, a uniform initial state and a switch probability of 0.17. Seed 9305 generates 2048 training records followed by 256 held-out records. Only training counts fit the initial probability and two shared transition probabilities. They are estimated separately even though the generator switches symmetrically.
Генератор: 12 бинарных значений, равномерное начальное состояние и вероятность смены состояния 0.17. Seed 9305 создаёт 2048 обучающих, затем 256 отложенных записей. Начальная вероятность и два общих перехода оцениваются только по обучающим данным. Переходы оцениваются отдельно, хотя генератор переключается симметрично.
Each pair of counts starts at [1,1]: add-one smoothing keeps unseen outcomes possible. Evaluation divides negative log2 probability by 12 and averages over held-out records. The uniform binary baseline is exactly one bit per symbol. Enumerating all 4096 possible records checks normalization independently of the training sample.
Каждая пара счётчиков начинается с [1,1]: добавление единицы сохраняет возможность ненаблюдённых исходов. При оценке делим отрицательный log2 вероятности на 12 и усредняем по отложенным записям. Равномерный baseline — ровно один бит на символ. Перебор 4096 возможных записей проверяет нормировку независимо от обучающей выборки.
The three continuations keep prefix [1,0,0]. Generation uses fitted probabilities; it never reads the held-out future. / Три продолжения сохраняют префикс [1,0,0]. Генерация использует обученные вероятности и не читает будущее отложенной записи.
import json
import random
import statistics
def autoregressive_models():
rng = random.Random(9305)
length = 12
def sample():
row = [rng.randrange(2)]
for _ in range(length - 1):
row.append(row[-1] ^ int(rng.random() < 0.17))
return row
training = [sample() for _ in range(2048)]
held_out = [sample() for _ in range(256)]
initial = [1, 1]
transitions = [[1, 1], [1, 1]]
for row in training:
initial[row[0]] += 1
for before, after in zip(row, row[1:]):
transitions[before][after] += 1
first = [x / sum(initial) for x in initial]
conditional = [[x / sum(row) for x in row] for row in transitions]
def complete(prefix, generator):
row = list(prefix)
if not row:
row.append(int(generator.random() < first[1]))
while len(row) < length:
row.append(int(generator.random() < conditional[row[-1]][1]))
return row
def probability(row):
p = first[row[0]]
for before, after in zip(row, row[1:]):
p *= conditional[before][after]
return p
mass = sum(probability(row) for row in itertools.product((0, 1), repeat=length))
bits = -statistics.mean(math.log2(probability(row)) / length for row in held_out)
generated = [complete([1, 0, 0], random.Random(9410 + i)) for i in range(3)]
assert abs(mass - 1) < 1e-12 and bits > 0
assert all(row[:3] == [1, 0, 0] and len(row) == length for row in generated)
return {'sequence_length': length, 'training_sequences': len(training),
'held_out_sequences': len(held_out), 'initial_probabilities': first,
'transition_probabilities': conditional, 'enumerated_probability_mass': mass,
'held_out_bits_per_symbol': bits, 'uniform_bits_per_symbol': 1,
'conditional_completions': generated,
'scope': 'A fitted binary Markov model with causal prefix sampling; no PixelCNN or poster corpus.'}
def rounded(value):
if isinstance(value, float):
return round(value, 12)
if isinstance(value, list):
return [rounded(item) for item in value]
if isinstance(value, dict):
return {key: rounded(item) for key, item in value.items()}
return value
sensor_result = autoregressive_models()
print(json.dumps(rounded(sensor_result), indent=2))3. Check the paths, not trained weights / Проверить пути, а не обученные веса
A first 3×3 A mask allows offsets (-1,-1), (-1,0), (-1,1), (0,-1). Later B masks additionally allow (0,0). Compose the offsets to find every structurally reachable input. These are potential paths: trained weights could remove a dependency by cancellation, but cannot create a forbidden path. This is not a neural-network training experiment.
Первая маска A 3×3 разрешает сдвиги (-1,-1), (-1,0), (-1,1), (0,-1). Последующие B также разрешают (0,0). Сложим сдвиги, чтобы найти все структурно доступные входы. Это потенциальные пути: обученные веса могут убрать зависимость из-за сокращения, но не создадут запрещённый путь. Это не эксперимент по обучению нейросети.
Inspect the four-layer grid before running. A 1 marks a reachable input; the last printed row is the output's own row. / Перед запуском рассмотрите сетку четырёх слоёв. 1 отмечает доступный вход; последняя напечатанная строка совпадает со строкой выхода.
def receptive_field(layers):
assert layers >= 1
mask_a = {(-1, -1), (-1, 0), (-1, 1), (0, -1)}
mask_b = mask_a | {(0, 0)}
reachable = set(mask_a)
for _ in range(layers - 1):
reachable = {(r + dr, c + dc)
for r, c in reachable for dr, dc in mask_b}
assert all(r < 0 or (r == 0 and c < 0) for r, c in reachable)
return reachable
field = receptive_field(4)
for r in range(-4, 1):
print(' '.join(str(int((r, c) in field)) for c in range(-4, 5)))
missing = sum((r, c) not in field for r in range(-4, 0) for c in range(-4, 5))
assert missing == 6
print('missing earlier inputs in the upper rectangle:', missing)
print('current or future raw inputs reachable:', any(r > 0 or (r == 0 and c >= 0) for r, c in field))
assert sensor_result['held_out_bits_per_symbol'] > 0
assert all(row[:3] == [1, 0, 0] for row in sensor_result['conditional_completions'])
print('sensor normalization, held-out evaluation and prefix checks passed')Explore / Попробовать
-
Change the generator's switch probability to 0.5 and rerun. Explain why the advantage over the uniform baseline should shrink; a finite held-out sample may fluctuate around its expected value. Change one assumption at a time.
-
Change only the completion prefix. What stays fixed in the fitted model, and what changes in the first continuation step?
-
Change the number of mask layers. Count missing earlier pixels inside the matching upper rectangle; do not confuse them with forbidden future pixels.
-
Измените вероятность переключения генератора на 0.5 и перезапустите. Объясните, почему преимущество перед равномерным baseline должно уменьшиться; конечная отложенная выборка может колебаться вокруг ожидаемого значения. Меняйте по одному условию.
-
Измените только префикс продолжения. Что остаётся фиксированным в обученной модели, а что меняется на первом шаге продолжения?
-
Измените число слоёв маски. Посчитайте пропущенные ранние пиксели внутри соответствующего верхнего прямоугольника, не смешивая их с запрещённым будущим.
Limits / ограничения. These saved results belong to a synthetic first-order baseline, not to PixelCNN, image synthesis or a physical sensor dataset. The smoothing convention, sequence length and generator are explicit choices for this exercise. They do not establish performance on other data.
Сохранённые результаты относятся к синтетической модели первого порядка, а не к PixelCNN, генерации изображений или данным физического датчика. Сглаживание, длина записи и генератор — условия упражнения. Они не устанавливают качество на других данных.