此函数将各种类型的 Python 对象转换为 Tensor 对象.它接受 Tensor 对象,numpy 数组,Python 列表和 Python 标量
convert_to_tensor ( value , dtype = None , name = None , preferred_dtype = None )
import numpy as np def my_func(arg): arg = tf.convert_to_tensor(arg, dtype=tf.float32) return tf.matmul(arg, arg) + arg # The following calls are equivalent. value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]])) value_2 = my_func([[1.0, 2.0], [3.0, 4.0]]) value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))
返回基于值的输出.
convert_to_tensor_or_indexed_slices ( value , dtype = None , name = None )
将给定的对象转换为张量或 IndexedSlices.
如果值为 IndexedSlices 或 SparseTensor,则将其原封不动地返回.否则,它将转换为使用 convert_to_tensor () 的张量.
基于值的张量、IndexedSlices 或 SparseTensor.
convert_to_tensor_or_sparse_tensor ( value , dtype = None , name = None )
返回基于值的 SparseTensor 或张量.
RuntimeError: 如果结果类型与 dtype 不兼容.
主要是两个方法: 1.数组转tensor:数组a, tensor_a=tf.convert_to_tensor(a) 2.tensor转数组:tensor b, array_b=b.eval()
import tensorflow as tf
import numpy as np
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
print (a)
b=tf.constant(a)
with tf.Session() as sess:
print (b)
for x in b.eval(): #b.eval()就得到tensor的数组形式
print (x)
print (‘a是数组‘,a)
tensor_a=tf.convert_to_tensor(a)
print (‘现在转换为tensor了...‘,tensor_a)
1.1 list 转 numpy
ndarray = np.array(list)
1.2 numpy 转 list
list = ndarray.tolist()
2.1 list 转 torch.Tensor
tensor=torch.Tensor(list)
2.2 torch.Tensor 转 list
先转numpy,后转list
list = tensor.numpy().tolist()
3.1 torch.Tensor 转 numpy
ndarray = tensor.numpy()
*gpu上的tensor不能直接转为numpy
ndarray = tensor.cpu().numpy()
3.2 numpy 转 torch.Tensor
tensor = torch.from_numpy(ndarray)
tensor numpy.array panda.dataframe list等数据类型的转换
原文:https://www.cnblogs.com/xingnie/p/12416373.html