183

使用 Tensorflow 构建 CNN 进行情感分析实践 - 腾讯云社区 - 腾讯云

 6 years ago
source link: https://cloud.tencent.com/community/article/726574?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

使用 Tensorflow 构建 CNN 进行情感分析实践

修改于2017-10-17 01:42:33阅读 4.5K0

导语 一次简单的实验。出于兴趣的自学,求拍砖。

Web挖掘中的情感分析类问题,其实是一个分类问题。而CNN可以用来处理分类任务,就是在最终的softmax函数计算属于各个类的概率,并归属到概率最大的类。

本次实验参照的是Kim Yoon的论文Convolutional Neural Networks for Sentence Classification

代码放在我的GitHub上。可以直接使用。

2.1 数据集

本次实验使用的数据集来自Kaggle。具体文件都在/data路径下(train-kaggle.txt)。训练数据集中每行都包括5个等级的情感(0到4)及具体的影评。dev.txt是验证数据集。用训练数据集训练,根据在验证数据集上的表现选取模型,最后用选定的模型进行分类,得到结果,即result.txt

2.2 网络

下面这张图来自前面提到的Kim Yoon的论文。也是我们代码要实现的网络。第一层是嵌入层,将词组装成低维度的向量。下一层是卷积层,在前一层得到的向量上进行卷积。再下一层,即池化,将卷积层的结果转成特征向量,进行正则化等操作,最后在softmax层得到分类结果。

2.3 代码实现

查看text_cnn.py,这里定义了用于文本分类任务的TextCNN类。初始化时会指定句子长度、类别个数等参数。

class TextCNN(object):
def __init__(
  self, sequence_length, num_classes, vocab_size,
  embedding_size, filter_sizes, num_filters, l2_reg_lambda=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)

代码指定了在CPU上执行,tf.nn.embedding_lookup(...)方法执行真正的嵌入操作。

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)

上面这段代码是卷积层和池化操作,在TensorBoard中可以看可视化的结构:

3 实验结果

执行下面这行命令:

tensorboard --logdir ./runs/1497715905/summaries/

然后访问127.0.0.1:6060,可以在dashboard上看到精度与损失随着迭代变化的曲线。

而用这个模型给测试集分类的结果,就在result.txt中。

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 [email protected] 删除。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK