蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行数值和符号参考的独立检查

PYTHONWindows、Python 3.12.14、标准库。notation-lab.py
notation-lab.py136 行
"""Run independent numerical and logical examples for the notation reference."""
from fractions import Fraction as F
import json
from math import cos, e, exp, factorial, inf, isclose, log, log2, pi, prod, sin, sqrt
from platform import python_version
from statistics import fmean, pvariance


def dot(left, right):
    return sum(a * b for a, b in zip(left, right, strict=True))


def softmax(scores):
    offset = max(scores)
    weights = [exp(score - offset) for score in scores]
    return [w / sum(weights) for w in weights]


def run():
    cases = []

    def check(name, inputs, expected, actual):
        if expected != actual:
            raise AssertionError(f"{name}: expected {expected!r}, got {actual!r}")
        cases.append(dict(name=name, input=inputs, expected=expected, actual=actual, passed=True))

    check("operations_precedence", [2, 6, 3], [8, -4, 18, 2, 20], [2+6, 2-6, 6*3, 6/3, 2+6*3])
    check("sign_absolute_and_order", [-3, 0, 3], [[-3, 3], 3, True, False, True],
          [sorted({3, -3}), abs(-3), -3 < 0 < 3, 0 != 0, 0 <= 0 <= 3])
    check("pi_and_e_are_approximations", "explicit absolute tolerances", [True, False, True],
          [isclose(pi, 3.142, abs_tol=0.001), pi == 3.142, isclose(e, 2.71828, abs_tol=0.00001)])
    check("root_power_and_factorial_branches", [49, -27, 5, 0], [7, -3, 125, 1, "1/5", 120, 1],
          [sqrt(49), -round(27 ** (1/3)), 5**3, 5**0, str(F(5)**-1), factorial(5), factorial(0)])
    check("reciprocal_grows_along_positive_path", [1, 0.1, 0.01], [1, 10, 100, True],
          [int(1/x) for x in (1,0.1,0.01)] + [inf > 100])
    direct = log(32, 2)
    check("log_change_of_base", [32, 2], [5.0, 5.0, 5.0, 1.0],
          [direct, log(32)/log(2), log2(32), log(e)])
    check("product_quotient_powers_in_logs", {"m": 8, "n": 2, "base": 2}, [True]*4,
          [log2(8*2) == log2(8)+log2(2), log2(8/2) == log2(8)-log2(2),
           log2(8**2) == 2*log2(8), 2**3 * 2**4 == 2**(3+4)])
    errors = []
    for call in (lambda: log(0), lambda: log(-2), lambda: log(5, 1)):
        try:
            call()
        except (ValueError, ZeroDivisionError) as exc:
            errors.append(type(exc).__name__)
    check("log_domain_and_epsilon", [0, -2, "base 1", "floor at 1e-8"], [3, True, True],
          [len(errors), log(max(0.0, 1e-8)) < 0, exp(0) == 1])
    f = lambda value: 3 * value - 1
    g = lambda value: value ** 2
    inv = lambda value: (value + 1) / 3
    check("compose_inner_first_and_check_inverse", 2, [11, 25, 2, 3],
          [f(g(2)), g(f(2)), inv(f(2)), 5-2])
    scores = [-30, 0, 30]
    probabilities = [1/(1+exp(-s)) for s in scores]
    check("sigmoid_and_probability_bounds", scores, [True, 0.5, True, True],
          [0 < probabilities[0], probabilities[1], probabilities[2] < 1,
           1/(1+exp(-1000)) == 1])
    values = (2, 4, 6)
    check("sum_product_and_empty_ranges", values, [12, 48, 0, 1, 6],
          [sum(values), prod(values), sum([]), prod([]), values[2]])
    weights, features = (F(2), F(-3), F(1, 2)), (F(1), F(1, 2), F(2))
    bias = F(1, 4)
    weighted = dot(weights, features) + bias
    check("weighted_sum_source_goal", dict(weights=list(map(str, weights)), features=list(map(str, features)), bias=str(bias)),
          ["7/4", True], [str(weighted), weighted == 2*1 - 3*F(1,2) + F(1,2)*2 + F(1,4)])
    check("mse_is_mean_of_squared_errors", {"label":[1, 4], "predict":[2, 2]}, 2.5, fmean([(1-2)**2, (4-2)**2]))
    a, b = {0,2}, {1,2}
    check("set_relations_and_boolean_connectives", [sorted(a), sorted(b)], [[0,1,2],[2],True,False,True,True,True,False],
          [sorted(a|b), sorted(a&b), {2}<a, a<b, 0 in a, 1 not in a, not (a&{5}), a==b])
    flags = [(False,False),(False,True),(True,False),(True,True)]
    check("quantifiers_and_implication_truth_table", "finite domain and four boolean assignments",
          [True, True, False, True, [True,True,False,True], [True,False,False,True], [False,True,True,True], [False,False,False,True]],
          [all(x % 2 == 0 for x in a), any(x == 2 for x in b), any([]), all([]),
           [not p or q for p,q in flags], [p==q for p,q in flags], [p or q for p,q in flags], [p and q for p,q in flags]])
    check("open_closed_and_half_open_endpoints", [0, 0.5, 1], [[False,True,False],[True,True,True],[False,True,True]],
          [[predicate(x) for x in (0,0.5,1)] for predicate in (
              lambda x: 0 < x < 1, lambda x: 0 <= x <= 1, lambda x: 0 < x <= 1)])
    data = [[2,3,4],[5,6,7]]
    check("vector_matrix_indices_and_shape", [1,2], [[2,3], 4, [2,5]],
          [[len(data), len(data[0])], data[1-1][3-1], [row[0] for row in data]])
    sample = ["A","AB","B","neither"]
    intersection = sum(label=="AB" for label in sample)
    event_a = sum("A" == label or label == "AB" for label in sample)
    event_b = sum("B" == label or label == "AB" for label in sample)
    n = len(sample)
    check("joint_conditional_and_bayes", sample, ["1/2","1/4","1/2","1/2"],
          list(map(str, (F(event_a,n), F(intersection,n), F(intersection,event_b),
             F(intersection,event_a)*F(event_a,n)/F(event_b,n)))))
    check("expectation_variance_and_entropy", [0,1,1,2], [1,0.5,1,0,6.0],
          [fmean([0,1,1,2]),pvariance([0,1,1,2]),sum(-p*log2(p) for p in (0.5,0.5) if p),
           sum(-p*log2(p) for p in (0,1) if p), sqrt(36)])
    check("binary_cross_entropy_checks_both_labels", {"positive":0.75}, [0.287682,1.386294],
          [round(-(label*log(0.75)+(1-label)*log(0.25)),6) for label in (1,0)])
    m, k = ((1,2),(3,4)), ((2,0),(1,3))
    product = [[dot(row,col) for col in zip(*k)] for row in m]
    elementwise = [[x*y for x,y in zip(row,other)] for row,other in zip(m,k)]
    transposed = [list(col) for col in zip(*m)]
    check("matmul_hadamard_transpose_and_identity", [m,k], [[[4,6],[10,12]],[[2,0],[3,12]],[[1,3],[2,4]],m],
          [product,elementwise,transposed,tuple(tuple(dot(row,col) for col in ((1,0),(0,1))) for row in m)])
    determinant = m[0][0]*m[1][1]-m[0][1]*m[1][0]
    inverse = ((F(4,determinant), F(-2,determinant)), (F(-3,determinant), F(1,determinant)))
    check("inverse_requires_nonzero_determinant", m, [-2, [["1","0"],["0","1"]], 0],
          [determinant, [[str(dot(row,col)) for col in zip(*inverse)] for row in m], 4*1-2*2])
    x, y = [3,-4,0], [1,2,9]
    check("dot_l2_and_l1_source_goal", [x,y], [-5,5.0,7],
          [dot(x,y),sqrt(dot(x,x)),sum(abs(v) for v in x)])
    eps = 1e-6
    derivative = (sin(1+eps)-sin(1-eps))/(2*eps)
    func = lambda x,y: x*x + 3*x*y
    partial_x = (func(2+eps,1)-func(2-eps,1))/(2*eps)
    partial_y = (func(2,1+eps)-func(2,1-eps))/(2*eps)
    check("derivative_partial_gradient_and_step", [2, 1, 0.1], [True,[7,6],[1.3,0.4]],
          [isclose(derivative,cos(1),rel_tol=1e-8),[round(partial_x),round(partial_y)],
           [round(2-0.1*partial_x,6),round(1-0.1*partial_y,6)]])
    rectangles = sum((i+0.5)/100 for i in range(100))/100
    check("riemann_sum_and_small_angle_limit", "100 midpoint rectangles; radians",
          [0.5, True, True], [round(rectangles,12),isclose(sin(1e-6)/1e-6,1),sin(0)==0])
    choices = {0:5,1:-1,2:5,3:-1}
    check("arg_extrema_distinguish_values_and_ties", choices, [[0,2],[1,3],5,-1],
          [[key for key in choices if choices[key]==max(choices.values())],
           [key for key in choices if choices[key]==min(choices.values())],max(choices.values()),min(choices.values())])
    dist = softmax([999,1000,1003])
    check("softmax_proportionality_and_relu", [999,1000,1003],
          [True, 2, True, [0,0,3]], [isclose(sum(dist),1),max(range(len(dist)),key=dist.__getitem__),
           isclose(dist[2]/dist[0],exp(4)),[max(0,x) for x in (-3,0,3)]])
    check("operation_growth_linear_vs_quadratic", [4,8], [[4,8],[16,64]],
          [[sum(1 for _ in range(n)) for n in (4,8)],
           [sum(1 for _ in range(n) for _ in range(n)) for n in (4,8)]])
    return dict(version=python_version(), cases=cases)


if __name__ == "__main__":
    print(json.dumps(run(), default=str))
本例需在 Windows、Python 3.12.14、标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14、标准库。

入口文件:projects/ai-math-symbols-lab/notation-lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 notation-lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14、标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a83.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习