Tensorflow教程(2)Tensorflow的常用函数介绍

1、tf.constant

tf.constant用来定义一个常量,所谓常量,广义上讲就是“不变化的量”。我们先看下官方api是如何对constant函数来定义的:

tf.constant(
    value,
    dtype=None,
    shape=None,
    name='Const',
    verify_shape=False
)

其中包括5个输入值:

value(必填):常量的值,可以是一个数,也可以是一个向量或矩阵。

dtype(非):用来指定数据类型,例如tf.float32类型或tf.float64。

shape:用来指定数据的维度。

name:为常量定义名称。

verify_shape:默认值为False,如果值为True时,在定义常量时会自动检测value和shape维度是否相同,不同则报错,例如value定义为1,而shape定义为一个一行两列的矩阵(1,2),那么肯定会报错。

了解了参数的含义,我们用代码来验证一下吧!

#定义一个整数
a = tf.constant(1)
#定义一个向量
b = tf.constant([1,2])
#定义一个2行3列的矩阵
c = tf.constant([[1,2,3],[4,5,6]])
print(a)
print(b)
print(c)

输出结果:

Tensor("Const:0", shape=(), dtype=int32)
Tensor("Const_1:0", shape=(2,), dtype=int32)
Tensor("Const_2:0", shape=(2, 3), dtype=int32)

可以看出来变量a的shape是空,也就是0维,一个整数;

变量b的shape是(2,),只有一个维度,是一个向量,长度为2;

变量c的shape是(2,3),有两个维度,也就是一个2X3的矩阵。

当指定dtype参数时:

#定义一个整数
a = tf.constant(1,dtype=tf.float32)
#定义一个向量
b = tf.constant([1,2],dtype=tf.float32)
#定义一个2行3列的矩阵
c = tf.constant([[1,2,3],[4,5,6]],dtype=tf.float32)
print(a)
print(b)
print(c)

输出结果:

Tensor("Const:0", shape=(), dtype=float32)
Tensor("Const_1:0", shape=(2,), dtype=float32)
Tensor("Const_2:0", shape=(2, 3), dtype=float32)

可见数值的类型都变为float32类型。

当指定shape参数时:

#定义一个整数
a = tf.constant(2.,shape=())
b = tf.constant(2.,shape=(3,))
c = tf.constant(2.,shape=(3,4))
with tf.Session() as sess:
    print(a.eval())
    print(b.eval())
    print(c.eval())

输出结果:

2.0
[2. 2. 2.]
[[2. 2. 2. 2.]
 [2. 2. 2. 2.]
 [2. 2. 2. 2.]]

此时constant会根据shape指定的维度使用value值来进行填充,例如参数a指定维度为0,也就是一个整数;参数b指定维度为1长度为3,也就是一个向量;参数b指定维度为2长度为3X4,也就是定义一个3X4的矩阵,全部都使用value值2.0来进行填充。

当指定name参数时:

#不指定name
a = tf.constant(2.)
#指定name
b = tf.constant(2.,name="b")
print(a)
print(b)

输出结果:

Tensor("Const:0", shape=(), dtype=float32)
Tensor("b:0", shape=(), dtype=float32)

建议大家创建常量时最好定义一下name,只要是字符串就没有问题。

当指定verify_shape=True时:

a = tf.constant(2.,shape=(2,3),verify_shape=True)

输出结果报错:

TypeError: Expected Tensor's shape: (2,3), got ().

意思是value值和指定的shape维度不同,value是一个整数,而我们指定的shape为2X3的矩阵,所以报错!当我们去掉verify_shape参数时错误即消失。那么问题来了,此时这个常量到底是整数还是一个矩阵呢?当然是矩阵啦(一个被value值填充的2X3矩阵)!

猜你喜欢

转载自www.cnblogs.com/codeit/p/11184422.html