"""Show one gradient step and the mathematical ideas behind it."""
from json import dumps
from math import exp, isclose, log, prod, sqrt
from platform import python_version
from statistics import fmean, pvariance
FEATURE = (2.0, -1.0)
TARGET = 1
def dot(left, right):
return sum(a * b for a, b in zip(left, right, strict=True))
def sigmoid(value):
if value >= 0:
return 1 / (1 + exp(-value))
scaled = exp(value)
return scaled / (1 + scaled)
def predict(weights):
return sigmoid(dot(weights, FEATURE))
def loss(weights):
return -log(predict(weights))
def update(weights, rate):
gradient = tuple((predict(weights) - TARGET) * item for item in FEATURE)
return tuple(value - rate * slope for value, slope in zip(weights, gradient, strict=True))
def softmax(scores):
largest = max(scores)
powers = [exp(score - largest) for score in scores]
return [power / sum(powers) for power in powers]
def normalize(values, epsilon=1e-5):
center, scale = fmean(values), sqrt(pvariance(values) + epsilon)
return [(value - center) / scale for value in values]
def run():
cases = []
def check(name, inputs, expected, actual):
if actual != expected:
raise AssertionError(f"{name}: expected {expected!r}, observed {actual!r}")
cases.append(dict(name=name, input=inputs, expected=expected, actual=actual, passed=True))
check("dot_forms_a_score", dict(x=FEATURE, w=[0.25, 0.5]), 0.0, dot((0.25, 0.5), FEATURE))
weights = (0.0, 0.0)
check("score_probability_and_cross_entropy", dict(weights=weights, label=TARGET), [0.5, 0.693147],
[predict(weights), round(loss(weights), 6)])
estimate = (loss((0.000001, 0)) - loss((-0.000001, 0))) / 0.000002
check("calculus_matches_numerical_difference", "central difference at the origin",
-1.0, round(estimate, 6))
after = update(weights, 0.4)
check("linear_classifier_loss_decreases", dict(weights=weights, rate=0.4), [[0.4, -0.2], 0.731059, 0.313262],
[list(after), round(predict(after), 6), round(loss(after), 6)])
check("learning_rate_can_overshoot", "gradient step on (x-3)^2, starting at 0", [5.76, 81.0],
[round((0 - rate * 2 * (0 - 3) - 3) ** 2, 2) for rate in (0.1, 2)])
check("chain_products_can_shrink_or_grow", dict(depth=8, local_derivatives=[0.5, 2]),
[0.00390625, 256], [prod([slope] * 8) for slope in (0.5, 2)])
probabilities = softmax([1000, 1001, 1003])
check("softmax_defines_distribution", [1000, 1001, 1003], [True, True, True],
[isclose(sum(probabilities), 1.0), max(probabilities) == probabilities[2],
all(isclose(a, b) for a, b in zip(probabilities, softmax([0, 1, 3]), strict=True))])
normalized = normalize([1.0, 2.0, 6.0])
check("layer_normalization_rescales_features", [1.0, 2.0, 6.0], [True, True, True],
[isclose(fmean(normalized), 0, abs_tol=1e-12), isclose(pvariance(normalized), 1, abs_tol=3e-6),
not isclose(sum(normalized), 1)])
return dict(version=python_version(), cases=cases)
if __name__ == "__main__":
print(dumps(run()))
本例需在 Windows、Python 3.12.14,只用标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14,只用标准库。
入口文件:projects/ai-math-intro-lab/one-gradient-step.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
one-gradient-step.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14,只用标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a63.zip