最近在做QA系统,用tensorflow做了些实验,下面的的是一个cnn的评分网络。主要参考了《APPLYING DEEP LEARNING TO ANSWER SELECTION: A STUDY AND AN OPEN TASK》这篇论文与wildml博客中的一篇文章

import tensorflow as tf
import numpy as np
class QaCNN():
def __init__(self , batchsize , sequencesize , vecsize , outsize , filtersizes , num_filters):
self.vecsize = vecsize
self.outsize = outsize
self.batchsize = batchsize
self.sequencesize = sequencesize
self.question = tf.placeholder(tf.float32 , [None , vecsize * sequencesize],name='question')
self.answer_rigth = tf.placeholder(tf.float32 , [None , vecsize * sequencesize],name='answer_right')
self.answer_wrong = tf.placeholder(tf.float32 , [None , vecsize * sequencesize],name='answer_wrong') tenQ = tf.reshape(self.question , [-1 , self.sequencesize , self.vecsize , 1])
tenR = tf.reshape(self.answer_rigth , [-1 , self.sequencesize , self.vecsize , 1])
tenW = tf.reshape(self.answer_wrong , [-1 , self.sequencesize , self.vecsize , 1])
tensorResultQ = []
tensorResultR = []
tensorResultW = []
for i , filtersize in enumerate(filtersizes):
with tf.name_scope("conv-maxpool-%s" % filtersize):
filter_shape = [filtersize, self.vecsize, 1, num_filters]
#W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1),name='W')
W = tf.get_variable(initializer=tf.truncated_normal(filter_shape, stddev=0.1),
name="W-%s" % str(filtersize))
#b = tf.Variable(tf.constant(0.1, shape=[num_filters]),name='b')
b = tf.get_variable(initializer=tf.constant(0.1, shape=[num_filters]),
name="b-%s" % str(filtersize))
pooledQ = self.conv2dPool(tenQ , W , b , filtersize)
pooledR = self.conv2dPool(tenR, W , b , filtersize)
pooledW = self.conv2dPool(tenW , W , b , filtersize)
tensorResultQ.append(pooledQ)
tensorResultR.append(pooledR)
tensorResultW.append(pooledW) flat_length = len(filtersizes) * num_filters
tenQ_flat = tf.reshape(tf.concat(tensorResultQ,3),[-1,flat_length])
tenR_flat = tf.reshape(tf.concat(tensorResultR,3),[-1,flat_length])
tenW_flat = tf.reshape(tf.concat(tensorResultW,3),[-1,flat_length]) exy = tf.reduce_sum(tf.multiply(tenQ_flat , tenR_flat) , 1)
x = tf.sqrt(tf.reduce_sum(tf.multiply(tenQ_flat , tenQ_flat) , 1))
y = tf.sqrt(tf.reduce_sum(tf.multiply(tenR_flat , tenR_flat) , 1))
cosineQR = tf.div(exy , tf.multiply(x , y),name = 'cosineQR') exy = tf.reduce_sum(tf.multiply(tenQ_flat , tenW_flat) , 1)
x = tf.sqrt(tf.reduce_sum(tf.multiply(tenQ_flat , tenQ_flat) , 1))
y = tf.sqrt(tf.reduce_sum(tf.multiply(tenW_flat , tenW_flat) , 1))
cosineQW = tf.div(exy , tf.multiply(x , y),name = 'cosineQW') with tf.name_scope('losses'):
zero = tf.constant(0, shape=[self.batchsize], dtype=tf.float32)
margin = tf.constant(0.05, shape=[self.batchsize], dtype=tf.float32)
self.losses = tf.maximum(zero, tf.subtract(margin, tf.subtract(cosineQR, cosineQW)),name = 'loss_tensor')
self.loss = tf.reduce_sum(self.losses,name='loss')
with tf.name_scope('acc'):
self.correct = tf.equal(zero,self.losses)
self.accuracy = tf.reduce_mean(tf.cast(self.correct , 'float'),name='accuracy')
tf.summary.scalar('loss',self.loss)
self.variable_summaries(self.accuracy)
self.merged = tf.summary.merge_all() def variable_summaries(self , var):
'''Attach a lot of summaries to a Tensor (for TensorBoard visualization).'''
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean',mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev',stddev)
tf.summary.scalar('max',tf.reduce_max(var))
tf.summary.scalar('min',tf.reduce_min(var))
tf.summary.histogram('histogram',var) def conv2dPool(self ,x,W,b,filtersize):
conv = tf.nn.conv2d(x , W , strides =[1,1,1,1],padding='VALID')
h = tf.nn.relu(tf.nn.bias_add(conv ,b))
pooled = tf.nn.max_pool(h,ksize=[1,self.sequencesize - filtersize + 1 , 1, 1],strides=[1,1,1,1],padding='VALID')
return pooled
import numpy as np
import time
import os
import tensorflow as tf
from qacnn_g import *
from process import *
batchsize = 100
sequencesize = 10
vecsize = 200
outsize = 10
root = './lib/'
filtersize = [1,2,3,5]
num_filter = 500
if os.path.exists('./lib/corpus.seg.length.out'):
os.remove(root + 'corpus.seg.length.out')
logfolder = time.strftime("%Y%m%d_%H%M%S", time.localtime())
cnn = QaCNN(batchsize , sequencesize , vecsize , outsize , filtersize , num_filter)
train_step = tf.train.AdamOptimizer(1e-4).minimize(cnn.loss)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
train_writer = tf.summary.FileWriter('./LOGS/'+logfolder,sess.graph)
saver = tf.train.Saver(tf.all_variables())
print ('init...')
dataprocess = DataProcess(root + 'word2vec.bin')
dataprocess.normalize(root + 'corpus.seg.out', root + 'corpus.seg.length.out')
dataprocess.initdata(root + 'corpus.seg.length.out')
start = time.time()
for i in range(120000):
batch =dataprocess.nextbatch(batchsize)#ake_data(batchsize) #fake_data(20, True)
sess.run(train_step ,feed_dict={cnn.question: batch[0],cnn.answer_rigth:batch[1] , cnn.answer_wrong:batch[2]})
if i % 10 == 0:
summary,loss, accuracy,_ = sess.run([cnn.merged , cnn.loss , cnn.accuracy , train_step ] , {cnn.question: batch[0],cnn.answer_rigth:batch[1] , cnn.answer_wrong:batch[2]})
train_writer.add_summary(summary , i)
end = time.time()
elapse = (end - start)
print ('iterator %d.\tloss=%f\taccuracy=%f\telapse=%f'%(i,loss,accuracy,elapse))
start = time.time()
else:
sess.run(train_step ,feed_dict={cnn.question: batch[0],cnn.answer_rigth:batch[1] , cnn.answer_wrong:batch[2]})
train_writer.close()
saver.save(sess , './model/qa.cnn')
sess.close()
print ('end...')

使用了1200W数据来训练,下面是loss的拆线图。

accuracy

使用模型进行打分,这里取了cosineR这个正向答案与问题的cosine值进行度量。

# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import os
import time
from process import * tf.flags.DEFINE_string('./lib/corpus.out','','Data to predict')
tf.flags.DEFINE_string('checkpoint_dir','./model/','checkpoint directory from training run')
tf.flags.DEFINE_integer('batch_size',1000,'batch size')
tf.flags.DEFINE_string('root','./lib','root dir')
FLAGS = tf.flags.FLAGS
FLAGS._parse_flags()
print ('\nParameters:')
for attr , value in sorted(FLAGS.__flags.items()):
print ('{}={}'.format(attr.upper() , value)) print('') checkpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)
dataprocess = DataProcess('./lib/word2vec.bin')
dataprocess.initdata('./lib/corpus.seg.length.out')
graph = tf.Graph()
with graph.as_default():
sess = tf.Session()
with sess.as_default():
saver = tf.train.import_meta_graph('{}.meta'.format(checkpoint_file))
saver.restore(sess , checkpoint_file) start = time.time()
bestAnswer = None
maxScore = -1.0
for i in range(10000):
question = graph.get_operation_by_name('question').outputs[0]
answer_right = graph.get_operation_by_name('answer_right').outputs[0]
answer_wrong = graph.get_operation_by_name('answer_wrong').outputs[0]
loss = graph.get_operation_by_name('losses/loss').outputs[0]
cosineQR = graph.get_operation_by_name('cosineQR').outputs[0]
questionbatch = dataprocess.getSentenceVec('你叫什么名字',10,FLAGS.batch_size)
batchs = dataprocess.nextbatch(FLAGS.batch_size)
cosineQR = sess.run(cosineQR, {question:questionbatch, answer_right:batchs[1],answer_wrong:batchs[2]})
ndx = np.argmax(cosineQR)
score = cosineQR[ndx]
if maxScore < score:
maxScore = score
bestAnswer = batchs[3][ndx]
print ('iterate : %d\tscore:%f\tmaxscore:%f\tanswer:%s'%(i,score,maxScore,(batchs[3][ndx]).strip('\n')))
end = time.time()
print('time used:%f'%(end - start))
print('maxScore:%f'%maxScore)
print('best answer :%s'%bestAnswer)
def find(cosineTensor):
return np.argmax(cosineTensor)

cnn for qa的更多相关文章

  1. QA问答系统,QA匹配论文学习笔记

    论文题目: WIKIQA: A Challenge Dataset for Open-Domain Question Answering 论文代码运行: 首先按照readme中的提示安装需要的部分 遇 ...

  2. (QACNN)自然语言处理:智能问答 IBM 保险QA QACNN 实现笔记

    follow: https://github.com/white127/insuranceQA-cnn-lstm http://www.52nlp.cn/qa%E9%97%AE%E7%AD%94%E7 ...

  3. 自然语言处理:问答 + CNN 笔记

    参考 Applying Deep Learning To Answer Selection: A Study And An Open Task follow: http://www.52nlp.cn/ ...

  4. 敏捷团队中的QA由来

    QA,全称为Quality Analyst,即质量分析师(有些称为Quality Assurance,即质量保证师).为什么它总跟质量扯在一块?感觉这个角色明明做的都是测试的事情,为什么不直接叫做te ...

  5. Deep learning:五十一(CNN的反向求导及练习)

    前言: CNN作为DL中最成功的模型之一,有必要对其更进一步研究它.虽然在前面的博文Stacked CNN简单介绍中有大概介绍过CNN的使用,不过那是有个前提的:CNN中的参数必须已提前学习好.而本文 ...

  6. 卷积神经网络(CNN)学习算法之----基于LeNet网络的中文验证码识别

    由于公司需要进行了中文验证码的图片识别开发,最近一段时间刚忙完上线,好不容易闲下来就继上篇<基于Windows10 x64+visual Studio2013+Python2.7.12环境下的C ...

  7. 如何用卷积神经网络CNN识别手写数字集?

    前几天用CNN识别手写数字集,后来看到kaggle上有一个比赛是识别手写数字集的,已经进行了一年多了,目前有1179个有效提交,最高的是100%,我做了一下,用keras做的,一开始用最简单的MLP, ...

  8. CNN车型分类总结

    最近在做一个CNN车型分类的任务,首先先简要介绍一下这个任务. 总共30个类,训练集图片为车型图片,类似监控拍摄的车型图片,训练集测试集安6:4分,训练集有22302份数据,测试集有14893份数据. ...

  9. The difference between QA, QC, and Test Engineering

    Tuesday, March 06, 2007 Posted by Allen Hutchison, Engineering Manager and Jay Han, Software Enginee ...

随机推荐

  1. C++ c++与C语言的区别(空结构体)

    //区别⑨:空结构体声明(C++版本) #include<iostream> using namespace std; struct A{}; class B{}; void main() ...

  2. MySQL Python教程(2)

    mysql官网关于python的API是最经典的学习材料,相信对于所有函数浏览一遍以后,Mysql数据库用起来一定得心应手. 首先看一下Connector/Python API包含哪些类和模块. Mo ...

  3. selenium 获取按钮的笔记

    测试odoo时,发现大部分按钮都是动态生成,id也是动态的, 只能用xpath,但是配置一旦改变导致按钮位置改变 想到一个办法,遍历所有按钮,然后内容相符的才点击,测试代码如下 submit_loc ...

  4. 敏捷软件开发实践-Sprint Retrospective Meeting(转)

    介绍: 在敏捷开发模式中,Sprint Retrospective Meeting 也是一个必不可少的环节,它通常发生在每个Sprint的结尾,其主要作用是对于当前的迭代周期做一个阶段性的总结,包括好 ...

  5. html的a标签的 href 和 onclick。

    主要用于给超链接添加点击事件. aa.html <html> <body> <span>this si</span> </body> < ...

  6. RabbitMQ之Queues-5

    工作队列的主要任务是:避免立刻执行资源密集型任务,然后必须等待其完成.相反地,我们进行任务调度:我们把任务封装为消息发送给队列.工作进行在后台运行并不断的从队列中取出任务然后执行.当你运行了多个工作进 ...

  7. 将spark默认日志log4j替换为logback

    1.将jars文件夹下apache-log4j-extras-1.2.17.jar,commons-logging-1.1.3.jar, log4j-1.2.17.jar, slf4j-log4j12 ...

  8. MathType与Office公式编辑器有什么不同

    说到在论文中编辑公式,有经验的人都会知道要用公式编辑器来编辑,没经验的人也会被安利使用公式编辑器.然而在使用公式编辑器时,又有了两种选择,一种是使用Office自带的公式编辑器,一种是MathType ...

  9. ios 从URL中截取所包含的参数,并且以字典的形式返回和参数字典转URL

    //字典转链接(参数) - (NSString *)keyValueStringWithDict:(NSDictionary *)dict { if (dict == nil) { return ni ...

  10. Ubuntu16.04最快捷搭建小型局域网Git服务器

    导读 使用linux操作系统,不得不提Git版本管理器,这个Linus花了两周时间开发的分布式版本管理器(这就是大神,先膜了个拜...),毫无疑问,Git版本管理器与linux系统有着与生俱来的同一血 ...