torch.Tensor和numpy.ndarray

2022-10-31,,,

1. torch.Tensor和numpy.ndarray相互转换

import torch
import numpy as np
# <class 'numpy.ndarray'>
np_data = np.arange(6).reshape((2,3))
# <class 'torch.Tensor'>
torch_data = torch.from_numpy(np_data)
# <class 'numpy.ndarray'>
tensor2array = torch_data.numpy()
print('numpy array:\n',np_data,type(np_data),
'\ntorch tensor:\n',torch_data,type(torch_data),
'\ntensor to array:\n',tensor2array,type(tensor2array))
# numpy array:
# [[0 1 2]
# [3 4 5]] <class 'numpy.ndarray'>
# torch tensor:
# tensor([[0, 1, 2],
# [3, 4, 5]]) <class 'torch.Tensor'>
# tensor to array:
# [[0 1 2]
# [3 4 5]] <class 'numpy.ndarray'> torch.Tensor:是一个包含了一种数据类型元素的多维矩阵,缺省为torch.FloatTensor
2. torch.Tensor和numpy.ndarray一些简单操作,如均值,绝对值,sin,log等
data = [-1,-2,1,2]
tensor_default = torch.Tensor(data)
tensor = torch.FloatTensor(data)
print('tensor default type:\n',tensor_default,
'\ntensor FloatTensor type:\n',tensor,
'\nabs:',
'\nnumpy:',np.abs(data),
'\ntorch:',torch.abs(tensor),
'\nsin:',
'\nnumpy:',np.sin(data),
'\ntorch:',torch.sin(tensor),
'\nmean:',
'\nnumpy:',np.mean(data),
'\ntorch:',torch.mean(tensor),)
# tensor default type:
# tensor([-1., -2., 1., 2.])
# tensor FloatTensor type:
# tensor([-1., -2., 1., 2.])
# abs:
# numpy: [1 2 1 2]
# torch: tensor([1., 2., 1., 2.])
# sin:
# numpy: [-0.84147098 -0.90929743 0.84147098 0.90929743]
# torch: tensor([-0.8415, -0.9093, 0.8415, 0.9093])
# mean:
# numpy: 0.0
# torch: tensor(0.) 3. 矩阵乘法(正确的做法)
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data)
print(
'\nmatrix multiplication (matmul):',
'\nnumpy:\n', np.matmul(data, data), # [[7, 10], [15, 22]]
'\ntorch:\n', torch.mm(tensor, tensor)) # [[7, 10], [15, 22]]
# matrix multiplication (matmul):
# numpy:
# [[ 7 10]
# [15 22]]
# torch:
# tensor([[ 7., 10.],
# [15., 22.]])

torch.Tensor和numpy.ndarray的相关教程结束。

《torch.Tensor和numpy.ndarray.doc》

下载本文的Word格式文档,以方便收藏与打印。