一、numpy和torch
- numpy是python中处理数据的模块,可以处理各种的矩阵(matrix)。
- Torch自称为神经网络中的numpy。它会将torch产生的tensor放在GPU中加速运算,就像numpy会把array放在CPU中加速运算。
numpy和torch能很好的兼容,对于数据的运算形式也十分相似。numpy array和torch tensor之间也能很好的转换。
二、numpy和torch之间的转换以及运算
- numpy和torch之间的转换
import numpy
import torch
numpy_data=numpy.arange(6).reshape((2,3)) #numpy array 将数组转换为2行3列的形式
torch_data=torch.tensor([1,2,3,4,5,6]).reshape((3,2))#torch tensor
#numpy array与torch tensor之间的相互转换
array2tensor=torch.from_numpy(numpy_data)#numpy array->torch tensor,其参数必须是数组形式
tensor2array=torch_data.numpy() #torch tensor->numpy array
print(
'numpy array:\n',numpy_data,
'\nnumpy array->torch tensor:\n',array2tensor,
'\n\ntorch tensor:\n',torch_data,
'\ntorch tensor->numpy array:\n',tensor2array
)
运行结果:
numpy array:
[[0 1 2]
[3 4 5]]
numpy array->torch tensor:
tensor([[0, 1, 2],
[3, 4, 5]], dtype=torch.int32)
torch tensor:
tensor([[1, 2],
[3, 4],
[5, 6]])
torch tensor->numpy array:
[[1 2]
[3 4]
[5 6]]
- torch中的部分数学运算举例。(与numpy对比着来看一下)
import numpy
import torch
#abs 绝对值
data1=[-2,1,-3,-5]
tensor1=torch.IntTensor(data1) #转换为整型的tenor
print(
'abs_numpy:\n',numpy.abs(data1),
'\nabs_torch:\n',torch.abs(tensor1)
)
#sin 三角函数
data2=[numpy.pi/2.0]
tensor2=torch.FloatTensor(data2)
print(
'sin_numpy:\n',numpy.sin(data2),
'\nsin_torch:\n',torch.sin(tensor2)
)
#mean 平均值
data3=[1,2,3]
tensor3=torch.FloatTensor(data3)
print(
'mean_numpy:\n',numpy.mean(data3),
'\nmean_torch:\n',torch.mean(tensor3)
)
运算结果:
abs_numpy:
[2 1 3 5]
abs_torch:
tensor([2, 1, 3, 5], dtype=torch.int32)
sin_numpy:
[1.]
sin_torch:
tensor([1.])
mean_numpy:
2.0
mean_torch:
tensor(2.)
- torch中的矩阵运算与numpy中的矩阵运算的对比
import numpy import torch #矩阵相乘 np_matrix1=[[1,2],[3,4]] torch_matrix1=torch.IntTensor(np_matrix1) #matrix_multiply print( 'numpy_mutiply:\n',numpy.matmul(np_matrix1,np_matrix1), '\ntorch_multiply:\n',torch.matmul(torch_matrix1,torch_matrix1) ) torch_matrix2=torch.IntTensor([1,2,3]) #matrix_dot print( '\nnumpy_dot:\n',numpy.dot(np_matrix1,np_matrix1), '\ntorch_dot:\n',torch.dot(torch_matrix2,torch_matrix2), )
运行结果:
numpy_mutiply: [[ 7 10] [15 22]] torch_multiply: tensor([[ 7, 10], [15, 22]], dtype=torch.int32) numpy_dot: [[ 7 10] [15 22]] torch_dot: tensor(14, dtype=torch.int32)
注:tensor.dot() 只针对一维数组进行运算