Torch 或 Numpy
1. 用 Numpy 还是 Torch
Torch 自称为神经网络界的 Numpy, 因为他能将 torch 产生的 tensor 放在 GPU 中加速运算 (前提是有合适的 GPU), 就像 Numpy 会把 array 放在 CPU 中加速运算. 所以神经网络的话, 当然是用 Torch 的 tensor 形式数据最好.torch 做的和 numpy 能很好的兼容
np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data)#nump转换为torch
tensor2array = torch_data.numpy()#torch转换为numpy
print(
'\nnumpy', np_data,
'\ntorch', torch_data,
'\ntensor2array', tensor2array
)
''
numpy [[0 1 2]
[3 4 5]]
torch tensor([[0, 1, 2],
[3, 4, 5]], dtype=torch.int32)
tensor2array [[0 1 2]
[3 4 5]]
2. Torch 中的数学运算
API https://pytorch.org/docs/stable/torch.html
- 简单计算
# abs
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data) # 32bit
print(
'\nabs',
'\nnumpy:', np.abs(data), # [1 2 1 2]
'\ntorch:', torch.abs(tensor) # [1 2 1 2]
)
- 矩阵运算
矩阵运算才是神经网络中最重要的部分。
# matrix multiplication 矩阵点乘
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data) # 转换成32位浮点 tensor
# correct method
print(
'\nmatrix multiplication (matmul)',
'\nnumpy: ', np.matmul(data, data), # [[7, 10], [15, 22]]
'\ntorch: ', torch.mm(tensor, tensor) # [[7, 10], [15, 22]]
)
激励函数
- 神经网络每层出来的数据都是线性的关系,如果处理复杂问题通常非线性,通过激励函数改变。
- 平时要用到的就这几个.
relu
,sigmoid
,tanh
,softplus
```python
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import matplotlib.pyplot as plt
#fake data
x=torch.linspace(-5,5,200)#-5到5取200个点
x = Variable(x)
x_np=x.data.numpy()#画图不能用torch数据 要转numpy
y_relu=F.relu(x).data.numpy()
y_sigmoid=F.sigmoid(x).data.numpy()
plt.figure(1, figsize=(8, 6))
plt.subplot(221)
plt.plot(x_np, y_relu, c='red', label='relu')
plt.ylim((-1, 5))
plt.legend(loc='best')
plt.subplot(222)
plt.plot(x_np, y_sigmoid, c='red', label='sigmoid')
plt.ylim((-0.2, 1.2))
plt.legend(loc='best')
plt.show()
![在这里插入图片描述](https://img-blog.csdnimg.cn/39118272fc4c4e36b410477c244b1e72.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAa29tb3JlYmk2,size_20,color_FFFFFF,t_70,g_se,x_16)
教程及图源[https://mofanpy.com/tutorials/machine-learning/torch/activation/](https://mofanpy.com/tutorials/machine-learning/torch/activation/)