![[Pasted image 20260706233944.png]]

```python
x=torch.arange(12,dtype=torch.float32).reshape(3,4)
y=torch.tensor([[1,2,3,4],[5,6,7,8],[9,10,11,12]],dtype=torch.float32)
torch.cat((x,y),dim=0), torch.cat((x,y),dim=1)
# dim=0摞起来， dim=1 横着连起来
```
float64计算比较慢，深度学习通常用float32。
如果两个tensor的形状不一样，广播机制：
```python
a=torch.arange(3).reshape(3,1)
b=torch.arange(2).reshape(1,2)
a+b
#tensor([[0, 1], [1, 2], [2, 3]])
```

内存问题，训练省内存
id(Y) 为Y的内存。
```python
before = id(y)
y=y+x
id(y) == before
# False，内存改变了
```
如果原地操作：
```python
z= torch.zeros_like(y)
print('id(z):',id(z),'id(y):',id(y))
z[:]=y+x
print('id(z):',id(z),'id(y):',id(y))
#id(z): 1938722272064 id(y): 1938721257456 id(z): 1938722272064 id(y): 1938721257456 内存不变
```

```python
before = id(x)
x+=y # +=把x值加进y里这样内存不变
id(x) == before
# True，内存没变
```

线性代数课程
https://www.bilibili.com/video/BV1ys411472E?spm_id_from=333.788.comment.all.click&vd_source=2f2927cce38dfa94a61c8748ba9ebc2c

Scalar （标量）是用来 scale 向量（vector）的
basis vectors notation i=x j=y

对于$\mathbf{A} \in \mathbb{R}^{m \times n}$ ：**m为row n为column**

$$\begin{split}\mathbf{A}=\begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \cdots & a_{mn} \\ \end{bmatrix}.\end{split}$$
转置 Transpose
$$\begin{split}\mathbf{A}^\top =
\begin{bmatrix}
    a_{11} & a_{21} & \dots  & a_{m1} \\
    a_{12} & a_{22} & \dots  & a_{m2} \\
    \vdots & \vdots & \ddots  & \vdots \\
    a_{1n} & a_{2n} & \dots  & a_{mn}
\end{bmatrix}.\end{split}$$
Hadamard product 阿达玛乘积 A和B有相同维度，阿达玛乘积输出也是相同维度。
$$\begin{split}\mathbf{A} \odot \mathbf{B} =
\begin{bmatrix}
    a_{11}  b_{11} & a_{12}  b_{12} & \dots  & a_{1n}  b_{1n} \\
    a_{21}  b_{21} & a_{22}  b_{22} & \dots  & a_{2n}  b_{2n} \\
    \vdots & \vdots & \ddots & \vdots \\
    a_{m1}  b_{m1} & a_{m2}  b_{m2} & \dots  & a_{mn}  b_{mn}
\end{bmatrix}.\end{split}$$
Reduction
A.sum() 所有值累加
A.sum(axis=0) 顺着row累加
A.sum(axis=1) 顺着column累加
相似的有A.mean(axis=0) A.mean(axis=1)
还可以non reduction sum
sum_A = A.sum(axis=1, keepdims=True)
For instance, since `sum_A` keeps its two axes after summing each row, we can divide `A` by `sum_A` with broadcasting to create a matrix where each row sums up to 1.（可以把一行normalize，总值为1）
cumulative sum， A.cumsum(axis=0)

## Dot Products （vector -vector products)
$$\mathbf{x}, \mathbf{y} \in \mathbb{R}^d$$ Its dot product 点积函数为torch.dot(x, y)， 计算方法为：
$$
\mathbf{x}^\top \mathbf{y} = \sum_{i=1}^{d} x_i y_i
$$
Dot products are useful in a wide range of contexts. For example, given some set of values, denoted by a vector $\mathbf{x} \in \mathbb{R}^n$, and a set of weights, denoted by $\mathbf{w} \in \mathbb{R}^n$, the weighted sum of the values in x according to the weights w could be expressed as the dot product $\mathbf{x}^\top \mathbf{w}$. When the weights are nonnegative and sum to 1, i.e.,$\left(\sum_{i=1}^{n} {w_i} = 1\right)$, the dot product expresses a _weighted average_.

## Matrix–Vector Products 
函数为 torch.mv(A, x) 或者 A@x

$$\begin{split}\mathbf{A}\mathbf{x}
= \begin{bmatrix}
\mathbf{a}^\top_{1} \\
\mathbf{a}^\top_{2} \\
\vdots \\
\mathbf{a}^\top_m \\
\end{bmatrix}\mathbf{x}
= \begin{bmatrix}
 \mathbf{a}^\top_{1} \mathbf{x}  \\
 \mathbf{a}^\top_{2} \mathbf{x} \\
\vdots\\
 \mathbf{a}^\top_{m} \mathbf{x}\\
\end{bmatrix}.\end{split}$$
其中$\mathbf{a}^\top_{i} \in \mathbb{R}^n$ 代表A矩阵中的那一行（row）的vector。

$\mathbf{a}^\top_{i}$ 代表矩阵 $\mathbf{A}$ 的**第 $i$ 行**（row）。
**为什么带转置符号 $^\top$？**  
线性代数中，列向量默认写作 $\mathbf{v} \in \mathbb{R}^n$（竖着，$n \times 1$）。行向量则用列向量的转置表示，即 $\mathbf{v}^\top$（横着，$1 \times n$）。  
对于矩阵 $\mathbf{A} \in \mathbb{R}^{m \times n}$（$m$ 行，$n$ 列）：  
- 第 $i$ 行本质是横着的向量（$1 \times n$）。  
- 有时为了统一用“列符号”存储，先把这个行向量竖着记为 $\mathbf{a}_i \in \mathbb{R}^n$。  
- 当需要在公式中表示**横着的行向量**时，就写成 $\mathbf{a}^\top_{i}$。

We can think of multiplication with a matrix $\mathbf{A}\in \mathbb{R}^{m \times n}$ as a transformation that projects vectors from $\mathbb{R}^{n}$ to $\mathbb{R}^{n}$. These transformations are remarkably useful. For example, we can represent rotations as multiplications by certain square matrices. Matrix–vector products also describe the key calculation involved in computing the outputs of each layer in a neural network given the outputs from the previous layer.

## Matrix–Matrix Multiplication
$$\begin{split}\mathbf{A}=\begin{bmatrix}
 a_{11} & a_{12} & \cdots & a_{1k} \\
 a_{21} & a_{22} & \cdots & a_{2k} \\
\vdots & \vdots & \ddots & \vdots \\
 a_{n1} & a_{n2} & \cdots & a_{nk} \\
\end{bmatrix},\quad
\mathbf{B}=\begin{bmatrix}
 b_{11} & b_{12} & \cdots & b_{1m} \\
 b_{21} & b_{22} & \cdots & b_{2m} \\
\vdots & \vdots & \ddots & \vdots \\
 b_{k1} & b_{k2} & \cdots & b_{km} \\
\end{bmatrix}.\end{split}$$
$$\begin{split}\mathbf{A}=
\begin{bmatrix}
\mathbf{a}^\top_{1} \\
\mathbf{a}^\top_{2} \\
\vdots \\
\mathbf{a}^\top_n \\
\end{bmatrix},
\quad \mathbf{B}=\begin{bmatrix}
 \mathbf{b}_{1} & \mathbf{b}_{2} & \cdots & \mathbf{b}_{m} \\
\end{bmatrix}.\end{split}$$ $\mathbf{a}^\top_{i} \in \mathbb{R}^k$是A的row 向量的， $\mathbf{b}_{j} \in \mathbb{R}^k$是B的column向量，这个notation相当于把上面的压缩了。
$$\begin{split}\mathbf{C} = \mathbf{AB} = \begin{bmatrix}
\mathbf{a}^\top_{1} \\
\mathbf{a}^\top_{2} \\
\vdots \\
\mathbf{a}^\top_n \\
\end{bmatrix}
\begin{bmatrix}
 \mathbf{b}_{1} & \mathbf{b}_{2} & \cdots & \mathbf{b}_{m} \\
\end{bmatrix}
= \begin{bmatrix}
\mathbf{a}^\top_{1} \mathbf{b}_1 & \mathbf{a}^\top_{1}\mathbf{b}_2& \cdots & \mathbf{a}^\top_{1} \mathbf{b}_m \\
 \mathbf{a}^\top_{2}\mathbf{b}_1 & \mathbf{a}^\top_{2} \mathbf{b}_2 & \cdots & \mathbf{a}^\top_{2} \mathbf{b}_m \\
 \vdots & \vdots & \ddots &\vdots\\
\mathbf{a}^\top_{n} \mathbf{b}_1 & \mathbf{a}^\top_{n}\mathbf{b}_2& \cdots& \mathbf{a}^\top_{n} \mathbf{b}_m
\end{bmatrix}.\end{split}$$
所以Matrix - Matrix乘法可以简洁的写成这样。

## Norms 范数

范数就是用来衡量一个向量（或矩阵）的“长度”或“大小”的度量方式。
你可以把它理解为“距离”的广义概念：
在二维平面上，点 $(3,4)$ 到原点的距离是 $5$（勾股定理）。
在更高维的空间中，我们无法直观画图，但可以用范数来计算向量的“大小”。
常见向量范数的数学定义
设向量 $\mathbf{x} = \begin{bmatrix} x1 \\ x2 \\ \vdots \\ x_n \end{bmatrix}$：
L2 范数（最常用，欧几里得范数）
就是通常意义上的“距离”，即所有元素平方和的平方根：
$$
\|\mathbf{x}\|_2 = \sqrt{x_1^2 + x_2^2 + \cdots + x_n^2}
$$
在机器学习中，L2 范数常写作 $\|\mathbf{x}\|$（省略下标 2），用于正则化（防止过拟合）。
## L1 范数（绝对值范数）
所有元素绝对值之和：
$$
\|\mathbf{x}\|_1 = |x_1| + |x_2| + \cdots + |x_n|
$$
L1 范数常用于稀疏性约束（让权重矩阵中产生很多 0）。

## 无穷范数（最大范数）
所有元素中绝对值最大的那个：
$$
\|\mathbf{x}\|_\infty = \max(|x_1|, |x_2|, \dots, |x_n|)
$$

与点积、矩阵乘法的关联
点积 $\mathbf{x}^\top \mathbf{x}$ 给出的是“平方和”（标量），而 L2 范数的平方 正好等于这个点积：
$$
\|\mathbf{x}\|2^2 = \mathbf{x}^\top \mathbf{x}
$$
在神经网络中，损失函数（Loss Function）里经常会加上一项正则化项，例如 L2 正则化就是给损失函数加上 $\lambda \|\mathbf{W}\|2^2$，用来惩罚过大的权重。

矩阵的范数（补充知识）
矩阵也有范数，例如 Frobenius 范数（F 范数），它把矩阵所有元素的平方和开根号：
$$
\|\mathbf{A}\|F = \sqrt{\sum{i=1}^{m} \sum{j=1}^{n} |a{ij}|^2}
$$
你可以把它理解为“把矩阵拉直成一个长向量后计算 L2 范数”。
