Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
zackhy
GitHub Repository: zackhy/TextClassification
Path: blob/master/clstm_classifier.py
1 views
1
# -*- coding: utf-8 -*-
2
import numpy as np
3
import tensorflow as tf
4
5
6
class clstm_clf(object):
7
"""
8
A C-LSTM classifier for text classification
9
Reference: A C-LSTM Neural Network for Text Classification
10
"""
11
def __init__(self, config):
12
self.max_length = config.max_length
13
self.num_classes = config.num_classes
14
self.vocab_size = config.vocab_size
15
self.embedding_size = config.embedding_size
16
self.filter_sizes = list(map(int, config.filter_sizes.split(",")))
17
self.num_filters = config.num_filters
18
self.hidden_size = len(self.filter_sizes) * self.num_filters
19
self.num_layers = config.num_layers
20
self.l2_reg_lambda = config.l2_reg_lambda
21
22
# Placeholders
23
self.batch_size = tf.placeholder(dtype=tf.int32, shape=[], name='batch_size')
24
self.input_x = tf.placeholder(dtype=tf.int32, shape=[None, self.max_length], name='input_x')
25
self.input_y = tf.placeholder(dtype=tf.int64, shape=[None], name='input_y')
26
self.keep_prob = tf.placeholder(dtype=tf.float32, shape=[], name='keep_prob')
27
self.sequence_length = tf.placeholder(dtype=tf.int32, shape=[None], name='sequence_length')
28
29
# L2 loss
30
self.l2_loss = tf.constant(0.0)
31
32
# Word embedding
33
with tf.device('/cpu:0'), tf.name_scope('embedding'):
34
embedding = tf.Variable(tf.random_uniform([self.vocab_size, self.embedding_size], -1.0, 1.0),
35
name="embedding")
36
embed = tf.nn.embedding_lookup(embedding, self.input_x)
37
inputs = tf.expand_dims(embed, -1)
38
39
# Input dropout
40
inputs = tf.nn.dropout(inputs, keep_prob=self.keep_prob)
41
42
conv_outputs = []
43
max_feature_length = self.max_length - max(self.filter_sizes) + 1
44
# Convolutional layer with different lengths of filters in parallel
45
# No max-pooling
46
for i, filter_size in enumerate(self.filter_sizes):
47
with tf.variable_scope('conv-%s' % filter_size):
48
# [filter size, embedding size, channels, number of filters]
49
filter_shape = [filter_size, self.embedding_size, 1, self.num_filters]
50
W = tf.get_variable('weights', filter_shape, initializer=tf.truncated_normal_initializer(stddev=0.1))
51
b = tf.get_variable('biases', [self.num_filters], initializer=tf.constant_initializer(0.0))
52
53
# Convolution
54
conv = tf.nn.conv2d(inputs,
55
W,
56
strides=[1, 1, 1, 1],
57
padding='VALID',
58
name='conv')
59
# Activation function
60
h = tf.nn.relu(tf.nn.bias_add(conv, b), name='relu')
61
62
# Remove channel dimension
63
h_reshape = tf.squeeze(h, [2])
64
# Cut the feature sequence at the end based on the maximum filter length
65
h_reshape = h_reshape[:, :max_feature_length, :]
66
67
conv_outputs.append(h_reshape)
68
69
# Concatenate the outputs from different filters
70
if len(self.filter_sizes) > 1:
71
rnn_inputs = tf.concat(conv_outputs, -1)
72
else:
73
rnn_inputs = h_reshape
74
75
# LSTM cell
76
cell = tf.contrib.rnn.LSTMCell(self.hidden_size,
77
forget_bias=1.0,
78
state_is_tuple=True,
79
reuse=tf.get_variable_scope().reuse)
80
# Add dropout to LSTM cell
81
cell = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=self.keep_prob)
82
83
# Stacked LSTMs
84
cell = tf.contrib.rnn.MultiRNNCell([cell]*self.num_layers, state_is_tuple=True)
85
86
self._initial_state = cell.zero_state(self.batch_size, dtype=tf.float32)
87
88
# Feed the CNN outputs to LSTM network
89
with tf.variable_scope('LSTM'):
90
outputs, state = tf.nn.dynamic_rnn(cell,
91
rnn_inputs,
92
initial_state=self._initial_state,
93
sequence_length=self.sequence_length)
94
self.final_state = state
95
96
# Softmax output layer
97
with tf.name_scope('softmax'):
98
softmax_w = tf.get_variable('softmax_w', shape=[self.hidden_size, self.num_classes], dtype=tf.float32)
99
softmax_b = tf.get_variable('softmax_b', shape=[self.num_classes], dtype=tf.float32)
100
101
# L2 regularization for output layer
102
self.l2_loss += tf.nn.l2_loss(softmax_w)
103
self.l2_loss += tf.nn.l2_loss(softmax_b)
104
105
# logits
106
self.logits = tf.matmul(self.final_state[self.num_layers - 1].h, softmax_w) + softmax_b
107
predictions = tf.nn.softmax(self.logits)
108
self.predictions = tf.argmax(predictions, 1, name='predictions')
109
110
# Loss
111
with tf.name_scope('loss'):
112
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.input_y, logits=self.logits)
113
self.cost = tf.reduce_mean(losses) + self.l2_reg_lambda * self.l2_loss
114
115
# Accuracy
116
with tf.name_scope('accuracy'):
117
correct_predictions = tf.equal(self.predictions, self.input_y)
118
self.correct_num = tf.reduce_sum(tf.cast(correct_predictions, tf.float32))
119
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32), name='accuracy')
120
121