tf.constant

概述

创建一个常数张量,即:张量的值是不可变的

语法

tf.constant(
    value,
    dtype=None,
    shape=None,
    name='Const'
)
参数
  • value:常量值(或列表)
  • dtype:所得元素的类型。
  • shape:形状
  • name:名称(可选)
返回值
  • 一个常数张量

例子

import tensorflow as tf

a = tf.constant([1.0, 2.0])
print(a)
print(a.shape)
print(a.dtype)
print(a.numpy())

执行结果:

tf.Tensor([1. 2.], shape=(2,), dtype=float32)
(2,)
<dtype: 'float32'>
[1. 2.]

例子2-正确

def test():
    a=tf.constant(1)
    b=tf.constant(a)

test()

例子3-错误

def test():
    a=tf.constant(1)
    b=tf.constant([a])

test()

错误提示:

ValueError: TypeError: Scalar tensor has no `len()`
Traceback (most recent call last):

  File "/opt/conda/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py", line 895, in __len__
    raise TypeError("Scalar tensor has no `len()`")

TypeError: Scalar tensor has no `len()`

tf.constant([a])里面是list时,list内元素不能是tensor

例子4-tf.function 错误

@tf.function
def test():
    a=tf.constant(1)
    b=tf.constant(a)
test()

错误提示:

TypeError: List of Tensors when single Tensor expected

例子5—tf.function 错误

@tf.function
def test():
    a=tf.constant(1)
    b=tf.constant([a])
test()

错误提示:

TypeError: List of Tensors when single Tensor expected

原文出处:/show_1EF4ZcXqP8se.html