有两种方法可以获取 tf.Tensor
的形状。
可以通过查看 tf.Tensor
对象的 shape
属性获取这些信息。该方法会返回一个 TensorShape
对象。
可以调用 tf.shape
操作,返回 tf.Tensor对象。
>> from __future__ import absolute_import
>> from __future__ import division
>> from __future__ import print_function
>> import numpy as np
>> import tensorflow as tf
>> squarish_squares = tf.Variable([ [4, 9], [16, 25] ], tf.int32)
>> sess = tf.Session()
>> shape1 = squarish_squares.shape
>> shape2 = tf.shape(squarish_squares)
>> shape1
TensorShape([Dimension(2), Dimension(2)])
>> shape2
<tf.Tensor 'Shape:0' shape=(2,) dtype=int32>
>> sess.run(shape2)
array([2, 2])
以下代码展示了如何创建大小与给定矩阵中的列数相同的零矢量:
zeros = tf.zeros(my_matrix.shape[1])