Auto Byte

Science AI

# 基础入门：深度学习矩阵运算的概念和代码实现

#### 线性代数为什么如此实用？

```# Multiply two arrays
x = [1,2,3]
y = [2,3,4]
product = []
for i in range(len(x)):
product.append(x[i]*y[i])```
```# Linear algebra version
x = numpy.array([1,2,3])
y = numpy.array([2,3,4])
x * y```

#### 向量

```y = np.array([1,2,3])
x = np.array([2,3,4])
y + x = [3, 5, 7]
y - x = [-1, -1, -1]
y / x = [.5, .67, .75]```

```y = np.array（[1,2,3]）
x = np.array（[2,3,4]）
y * x = [ 2,6,12 ]```

#### 矩阵

```a = np.array([
[1,2,3],
[4,5,6]
])
a.shape == (2,3)```
```b = np.array([
[1,2,3]
])
b.shape == (1,3)```

```a = np.array(
[[1,2],
[3,4]])
a + 1
[[2,3],
[4,5]]```

```a = np.array([
[1,2],
[3,4]
])
b = np.array([
[1,2],
[3,4]
])```
```a + b
[[2, 4],
[6, 8]]```
```a — b
[[0, 0],
[0, 0]]```

• 两个矩阵的阶相等
• 矩阵的阶有一个维度是1
```a = np.array([
[1],
[2]
])
b = np.array([
[3,4],
[5,6]
])
c = np.array([
[1,2]
])```
```# Same no. of rows
# Different no. of columns
# but a has one column so this works
a * b
[[ 3, 4],
[10, 12]]```
```# Same no. of columns
# Different no. of rows
# but c has one row so this works
b * c
[[ 3, 8],
[5, 12]]```
```# Different no. of columns
# Different no. of rows
# but both a and c meet the
# size 1 requirement rule
a + c
[[2, 3],
[3, 4]]```

```a = np.array(
[[2,3],
[2,3]])
b = np.array(
[[3,4],
[5,6]])```
```# Uses python's multiply operator
a * b
[[ 6, 12],
[10, 18]]```

• 旋转矩阵90度
• 将每一行的元素都反向写一遍

```a = np.array([
[1, 2],
[3, 4]])```
```a.T
[[1, 3],
[2, 4]]```

#### 矩阵乘法

• 第一个矩阵列的数量必须等于第二个矩阵行的数量
• m×n阶矩阵左乘n×k阶矩阵的结果是m×k阶矩阵。新得出来矩阵就等于第一矩阵的行数×第二矩阵的列数。

A矩阵行向量与B矩阵列向量b1的点积，即下图所示：

#### 使用Numpy进行矩阵乘法运算

```a = np.array([
[1, 2]
])
a.shape == (1,2)```
```b = np.array([
[3, 4],
[5, 6]
])
b.shape == (2,2)```
```# Multiply
mm = np.dot(a,b)
mm == [13, 16]
mm.shape == (1,2)```