Optional
Reproduce the count-based model
Inspect the full fictional inputs, rerun the standard-library calculations, and check the stated invariants. Optional desktop practice.
- Version
- v2
- Minutes
- ~15
- 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.
Bag of words / Мешок слов
Optional practice. The lesson and its phone questions are complete without running code. / Необязательная практика: урок и задания на телефоне самостоятельны.
All inputs and calculations were authored for the Fedor Pakhurov project with Codex assistance. The example is fictional and contains no external corpus, model, or copied third-party implementation. Selected first-party functions are retained from the published reviewed fixture. This notebook adds packaging and explicit self-checks; it does not claim operational quality.
Все входы вымышлены; расчёты созданы для проекта Фёдора Пахурова с помощью Codex. Внешних корпусов, моделей и сторонних реализаций здесь нет. Функции взяты из указанной опубликованной проверенной версии; добавлены оформление и самопроверки.
Saved outputs use Python 3.9.7; standard library only, no network or file writes. Floating last digits and Unicode database values can differ across runtimes. / Сохранённый запуск: Python 3.9.7, только стандартная библиотека, без сети и записи файлов. Последние разряды и версия Unicode могут зависеть от среды.
import json
import math
import re
import unicodedata
from collections import Counter
from fractions import Fraction
def bag_of_words():
documents = ["desk lamp lamp pickup", "desk lamp return", "desk tripod return", "desk tripod tripod pickup"]
vocabulary = sorted({word for document in documents for word in document.split()})
counts = [[document.split().count(word) for word in vocabulary] for document in documents]
df = [sum(row[column] > 0 for row in counts) for column in range(len(vocabulary))]
idf = [1 + math.log((1 + len(documents)) / (1 + frequency)) for frequency in df]
raw = [[count * weight for count, weight in zip(row, idf)] for row in counts]
def normalized(row):
norm = math.sqrt(sum(value * value for value in row))
return [value / norm for value in row] if norm else [0.0] * len(row)
vectors = [normalized(row) for row in raw]
query = "lamp pickup"
query_counts = [query.split().count(word) for word in vocabulary]
query_vector = normalized([count * weight for count, weight in zip(query_counts, idf)])
cosine = [sum(a * b for a, b in zip(row, query_vector)) for row in vectors]
order = sorted(range(4), key=lambda index: (-cosine[index], index))
assert vocabulary == ["desk", "lamp", "pickup", "return", "tripod"]
assert df == [4, 2, 2, 2, 2]
assert order == [0, 1, 3, 2]
doubled = normalized([2 * value for value in raw[0]])
assert all(math.isclose(a, b) for a, b in zip(doubled, vectors[0]))
permutation_a = Counter("lamp before tripod".split())
permutation_b = Counter("tripod before lamp".split())
assert permutation_a == permutation_b
unknown = ["calendar".split().count(word) for word in vocabulary]
assert normalized(unknown) == [0.0] * len(vocabulary)
# A hand-specified linear score illustrates inference, not fitted performance.
coefficients = [0, 0, -1, 2, 0]
logits = [-0.5 + sum(x * w for x, w in zip(row, coefficients)) for row in counts]
labels = [0, 1, 1, 0]
def objective(parameters):
value = 0.0
for row, label in zip(vectors, labels):
z = parameters[0] + sum(a * b for a, b in zip(row, parameters[1:]))
value += math.log1p(math.exp(z)) - label * z
return value / len(labels) + 0.1 * sum(w * w for w in parameters[1:]) / 2
def gradient(parameters):
result = [0.0] + [0.1 * w for w in parameters[1:]]
for row, label in zip(vectors, labels):
z = parameters[0] + sum(a * b for a, b in zip(row, parameters[1:]))
error = 1 / (1 + math.exp(-z)) - label
for j, value in enumerate([1.0, *row]):
result[j] += error * value / len(labels)
return result
parameters = [0.0] * (len(vocabulary) + 1)
start_objective = objective(parameters)
for _ in range(400):
parameters = [w - 0.2 * g for w, g in zip(parameters, gradient(parameters))]
epsilon = 1e-5
for j, analytic in enumerate(gradient(parameters)):
plus, minus = parameters.copy(), parameters.copy()
plus[j] += epsilon
minus[j] -= epsilon
numerical = (objective(plus) - objective(minus)) / (2 * epsilon)
assert math.isclose(numerical, analytic, abs_tol=1e-9)
probabilities = [1 / (1 + math.exp(-(parameters[0] + sum(a * b for a, b in zip(row, parameters[1:])))))
for row in vectors]
assert objective(parameters) < start_objective
assert [int(p >= 0.5) for p in probabilities] == labels
return {"documents": documents, "vocabulary": vocabulary, "counts": counts,
"document_frequencies": df, "idf": idf, "tfidf_raw": raw,
"tfidf_l2": vectors, "query": query, "query_l2": query_vector,
"cosines": cosine, "ranked_document_ids": [index + 1 for index in order],
"hand_set_logits": logits, "zero_vector_unknown_query": normalized(unknown),
"nonzero_count": sum(value != 0 for row in counts for value in row),
"training_only_logistic": {"labels": labels, "steps": 400, "learning_rate": 0.2,
"l2": 0.1, "initial_objective": start_objective,
"final_objective": objective(parameters),
"bias_and_weights": parameters, "training_probabilities": probabilities}}
result = bag_of_words()
print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
assert result['ranked_document_ids'] == [1, 2, 4, 3]
assert result['nonzero_count'] == 12
fit = result['training_only_logistic']
assert fit['final_objective'] < fit['initial_objective']
assert [int(p >= .5) for p in fit['training_probabilities']] == fit['labels']
print('All local checks passed; this is a constructed example, not a benchmark.')