【问题标题】:How to configure and train the model using Glove and CNN for text classification?如何使用 Glove 和 CNN 配置和训练模型进行文本分类?
【发布时间】:2021-11-30 15:53:29
【问题描述】:

我曾使用 Glove 和 CNN 进行文本分类,发现以下问题:

File "c:\programfiles_anaconda\anaconda3\envs\math_stat_class\lib\site-packages\tensorflow\python\framework\ops.py", line 1657, in _create_c_op
    raise ValueError(str(e))

ValueError: Negative dimension size caused by subtracting 5 from 1 for '{{node max_pooling1d_9/MaxPool}} = MaxPool[T=DT_FLOAT, data_format="NHWC", ksize=[1, 5, 1, 1], padding="VALID", strides=[1, 5, 1, 1]](max_pooling1d_9/ExpandDims)' with input shapes: [?,1,1,128].

手套输入

EMBEDDING_DIM = 100
    
embeddings_index = {}
    
f = open(glove_path, encoding='utf-8')  
for line in f:    
    values = line.split()
    word = values[0]
    coefs = np.asarray(values[1:], dtype='float32')
    embeddings_index[word] = coefs
    f.close()
    
print('Found %s word vectors.' % len(embeddings_index))
    
embedding_matrix = np.zeros((len(word_index) + 1, EMBEDDING_DIM))
    
for word, i in word_index.items():
    embedding_vector = embeddings_index.get(word)
    if embedding_vector is not None:
        # words not found in embedding index will be all-zeros.
        embedding_matrix[i] = embedding_vector

CNN的层输入

# apply embedding matrix into an Embedding layer
# trainable=False to prevent the weights from being updated during training
embedding_layer = Embedding(len(word_index) + 1,
                            EMBEDDING_DIM,
                            weights=[embedding_matrix],
                            input_length=MAX_SEQUENCE_LENGTH,
                            trainable=False)

训练一维 CNN

sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')
embedded_sequences = embedding_layer(sequence_input)

x = Conv1D(128, 5, activation='relu')(embedded_sequences)   
print("x shape = ", x)

x = MaxPooling1D(5)(x)  
print("x shape = ", x)
        
x = Conv1D(128, 5, activation='relu')(x)
print("x shape = ", x)
    
#-----This line below produced error-----
x = MaxPooling1D(5)(x) #Error this line
#-----This line above produced error-----
        
print("x shape = ", x)

x = Conv1D(128, 5, activation='relu')(x)
print("x shape = ", x)
    
x = MaxPooling1D(35)(x)  # global max pooling
print("x shape = ", x)
    
x = Flatten()(x)
x = Dense(128, activation='relu')(x)
    
preds = Dense(len(labels_index), activation='softmax')(x)
model = Model(sequence_input, preds)
model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['acc'])
    
# Learning
model.fit(X_train, y_train, validation_data=(X_val, y_val),
          epochs=2, batch_size=128)

我的想法

1) Glove 输入是否存在一些问题/问题?

2)Conv1D:

  • 将“kernel_size”从 5 更改为新值。

3) MaxPooling1D:

  • 将 pool_size 从 5 更改为新值。
  • 指定其他参数:strides、padding 等。

4) 我目前在 tensorflow 2.20 和 python 3.6 上使用 keras

  • 我需要升级 tensorflow 和 python 吗?

但是,我想不出更好的方法。我可以给你一些建议吗?

【问题讨论】:

    标签: python tensorflow conv-neural-network stanford-nlp text-classification


    【解决方案1】:

    我想到了两件事:您的最大池化层每次都会减小下一个卷积层的输入大小,最终尺寸太小而无法运行另一个最大池化操作。尝试运行

     tf.print(model.summary) 
    

    在每次最大池化操作之后,您会很快发现您的张量无法进一步减少。然后,您可以考虑在最大池化层中使用不同的 pool_size

    我注意到的第二件事(我不确定它是否是故意的),但是 MaxPooling1D != Global Max Pooling。 Keras 同时支持operations。查看文档。

    另一方面,使用 CNN 进行句子分类被 Yoon Kim 的 work 广泛推广。在他的工作中,他展示了全局最大池操作在句子分类中的性能比跨步最大池操作要好得多(当使用词嵌入时,就像你正在做的那样)。

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      • 2017-07-18
      相关资源
      最近更新 更多