cnn for qa
最近在做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的更多相关文章
- QA问答系统,QA匹配论文学习笔记
论文题目: WIKIQA: A Challenge Dataset for Open-Domain Question Answering 论文代码运行: 首先按照readme中的提示安装需要的部分 遇 ...
- (QACNN)自然语言处理:智能问答 IBM 保险QA QACNN 实现笔记
follow: https://github.com/white127/insuranceQA-cnn-lstm http://www.52nlp.cn/qa%E9%97%AE%E7%AD%94%E7 ...
- 自然语言处理:问答 + CNN 笔记
参考 Applying Deep Learning To Answer Selection: A Study And An Open Task follow: http://www.52nlp.cn/ ...
- 敏捷团队中的QA由来
QA,全称为Quality Analyst,即质量分析师(有些称为Quality Assurance,即质量保证师).为什么它总跟质量扯在一块?感觉这个角色明明做的都是测试的事情,为什么不直接叫做te ...
- Deep learning:五十一(CNN的反向求导及练习)
前言: CNN作为DL中最成功的模型之一,有必要对其更进一步研究它.虽然在前面的博文Stacked CNN简单介绍中有大概介绍过CNN的使用,不过那是有个前提的:CNN中的参数必须已提前学习好.而本文 ...
- 卷积神经网络(CNN)学习算法之----基于LeNet网络的中文验证码识别
由于公司需要进行了中文验证码的图片识别开发,最近一段时间刚忙完上线,好不容易闲下来就继上篇<基于Windows10 x64+visual Studio2013+Python2.7.12环境下的C ...
- 如何用卷积神经网络CNN识别手写数字集?
前几天用CNN识别手写数字集,后来看到kaggle上有一个比赛是识别手写数字集的,已经进行了一年多了,目前有1179个有效提交,最高的是100%,我做了一下,用keras做的,一开始用最简单的MLP, ...
- CNN车型分类总结
最近在做一个CNN车型分类的任务,首先先简要介绍一下这个任务. 总共30个类,训练集图片为车型图片,类似监控拍摄的车型图片,训练集测试集安6:4分,训练集有22302份数据,测试集有14893份数据. ...
- The difference between QA, QC, and Test Engineering
Tuesday, March 06, 2007 Posted by Allen Hutchison, Engineering Manager and Jay Han, Software Enginee ...
随机推荐
- Javascript 验证上传图片大小[客户端验证]
需求分析: 在做上传图片的时候,如果不限制上传图片大小,后果非常的严重.那么我们怎样才可以解决一个棘手的问题呢?有两种方式: 1)后台处理: 也就是AJAX POST提交到后台,把图片上传到服务器上, ...
- Spring的一种拦截器SimpleUrlHandlerMapping
spring的一种拦截器,用于在XML文件中配置以拦截url,它是以map映射的方式进行拦截.映射是从前台urls到具体后台的beans.同时支持到bean实例和bean名称的映射,后者要求非单实例控 ...
- PHP中strlen和mb_strlen函数的区别
strlen strlen — 获取字符串长度 int strlen ( string $string ) 返回给定的字符串 string 的长度. mb_strlen int mb_strlen ( ...
- VB.NET多线程入门
近期项目中遇到了一个处理速度慢阻塞用户界面操作的问题,因此想用多线程来解决. 在处理数据的循环中,新建线程,在新建的线程中处理数据.多线程同一时候处理数据,以此来达到加速的目的,使用户界面操作变得流畅 ...
- sdut 2158:Hello World!(第一届山东省省赛原题,水题,穷举)
Hello World! Time Limit: 1000MS Memory limit: 65536K 题目描述 We know that Ivan gives Saya three problem ...
- poj 1090:The Circumference of the Circle(计算几何,求三角形外心)
The Circumference of the Circle Time Limit: 2 Seconds Memory Limit: 65536 KB To calculate the c ...
- u盘作为git仓库,完成不同地方的代码同步
参考网上一篇 "把Git Repository建到U盘上去" 1.我经常有这样的需求,工作.家里需要对同一份代码或文档编辑,并希望在不同地方能同步: 如果是私密性不那么强,可以直接 ...
- ResNet 结构理解
博客来源于:https://blog.csdn.net/buyi_shizi/article/details/53336192:https://blog.csdn.net/dcrmg/article/ ...
- GCC命令基础
gcc命令使用GNU推出的基于C/C++的编译器,是开放源代码领域应用最广泛的编译器,具有功能强大,编译代码支持性能优化等特点, 现在很多程序员都应用GCC,怎样才能更好的应用GCC. 目前,GCC可 ...
- 【BZOJ1217】[HNOI2003]消防局的设立 树形DP
[BZOJ1217][HNOI2003]消防局的设立 Description 2020年,人类在火星上建立了一个庞大的基地群,总共有n个基地.起初为了节约材料,人类只修建了n-1条道路来连接这些基地, ...