tensorflow constant 中 shape 参数的理解

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个数字的话就用最后一个数字进行填充。

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值