ATT-CNN实现修改--循环变矩阵乘法

开篇
对于自然语言处理(NLP)我是一个入门菜鸟,在后面一段工作时间中,我将大量接触金融的AI业务,因此需要补充些该领域的知识。经过了解发现AI金融有很多业务是和NLP相关的,当然也有OCR、图像检测分类、人脸识别和语音识别等。

上周接触了一下文本分类,了解的不多,学习了一下ATT-CNN用于文本分类的代码,发现了一些问题,写这篇博客记录一下。首先描述下代码中实现文本分类(句子为单样本)的方式:1、中文文本分词、分字符,用的是jieba;2、构建字典、词典,最长句子作为所有句向量的长度;3、字、词向量嵌入用embedding_lookup;4、句子与单个字符或词用attention,单个词向量使用attention之后增加一倍的长度;5、字词分别做卷积、池化,然后拼接合并,用统一标签求loss。

主要就是在上述的第4步骤中,原始的代码用了多次循环去求取增加的这一倍向量,导致前向计算和反向求导所用时间巨长,加载图的过程就花费不止2个小时,所以修改了下实现方式。

ATT-CNN的介绍
https://blog.csdn.net/tcx1992/article/details/83344272

原作者代码实现
https://github.com/tcxdgit/cnn_multilabel_classification/blob/master/cnn_attention_model.py

参考的方法
https://www.jianshu.com/p/cc6407444a8c

改动前

def word_attention(self, x_i, x, index):

"""

计算词attention

    :paramx_i: 当前时间(step)的词向量

    :paramx: 所有时间(整个句子)的向量(矩阵)

    :paramindex: 当前step

    :return:

"""

```python
    with tf.device(self.train_device):

e_i =list()

c_i =list()

for outputin x:

output = tf.reshape(output, [-1, self.embedding_size])
att_hidden = tf.tanh(tf.add(tf.matmul(x_i, self.attention_W), tf.matmul(output, self.attention_U)))

e_i_j = tf.matmul(att_hidden, self.attention_V)

e_i.append(e_i_j)

e_i = tf.concat(e_i, axis=1)

alpha_i = tf.split(tf.nn.softmax(e_i), self.sentence_length, 1)

for j, (alpha_i_j, output)in enumerate(zip(alpha_i, x)):

if j == index:

continue

            else:

output = tf.reshape(output, [-1, self.embedding_size])

c_i_j = tf.multiply(alpha_i_j, output)

c_i.append(c_i_j)

c_i = tf.reduce_sum(tf.reshape(tf.concat(c_i, axis=1), [-1, self.sentence_length -1, self.embedding_size]), 1)

return c_i

改动后

def word_attention_wpf(self, x_i, x, index):

"""

计算词attention

    :paramx_i: 当前时间(step)的词向量

    :paramx: 所有时间(整个句子)的向量(矩阵)

    :paramindex: 当前step

    :return:

"""

    with tf.device(self.train_device):

output=tf.tile(tf.expand_dims(tf.matmul(x_i, self.attention_W),1),[1,x.get_shape().as_list()[1],1])

att_hidden = tf.tanh(tf.add(output, tf.tensordot(x, self.attention_U,axes=1)))

e_i_j = tf.tensordot(att_hidden, self.attention_V,axes=1)

alpha_i = tf.nn.softmax(e_i_j)

c_i_j = tf.multiply(alpha_i, x)

#tf.assign(c_i_j[:,index,:],0)

        c_i = tf.reduce_sum(c_i_j,1)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值