torch的tensor和Numpy的ndarrays

torch被称为神经网络中的numpy,tensor和ndarrays也是比较相似的。

Torch自称为神经网络界的Numpy,它能将torch产生的tensor放在GPU中加速运算,就想Numpy会把array放在CPU中加速运算。所以在神经网络中,用Torch的tensor形式更优。文章链接:链接

 疑问一:为什么torch比numpy更适合GPU计算呢?仅仅是因为可以在GPU中加速运算?为什么能加速运算?

疑问二:torch因为什么特性才使得它更适合GPU运算?

疑问三:torch在CPU中计算时不如numpy?为什么?

tensor是张量,但常常和矩阵混淆,张量和矩阵的区别可以参考这篇文章矩阵与张量

tensor和numpy之间以互相转换

import numpy as np
import torch

np_data = np.arange(9).reshape(3,3)
#from_numpy(ndarrys) can change array to tensor
torch_data = torch.from_numpy(np_data)
#tensor1.numpy() can change tensor1 to array 
tensor2array = torch_data.numpy()

print('\nnp_data:\n',np_data,
'\ntorch_data:\n',torch_data,
'\ntensor2array:\n',tensor2array)

输出打印:

np_data:
 [[0 1 2]
 [3 4 5]
 [6 7 8]]
torch_data:
 tensor([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])
tensor2array:
 [[0 1 2]
 [3 4 5]
 [6 7 8]]

可以看到若对象是tensor的话,在输出的时候前面会有一个tensor
 
一般情况下,列表对象(list)或元组(tuple)不能直接作为torch方法的参数,需要先转化为tensor对象,而numpy却可以,但这也不是绝对的,有一些方法也是需要转化的。

发布了52 篇原创文章 · 获赞 6 · 访问量 9020

猜你喜欢

转载自blog.csdn.net/PMPWDF/article/details/97261101