矩阵与批量计算Matrices & Batch Computation
怎样把许多样本的同一种计算整齐地放在一起?How can the same calculation be organized across many samples?
前置知识:Prerequisites: B04:点积、夹角与投影。B04: dot products, angles and projections.
复习前置:Review prerequisites: B04 · 点积、夹角与投影Dot Products, Angles & Projections
学完后你能:After this lesson you can: 识别样本与特征,判断乘法形状,并手算一个输出格。Identify samples and features, check multiplication shapes, and calculate one output cell.
动手观察Explore
选择一个输出格,观察高亮的样本行、权重列和逐项计算。切换到不匹配形状,查看原因。Choose an output cell to highlight its sample row, weight column and calculation. Switch to incompatible shapes to see why multiplication fails.
从观察到解释From observation to explanation
从表到矩阵From a table to a matrix
约定每行是一个样本、每列是一个特征。两行三列的 X 有 2 个样本、每个 3 个特征。W 的每一列描述如何把这 3 个特征合成为一个输出。Use one row per sample and one column per feature. A 2-by-3 X has 2 samples with 3 features each. Each column of W describes how to combine those 3 features into one output.
一个格子是一组点积One cell is a dot product
若第一行是 (1, 2, 3),第一列权重是 (1, 0, 2),对应结果为 1×1 + 2×0 + 3×2 = 7。其余格子重复同样规则。If the first row is (1, 2, 3) and the first weight column is (1, 0, 2), the output is 1×1 + 2×0 + 3×2 = 7. The remaining cells follow the same rule.
先检查形状Check the shapes first
(2×3) 乘 (3×2) 得到 2×2:内侧两个 3 必须相同,外侧两个数决定结果形状。转置 Xᵀ 会交换行和列,原来的特征成为行。(2×3) times (3×2) gives 2×2: the inner dimensions 3 must match, and the outer dimensions determine the result. Transposing Xᵀ swaps rows and columns, so the original features become rows.
公式与符号Formula and symbols
X 是数据表,n 是样本数(行)、d 是每个样本的特征数(列);W 是权重表,k 是输出数;Y 是结果。i、j、r 是行、列和特征编号,Σ 表示累加。X is the data table; n is the number of samples (rows) and d the features per sample (columns). W is the weight table, k the number of outputs, and Y the result. i, j and r index sample, output and feature; Σ means sum.
留意这个区别Watch for this
矩阵乘法不是相同位置逐项相乘。内侧维数不等时,这个行与列的点积无法定义。Matrix multiplication is not element-by-element multiplication. When the inner dimensions differ, the required row–column dot product is undefined.
继续探索Explore further
课后练习
检验你的理解