Numpy是經典的數學計算庫,Torch中的Tensor能夠與之互相轉換,從而能夠充分利用兩者的計算函數和模型,以及使用其它支持Numpy的軟件庫和工具。但需注意,轉換須要花費額外的內存和CPU等計算資源。html
依賴軟件包:python
Torch的更多數學操做,參考: http://pytorch.org/docs/torch.html#math-operationsgit
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:github
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.)