Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
zackhy
GitHub Repository: zackhy/TextClassification
Path: blob/master/cnn_classifier.py
1 views
1
# -*- coding: utf-8 -*-
2
import tensorflow as tf
3
4
class cnn_clf(object):
5
"""
6
A CNN classifier for text classification
7
"""
8
def __init__(self, config):
9
self.max_length = config.max_length
10
self.num_classes = config.num_classes
11
self.vocab_size = config.vocab_size
12
self.embedding_size = config.embedding_size
13
self.filter_sizes = list(map(int, config.filter_sizes.split(",")))
14
self.num_filters = config.num_filters
15
self.l2_reg_lambda = config.l2_reg_lambda
16
17
# Placeholders
18
self.input_x = tf.placeholder(dtype=tf.int32, shape=[None, self.max_length], name='input_x')
19
self.input_y = tf.placeholder(dtype=tf.int64, shape=[None], name='input_y')
20
self.keep_prob = tf.placeholder(dtype=tf.float32, name='keep_prob')
21
22
# L2 loss
23
self.l2_loss = tf.constant(0.0)
24
25
# Word embedding
26
with tf.device('/cpu:0'), tf.name_scope('embedding'):
27
embedding = tf.Variable(tf.random_uniform([self.vocab_size, self.embedding_size], -1.0, 1.0),
28
name="embedding")
29
embed = tf.nn.embedding_lookup(embedding, self.input_x)
30
inputs = tf.expand_dims(embed, -1)
31
32
# Convolution & Maxpool
33
pooled_outputs = []
34
for i, filter_size in enumerate(self.filter_sizes):
35
with tf.variable_scope("conv-maxpool-%s" % filter_size):
36
# Convolution
37
filter_shape = [filter_size, self.embedding_size, 1, self.num_filters]
38
W = tf.get_variable("weights", filter_shape, initializer=tf.truncated_normal_initializer(stddev=0.1))
39
b = tf.get_variable("biases", [self.num_filters], initializer=tf.constant_initializer(0.0))
40
41
conv = tf.nn.conv2d(inputs,
42
W,
43
strides=[1, 1, 1, 1],
44
padding='VALID',
45
name='conv')
46
# Activation function
47
h = tf.nn.relu(tf.nn.bias_add(conv, b), name='relu')
48
49
# Maxpool
50
pooled = tf.nn.max_pool(h,
51
ksize=[1, self.max_length - filter_size + 1, 1, 1],
52
strides=[1, 1, 1, 1],
53
padding='VALID',
54
name='pool')
55
pooled_outputs.append(pooled)
56
57
num_filters_total = self.num_filters * len(self.filter_sizes)
58
h_pool = tf.concat(pooled_outputs, 3)
59
h_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])
60
61
# Add dropout
62
h_drop = tf.nn.dropout(h_pool_flat, keep_prob=self.keep_prob)
63
64
# Softmax
65
with tf.name_scope('softmax'):
66
softmax_w = tf.Variable(tf.truncated_normal([num_filters_total, self.num_classes], stddev=0.1), name='softmax_w')
67
softmax_b = tf.Variable(tf.constant(0.1, shape=[self.num_classes]), name='softmax_b')
68
69
# Add L2 regularization to output layer
70
self.l2_loss += tf.nn.l2_loss(softmax_w)
71
self.l2_loss += tf.nn.l2_loss(softmax_b)
72
73
self.logits = tf.matmul(h_drop, softmax_w) + softmax_b
74
predictions = tf.nn.softmax(self.logits)
75
self.predictions = tf.argmax(predictions, 1, name='predictions')
76
77
# Loss
78
with tf.name_scope('loss'):
79
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.input_y, logits=self.logits)
80
# Add L2 losses
81
self.cost = tf.reduce_mean(losses) + self.l2_reg_lambda * self.l2_loss
82
83
# Accuracy
84
with tf.name_scope('accuracy'):
85
correct_predictions = tf.equal(self.predictions, self.input_y)
86
self.correct_num = tf.reduce_sum(tf.cast(correct_predictions, tf.float32))
87
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32), name='accuracy')
88
89