tf.shape(a)和a.get_shape()比较
相同点:都可以得到tensor a的尺寸
不同点:tf.shape()中a 数据的类型可以是tensor, list, array
a.get_shape()中a的数据类型只能是tensor,且返回的是一个元组(tuple)
如果需要根据上一层的动态shape计算当前层的shape,该如何做呢
x=tf.placeholder(tf.float32, shape=[None, 227,227,3] )
但在运行的时候想知道None 到底是多少,这时候,只能通过tf.shape(x)[0] 这种方式来获得.输出的shape,例如:
out_shape=[tf.shape(x)[0],tf.shape(x)[1],tf.shape(x)[2]tf.shape(x)[3]]
但是tf.shape(x)[0]的值是None,这样是无法直接指定shape的,程序会崩
由于返回的时tensor,所以我们可以使用其他tensorflow节点操作进行处理,如下面的转置卷积中,使用stack来合并各个shape的分量,
1 2 3 4 5 6 7 8 9 10 11 | def ?conv2d_transpose(x, input_filters, output_filters, kernel, strides): ???? with tf.variable_scope( 'conv_transpose' ): ???????? shape? = ?[kernel, kernel, output_filters, input_filters] ???????? weight? = ?tf.Variable(tf.truncated_normal(shape, stddev = 0.1 ), name = 'weight' ) ???????? batch_size? = ?tf.shape(x)[ 0 ] ???????? height? = ?tf.shape(x)[ 1 ]? * ?strides ???????? width? = ?tf.shape(x)[ 2 ]? * ?strides ???????? output_shape? = ?tf.stack([batch_size, height, width, output_filters]) return ?tf.nn.conv2d_transpose(x, weight, output_shape, strides = [ 1 , strides, strides,? 1 ], name = 'conv_transpose' ) |
这样就可以将数值和tensor合并转为Tensor,程序就不会报错啦
|