1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 基于tensorflow 的cnn实现文本分类

基于tensorflow 的cnn实现文本分类

时间:2022-12-16 04:01:58

相关推荐

基于tensorflow 的cnn实现文本分类

# coding: utf-8# In[72]:import os, xlrdimport codecs, reimport jiebaimport rarfile import os import jieba.analyse# In[22]:file_name = '/mfsdata/pachong/cnn/Data_MeiTi'#读取文件路径#files = os.listdir(file_name)files=os.listdir(file_name)#文件夹名# In[32]:#数据读取函数def Read_content(title):All_content=[]file_content=os.listdir(title)for singe_file in file_content:path=title+'/'+singe_fileParse=codecs.open(path,'r','utf-8')Content=Parse.read()All_content.append(Content,)return All_content# In[135]:#正则表达式去除标点符号,数字等import re#from zhon.hanzi import punctuationdef Re(line):punctuation=u'▼◆!.※\\×·■★〓!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~"#$%&'()*+,-/:;<=>@[\]^_`{|}~⦅⦆「」、\u3000、\ue65c〃〈〉《》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏﹑﹔·!?。。'line=re.sub(r"[%s]+" %punctuation,' ',line)line=re.sub(r'\d+',' ',line)line=re.sub(r'[A-Za-z0-9]',' ',line)line=re.sub('\s+',' ',line)line=re.sub(r'\b.\b',' ',line)#line=re.sub(r'\ue65c',' ',line)line=re.sub(r'\\+',' ',line)line=re.sub('\s+',' ',line)return line# In[109]:#文本分词函数def Content_deal(line):line=line.split('__Label__')contents=Re(' '.join(jieba.cut(line[0])))return contents+'__lable__'+line[ 1]# In[67]:All_content=[]#文本列表for i in files:title=file_name+"/"+ isinge__All_content=Read_content(title)singe__All= [text+'__Label__'+i.decode('gbk') for text in singe__All_content]All_content=All_content+ singe__All# In[ ]:# In[113]:#from tqdm import tqdm#Deal_content=[]#for single_content in tqdm(All_content):# Deal_content.append(Content_deal(single_content))# In[152]:#将文本分词,去除特殊字符import timeimport multiprocessingpool = multiprocessing.Pool(processes = 5)t1=time.time()Deal_Data=pool.map(Content_deal,All_content)t2=time.time()print t2-t1# In[150]:#将分词处理好的数字写出到txt 文件import pandas as pdDeal_Data1=pd.DataFrame(Deal_Data,index=None)Deal_Data1.to_csv("/mfsdata/pachong/cnn/MeiTi_Deal_data.txt",header=None,index=None,encoding='utf-8')# In[160]:from gensim.models import Word2VecS_model = Word2Vec.load('/mfsdata/pachong/cnn/Sougou.model') #load词向量模型# In[202]:for f in files:print f.decode('gbk')# In[968]:#词向量及其词标签label 词标签,num_label 词标签向量化。词向量矩阵def Word_Vec(sentent):sentent=sentent.split('__lable__')dictL={u'游戏':0,u'星座':1,u'时尚':2,u'娱乐':3,u'养生':4}#,u'其他':5}content=sentent[0].split(' ')label=sentent[1]num_label=np.zeros(5)num_label[dictL[label]]=1Array=[]for i in content:try:Array.append(S_model.wv[i])except:continuereturn label,num_label,np.array(Array)# In[969]:DATA=[]Label=[]for sentent in Deal_Data:sent_sent=sentent.split('__lable__')if sent_sent[1]!=u'其他':label,num_label,data= Word_Vec(sentent)Label.append(num_label)DATA.append(data)#词向量中去除其他的项# In[1013]:SENT=[]for sentent in Deal_Data:sent_sent=sentent.split('__lable__')if sent_sent[1]!=u'其他':SENT.append(sentent)# In[1036]:print SENT[0]# In[978]:#统一词长度,按词长500统计def Same_Len(DATA):N=500#N=max[data.shape[0] for data in DATAfor i in range(len(DATA)):if DATA[i].shape[0]<N:if DATA[i].any():l=N-DATA[i].shape[0]gg=np.zeros((l,200))DATA[i]= np.row_stack((DATA[i], gg)) else:#l=N-DATA[i].shape[0]gg=np.zeros((N,200))DATA[i]=ggelse:DATA[i]=DATA[i][:N,]return DATA#DATA= np.delete(DATA, ([3290,6313,6570,7357,10390]), axis=0)# DATA[i][DATA[i].shape[0]:10,]#print 'ooook'#for i in range(10948):# if DATA[i].shape[0]!=10:# print i,DATA[i].shape[0]DATA1=Same_Len(DATA)# In[979]:DATA[0].shapefor i in range(len(DATA1)):if DATA1[i].shape!=(500,200):print i,DATA1[i].shape[0]# In[980]:print len(DATA1)print len(Label)print Label[0].shape# In[981]:import random#DATA1=np.array(DATA1)#10390#DATA1=np.delete(DATA1,10390,0)# In[983]:Label=np.array(Label)DATA1=np.array(DATA1)N=random.sample(range(8913), 8913)DATA_train=DATA1[N[:8000]]DATA_test=DATA1[N[8001:]]Label_train=Label[N[:8000]]Label_test=Label[N[8001:]]# In[984]:for i in range(len(DATA1)):if DATA1[i].shape!=(500,200):print i,DATA1[i].shape[0]# In[985]:DATA1.shape# In[938]:#from tensorflow.examples.tutorials.mnist import input_data#mnist = input_data.read_data_sets('MNIST_data', one_hot=True)# In[986]:import tensorflow as tfsess = tf.InteractiveSession()#为了建立模型,我们需要先创建一些权值(w)和偏置(b)等参数,这些参数的初始化过程中需要加入一小部分的噪声以破坏参数整体的对称性,同时避免梯度为0.#由于我们使用ReLU激活函数(详细介绍)),所以我们通常将这些参数初始化为很小的正值。为了避免重复的初始化操作,我们可以创建下面两个函数:def weight_variable(shape):initial = tf.truncated_normal(shape, stddev=0.1)return tf.Variable(initial)def bias_variable(shape):initial = tf.constant(0.1, shape=shape)return tf.Variable(initial)#TensorFlow同样提供了方便的卷积和池化计算。怎样处理边界元素?怎样设置卷积窗口大小?#在这个例子中,我们始终使用vanilla版本。这里的卷积操作仅使用了滑动步长为1的窗口,使用0进行填充,所以输出规模和输入的一致;#而池化操作是在2 * 2的窗口内采用最大池化技术(max-pooling) 。为了使代码简洁,同样将这些操作抽象为函数形式#其中,padding='SAME'表示通过填充0,使得输入和输出的形状一致def conv2d(x, W):return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID')#def max_pool_2x2(x):# return tf.nn.top_k(x,2)def max_pool_2x2(x):return tf.reduce_max(x, reduction_indices=[1, 2], keep_dims=True, name=None)# return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],#strides=[1, 2, 2, 1], padding='VALID')# In[987]:#为了使得图片与计算层匹配,我们首先reshape输入图像x为4维的tensor,第2、3维对应图片的宽和高,最后一维对应颜色通道的数目。(?第1维为什么是-1?)x=tf.placeholder(tf.float32,[50,500,200,1])y_=tf.placeholder(tf.float32,[50,5])print x# In[988]:#第一层是卷积层,卷积层将要计算出32个特征映射(feature map),对每个5 * 5的patch。它的权值tensor的大小为[5, 5, 1, 32].#前两维是patch的大小,第三维时输入通道的数目,最后一维是输出通道的数目。我们对每个输出通道加上了偏置(bias)。#[2,200]的卷积核 共有250个,1为通道W_conv = weight_variable([2, 200, 1, 250])b_conv = bias_variable([250])#然后,使用weight tensor对x_image进行卷积计算,加上bias,再应用到一个ReLU激活函数,最终采用最大池化。h_conv = tf.nn.relu(conv2d(x, W_conv) + b_conv)print h_convh_pool = max_pool_2x2(h_conv)print h_poolW_conv1 = weight_variable([3, 200, 1, 250])b_conv1 = bias_variable([250])#然后,使用weight tensor对x_image进行卷积计算,加上bias,再应用到一个ReLU激活函数,最终采用最大池化。h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1)#print h_conv1h_pool1 = max_pool_2x2(h_conv1)print h_pool1W_conv2 = weight_variable([4, 200, 1, 250])b_conv2 = bias_variable([250])h_conv2 = tf.nn.relu(conv2d(x, W_conv2) + b_conv2)h_pool2 = max_pool_2x2(h_conv2)#print h_conv2print h_pool2 #然后,使用weight tensor对x_image进行卷积计算,加上bias,再应用到一个ReLU激活函数,最终采用最大池化。#h_conv2 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1)#print h_conv2#h_pool2 = max_pool_2x2(h_conv1)#tf.concatW_conv3 = weight_variable([5 , 200, 1, 250])b_conv3 = bias_variable([250])h_conv3 = tf.nn.relu(conv2d(x, W_conv3) + b_conv3)h_pool3 = max_pool_2x2(h_conv3)print h_pool3h_pool4=tf.concat([h_pool,h_pool1,h_pool2,h_pool3],3)print h_pool4.shape# In[989]:#第二层:卷积层。为了使得网络有足够深度,我们重复堆积一些相同类型的层。第二层将会有64个特征,对应每个5 * 5的patch。#W_conv2 = weight_variable([5, 200, 32, 64])#b_conv2 = bias_variable([64])#h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)#h_pool2 = max_pool_2x2(h_conv2)# In[1006]:##### 全连接层。到目前为止,图像的尺寸被缩减为7 * 7,我们最后加入一个神经元数目为1024的全连接层来处理所有的图像上。#接着,将最后的pooling层的输出reshape为一个一维向量,与权值相乘,加上偏置,再通过一个ReLu函数。W_fc1 = weight_variable([1*1 * 1000,650])b_fc1 = bias_variable([650])#print h_pool1.shapeh_pool1_flat =tf.reshape(h_pool4, [-1, 1*1*1000])#print W_fc1.shapeprint h_pool1_flat.shapeprint W_fc1 h_fc1 = tf.nn.softmax(tf.matmul(h_pool1_flat, W_fc1) + b_fc1)#print h_fc1.shape# In[1007]:#为了减少过拟合程度,在输出层之前应用dropout技术(即丢弃某些神经元的输出结果)。#我们创建一个placeholder来表示一个神经元的输出在dropout时不被丢弃的概率。Dropout能够在训练过程中使用,而在测试过程中不使用。#TensorFlow中的tf.nn.dropout操作能够利用mask技术处理各种规模的神经元输出keep_prob = tf.placeholder(tf.float32)h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)print h_fc1_drop# In[1008]:#输出层。最终,我们用一个softmax层,得到类别上的概率分布。(与之前的Softmax Regression模型相同)。W_fc2 = weight_variable([650, 5])b_fc2 = bias_variable([5])print b_fc2y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)print y_conv.shape# In[1009]:cross_entropy =tf.reduce_mean( -tf.reduce_sum(y_*tf.log(y_conv),reduction_indices=[1]))train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))# In[1010]:x_data[0].shape# In[1011]:#模型训练和测试。为了测试模型的性能,需要先对模型进行训练,然后应用在测试集上。和之前Softmax Regression模型中的训练、测试过程类似。区别在于:#用更复杂的ADAM最优化方法代替了之前的梯度下降;#增了额外的参数keep_prob在feed_dict中,以控制dropout的几率;#在训练过程中,增加了log输出功能(每100次迭代输出一次)。#cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))#train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)#correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))#accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))#sess.run(tf.global_variables_initializer())sess.run(tf.global_variables_initializer())i=0#while i <10000:for i in range(7950):x_data=[np.expand_dims(_, 2) for _ in DATA_train[i:i+50]]# print x_data[0].shapey_data=list(Label_train[i:i+50])i=i+50# batch = mnist.train.next_batch(50)if i%100 == 0:train_accuracy = accuracy.eval(feed_dict={x:x_data, y_: y_data, keep_prob: 1.0})print("step %d, training accuracy %g"%(i, train_accuracy))train_step.run(feed_dict={x:x_data, y_:y_data, keep_prob: 0.5})# In[1012]:kc=0i=0J=[] while i<900:DATA_test1=[np.expand_dims(_, 2) for _ in DATA_test[i:i+50]]probability=y_conv.eval(session=sess,feed_dict={x:DATA_test1,keep_prob:1.0})jc=0for j in range(i,i+50):llabel=np.zeros(5)# np.where(probability[0]==max(probability[0]))llabel[np.where(probability[j%50]==max(probability[j%50]))]=1if (llabel==Label_test[j]).all():jc=jc+1kc=kc+1#print "第%d条正确" %j#else:# print "第%d条错误" %jJ.append(jc)print kci=i+50print J # In[ ]:#################以下为hannlp内容#CRF分词。CRF对新词有很好的识别能力,但是开销较大。HanLP= JClass('com.hankcs.hanlp.HanLP')SEG=JClass('com.hankcs.hanlp.seg.Segment')segemntTool = print anizationRecognition(u'中国科学院计算技术公司的宗成庆').toString()# In[ ]:s1=u'重点大学本科及以上学历,计算机、信息系统、电子商务等相关专业;2年以上商业软件开发和管理经验;精通Java语言,精通Spring等开源框架,有系统架构工作经验;熟悉Oracle数据库服务器,熟悉Unix/Linux操作系统;良好的沟通能力和团队合作精神;具有金融行业、支付行业从业经历者优先。加分项:zookeeper、redis、kafka等。's1=u'本科及以上学历,计算机相关专业优先,工作经验3~6年;精通Java编程,网络编程;对于面向对象模型和设计模式有比较清晰的认识;熟悉数据库开发技术及相关工具, 如Mysql等;精通SpringMVC等开发框架;精通掌握mybatis,熟练主流关系数据库Mysql、postgresql、Oracle,对主流的nosql服务有过研究;能熟练进行多线程并发编程,有过多线程,线程池开发经验,熟练JAVA NIO编程,对netty,mina框架有过研究,并在实际项目中用到;熟悉精通Redis、Dubbo、Kafka、ActiveMQ等RPC框架和消息框架;了解linux系统常用命令,能够进行独立部署和相关问题排查;具备强烈的责任心,能够脚踏实地的做事;具有优秀的学习能力,良好的逻辑分析能力,良好的沟通能力和团队合作精神.'s2=u'位职责:对指定网站进行数据抓取,清洗以及汇总的开发工作。 互联网网站,网页,链接的特征挖掘。 负责系统日常运营资源调度优化及运营指标分析调优,并能实时监控爬虫的进度和警报反馈。 负责特殊网页采集任务的分析及采集方案设计。 数学,统计,计算机相关专业本科以上学历熟悉Python以及数据分析相关工具,了解Shell熟悉SQL语言,追求SQL性能,熟悉MySQL、MongoDB等熟悉Hadoop、数据仓库、Spark等大数据技术者优先'#关键词提取print(HanLP.extractKeyword(s1, 10).toString())print(HanLP.extractKeyword(s2, 10).toString())#####自动摘要print(HanLP.extractSummary(s1, 5).toString())print(HanLP.extractSummary(s2, 5).toString())###短语提取print (HanLP.extractPhrase(s1, 10).toString())print (HanLP.extractPhrase(s2, 10).toString())# 命名实体识别与词性标注NLPTokenizer = JClass('com.hankcs.hanlp.tokenizer.NLPTokenizer')print(NLPTokenizer.segment(s1).toString())print(NLPTokenizer.segment(s2).toString())# In[1033]:from jpype import *startJVM(getDefaultJVMPath(), "-Djava.class.path=/mfsdata/hanlp/hanlp-1.3.4.jar:/mfsdata/hanlp")HanLP = JClass('com.hankcs.hanlp.HanLP')###分词s1=u"一桶冰水当头倒下,微软的比尔盖茨、Facebook的扎克伯格跟桑德博格、亚马逊的贝索斯、苹果的库克全都不惜湿身入镜,这些硅谷的科技人,飞蛾扑火似地牺牲演出,其实全为了慈善。世界上最长的姓名是简森·乔伊·亚历山大·比基·卡利斯勒·达夫·埃利奥特·福克斯·伊维鲁莫·马尔尼·梅尔斯·帕特森·汤普森·华莱士·普雷斯顿。"print(HanLP.segment(s1).toString())print(HanLP.segment(u'你好,欢迎在Python中调用HanLP的API').toString())##标准分词 与HanLP.segment等价StandardTokenizer = JClass('com.hankcs.hanlp.tokenizer.StandardTokenizer')print(StandardTokenizer.segment(u'你好,欢迎在Python中调用HanLP的API').toString())# 命名实体识别与词性标注NLPTokenizer = JClass('com.hankcs.hanlp.tokenizer.NLPTokenizer')print(NLPTokenizer.segment(u'中国科学院计算技术研究所的宗成庆教授正在教授自然语言处理课程').toString())##索引分词IndexTokenizer是面向搜索引擎的分词器,能够对长词全切分,另外通过term.offset可以获取单词在文本中的偏移量IndexTokenizer = JClass('com.hankcs.hanlp.tokenizer.IndexTokenizer')termlist=IndexTokenizer.segment(u"主副食品").toString()###N最短路径分词 不通nShortSegment = JClass('com.hankcs.hanlp.tokenizer.NShortSegment')#机构名识别Organization = JClass("com.hankcs.hanlp.HanLP.newSegment").enableOrganizationRecognize')print Organization.seg(u"我在上海林原科技有限公司兼职工作").toString()###关键字提取document = u"水利部水资源司司长陈明忠9月29日在国务院新闻办举行的新闻发布会上透露," u"根据刚刚完成了水资源管理制度的考核,有部分省接近了红线的指标," u"有部分省超过红线的指标。对一些超过红线的地方,陈明忠表示,对一些取用水项目进行区域的限批," u"严格地进行水资源论证和取水许可的批准。"#关键词提取print(HanLP.extractKeyword(document, 2).toString())#####自动摘要print(HanLP.extractSummary(document, 3).toString())print HanLP.TextRankSentence.getTopSentenceList(document, 3).toString()# 依存句法分析print(HanLP.parseDependency(u"徐先生还具体帮助他确定了把画雄鹰、松鼠和麻雀作为主攻目标。").toString())###短语提取document1= u"算法工程师" u"目前国内从事算法研究的工程师不少,但算法工程师要有音频,视频算法处理能力"print HanLP.extractPhrase(document1, 10).toString()# In[ ]:# In[1030]:#startJVM(getDefaultJVMPath(), "-Djava.class.path=mfsdata/hanlp/hanlp-1.3.4.jar:/mfsdata/hanlp")#\hanlp\hanlp-1.2.8.jar;C:\hanlp", "-Xms1g", "-Xmx1g") # 启动JVM,Linux需替换分号;为冒号:#HanLP = JClass('com.hankcs.hanlp.HanLP')# 中文分词startJVM(getDefaultJVMPath(), "-Djava.class.path=/mfsdata/hanlp/hanlp-1.3.4.jar:/mfsdata/hanlp")HanLP = JClass('com.hankcs.hanlp.HanLP')TraditionalChineseTokenizer = JClass("com.hankcs.hanlp.tokenizer.TraditionalChineseTokenizer")# In[ ]:shutdownJVM()# In[1021]:#DATA# In[ ]:# In[ ]:# In[ ]:# In[ ]:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。