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

检查数组各轴、索引与通道位置

PYTHONWindows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。shape-numerics.py
shape-numerics.py90 行
"""Verify array ranks, indexing, layouts and small CPU tensor operations."""
import json
import platform
import sys

import numpy as np

if "--torch" in sys.argv:
    import torch
    import torch.nn.functional as F

cases = []


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


def shape_info(value):
    return [list(value.shape), value.ndim, value.size]


temperature = np.array(18)
hourly = np.array([13, 14, 16, 18, 20, 21, 19, 17])
table = hourly[:6].reshape(2,3)
stack = np.arange(12).reshape(2,2,3) + 20
images = np.arange(12).reshape(3,2,2,1) + 30
check("scalar_shape_and_index", 18, [[],0,1,18], shape_info(temperature) + [int(temperature[()])])
check("vector_shape_and_index", hourly.tolist(), [[8],1,8,20], shape_info(hourly) + [int(hourly[4])])
check("matrix_shape_and_index", table.tolist(), [[2,3],2,6,20], shape_info(table) + [int(table[1,1])])
check("three_axis_shape_and_index", list(stack.shape), [[2,2,3],3,12,28], shape_info(stack) + [int(stack[1,0,2])])
check("grayscale_batch_keep_channel", [3,2,2,1], [[3,2,2,1],4,12,41],
      shape_info(images) + [int(images[2,1,1,0])])
check("weather_tensor_uses_city_day_hour", [300,7,24,2,1,12], [[300,7,24],3,50400,372],
      shape_info(np.arange(50400).reshape(300,7,24)) + [int(np.arange(50400).reshape(300,7,24)[2,1,12])])
check("dimension_does_not_equal_size", "vector, column, empty array",
      [[[8],1,8],[[8,1],2,8],[[2,0,3],3,0]], [shape_info(value) for value in
       (hourly,hourly[:,None],np.empty((2,0,3)))])
cube = np.fromfunction(lambda i,j,k: 10+(19*i+11*j+23*k)%67, (3,3,3), dtype=int)
check("cube_value_and_fixed_channel", [3,3,3,1,2,0], [51,[[33,44,55],[52,63,74],[71,15,26]]],
      [int(cube[1,2,0]),cube[:,:,1].tolist()])
check("slice_retaining_axis", [3,3,3], [[3,3],[3,3,1]], [list(cube[:,:,1].shape),list(cube[:,:,1:2].shape)])

pixels = np.arange(2*2*3*3).reshape(2,2,3,3)
channels_first = pixels.transpose(0,3,1,2)
check("image_axes_and_pixel_preserved", [list(pixels.shape), [1,1,2,0]], [[2,3,2,3],33,33],
      [list(channels_first.shape),int(pixels[1,1,2,0]),int(channels_first[1,0,1,2])])
incorrect_layout = pixels.reshape(2,3,2,3)
check("reshape_does_not_reorder_channels", [1,0,1,2], [23,33],
      [int(incorrect_layout[1,0,1,2]),int(channels_first[1,0,1,2])])
embeddings = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
ids = np.array([[3,1],[1,0]])
check("embedding_rows_keep_id_order", ids.tolist(), [[2,2,3],[[10,11,12],[4,5,6]]],
      [list(embeddings[ids].shape),embeddings[ids][0].tolist()])
weights = np.zeros((256,784), dtype=int)
weights[0,:2] = [3,-1]
weights[1,:2] = [1,4]
sample = np.zeros(784, dtype=int)
sample[:2] = [2,5]
bias = np.zeros(256, dtype=int)
bias[:2] = [-2,-10]
check("dense_matmul_and_relu", [list(weights.shape), list(sample.shape), [2,5]],
      [[256],[1,22],[0,12]], [list((weights@sample).shape),(weights@sample)[:2].tolist(),
       np.maximum(weights@sample+bias,0)[:2].tolist()])
try:
    weights @ np.zeros(783)
except ValueError:
    check("dense_shape_error", [[256,784],[783]], "ValueError", "ValueError")
else:
    raise AssertionError("mismatched feature axis accepted")
video = np.arange(2*3*2*3*2).reshape(2,3,2,3,2)
check("video_axes_keep_sample_and_frame", list(video.shape), [[2,2,3,2,3],71,71],
      [list(video.transpose(0,4,1,2,3).shape),int(video[1,2,1,2,1]),int(video.transpose(0,4,1,2,3)[1,1,2,1,2])])

if "--torch" in sys.argv:
    torch.set_num_threads(1)
    tensor = torch.from_numpy(pixels.astype(np.float32))
    nchw = tensor.permute(0,3,1,2)
    kernel2 = torch.ones((1,3,1,1))
    check("torch_conv2d_permuted_image", [list(tensor.shape), list(kernel2.shape)], [[2,1,2,3],102],
          [list(F.conv2d(nchw,kernel2).shape),int(F.conv2d(nchw,kernel2)[1,0,1,2])])
    frames = torch.from_numpy(video.astype(np.float32)).permute(0,4,1,2,3)
    kernel3 = torch.ones((1,2,1,1,1))
    check("torch_conv3d_permuted_video", [list(frames.shape),list(kernel3.shape)], [[2,1,3,2,3],141],
          [list(F.conv3d(frames,kernel3).shape),int(F.conv3d(frames,kernel3)[1,0,2,1,2])])
print(json.dumps(dict(version=platform.python_version(),library_versions={
    "numpy":np.__version__, "torch":str(torch.__version__) if "--torch" in sys.argv else None},
    cases=cases), 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-shapes-lab/shape-numerics.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 shape-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章) · 含当前章节或实例 · mbskycom202612a79.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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