本文介绍了如何将 CIFAR10 教程转换为 NCHW的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 Tensorflow CIFAR10 教程从 NHWC 转换为 NCHW,但可以不知道怎么做.我只找到了诸如 this 之类的答案,这是几行代码,没有解释它的工作原理和位置使用它.以下是我使用这种方法进行的几次不成功尝试:

I'm trying to convert the Tensorflow CIFAR10 tutorial from NHWC to NCHW, but can't figure out how to do so. I have only found answers such as this, which is a couple of lines of code without an explanation of how it works and where to use it. Here are a couple of unsuccessful attempts I have made using this approach:

def inference(images):

    with tf.variable_scope('conv1') as scope:
    kernel = _variable_with_weight_decay('weights',
                                     shape=[5, 5, 3, 64],
                                     stddev=5e-2,
                                     wd=0.0)

    # ****************************************************************** #

    ### Original
    conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')

    ### Attempt 1
    imgs = tf.transpose(images, [0, 3, 1, 2]) # NHWC -> NCHW
    conv = tf.nn.conv2d(imgs, kernel, [1, 1, 1, 1], padding='SAME')
    conv = tf.transpose(conv, [0, 2, 3, 1]) # NCHW -> NHWC

    ### Attempt 2
    kern = tf.transpose(kernel, [0, 3, 1, 2]) # NHWC -> NCHW
    conv = tf.nn.conv2d(images, kern, [1, 1, 1, 1], padding='SAME')
    conv = tf.transpose(conv, [0, 2, 3, 1]) # NCHW -> NHWC

    # ****************************************************************** #

    biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.0))
    pre_activation = tf.nn.bias_add(conv, biases)
    conv1 = tf.nn.relu(pre_activation, name=scope.name)
    _activation_summary(conv1)
    
    ...

哪个得到错误(分别):

Which get the errors (respectively):

ValueError: Dimensions must be equal, but is 24 and 3 for 'conv1/Conv2D' (op: 'Conv2D') 输入形状:[64,3,24,24], [5,5,3,64].

ValueError: Dimensions must be equal, but is 3 and 5 for 'conv1/Conv2D' (op: 'Conv2D') 输入形状:[64,24,24,3], [5,64,5,3].

ValueError: Dimensions must be equal, but are 3 and 5 for 'conv1/Conv2D' (op: 'Conv2D') with input shapes: [64,24,24,3], [5,64,5,3].

有人可以提供一组我可以遵循的步骤以成功将此示例转换为 NCHW.

Can someone please provide a set of steps I can follow to convert this example to NCHW successfully.

推荐答案

在您的尝试 #1 中,尝试以下操作:

In your attempt #1 , try the following:

conv = tf.nn.conv2d(imgs, kernel, [1, 1, 1, 1], padding='SAME', data_format = 'NCHW')

(即在参数中添加data_format = 'NCHW')

例如如下:

import tensorflow as tf

config = tf.ConfigProto()
config.gpu_options.allow_growth = True

with tf.Session(config=config) as session:

    kernel = tf.ones(shape=[5, 5, 3, 64])
    images = tf.ones(shape=[64,24,24,3])

    imgs = tf.transpose(images, [0, 3, 1, 2]) # NHWC -> NCHW
    conv = tf.nn.conv2d(imgs, kernel, [1, 1, 1, 1], padding='SAME', data_format = 'NCHW')
    conv = tf.transpose(conv, [0, 2, 3, 1]) # NCHW -> NHWC

    print("conv=",conv.eval())

这篇关于如何将 CIFAR10 教程转换为 NCHW的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 21:20