shaoheshaohe 发表于 2020-5-13 08:41:05

torch.Tensor和numpy.ndarray

1. torch.Tensor和numpy.ndarray相互转换https://common.cnblogs.com/images/copycode.gif
import torchimport 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))

shaoheshaohe 发表于 2020-5-13 08:41:31

3. 矩阵乘法(正确的做法)
data = [, ]
tensor = torch.FloatTensor(data)
print(
    '\nmatrix multiplication (matmul):',
    '\nnumpy:\n', np.matmul(data, data),   # [, ]
    '\ntorch:\n', torch.mm(tensor, tensor))# [, ]

shaoheshaohe 发表于 2020-5-13 08:41:46

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),)
页: [1]
查看完整版本: torch.Tensor和numpy.ndarray