tf.convert_to_tensor转变tensor矩阵

介绍

将给定的value转换为Tensor。如:可以让列表转变tensor矩阵

语法

tf.convert_to_tensor(
    value,
    dtype=None,
    dtype_hint=None,
    name=None
)
参数
  • value:可以转换成Tensor的值
  • dtype:类型。如果为空,根据value设置
  • dtype_hint:返回的张量的可选元素类型,当dtype为None时使用。在某些情况下,调用者在转换为张量时可能没有dtype的想法,因此dtype_hint可用作软优先级。如果dtype_hint无法转换为,则此参数无效。

例子

list转换成tensor矩阵

a=tf.convert_to_tensor([1,2,3])
print(a)

执行结果:

tf.Tensor([1 2 3], shape=(3,), dtype=int32)

多个tensor转换成tensor矩阵

a=tf.constant(1)
b=tf.constant(2)
c=tf.constant(3)

d=tf.convert_to_tensor([a,b,c])
print(d)

执行结果:

tf.Tensor([1 2 3], shape=(3,), dtype=int32)

多个tensor矩阵 进行转换

shape必须相同,此时相当于tf.stack()

a=tf.constant([1,2])
b=tf.constant([3,4])

c=tf.convert_to_tensor([a,b])
print(c)

执行结果:

tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int32)

相当于tf.stack:

c=tf.stack((a,b))
print(c)

执行结果:

tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int32)

原文出处:/show_1EF5HEq65St5.html