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

逐项检查形状、线性变换与卷积展开

PYTHONWindows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。matrix-numerics.py
matrix-numerics.py98 行
"""Check matrix shape rules, composition, revenue and im2col independently."""
import json
import platform
import sys

import numpy as np

checks = []


def verify(name,inputs,expected,actual):
    assert actual == expected, (name,expected,actual)
    checks.append(dict(name=name,input=inputs,expected=expected,actual=actual,passed=True))


def add_equal(left,right):
    if left.ndim != 2 or left.shape != right.shape:
        raise ValueError("matrix addition requires identical shapes")
    return left+right


sales=np.array([[4,2,1],[2,5,3],[3,1,4]])
prices=np.array([[2,3],[6,7],[4,5]])
verify("local_revenue_matrix",[sales.tolist(),prices.tolist()],[[24,31],[46,56],[28,36]],(sales@prices).tolist())
verify("row_column_dot_for_cell",[[2,5,3],[3,7,5]],56,int(sales[1]@prices[:,1]))
verify("same_shape_matrix_addition",sales.tolist(),[[5,3,2],[3,6,4],[4,2,5]],
       add_equal(sales,np.ones((3,3),dtype=int)).tolist())
try:
    add_equal(sales,np.ones((1,3),dtype=int))
except ValueError as exc:
    verify("addition_different_shapes_refused",[[3,3],[1,3]],"matrix addition requires identical shapes",str(exc))
else:
    raise AssertionError("unexpected shape acceptance")
try:
    sales@prices.T
except ValueError:
    verify("matrix_inner_axis_mismatch",[[3,3],[2,3]],"ValueError","ValueError")
else:
    raise AssertionError("unexpected shape acceptance")
verify("reversed_order_valid_different_shape",[[2,3],[3,3]],[2,3],list((prices.T@sales).shape))
stretch=np.diag([2,1])
rotate=np.array([[0,-1],[1,0]])
vector=np.array([1,2])
verify("rotation_stretch_order",vector.tolist(),[[-4,1],[-2,2]],
       [(stretch@rotate@vector).tolist(),(rotate@stretch@vector).tolist()])
verify("identity_and_singular_circle_points",[[1,0],[0,1],[-1,0],[0,-1]],
       [[2,0],[0,0],[-2,0],[0,0]],(np.array([[1,0],[0,1],[-1,0],[0,-1]])@np.diag([2,0])).tolist())
precedent=np.array([[10,5,3],[8,7,4],[12,4,6]])
old_price=np.array([[3,3.5],[5,5.5],[4,4]])
verify("recalculate_historical_revenue", [precedent.tolist(),old_price.tolist()],[[67,74.5],[75,82.5],[80,88]],
       (precedent@old_price).tolist())
image=np.arange(1,10).reshape(3,3)
kernel=np.array([[1,0],[0,-1]])
windows=np.lib.stride_tricks.sliding_window_view(image,(2,2))
col=windows.reshape(-1,4)
verify("im2col_two_by_two_kernel", [image.tolist(),kernel.tolist()],[[-4,-4],[-4,-4]],
       (col@kernel.ravel()).reshape(2,2).tolist())
a=np.array([[1],[2],[0]])
b=np.array([[3,-1,2]])
update=a@b
verify("rank_one_update", [a.tolist(),b.tolist()], [[[3,-1,2],[6,-2,4],[0,0,0]],1],
       [update.tolist(),int(np.linalg.matrix_rank(update))])
verify("separate_elementwise_and_matmul", [[[1,2],[3,4]],[[1,0],[0,2]]],
       [[[1,0],[0,8]],[[1,4],[3,8]]],
       [(np.array([[1,2],[3,4]])*np.diag([1,2])).tolist(),(np.array([[1,2],[3,4]])@np.diag([1,2])).tolist()])
q=np.array([[1,2],[2,1]])
k=np.array([[1,0],[0,1],[2,2]])
verify("matrix_attention_rectangular_scores", [q.tolist(),k.tolist()], [[1,2,6],[2,1,6]], (q@k.T).tolist())
weight=np.array([[2,1,-1],[0,1,3]])
x=np.array([[2,0,1],[0,1,2]])
bias=np.array([-1,2])
verify("batch_layout_transposes_correctly",[x.tolist(),weight.tolist()],
       [[[3,3],[-1,7]],[[3,-1],[3,7]],[[2,5],[-2,9]]],
       [(x@weight.T).tolist(),(weight@x.T).tolist(),(x@weight.T+bias).tolist()])
frozen=np.eye(3,dtype=int)
verify("lora_rank_one_scaled_update",[a.tolist(),b.tolist(),2],[[7,-2,4],[12,-3,8],[0,0,1]],
       (frozen+2*update).tolist())
torch_version = None
if "--torch" in sys.argv:
    import torch
    import torch.nn.functional as F
    torch.set_num_threads(1)
    torch_version = str(torch.__version__)
    linear=torch.nn.Linear(3,2)
    with torch.no_grad():
        linear.weight.copy_(torch.tensor(weight,dtype=torch.float32))
        linear.bias.copy_(torch.tensor(bias,dtype=torch.float32))
        verify("torch_affine_forward",x.tolist(),[[2,5],[-2,9]],linear(torch.tensor(x,dtype=torch.float32)).tolist())
    input_image=torch.tensor(image,dtype=torch.float32).reshape(1,1,3,3)
    conv_kernel=torch.tensor(kernel,dtype=torch.float32).reshape(1,1,2,2)
    unfolded=F.unfold(input_image,(2,2))
    equivalent=conv_kernel.reshape(1,4)@unfolded
    verify("torch_unfold_matches_conv2d", [list(input_image.shape),list(conv_kernel.shape)],
           [[1,4,4],[-4,-4,-4,-4],[-4,-4,-4,-4]],
           [list(unfolded.shape),equivalent.flatten().tolist(),F.conv2d(input_image,conv_kernel).flatten().tolist()])
print(json.dumps(dict(version=platform.python_version(),library_versions={"numpy":np.__version__,"torch":torch_version},
                      cases=checks),ensure_ascii=False))
本例需在 Windows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。

入口文件:projects/ai-math-matrix-operations-lab/matrix-numerics.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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