# PyTorch向量运算实例图解

## 数学运算

1 + [1, 2, 3] [4, 5, 6] 2 a + b [5, 7, 9]
2 [1, 2, 3] [4, 5, 6] 2 A+2 [3, 4, 5]
3 [1, 2, 3] [4, 5, 6] 2 A-B [-3, -3, -3]
4 [1, 2, 3] [4, 5, 6] 2 B-2 [2, 3, 4]
5 * [1, 2, 3] [4, 5, 6] 2 A*B [4, 10, 18]
6 [1, 2, 3] [4, 5, 6] 2 A*2 [2, 4, 6]
7 / [1, 2, 3] [4, 5, 6] 2 B/A [4, 2, 2]
8 [1, 2, 3] [4, 5, 6] 2 B/2 [2, 2, 3]
``````import torch
A=torch.tensor([1, 2, 3])
B=torch.tensor([4, 5, 6])
A+B
A+2
A-B
B-2
A*B
A*2
B/A
B/2``````

``````tensor([5, 7, 9])
tensor([3, 4, 5])
tensor([-3, -3, -3])
tensor([2, 3, 4])
tensor([ 4, 10, 18])
tensor([2, 4, 6])
tensor([4, 2, 2])
tensor([2, 2, 3])``````

## 点积和线性空间

### 例子

``````import torch
t1= torch.tensor([1, 2, 3])
t2= torch.tensor([4, 5, 6])
DotProduct= torch.dot(t1, t2)
print(DotProduct)
torch.linspace(2, 9)``````

``````tensor(32)
tensor([2.0000, 2.0707, 2.1414, 2.2121, 2.2828, 2.3535, 2.4242, 2.4949, 2.5657, 2.6364, 2.7071, 2.7778, 2.8485, 2.9192, 2.9899, 3.0606, 3.1313, 3.2020, 3.2727, 3.3434, 3.4141, 3.4848, 3.5556, 3.6263, 3.6970, 3.7677, 3.8384, 3.9091, 3.9798, 4.0505, 4.1212, 4.1919, 4.2626, 4.3333, 4.4040, 4.4747, 4.5455, 4.6162, 4.6869, 4.7576, 4.8283, 4.8990, 4.9697, 5.0404, 5.1111, 5.1818, 5.2525, 5.3232, 5.3939, 5.4646, 5.5354, 5.6061, 5.6768, 5.7475, 5.8182, 5.8889, 5.9596, 6.0303, 6.1010, 6.1717, 6.2424, 6.3131, 6.3838, 6.4545, 6.5253, 6.5960, 6.6667, 6.7374, 6.8081, 6.8788, 6.9495, 7.0202, 7.0909, 7.1616, 7.2323, 7.3030, 7.3737, 7.4444, 7.5152, 7.5859, 7.6566, 7.7273, 7.7980, 7.8687, 7.9394, 8.0101, 8.0808, 8.1515, 8.2222, 8.2929, 8.3636, 8.4343, 8.5051, 8.5758, 8.6465, 8.7172, 8.7879, 8.8586, 8.9293, 9.0000])``````

## 在二维坐标系上绘制函数

### 例子

``````import torch
import numpy as np
import matplotlib.pyplot as plt
x=torch.linspace(0, 10, 100)
y=torch.exp(x)
plt.plot(x.numpy(), y.numpy())
plt.show()``````

### 例子

``````import torch
import numpy as np
import matplotlib.pyplot as plt
x=torch.linspace(0, 10, 100)
y=torch.sin(x)
plt.plot(x.numpy(), y.numpy())
plt.show()``````

• 回顶