一.概述
格式:tf.constant(value, dtype=None, shape=None, name='Const', verify_shape=False)
- value:是一个必须的值,可以是一个数值,也可以是一个列表;可以是一维的,也可以是多维的。
#创建数值常量
tensor=tf.constant(1)
#用取值函数eval()来查看创建的tensor的值
sess=tf.Session()
with sess.as_default():
print('结果是:',tensor.eval())
#创建列表常量
tensor=tf.constant([1,2])
#用取值函数eval()来查看创建的tensor的值
sess=tf.Session()
with sess.as_default():
print('结果是:', tensor.eval())
- dtype:数据类型,一般可以是tf.float32, tf.float64等
- shape:表示张量的“形状”,即维数以及每一维的大小
#如果指定了第三个参数,当第一个参数value是数字时,张量的所有元素都会用该数字填充
tensor=tf.constant(-1, shape=[2, 3])
sess=tf.Session()
with sess.as_default():
print('结果是:', tensor.eval())
结果是:[[-1 -1 -1]
[-1 -1 -1]]
#而当第一个参数value是一个列表时,注意列表的长度必须小于等于第三个参数shape的大小(即各维大小的乘
#积),否则会报错,这是因为函数会生成一个shape大小的张量,然后用value这个列表中的值一一填充
#shape中的元素。这里列表大小为7,而shape大小为2*3=6,无法正确填充,所以发生了错误。
tensor=tf.constant([1, 2, 3, 4, 5, 6, 7], shape=[2, 3])
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
tensor=tf.constant([1, 2, 3, 4, 5, 6, 7], shape=[2, 3])
ValueError: Too many elements provided. Needed at most 6, but received 7
#而如果列表大小小于shape大小,则会用列表的最后一项元素填充剩余的张量元素
tensor=tf.constant([1, 2], shape=[1, 4, 3])
sess=tf.Session()
with sess.as_default():
print('结果是:', tensor.eval())
结果是: [[[1 2 2]
[2 2 2]
[2 2 2]
[2 2 2]]]
- name: 可以是任何内容,只要是字符串就行
- verify_shape:默认为False,如果修改为True的话表示检查value的形状与shape是否相符,如果不符会报错。
二.用法详解
1.特殊值元素的构建
# create a tensor of shape and all elements are zeros
tf.zeros(shape, dtype=tf.float32, name=None)
tf.zeros([2, 3], tf.int32) ==> [[0, 0, 0], [0, 0, 0]]
# create a tensor of shape and type (unless type is specified) as the input_tensor
#but all elements are zeros.
tf.zeros_like(input_tensor, dtype=None, name=None, optimize=True)
# input_tensor is [0, 1], [2, 3], [4, 5]]
tf.zeros_like(input_tensor) ==> [[0, 0], [0, 0], [0, 0]]
# create a tensor of shape and all elements are ones
tf.ones(shape, dtype=tf.float32, name=None)
tf.ones([2, 3], tf.int32) ==> [[1, 1, 1], [1, 1, 1]]
# create a tensor of shape and type (unless type is specified) as the input_tensor
#but all elements are ones.
tf.ones_like(input_tensor, dtype=None, name=None, optimize=True)
# input_tensor is [0, 1], [2, 3], [4, 5]]
tf.ones_like(input_tensor) ==> [[1, 1], [1, 1], [1, 1]]
# create a tensor filled with a scalar val
tf.fill(dims, value, name=None)
tf.ones([2, 3], 8) ==> [[8, 8, 8], [8, 8, 8]]
2.常量序列
# create a sequence of num evenly-spaced values are generated beginning at start. If
#num > 1, the values in the sequence increase by stop - start / num - 1, so that the
#last one is exactly stop.
# start, stop, num must be scalars
# comparable to but slightly different from numpy.linspace
# numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
tf.linspace(start, stop, num, name=None)
tf.linspace(10.0, 13.0, 4, name="linspace") ==> [10.0 11.0 12.0 13.0]
# create a sequence of numbers that begins at start and extends by increments of
#delta up to but not including limit
# slight different from range in Python
tf.range(start, limit=None, delta=1, dtype=None, name='range')
# 'start' is 3, 'limit' is 18, 'delta' is 3
tf.range(start, limit, delta) ==> [3, 6, 9, 12, 15]
# 'start' is 3, 'limit' is 1, 'delta' is -0.5
tf.range(start, limit, delta) ==> [3, 2.5, 2, 1.5]
# 'limit' is 5
tf.range(limit) ==> [0, 1, 2, 3, 4]
注意:Note that unlike NumPy or Python sequences, TensorFlow sequences are not iterable.
for _ in np.linspace(0, 10, 4): # OK
for _ in tf.linspace(0, 10, 4): # TypeError("'Tensor' object is not iterable.")
for _ in range(4): # OK
for _ in tf.range(4): # TypeError("'Tensor' object is not iterable.")
三.随机变量
tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)
tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None,
name=None)
tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None,
name=None)
tf.random_shuffle(value, seed=None, name=None)
tf.random_crop(value, size, seed=None, name=None)tf.multinomial(logits, num_samples, seed=None, name=None)tf.random_gamma(shape, alpha, beta=None, dtype=tf.float32, seed=None, name=Non
四.数学计算
a = tf.constant([3, 6])
b = tf.constant([2, 2])
tf.add(a, b) # >> [5 8]
tf.add_n([a, b, b]) # >> [7 10]. Equivalent to a + b + b
tf.mul(a, b) # >> [6 12] because mul is element wise
tf.matmul(a, b) # >> ValueError
tf.matmul(tf.reshape(a, shape=[1, 2]), tf.reshape(b, shape=[2, 1])) # >> [[18]]
tf.div(a, b) # >> [1 3]
tf.mod(a, b) # >> [1 0]