tensorflow 新手,代码不整洁不规范请谅解。
对 tensorflow 的 constant 方法中的 shape 参数不甚理解,现在搞懂了,在此做一笔记,供人参考,tensorflow 中 reshape 方法的理解也是一样的。
1.
import tensorflow as tf
a = tf.constant([[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]],shape = [3,3])
b = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(b)
print(sess.run(a))输出为:[[ 1. 2. 3.]
[ 4. 5. 6.]
[ 7. 8. 9.]]很好理解。
2.
import tensorflow as tf
a = tf.constant([[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]],shape = [1,3,3])
b = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(b)
print(sess.run(a))输出为:[[[ 1. 2. 3.]
[ 4. 5. 6.]
[ 7. 8. 9.]]]也很好理解,在例1的外层加一个中括号就行。
3.
import tensorflow as tf
a = tf.constant([[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]],shape = [1,3,3,1])
b = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(b)
print(sess.run(a))输出为:
[[[[ 1.]
[ 2.]
[ 3.]]
[[ 4.]
[ 5.]
[ 6.]]
[[ 7.]
[ 8.]
[ 9.]]]]第一次看到这个的时候很不理解,因为结果很奇怪,不直观,但是其实这也是一个 3 × 3 矩阵的表示,shape中有四个数字,代表着输出的维数为4,在分割的过程中如果只剩一个数字,那么在这个数字外面加上一个中括号就充当了一维。
下面问题的输出应该猜到了吧。
a = tf.constant([[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]],shape = [1,3,3,1,1])4.
import tensorflow as tf
a = tf.constant([[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]],shape = [1,3,3,2])
b = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(b)
print(sess.run(a))输出为:
[[[[ 1. 2.]
[ 3. 4.]
[ 5. 6.]]
[[ 7. 8.]
[ 9. 9.]
[ 9. 9.]]
[[ 9. 9.]
[ 9. 9.]
[ 9. 9.]]]]有点惊讶吧。原因是这样的,shape中维数为4,至少有1 × 3 × 3 × 2 = 18个数字,如果所给参数中少于18个数字的话就用最后一个数字进行填充。
本文解析了TensorFlow中constant方法的shape参数作用,并通过实例展示了不同shape设置下张量的变化,有助于理解张量维度及填充规则。
4481

被折叠的 条评论
为什么被折叠?



