Tensor Transformations - Shapes and Shaping: TensorFlow provides several operations that you can use to determine the shape of a tensor and change the shape of a tensor.
tensorflow提供了一些操作,让用户可以定义和修改tensor的形状
以tensor形式,返回tensor形状。
tf.shape(input, name=None, out_type=tf.int32)
import tensorflow as tf
t = tf.constant(value=[[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]], dtype=tf.int32)
with tf.Session() as sess:
print (sess.run(tf.shape(t)))
[2 2 3]
另一种方法也可以的到类似答案:
import tensorflow as tf
t = tf.constant(value=[[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]], dtype=tf.int32)
print (t.shape)
(2, 2, 3)
以tensor形式,返回tensor元素总数。
tf.size(input, name=None, out_type=tf.int32)
import tensorflow as tf
t = tf.ones(shape=[2, 5, 10], dtype=tf.int32)
with tf.Session() as sess:
print (sess.run(tf.size(t)))
100
以tensor形式,返回tensor阶数。
tf.rank(input, name=None)
import tensorflow as tf
t = tf.constant(value=[[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]], dtype=tf.int32)
with tf.Session() as sess:
print (sess.run(tf.rank(t)))
3
以tensor形式,返回重新被塑形的tensor。
tf.reshape(tensor, shape, name=None)
import tensorflow as tf
t = tf.constant(value=[1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=tf.int32)
with tf.Session() as sess:
print (sess.run(t))
print
print (sess.run(tf.reshape(t, [3, 3])))
[1 2 3 4 5 6 7 8 9]
[[1 2 3]
[4 5 6]
[7 8 9]]
以tensor形式,返回移除指定维后的tensor。
tf.squeeze(input, axis=None, name=None, squeeze_dims=None)
axis=None
时:
Removes dimensions of size 1 from the shape of a tensor.
将tensor中 维度为1 的 所有维 全部移除axis=[2, 4]
时:
将tensor中 维度为1 的 第2维 和 第4维 移除import tensorflow as tf
t = tf.ones(shape=[1, 2, 1, 3, 1, 1], dtype=tf.int32)
with tf.Session() as sess:
print (sess.run(tf.shape(t)))
print
print (sess.run(tf.shape(tf.squeeze(t))))
print
print (sess.run(tf.shape(tf.squeeze(t, axis=[2, 4]))))
[1 2 1 3 1 1]
[2 3]
[1 2 3 1]
以tensor形式,返回插入指定维后的tensor。
tf.expand_dims(input, axis=None, name=None, dim=None)
import tensorflow as tf
t = tf.ones(shape=[2, 3, 5], dtype=tf.int32)
with tf.Session() as sess:
print (sess.run(tf.shape(t)))
print
print (sess.run(tf.shape(tf.expand_dims(t, 0))))
print
print (sess.run(tf.shape(tf.expand_dims(t, 1))))
print
print (sess.run(tf.shape(tf.expand_dims(t, 2))))
print
print (sess.run(tf.shape(tf.expand_dims(t, 3))))
print
print (sess.run(tf.shape(tf.expand_dims(t, -1))))
[2 3 5]
[1 2 3 5]
[2 1 3 5]
[2 3 1 5]
[2 3 5 1]
[2 3 5 1]