import tensorflow as tf
a = tf.constant([[0, 1, 2, 3], [4, 5, 6, 7]], dtype=tf.float32)
a_rank = tf.rank(a) # 获取张量的秩
a_shape = tf.shape(a) # 获取张量的形状
b = tf.reshape(a, [4, 2]) # 对张量进行重构
# 运行会话以显示结果
with tf.Session() as sess:
print('constant tensor:\n {}'.format(sess.run(a)))
print('the rank of tensor: {}'.format(sess.run(a_rank)))
print('the shape of tensor: {}'.format(sess.run(a_shape)))
print('reshaped tensor:\n {}'.format(sess.run(b)))
# 对张量进行切片
print("tensor's first column: {}".format(sess.run(a[:, 0])))
print("tensor's second column: {}".format(sess.run(a[:, 1])))
print("tensor's second row: {}".format(sess.run(a[1, :])))
运行结果:
constant tensor:
[[0. 1. 2. 3.]
[4. 5. 6. 7.]]
the rank of tensor: 2
the shape of tensor: [2 4]
reshaped tensor:
[[0. 1.]
[2. 3.]
[4. 5.]
[6. 7.]]
tensor's first column: [0. 4.]
tensor's second column: [1. 5.]
tensor's second row: [4. 5. 6. 7.]
其中对张量进行切片的操作要看清!!!这里的切片是垂直切的!当然可以水平切!!!