深度学习面试题23:批次张量和卷积核的简易定义方式

目录

  直接定义的缺点

  简易定义的方式

  参考资料


 

直接定义的缺点

在tensorflow中假设有一批输入为:

其定义如下:

tf.constant([
    [
        [
            [3, 1, -3],
            [1, -1, 7]
        ],
        [
            [-2, 2, -5],
            [2, 7, 3]
        ]
    ],
    [
        [
            [-1, 3, 1],
            [-3, -8, 6]
        ],
        [
            [4, 6, 8],
            [5, 9, -5]
        ]
    ]
], tf.float32)
View Code

这是一个4维张量,中括号的层次比较多,因此定义起来很容易写错;另外一批卷积核的定义方式和他不同,这也增加了定义的难度。

批次输入的张量的定义方式为:[batch, in_height, in_width, in_channels]

多个卷积核的定义方式为:[filter_height, filter_width, in_channels, out_channels]

 返回目录

 

简易定义的方式

 

对一批输入:

按照图中蓝色的顺序声明一个一维张量,然后按照[batch, in_height, in_width, in_channels],对一维张量reshape。

对一批卷积核:

按照图中红色的顺序声明一个一维张量,然后按照[filter_height, filter_width, in_channels, out_channels],对一维张量reshape。

这样的话不需要写很多行并且包含复杂中括号关系的代码,看着张量能快速写出对应声明,提高写代码的效率,另外出错的概率会降低

import tensorflow as tf

# [batch, in_height, in_width, in_channels]
input = tf.constant([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], tf.float32)
input = tf.reshape(input,[2,2,2,2])
print(input.shape)

# [filter_height, filter_width, in_channels, out_channels]
kernel = tf.constant([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], tf.float32)
kernel = tf.reshape(kernel,[2,2,2,2])
print(kernel.shape)

print(tf.Session().run(tf.nn.conv2d(input,kernel,[1,1,1,1],"VALID")))
View Code

 返回目录

 

参考资料

《图解深度学习与神经网络:从张量到TensorFlow实现》_张平

 

 返回目录

 

posted @ 2019-07-26 14:17  黎明程序员  阅读(751)  评论(0编辑  收藏  举报