【问题标题】:shape of Conv2d in multiclass text classification多类文本分类中 Conv2d 的形状
【发布时间】:2020-11-23 17:06:57
【问题描述】:

我正在使用卷积神经网络进行多类文本分类,我在手套嵌入权重上应用了以下代码,我得到了很好的结果,但我对 CONV2D 形状有疑问: 为什么在 CONV2D 1 中我们得到 conv_1 (None, 407, 1, 64) 和分别在 conv_2 :None, 406, 1, 64) 和 conv_2 :405 中?

               


Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_18 (InputLayer)           (None, 409)          0                                            
__________________________________________________________________________________________________
embedding_17 (Embedding)        (None, 409, 100)     1766600     input_18[0][0]                   
__________________________________________________________________________________________________
reshape_10 (Reshape)            (None, 409, 100, 1)  0           embedding_17[0][0]               
__________________________________________________________________________________________________
conv_1 (Conv2D)                 (None, 407, 1, 64)   19264       reshape_10[0][0]                 
__________________________________________________________________________________________________
conv_2 (Conv2D)                 (None, 406, 1, 64)   25664       reshape_10[0][0]                 
__________________________________________________________________________________________________
conv_3 (Conv2D)                 (None, 405, 1, 64)   32064       reshape_10[0][0]                 
__________________________________________________________________________________________________
max_pooling2d_16 (MaxPooling2D) (None, 1, 1, 64)     0           conv_1[0][0]                     
__________________________________________________________________________________________________
max_pooling2d_17 (MaxPooling2D) (None, 1, 1, 64)     0           conv_2[0][0]                     
__________________________________________________________________________________________________
max_pooling2d_18 (MaxPooling2D) (None, 1, 1, 64)     0           conv_3[0][0]                     
__________________________________________________________________________________________________
concatenate_6 (Concatenate)     (None, 3, 1, 64)     0           max_pooling2d_16[0][0]           
                                                                 max_pooling2d_17[0][0]           
                                                                 max_pooling2d_18[0][0]           
__________________________________________________________________________________________________
flatten_5 (Flatten)             (None, 192)          0           concatenate_6[0][0]              
__________________________________________________________________________________________________
dropout_11 (Dropout)            (None, 192)          0           flatten_5[0][0]                  
__________________________________________________________________________________________________
dense_11 (Dense)                (None, 3)            579         dropout_11[0][0]                 
==================================================================================================
Total params: 1,844,171
Trainable params: 1,844,171
Non-trainable params: 0
__________________________________________________________________________________________________
None
from keras.layers import Dense, Input, GlobalMaxPooling1D
from keras.layers import Conv1D, MaxPooling1D, Embedding
from keras.models import Model
from keras.layers import Input, Dense, Embedding, Conv2D, MaxPooling2D, Dropout,concatenate
from keras.layers.core import Reshape, Flatten
from keras.callbacks import EarlyStopping
from keras.optimizers import Adam
from keras.models import Model
from keras import regularizers

sequence_length = 409
filter_sizes = [3,4,5]
num_filters = 64
drop = 0.5
EMBEDDING_DIM=100


embedding_layer = Embedding(len(tokenizer.word_index) + 1,
                            EMBEDDING_DIM,
                            weights=[embedding_matrix],
                            trainable=True)


inputs = Input(shape=(sequence_length,))
embedding = embedding_layer(inputs)
reshape = Reshape((sequence_length,EMBEDDING_DIM,1))(embedding)

conv_0 = Conv2D(num_filters, (filter_sizes[0], EMBEDDING_DIM),activation='relu',kernel_regularizer=regularizers.l2(0.01),name='conv_1')(reshape)
conv_1 = Conv2D(num_filters, (filter_sizes[1], EMBEDDING_DIM),activation='relu',kernel_regularizer=regularizers.l2(0.01),name='conv_2')(reshape)
conv_2 = Conv2D(num_filters, (filter_sizes[2], EMBEDDING_DIM),activation='relu',kernel_regularizer=regularizers.l2(0.01),name='conv_3')(reshape)

maxpool_0 = MaxPooling2D((sequence_length - filter_sizes[0] + 1, 1), strides=(1,1))(conv_0)
maxpool_1 = MaxPooling2D((sequence_length - filter_sizes[1] + 1, 1), strides=(1,1))(conv_1)
maxpool_2 = MaxPooling2D((sequence_length - filter_sizes[2] + 1, 1), strides=(1,1))(conv_2)

merged_tensor = concatenate([maxpool_0, maxpool_1, maxpool_2], axis=1)
flatten = Flatten()(merged_tensor)
reshape = Reshape((3*num_filters,))(flatten)
dropout = Dropout(drop)(flatten)
output = Dense(units=3, activation='softmax',kernel_regularizer=regularizers.l2(0.01))(dropout)

# this creates a model that includes
model = Model(inputs, output)
adam = Adam(lr=1e-3)

model.compile(loss='categorical_crossentropy',
              optimizer=adam,
              metrics=['acc'])
print(model.summary())

【问题讨论】:

    标签: python keras deep-learning conv-neural-network


    【解决方案1】:

    这没什么好担心的。这是任何带有内核的卷积操作的基本问题。在图像上卷积的内核的大小会导致一些像素被遗漏。这是link 更详细地描述了该问题。

    假设输入shape为?ℎ×??,卷积核shape为?ℎ×??,那么输出shape为(?ℎ−?ℎ+1)×(??−??+1)

    处理此问题的一种方法是将层中的padding 参数设置为'same'

    tf.keras.layers.Conv2D(
        filters, kernel_size, strides=(1, 1), padding='same', data_format=None,
        dilation_rate=(1, 1), groups=1, activation=None, use_bias=True,
        kernel_initializer='glorot_uniform', bias_initializer='zeros',
        kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None,
        kernel_constraint=None, bias_constraint=None, **kwargs
    )
    

    使用 padding = 'valid'

    > input_shape = (4, 28, 28, 3)
    > x = tf.random.normal(input_shape)
    > y = tf.keras.layers.Conv2D(2, 3, activation='relu', input_shape=input_shape[1:])(x)
    > print(y.shape)
    (4, 26, 26, 3)
    

    使用填充 = 'same'

    > input_shape = (4, 28, 28, 3)
    > x = tf.random.normal(input_shape)
    > y = tf.keras.layers.Conv2D(2, 3, activation='relu', padding="same", input_shape=input_shape[1:])(x)
    > print(y.shape)
    (4, 28, 28, 3)
    

    编辑:您最好将 conv1d 用于文本/时间数据,而不是使用 conv2d 进行多次重塑。这是您的一维卷积模型架构。

    我不确定你为什么要为 maxpooling 层做你正在做的事情。我基本上试图保持相同的前向计算,但你应该看看这些层,看看它们是否有意义。

    from tensorflow.keras import layers, Model, regularizers
    
    vocab_size = 1000
    
    inp = layers.Input(shape=(409,))
    emb = layers.Embedding(vocab_size, 100)(inp)
    conv1 = layers.Conv1D(64, 3, padding='same')(emb)
    conv2 = layers.Conv1D(64, 4, padding='same')(emb)
    conv3 = layers.Conv1D(64, 5, padding='same')(emb)
    
    max1 = layers.MaxPool1D(409, strides=1)(conv1)
    max2 = layers.MaxPool1D(409, strides=1)(conv2)
    max3 = layers.MaxPool1D(409, strides=1)(conv3)
    
    conc = layers.concatenate([max1, max2, max3])
    flat = layers.Flatten()(conc)
    drop = layers.Dropout(0.5)(flat)
    out = layers.Dense(3, activation='softmax', kernel_regularizer='l2')(drop)
    
    model = Model(inp,out)
    model.summary()
    
    __________________________________________________________________________________________________
    Layer (type)                    Output Shape         Param #     Connected to                     
    ==================================================================================================
    input_21 (InputLayer)           [(None, 409)]        0                                            
    __________________________________________________________________________________________________
    embedding_20 (Embedding)        (None, 409, 100)     100000      input_21[0][0]                   
    __________________________________________________________________________________________________
    conv1d_50 (Conv1D)              (None, 409, 64)      19264       embedding_20[0][0]               
    __________________________________________________________________________________________________
    conv1d_51 (Conv1D)              (None, 409, 64)      25664       embedding_20[0][0]               
    __________________________________________________________________________________________________
    conv1d_52 (Conv1D)              (None, 409, 64)      32064       embedding_20[0][0]               
    __________________________________________________________________________________________________
    max_pooling1d_39 (MaxPooling1D) (None, 1, 64)        0           conv1d_50[0][0]                  
    __________________________________________________________________________________________________
    max_pooling1d_40 (MaxPooling1D) (None, 1, 64)        0           conv1d_51[0][0]                  
    __________________________________________________________________________________________________
    max_pooling1d_41 (MaxPooling1D) (None, 1, 64)        0           conv1d_52[0][0]                  
    __________________________________________________________________________________________________
    concatenate_11 (Concatenate)    (None, 1, 192)       0           max_pooling1d_39[0][0]           
                                                                     max_pooling1d_40[0][0]           
                                                                     max_pooling1d_41[0][0]           
    __________________________________________________________________________________________________
    flatten_5 (Flatten)             (None, 192)          0           concatenate_11[0][0]             
    __________________________________________________________________________________________________
    dropout_4 (Dropout)             (None, 192)          0           flatten_5[0][0]                  
    __________________________________________________________________________________________________
    dense_3 (Dense)                 (None, 3)            579         dropout_4[0][0]                  
    ==================================================================================================
    Total params: 177,571
    Trainable params: 177,571
    Non-trainable params: 0
    

    【讨论】:

    • 感谢当我添加 padding="same" 时,错误:新数组的总大小必须保持不变
    • 不管是文本还是图像,卷积都是很自然的事情。另外,我看到您正在使用 conv2d 但仍在单个维度上进行卷积。为什么不直接使用 conv1d?这就是通常用于文本分类的内容。
    • 另外,您面临的问题更多是与这里使用的稍微奇怪的内核形状有关。\
    • 不用重塑和添加新维度,只需使用 conv1d。这将涉及类似于您当前正在做的嵌入。
    • 非常感谢您能帮我实现吗?我是 python 和 cnn 的新手..
    猜你喜欢
    • 2015-06-26
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多