Tensor 张量转化

list 2 torch.Tensor

tensor=torch.Tensor(list)

torch.Tensor 2 list

list = tensor.numpy().tolist()

torch.Tensor 2 numpy

ndarray = tensor.numpy()
#gpu上的tensor不能直接转为numpy
ndarray = tensor.cpu().numpy()

numpy 2 torch.Tensor

tensor = torch.from_numpy(ndarray) 

list ,numpy 2 tensor

torch.FloatTensor(a)
torch.FloatTensor(1).fill_(0.).to(self.device) 
result:
tensor([0.], device='cuda:0', grad_fn=<MulBackward0>)

tensor.requires_grad=True可以跟踪计算,例如grad_fn=

tensorflow中将张量和数组相互转换


import tensorflow as tf
 
sess=tf.Session()
sess.run(tf.global_variables_initializer())
#转化为numpy数组
img_numpy=img.eval(session=sess)
print("out2=",type(img_numpy))
#转化为tensor
img_tensor= tf.convert_to_tensor(img_numpy)
print("out2=",type(img_tensor))

Citation

https://www.cnblogs.com/siyuan1998/p/10792481.html
https://blog.csdn.net/zk_ken/article/details/81222943

你可能感兴趣的:(python,numpy,tensorflow)