如何使用张量流将具有“是”或“否”的分类更改为得分“是”或“否”?

时间:2018-07-15 05:06:55

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

我不是深度学习的新手。我使用tensorflow参照此tutorial构建我的TextCNN模型(两个类别)。
该模型可以预测文本的类别。但是我想要一个分数([0,1]中的连续值)而不是离散值。例如,如果模型给出0.77,则文本更有可能是该类别之一;如果给出1.0,则文本实际上就是该类别。
这是我的代码的一部分。

def cnn(self):
    # word embedding
    with tf.device('/cpu:0'):
        embedding = tf.get_variable('embedding', [self.config.vocab_size, self.config.embedding_dim])
        embedding_inputs = tf.nn.embedding_lookup(embedding, self.input_x)

    with tf.name_scope("cnn"):
        # CNN layer
        conv = tf.layers.conv1d(embedding_inputs, self.config.num_filters, self.config.kernel_size, name='conv')
        # global max pooling layer
        gmp = tf.reduce_max(conv, reduction_indices=[1], name='gmp')

    with tf.name_scope("score"):
        # full connected layer
        fc = tf.layers.dense(gmp, self.config.hidden_dim, name='fc1')
        fc = tf.contrib.layers.dropout(fc, self.keep_prob)
        fc = tf.nn.relu(fc)

        # classification
        self.logits = tf.layers.dense(fc, self.config.num_classes, name='fc2')
        self.y_pred_cls = tf.argmax(tf.nn.softmax(self.logits), 1)  # 预测类别

    with tf.name_scope("optimize"):
        # Loss function, cross entropy
        cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.input_y)
        self.loss = tf.reduce_mean(cross_entropy)
        # optimizer
        self.optim = tf.train.AdamOptimizer(learning_rate=self.config.learning_rate).minimize(self.loss)

    with tf.name_scope("accuracy"):
        # accuracy
        correct_pred = tf.equal(tf.argmax(self.input_y, 1), self.y_pred_cls)
        self.acc = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

谢谢。

1 个答案:

答案 0 :(得分:0)

使用tf.nn.softmax(self.logits)来获得概率分数。另请参阅以下问题:What is logits, softmax and softmax_cross_entropy_with_logits?

相关问题