【问题标题】:How to extract activations from dense layer如何从密集层中提取激活
【发布时间】:2020-08-24 12:55:38
【问题描述】:

我正在尝试为此paperrepo 中的代码)实现预处理代码。这里的论文中描述了预处理代码:

“卷积神经网络 (Kim, 2014) 是 用于从成绩单中提取文本特征 的话语。我们使用单个卷积 层,然后是最大池和全连接层以获得特征表示 对于话语。这个网络的输入是 300 维预训练的 840B GloVe 向量(Pennington 等人,2014)。我们使用过滤器 大小为 3、4 和 5,每个有 50 个特征图。这 然后将卷积特征与 窗口大小为 2,然后是 ReLU 激活(Nair 和 Hinton,2010)。 然后将这些连接起来并馈送到一个 100 维的全连接层,该层的激活形成话语的表示。 该网络在 带有情感标签的话语水平。”

论文作者表示,CNN 特征提取代码可以在这个repo 中找到。但是,此代码适用于进行序列分类的完整模型。它完成了上面引用中的所有内容,除了粗体部分(并且它进一步完成了分类)。我希望编辑代码以构建连接并馈送到 100d 层,然后提取激活。要训​​练的数据可以在 repo(它的 IMDB 数据集)中找到。

每个序列的输出应该是 (100, ) 张量。

这是 CNN 模型的代码:

import tensorflow as tf
import numpy as np


class TextCNN(object):
    """
    A CNN for text classification.
    Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.
    """
    def __init__(
      self, sequence_length, num_classes, vocab_size,
      embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0):

        # Placeholders for input, output and dropout
        self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x")
        self.input_y = tf.placeholder(tf.float32, [None, num_classes], name="input_y")
        self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")

        # Keeping track of l2 regularization loss (optional)
        l2_loss = tf.constant(0.0)

        # Embedding layer
        with tf.device('/cpu:0'), tf.name_scope("embedding"):
            self.W = tf.Variable(
                tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),
                name="W")
            self.embedded_chars = tf.nn.embedding_lookup(self.W, self.input_x)
            self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)

        # Create a convolution + maxpool layer for each filter size
        pooled_outputs = []
        for i, filter_size in enumerate(filter_sizes):
            with tf.name_scope("conv-maxpool-%s" % filter_size):
                # Convolution Layer
                filter_shape = [filter_size, embedding_size, 1, num_filters]
                W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
                b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")
                conv = tf.nn.conv2d(
                    self.embedded_chars_expanded,
                    W,
                    strides=[1, 1, 1, 1],
                    padding="VALID",
                    name="conv")
                # Apply nonlinearity
                h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
                # Maxpooling over the outputs
                pooled = tf.nn.max_pool(
                    h,
                    ksize=[1, sequence_length - filter_size + 1, 1, 1],
                    strides=[1, 1, 1, 1],
                    padding='VALID',
                    name="pool")
                pooled_outputs.append(pooled)

        # Combine all the pooled features
        num_filters_total = num_filters * len(filter_sizes)
        self.h_pool = tf.concat(pooled_outputs, 3)
        self.h_pool_flat = tf.reshape(self.h_pool, [-1, num_filters_total])

        # Add dropout
        with tf.name_scope("dropout"):
            self.h_drop = tf.nn.dropout(self.h_pool_flat, self.dropout_keep_prob)

        # Final (unnormalized) scores and predictions
        with tf.name_scope("output"):
            W = tf.get_variable(
                "W",
                shape=[num_filters_total, num_classes],
                initializer=tf.contrib.layers.xavier_initializer())
            b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b")
            l2_loss += tf.nn.l2_loss(W)
            l2_loss += tf.nn.l2_loss(b)
            self.scores = tf.nn.xw_plus_b(self.h_drop, W, b, name="scores")
            self.predictions = tf.argmax(self.scores, 1, name="predictions")

        # Calculate mean cross-entropy loss
        with tf.name_scope("loss"):
            losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.scores, labels=self.input_y)
            self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss

        # Accuracy
        with tf.name_scope("accuracy"):
            correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))
            self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")

我想将连接到 100d 层以获得激活,我想在第 59 行左右(就在底部附近的 # Add Dropout 部分之前,然后注释掉它下面的其余部分)。我该怎么做?

【问题讨论】:

    标签: python tensorflow keras nlp conv-neural-network


    【解决方案1】:

    您尝试实现的卷积神经网络是 NLP 领域的一个很好的基准。在paper(Kim,2014)中首次介绍了它。

    我发现您报告的代码非常有用,但可能比我们需要的更复杂。我尝试用简单的 keras 重写网络(我只错过了正则化)

    def TextCNN(sequence_length, num_classes, vocab_size, 
                embedding_size, filter_sizes, num_filters, 
                embedding_matrix):
    
        sequence_input = Input(shape=(sequence_length,), dtype='int32')
    
        embedding_layer = Embedding(vocab_size,
                                    embedding_size,
                                    weights=[embedding_matrix],
                                    input_length=sequence_length,
                                    trainable=False)
    
        embedded_sequences = embedding_layer(sequence_input)
    
        convs = []
        for fsz in filter_sizes:
            x = Conv1D(num_filters, fsz, activation='relu', padding='same')(embedded_sequences)
            x = MaxPooling1D(pool_size=2)(x)
            convs.append(x)
    
        x = Concatenate(axis=-1)(convs)
        x = Flatten()(x)
        x = Dropout(0.5)(x)
        output = Dense(num_classes, activation='softmax')(x)
    
        model = Model(sequence_input, output)
        model.compile(loss='categorical_crossentropy',
                      optimizer='adam',
                      metrics=['accuracy'])
    
        return model
    

    初始嵌入是使用在 GLOVE 中学习的权重设置的。您可以上传它们或使用其他技术(Word2Vec 或 FastText)学习新的嵌入表示并上传它们。像往常一样计算拟合度

    我强调以上是网络的原始表示。如果你想在输出之前插入一个 100 的密集层,可以通过这种方式简单地修改(这里是 code reference):

    def TextCNN(sequence_length, num_classes, vocab_size, 
                embedding_size, filter_sizes, num_filters, 
                embedding_matrix):
    
        sequence_input = Input(shape=(sequence_length,), dtype='int32')
    
        embedding_layer = Embedding(vocab_size,
                                    embedding_size,
                                    weights=[embedding_matrix],
                                    input_length=sequence_length,
                                    trainable=False)
    
        embedded_sequences = embedding_layer(sequence_input)
    
        convs = []
        for fsz in filter_sizes:
            x = Conv1D(num_filters, fsz, activation='relu', padding='same')(embedded_sequences)
            x = MaxPooling1D(pool_size=2)(x)
            convs.append(x)
    
        x = Concatenate(axis=-1)(convs)
        x = Flatten()(x)
        x = Dense(100, activation='relu', name='extractor')(x)
        x = Dropout(0.5)(x)
        output = Dense(num_classes, activation='softmax')(x)
    
        model = Model(sequence_input, output)
        model.compile(loss='categorical_crossentropy',
                      optimizer='adam',
                      metrics=['accuracy'])
    
        return model
    
    model = TextCNN(sequence_length=50, num_classes=10, vocab_size=3333, 
            embedding_size=100, filter_sizes=[3,4,5], num_filters=50, 
            embedding_matrix)
    
    model.fit(....)
    

    为了提取我们感兴趣的特征,我们需要 Dense100 的输出(我们将其命名为“提取器”)。我还建议this tutorial 进行过滤和特征提取。

    extractor = Model(model.input, model.get_layer('extractor').output)
    representation = extractor.predict(np.random.randint(0,200, (1000,50)))
    

    representation 将是一个形状为 (n_sample, 100) 的数组

    【讨论】:

      猜你喜欢
      • 2018-11-24
      • 1970-01-01
      • 2019-09-05
      • 2021-04-27
      • 2017-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多