蓝色天空网mbsky.com · 知识 · 实践 · 创造AI 数学基础 · 本地阅读预览
教程 / AI / 智能开发 / AI 数学基础

标量、向量、矩阵与张量

从实测 shape、ndim 和 size 理解索引、轴转换和真实卷积输入。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

数据有几根轴

张量在数值框架中可以有零根、一根或多根轴,轴数叫阶数或 ndim。气温 18 ℃ 可存成零维数组,shape 是空元组 (),size 为 1。NumPy 用空的索引元组 a[()] 读取其中的数。标量数学上可写为 x∈ℝ。

依时间排序的 8 次测温形成形状 (8,) 的一维数组,一个索引即可定位。实数列向量可写为 v=[v₁,…,vₙ]ᵀ∈ℝⁿ。一维 NumPy 向量没有独立的行列布局,(8,1) 才明确表示 8 行 1 列。

按天和小时组织一周温度,可得到 (7,24) 的矩阵。形状先写行数,再写列数。A∈ℝᵐˣⁿ 的 Aᵢⱼ 是第 i 行第 j 列元素,数学编号通常从 1 开始,Python 从 0 开始。

加一根城市轴后,300 张温度表组成 (300,7,24) 的三维阵列,需要城市、日期、小时三个索引。一般 k 阶数组有 k 根轴,形状写作 (d₁,…,dₖ),元素总数是各轴长度的乘积。大小与阶数各自描述不同属性。

在 NumPy 里看到形状

用 np.array 创建零维和一维数组,用 reshape 建立二维或三维测试数据。实验创建一个标量、8 项向量、2×3 矩阵、2×2×3 阵列及 3×2×2×1 的灰度图片批次。调试时先打印 shape,再查每一轴代表什么。空轴可使 size 为零,ndim 仍由轴数决定。

灰度批次有四根轴,最后一轴长度为一。
本站数组形状实验,四维灰度图片批次。

旋转坐标并固定一根轴

实验将 3×3×3 的 27 个值画成可旋转的点。三根轴代表行 i、列 j、通道 k。每个点的颜色随对应数值变化,选中可查看索引。固定 k=1 只保留九个点,切片得到 3×3 矩阵;使用 1:2 保留长度为 1 的通道轴。

第一个索引从零开始,固定 k 轴在一得到三行三列。
本站张量坐标实验,选中通道一得到九个点。

按操作选定轴顺序

彩色图片可用 (224,224,3) 表示,32 张堆叠为 (32,224,224,3)。Keras Conv2D 默认通常是通道后置,可按层或配置选择。PyTorch Conv2d 的批次输入按 (N,C,H,W)。NumPy 用 transpose(0,3,1,2),PyTorch 用 permute(0,3,1,2) 搬动轴,再核对对应像素;reshape 只改变形状和线性元素的组织方式。

词元嵌入表按词元 ID 取行,输出还保留输入 ID 数组的形状,末尾加一根嵌入轴。具体配置示例为 BERT Base Uncased 的 30522×768,GPT-2 的 50257×768,GPT-2 XL 的 50257×1600。表的行由分词器词元编号决定。

28×28 单通道图片展开为 784 项。若第一层输出 256 项,W 的形状为 (256,784),计算 W@x 产生 256 项,再加偏置并应用激活函数。小实验检查加权和和 ReLU,还验证输入 783 项时矩阵乘法会报错。

彩色视频可按 (时间,高,宽,通道) 排列,例如 (16,224,224,3),在前面加批次轴后是 (8,16,224,224,3)。使用 PyTorch Conv3d 时应调整成 (批次,通道,时间,高,宽)。实验用较小数据验证轴互换后帧内的数值和操作输出。

从索引判断阶数

名称ndim形状索引数示例
标量0()0一个数 18。
向量1(n,)1八个时刻的气温。
矩阵2(m,n)2按行列排列的 2×3 数据。
三阶数组3(d₁,d₂,d₃)3按城市、天气日期与小时排列。

三个不同的 NumPy 属性

属性取值含义标量8 项向量矩阵阵列
.shape各轴长的元组()(8,)(2,3)(2,2,3)
.ndim轴数0123
.size乘积,即元素数18612

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

python · 阅读源码
"""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))
预期结果 · 待实际运行核验
  • 零维数组有一个元素。灰度批次是 (3,2,2,1)。轴换序后同一图像像素仍为 33,直接 reshape 对应位置会变成 23。
检查数组各轴、索引与通道位置

所需环境:Windows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。

当前源码 SHA256:c8ea98413027c49a346e5ce2ffde7a4261317ac3fdd24336cb42651941034a83

解压后复跑

浏览器打开互动页,有 NumPy 时运行数值示例。

下载张量形状实验

所需环境:Windows、Python 3.12.14、NumPy 2.5.4、PyTorch 2.10.0+cpu、Chromium。

ZIP SHA256:38c5be9274f0bd0b7f66c4aa81e4912a4403b409dbd47c078eb008a4597285bb

常见错误与边界

  • .ndim 是轴数,.size 是元素数。
  • 先分辨通道轴和批次轴,再决定是否交换轴。

练习与解答

固定第三轴索引 1,3×3×3 阵列的切片大小是多少?

展开参考解答

点索引保留 3×3,切片 1:2 保留 3×3×1。

规范与官方依据