tf.ones_like 函数ones_like(tensor,dtype=None,name=None,optimize=True)
函数目的是创建一个和输入参数(tensor)维度一样,元素都为1的张量。
tensor:输入参数dtype:返回的 Tensor 类型.必须是:float32,float64,int8,int16,int32,int64,uint8,complex64,complex128或bool.name:操作的名称(可选).optimize:如果为 true,则尝试静态确定 “张量” 的形状并将其编码为常量.
import tensorflow as tfsess=tf.InteractiveSession( )a = tf.constant([1,2,3,4,5,6])b = tf.constant([1,2,3,4,5,6], shape=[2, 3])c=tf.constant([1,2,3,4,5,6], shape=[2, 2, 3])d=tf.ones_like(a)e=tf.ones_like(b)f=tf.ones_like(c)print(sess.run(a))print(sess.run(tf.shape(a)),"\n")print(sess.run(b))print(sess.run(tf.shape(b)),"\n")print(sess.run(c))print(sess.run(tf.shape(c)),"\n")print(sess.run(d))print(sess.run(tf.shape(d)),"\n")print(sess.run(e))print(sess.run(tf.shape(e)),"\n")print(sess.run(f))print(sess.run(tf.shape(f)),"\n")输出结果:[1 2 3 4 5 6][6] [[1 2 3][4 5 6]][2 3] [[[1 2 3][4 5 6]][[6 6 6][6 6 6]]][2 2 3] [1 1 1 1 1 1][6] [[1 1 1][1 1 1]][2 3] [[[1 1 1][1 1 1]][[1 1 1][1 1 1]]][2 2 3]