当前位置: 首页 > 知识库问答 >
问题:

在Keras中,conv2d和conv2d之间有什么区别?

东方旭东
2023-03-14

我对Keras中的Conv2DConv2D感到困惑。他们之间有什么区别?我认为第一个是一个层,第二个是一个后端函数,但这意味着什么?在Conv2D中,我们发送过滤器的数量、过滤器的大小和跨步(Conv2D(64,(3,3),跨步=(8,8))(输入))但是在Conv2D中,我们使用Conv2D(输入,内核,跨步=(8,8))内核是什么(64,3,3),我们把过滤器的数量和大小放在一起?我应该在哪里输入内核数?你能帮我解决这个问题吗?非常感谢。

pytorch中的代码

def apply_conv(self, image, filter_type: str):

        if filter_type == 'dct':
            filters = self.dct_conv_weights
        elif filter_type == 'idct':
            filters = self.idct_conv_weights
        else:
            raise('Unknown filter_type value.')

        image_conv_channels = []
        for channel in range(image.shape[1]):
            image_yuv_ch = image[:, channel, :, :].unsqueeze_(1)
            image_conv = F.conv2d(image_yuv_ch, filters, stride=8)
            image_conv = image_conv.permute(0, 2, 3, 1)
            image_conv = image_conv.view(image_conv.shape[0], image_conv.shape[1], image_conv.shape[2], 8, 8)
            image_conv = image_conv.permute(0, 1, 3, 2, 4)
            image_conv = image_conv.contiguous().view(image_conv.shape[0],
                                                  image_conv.shape[1]*image_conv.shape[2],
                                                  image_conv.shape[3]*image_conv.shape[4])

            image_conv.unsqueeze_(1)

            # image_conv = F.conv2d()
            image_conv_channels.append(image_conv)

        image_conv_stacked = torch.cat(image_conv_channels, dim=1)

        return image_conv_stacked

Keras中已更改的代码

def apply_conv(self, image, filter_type: str):

        if filter_type == 'dct':
            filters = self.dct_conv_weights
        elif filter_type == 'idct':
            filters = self.idct_conv_weights
        else:
            raise('Unknown filter_type value.')
        print(image.shape)

        image_conv_channels = []
        for channel in range(image.shape[1]):
            print(image.shape)
            print(channel)
            image_yuv_ch = K.expand_dims(image[:, channel, :, :],1)
            print( image_yuv_ch.shape)
            print(filters.shape)
            image_conv = Kr.backend.conv2d(image_yuv_ch,filters,strides=(8,8),data_format='channels_first')
           image_conv = Kr.backend.permute_dimensions(image_conv,(0, 2, 3, 1))
            image_conv = Kr.backend.reshape(image_conv,(image_conv.shape[0], image_conv.shape[1], image_conv.shape[2], 8, 8))
            image_conv =  Kr.backend.permute_dimensions(image_conv,(0, 1, 3, 2, 4))
            image_conv = Kr.backend.reshape(image_conv,(image_conv.shape[0],
                                                  image_conv.shape[1]*image_conv.shape[2],
                                                  image_conv.shape[3]*image_conv.shape[4]))

            Kr.backend.expand_dims(image_conv,1)

            # image_conv = F.conv2d()
            image_conv_channels.append(image_conv)

        image_conv_stacked = Kr.backend.concatenate(image_conv_channels, axis=1)

        return image_conv_stacked

但当我执行代码时,它会产生以下错误:

回溯(最近一次呼叫最后一次):

文件“”,第383行,在解码的_noise=JPEG压缩()中(act11)#16

文件"D:\Software\Anaconda3\envs\py36\lib\site-包\keras\Engine\base_layer.py",第457行,在调用输出=self.call(输入,**kwargs)

调用图像_dct=self中第169行的文件“”。应用_conv(带噪_图像,“dct”)

文件“”,第132行,在apply_conv image_conv=Kr.backend中。conv2d(图像、过滤器、步幅=(8,8)、数据格式=“通道优先”)

文件"D:\Software\Anaconda3\envs\py36\lib\site-包\keras\backend\tensorflow_backend.py",第3650行,在concon2d中data_format=tf_data_format)

文件"D:\Software\Anaconda3\envs\py36\lib\site-包\tensorflow\python\ops\nn_ops.py",第779行,卷积data_format=data_format)

文件"D:\Software\Anaconda3\envs\py36\lib\site-包\tensorflow\python\ops\nn_ops.py",第839行,在初始化filter_shape[num_spatial_dims]))

ValueError:输入通道数与筛选器的相应维度不匹配,1!=8.

新的代码

for channel in range(image.shape[1]):
            image_yuv_ch = K.expand_dims(image[:, channel, :, :],axis=1)
            image_yuv_ch = K.permute_dimensions(image_yuv_ch, (0, 2, 3, 1))
            image_conv = tf.keras.backend.conv2d(image_yuv_ch,kernel=filters,strides=(8,8),padding='same')
            image_conv = tf.keras.backend.reshape(image_conv,(image_conv.shape[0],image_conv.shape[1], image_conv.shape[2],8,8))

错误:

回溯(最近一次呼叫最后一次):

文件“”,第263行,在解码的_noise=JPEG压缩()中(act11)#16

文件"D:\Software\Anaconda3\envs\py36\lib\site-包\keras\Engine\base_layer.py",第457行,在调用输出=self.call(输入,**kwargs)

file",第166行,调用image_dct=self.apply_conv(noised_image,'dct')

文件",第128行,apply_convimage_conv=tf.keras.backend.reshape(image_conv,(image_conv.shape[0],image_conv.shape[1],image_conv.shape[2],8,8))

文件“D:\software\Anaconda3\envs\py36\lib\site packages\tensorflow\python\keras\backend.py”,第2281行,位于重塑返回数组操作中。重塑(x,形状)

文件"D:\软件\Anaconda3\envs\py36\lib\site-包\tenstorflow\python\ops\gen_array_ops.py",第6482行,在reshape"Reshape"中,张量=张量,形状=形状,名称=名称)

文件"D:\Software\Anaconda3\envs\py36\lib\site-包\tenstorflow\python\框架\op_def_library.py",第513行,在_apply_op_helper引发错误

文件"D:\Software\Anaconda3\envs\py36\lib\site-包\tenstorflow\python\框架\op_def_library.py",第510行,_apply_op_helperpreferred_dtype=default_dtype)

文件“D:\software\Anaconda3\envs\py36\lib\site packages\tensorflow\python\framework\ops.py”,第1146行,位于内部\u convert\u tensor ret=conversion\u func(值,dtype=dtype,name=name,as\u ref=as\u ref)

文件"D:\Software\Anaconda3\envs\py36\lib\site-包\tenstorflow\python\框架\constant_op.py",第229行,_constant_tensor_conversion_function返回常量(v, dtype=dtype, name=name)

文件“D:\software\Anaconda3\envs\py36\lib\site packages\tensorflow\python\framework\constant\u op.py”,第208行,在常量值中,dtype=dtype,shape=shape,verify\u shape=verify\u shape)

文件"D:\Software\Anaconda3\envs\py36\lib\site-包\tenstorflow\python\框架\tensor_util.py",第531行,在make_tensor_proto"支持的类型."%(类型(值),值))

将类型对象转换为张量失败。内容:(尺寸(无)、尺寸(4)、尺寸(4)、8、8)。考虑将元素转换为支持的类型。

共有1个答案

戚同
2023-03-14

Tensorflow和Keras现在使用的是channel\u last惯例。因此,首先应使用K.permute\u dimension将通道dim排列到最后一个。您可以在colab中尝试此代码。研究谷歌。com来了解你自己。

  • conv2d执行二维卷积文档的函数
# The second 
import keras
conv_layer = keras.layers.Conv2D(filters=64, kernel_size=8, strides=(4, 4), padding='same')

基本上,它们不同于定义和使用的方式<代码>K.conv2d用于keras内部。层。Conv2Dconv_层对某些输入x应用卷积时,例如conv_层

下面的例子可以帮助您更容易地理解say_helloSayHello之间的区别。

def say_hello(word, name):
    print(word, name)


class SayHello():

    def __init__(self, word='Hello'):
        self.word = word
        pass

    def __call__(self, name):
        say_hello(self.word, name)


say_hello('Hello', 'Nadia') #Hello Nadia

sayhello = SayHello(word='Hello') # you will get an instance `sayhello` from class SayHello

sayhello('Nadia') # Hello Nadia

  • 内核这里是形状的张量(kernel_size,kernel_size,in_channels,out_channels)
  • 如果你想得到形状(8,8,64)的image_conv,那么步幅=(4,4)
import tensorflow as tf
import tensorflow.keras.backend as K

image = tf.random_normal((10,3, 32, 32))
print(image.shape) # shape=(10, 3, 32, 32)

channel = 1
image_yuv_ch = K.expand_dims(image[:, channel,:,:], axis=1) # shape=(10, 1, 32, 32)
image_yuv_ch = K.permute_dimensions(image_yuv_ch, (0, 2, 3, 1)) # shape=(10, 32, 32, 1)

# The first K.conv2d
in_channels = 1
out_channels = 64 # same as filters
kernel = tf.random_normal((8, 8, in_channels, out_channels)) # shape=(8, 8, 1, 64)

image_conv = tf.keras.backend.conv2d(image_yuv_ch, kernel=kernel, strides=(4, 4), padding='same')
print(image_conv.shape) #shape=(10, 8, 8, 64)


# The second 
import keras
conv_layer = keras.layers.Conv2D(filters=64, kernel_size=8, strides=(4, 4), padding='same')
image_conv = conv_layer(image_yuv_ch)
print(image_conv.shape) #shape=(10, 8, 8, 64)
 类似资料:
  • 我试图理解二维卷积神经网络和二维深度卷积神经网络计算的异同。(我理解这些概念)。 例如,假设有一个输入图像是3x3,具有3个通道(RGB),填充为1,步幅为1。过滤器是2x2。 输出是什么?(可以忽略激活和偏差) 我知道常规con2D将有1 3x3输出,而dw con2D将有3输出。除此之外,我有点困惑。谢谢

  • 我不明白为什么通道维度不包含在Keras中con2D层的输出维度中。 我有以下型号 我的问题末尾给出了模型摘要。输入层获取宽度为128、高度为128的RGB图像。第一个conv2D层告诉我输出维度是(None、61、61、24)。我使用的内核大小是(8,8),跨步是(2,2),没有填充。值61=下限((128-8 2 x 0)/2 1)和24(内核/过滤器的数量)是有意义的。但为什么维度中不包括不

  • 我试图在Windows10机器上用Python 3.5.2 | Anaconda4.2.0(64位)实现图像序列预测。我有keras和tensorflow的最新版本。 每个图像都是160x128。我的培训集是1008个图像,大小为1008x160x128x1。我想做一个简单的网络,有一个卷积层和一个LSTM层,现在,每个图像被卷积以提取特征,然后输入LSTM以了解时间依赖性。输出应为k(在k=1以

  • 问题内容: 我正在使用keras构建用于图像分割的卷积神经网络,我想使用“反射填充”而不是“相同”的填充,但是我找不到在keras中做到这一点的方法。 有没有办法实现反射层并将其插入keras模型中? 问题答案: 找到了解决方案!我们只需要创建一个将图层作为输入的新类,并使用tensorflow预定义函数即可。

  • 问题内容: 在此示例中: 无法编译为: 而被编译器接受。 这个答案说明唯一的区别是,与不同,它允许您稍后引用类型,似乎并非如此。 是什么区别,并在这种情况下,为什么不第一编译? 问题答案: 通过使用以下签名定义方法: 并像这样调用它: 在jls§8.1.2中,我们发现(有趣的部分被我加粗了): 通用类声明定义了一组参数化类型(第4.5节), 每种可能通过类型arguments调用类型参数节的类型

  • 问题内容: 我是AngularJS的新手。谁能解释一下这些AngularJS运算符之间的区别:用适当的示例隔离范围时。 问题答案: 允许将在指令属性上定义的值传递到指令的隔离范围。该值可以是简单的字符串值(),也可以是带有嵌入式表达式()的AngularJS插值字符串。将其视为从父作用域到子指令的“单向”通信。 允许指令的隔离范围将值传递到父范围中,以便在属性中定义的表达式中进行求值。请注意,指令