2019/09/17 10:55

# 201_PyTorch中文教程：Torch与Numpy互操作

Numpy是经典的数学计算库，Torch中的Tensor可以与之互相转换，从而可以充分利用二者的计算函数和模型，以及使用其它支持Numpy的软件库和工具。但需注意，转换需要花费额外的内存和CPU等计算资源。

• torch
• numpy

Torch的更多数学操作，参考： http://pytorch.org/docs/torch.html#math-operations

import torch
import numpy as np
# 转换 numpy 为 tensor，或者转回来。
np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data)
tensor2array = torch_data.numpy()
print(
'\nnumpy array:', np_data,          # [[0 1 2], [3 4 5]]
'\ntorch tensor:', torch_data,      #  0  1  2 \n 3  4  5    [torch.LongTensor of size 2x3]
'\ntensor to array:', tensor2array, # [[0 1 2], [3 4 5]]
)
numpy array: [[0 1 2]
[3 4 5]]
torch tensor: tensor([[0, 1, 2],
[3, 4, 5]])
tensor to array: [[0 1 2]
[3 4 5]]
# 求绝对值
data = [-1, -2, 1, 2]
tensor = torch.FloatTensor(data)  # 32-bit floating point
print(
'\nabs',
'\nnumpy: ', np.abs(data),          # [1 2 1 2]
'\ntorch: ', torch.abs(tensor)      # [1 2 1 2]
)
abs
numpy:  [1 2 1 2]
torch:  tensor([1., 2., 1., 2.])
tensor.abs()
tensor([1., 2., 1., 2.])
# 求sin值
print(
'\nsin',
'\nnumpy: ', np.sin(data),      # [-0.84147098 -0.90929743  0.84147098  0.90929743]
'\ntorch: ', torch.sin(tensor)  # [-0.8415 -0.9093  0.8415  0.9093]
)
sin
numpy:  [-0.84147098 -0.90929743  0.84147098  0.90929743]
torch:  tensor([-0.8415, -0.9093,  0.8415,  0.9093])
tensor.sigmoid()
tensor([0.2689, 0.1192, 0.7311, 0.8808])
tensor.exp()
tensor([0.3679, 0.1353, 2.7183, 7.3891])
# mean
print(
'\nmean',
'\nnumpy: ', np.mean(data),         # 0.0
'\ntorch: ', torch.mean(tensor)     # 0.0
)
mean
numpy:  0.0
torch:  tensor(0.)
# 矩阵乘法，matrix multiplication
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data)  # 32-bit floating point
# correct method
print(
'\nmatrix multiplication (matmul)',
'\nnumpy: ', np.matmul(data, data),     # [[7, 10], [15, 22]]
'\ntorch: ', torch.mm(tensor, tensor)   # [[7, 10], [15, 22]]
)
matrix multiplication (matmul)
numpy:  [[ 7 10]
[15 22]]
torch:  tensor([[ 7., 10.],
[15., 22.]])
# 不正确的方法
data = np.array(data)
tensor = torch.Tensor(data)

# 参考：https://www.cnblogs.com/yangzhaonan/p/10439416.html
print(
'\nmatrix multiplication (dot)',
'\nnumpy: ', data.dot(data),        # [[7, 10], [15, 22]]
'\ntorch: ', torch.dot(tensor.dot(tensor))     # NOT WORKING! Beware that torch.dot does not broadcast, only works for 1-dimensional tensor
)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-22-de97c709d870> in <module>()
7     '\nmatrix multiplication (dot)',
8     '\nnumpy: ', data.dot(data),        # [[7, 10], [15, 22]]
----> 9     '\ntorch: ', torch.dot(tensor.dot(tensor))     # NOT WORKING! Beware that torch.dot does not broadcast, only works for 1-dimensional tensor
10 )

TypeError: dot() missing 1 required positional arguments: "tensor"

Note that:

torch.dot(tensor1, tensor2) → float

Computes the dot product (inner product) of two tensors. Both tensors are treated as 1-D vectors.

tensor.mm(tensor)
tensor([[ 7., 10.],
[15., 22.]])
tensor * tensor
tensor([[ 1.,  4.],
[ 9., 16.]])
torch.dot(torch.Tensor([2, 3]), torch.Tensor([2, 1]))
tensor(7.)

0
0 收藏

0 评论
0 收藏
0