矩阵乘法实现神经网络前向传播
核对单行、批处理和两层网络的输入、权重、偏置及输出维度。
学完这一章,你能够
- 核对单行、批处理和两层网络的输入、权重、偏置及输出维度。
样本按行排成一个批次
把一批读数按行送进网络。每个输出单元接收全部输入特征,先对它们加权求和,再加上偏置。行批量写法为 Z = XW + b。若 X 是 m×n,W 是 n×p,结果是 m×p。b 的 p 个分量加到每一行。列向量写法 y = Wx + b 采用相反的权重维度顺序。
两层网络如何接上
第 j 个线性输出等于第 j 列权重与样本特征的点积,加上 bⱼ。四维输入经 4×6 权重先得到六维,再经 6×2 权重得到二维。ReLU 把负数截到 0。Sigmoid 分别处理两个输出,相加通常不会等于 1。互斥的多类任务常将 logits 交给交叉熵,按需要另算 softmax。
复算结果和错误分支
固定首个样本和权重,线性输出得到 (1.5, −1, −2),应用 ReLU 后只剩首项为正。八行批量处理后保持八个样本。若 X 有四列而 W 有五行,NumPy 矩阵乘法会报错。代码也检查偏置形状与激活名称。
PyTorch Linear 存储 (输出特征数, 输入特征数) 的权重,要把本站 NumPy 权重转置再复制过去。本实验同时计算图像全连接、序列 Q/K/V 投影、嵌入查表与分类头对应的实际形状。
四个网络部件的维度
| 部件 | 输入到输出 | 操作说明 |
|---|---|---|
| 全连接层 | (32,784) 乘以 (784,128) 得 (32,128)。 | 把每行 28×28 的展平像素映射为 128 个特征。 |
| Q、K、V 投影 | 本例三次 (B,L,D) 乘以 (D,D) 得 (B,L,D)。 | 同时打包时最后一维为 3D,模型也可采用不同的键和值维度。 |
| 嵌入索引 | ID 的 (B,L) 形状扩展为 (B,L,D)。 | 从词表权重逐 ID 取行。 |
| 分类头 | (B,768) 乘以 (768,10) 得 (B,10)。 | 每行产生十个未归一化类别分数。 |
跑一遍单样本、批量和两层前向计算
"""Work through fixed dense network shapes and compare the linear layer with PyTorch."""
import argparse
import json
import platform
import numpy as np
CASES = []
def record(name, operation, inputs, expected, actual):
assert actual == expected, (name, expected, actual)
CASES.append(dict(name=name, operation=operation, inputs=inputs,
expected=expected, actual=actual, passed=True))
def dense(samples, weights, bias, activation="linear"):
if bias.shape != (weights.shape[1],):
raise ValueError("Provide one bias value per output feature")
result = samples @ weights + bias
if activation == "linear":
return result
if activation == "relu":
return np.maximum(result, 0)
if activation == "sigmoid":
# exp(-abs(x)) stays in [0, 1], even for large negative logits.
decay = np.exp(-np.abs(result))
return np.where(result >= 0, 1 / (1 + decay), decay / (1 + decay))
raise ValueError(f"Unknown activation: {activation}")
def rejected(run):
try:
run()
except ValueError as error:
return type(error).__name__
return "accepted"
def main():
cli = argparse.ArgumentParser()
cli.add_argument("--torch", action="store_true")
args = cli.parse_args()
versions = {"numpy": np.__version__}
first = np.array([[2., -1., 3., 1.]])
w = np.array([[1., 0., -1.], [2., 1., 0.], [0., -1., 1.], [1., 2., -1.]])
b = np.array([.5, 1., -2.])
single = dense(first, w, b)
relu = dense(first, w, b, "relu")
record("single_row_relu", "compute one sample before and after activation",
{"sample": first.tolist(), "weights": w.tolist(), "bias": b.tolist()},
[[[1.5, -1., -2.]], [[1.5, 0., 0.]]], [single.tolist(), relu.tolist()])
samples = np.concatenate((first, np.arange(28).reshape(7, 4) / 10))
batch = dense(samples, w, b, "relu")
record("batch_preserves_row_count", "compare batched and per-row results",
{"shape": list(samples.shape)}, [[8, 3], True],
[list(batch.shape), bool(np.allclose(batch, np.vstack([dense(samples[j:j+1], w, b, "relu") for j in range(8)])))])
w1 = np.column_stack((np.eye(4), [-1, 0, 0, 0], np.ones(4)))
w2 = np.array([[1., 0.], [0., 1.], [0., 1.], [0., 0.], [0., 0.], [0., -1.]])
hidden = dense(samples, w1, np.zeros(6), "relu")
prediction = dense(hidden, w2, np.array([-1., 1.]), "sigmoid")
record("stack_two_layers", "pass an 8 by 4 batch through ReLU and sigmoid layers",
{"weight_shapes": [list(w1.shape), list(w2.shape)]},
[[8, 6], [8, 2], [2, 0, 3, 1, 0, 5], [.731059, .268941]],
[list(hidden.shape), list(prediction.shape), hidden[0].tolist(), np.round(prediction[0], 6).tolist()])
record("incompatible_feature_dimensions", "multiply four columns by a matrix of five rows",
[[8, 4], [5, 3]], "ValueError", rejected(lambda: dense(samples, np.ones((5, 3)), b)))
record("bias_and_activation_validation", "reject a scalar bias and an unknown activation",
["scalar", "unknown"], ["ValueError", "ValueError"],
[rejected(lambda: dense(samples, w, np.array(.5))), rejected(lambda: dense(samples, w, b, "unknown"))])
qkv = np.ones((2, 3, 4)) @ np.ones((4, 12))
ids = np.array([[0, 1, 0], [2, 2, 1]])
lookup = np.arange(12).reshape(3, 4)
shapes = [np.ones((32, 784)) @ np.ones((784, 128)), *np.split(qkv, 3, axis=-1),
lookup[ids], np.ones((2, 768)) @ np.ones((768, 10))]
record("network_layer_shapes", "compute dense, Q/K/V, embedding and classifier output shapes",
{"layers": 6}, [[32, 128], [2, 3, 4], [2, 3, 4], [2, 3, 4], [2, 3, 4], [2, 10]],
[list(tensor.shape) for tensor in shapes])
two = dense(np.ones((1, 1)), np.array([[800., -800.]]), np.zeros(2), "sigmoid")
record("sigmoid_float_range", "verify saturating extremes and an ordinary multi-label row",
[800, -800, 1, 1], [[[1., 0.]], 1.462117],
[two.tolist(), round(float(dense(np.ones((1, 1)), np.ones((1, 2)), np.zeros(2), "sigmoid").sum()), 6)])
if args.torch:
import torch
versions["torch"] = torch.__version__
layer = torch.nn.Linear(4, 3, dtype=torch.float64)
with torch.no_grad():
layer.weight.copy_(torch.from_numpy(w.T))
layer.bias.copy_(torch.from_numpy(b))
observed = layer(torch.from_numpy(samples)).numpy()
record("pytorch_linear_weight_layout", "transpose NumPy weights before loading torch Linear",
{"numpy": list(w.shape), "torch": list(layer.weight.shape)}, [[3, 4], True],
[list(layer.weight.shape), bool(np.allclose(observed, dense(samples, w, b)))])
print(json.dumps(dict(version=platform.python_version(), library_versions=versions, cases=CASES)))
if __name__ == "__main__":
main()
- 两层网络的输入、隐藏层和输出为 (8,4)、(8,6)、(8,2)。第一行的两个输出约为 0.731059、0.268941。
所需环境:Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。
当前源码 SHA256:8eb1e77eb8d3740fe9e7e154b68312c4c2e5782d1cf0c79a522657418aba81e0
复跑实验
解压后按 README 运行自编程序。
所需环境:Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。
ZIP SHA256:9962dd554b4595e4fcb862789dd54555d81dba1155fd8e4d3f97014d14cb2d0a
常见错误与边界
- 先确定代码采用的权重布局,再从另一框架导入。
- 偏置在特征维度广播。两种输出激活的数值含义分别判断。
练习与解答
同一批输入有 16 行、4 列,配 4×3 权重,结果是几行几列?
展开参考解答
16 行、3 列。权重矩阵的行数仍需匹配输入最后一维。