首页 > 其他 > 详细

torch.Tensor和numpy.ndarray

时间:2019-07-14 13:31:16      阅读:100      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/jeshy/p/11183632.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!