利用人工智能(Magpie开源库)给一段中文的文本内容进行分类打标签

时间:2024-04-15 09:47:21

当下人工智能是真心的火热呀,各种原来传统的业务也都在尝试用人工智能技术来处理,以此来节省人工成本,提高生产效率。既然有这么火的利器,那么我们就先来简单认识下什么是人工智能吧,人工智能是指利用语音识别、语义理解、图像识别、视觉处理、机器学习、大数据分析等技术实现机器智能自动化做出响应的一种模拟人行为的手段。而我们这里介绍的Magpie则属于人工智能领域里语义理解、机器学习中的一个具体的实现技术。

 

前述

近期因为工作原因,需要从来自于客户聊天对话的文本中进行用户行为判断,并对其打上相应的标签。而我需要解决的就是利用文本内容进行机器自动分类打标签,但在业务中,一段文本会存有不同的多个标签,那么如何来实现呢?通过Github,找到了Magpie,发现其与我的需求非常吻合。一番折腾后,就有了本文章。

 

Magpie

Magpie是一个开源的文本分类库,基于一个高层神经网络Keras技术编写,后端默认由Tensorflow来处理。Magpie是由Python语言开发的,且默认只支持英文文本分类,我因为业务需要便在其基础上做了中文文本的支持。如下是Magpie相关的网址:

Magpie官网:https://github.com/inspirehep/magpie

Keras中文文档:https://keras-cn.readthedocs.io/en/latest/

 

实现

通过上面的介绍,我们清楚了需要实现的业务与目的,以及采用的技术手段。那么,就让我们一起来看看借助Magpie会有什么神秘的事情发生吧。

1、从Magpie下载源码包到本地,通过PyCharm IDE开发工具打开项目后发现有“data”、“magpie”、“save”等目录。其中“data”目录用于存放训练的源数据,“magpie”目录用于存放源代码,“save”目录用于存放训练后的模型文件,具体结如下图:

image

 

2、在项目中引用相应的第三方类库,如下:

  1 \'nltk~=3.2\',
  2 \'numpy~=1.12\',
  3 \'scipy~=0.18\',
  4 \'gensim~=0.13\',
  5 \'scikit-learn~=0.18\',
  6 \'keras~=2.0\',
  7 \'h5py~=2.6\',
  8 \'jieba~=0.39\',

 

3、对项目有了一定认识后,现在我们来准备源数据。我们这里假定有三种标签,分别为“军事“、”旅游“\'、”政治”,每个标签各准备一定数量的源数据(训练数据理论上是越多越好,这里我偷懒就只按每个标签各准备了50条数据),其中拿出70%做为训练数据,30%做为测试数据,根据Magpie规则将训练源数据放到“data”目录内。

 

4、数据准备好后,我们需要改动源代码,使其能支持中文。中文面临一个问题就是分词,而我们这里使用jieba分词库。依次打开”magpie\base“目下的”Document“类中,并在该类内加入相应的分词代码,具体代码如下:

  1 from __future__ import print_function, unicode_literals
  2 
  3 import re
  4 import io
  5 import os
  6 import nltk
  7 import string
  8 import jieba
  9 
 10 from nltk.tokenize import WordPunctTokenizer, sent_tokenize, word_tokenize
 11 
 12 nltk.download(\'punkt\', quiet=True)  # make sure it\'s downloaded before using
 13 
 14 class Document(object):
 15 
 16     """ Class representing a document that the keywords are extracted from """
 17     def __init__(self, doc_id, filepath, text=None):
 18         self.doc_id = doc_id
 19 
 20         if text:
 21             text = self.clean_text(text)
 22             text = self.seg_text(text)
 23             self.text = text
 24             self.filename = None
 25             self.filepath = None
 26         else:  # is a path to a file
 27             if not os.path.exists(filepath):
 28                 raise ValueError("The file " + filepath + " doesn\'t exist")
 29 
 30             self.filepath = filepath
 31             self.filename = os.path.basename(filepath)
 32             with io.open(filepath, \'r\', encoding=\'gbk\') as f:
 33                 text_context = f.read()
 34                 text_context = self.clean_text(text_context)
 35                 self.text = self.seg_text(text_context)
 36                 print(self.text)
 37         self.wordset = self.compute_wordset()
 38 
 39 
 40 
 41     # 利用jieba包进行分词,并并且去掉停词,返回分词后的文本
 42     def seg_text(self,text):
 43         stop = [line.strip() for line in open(\'data/stopwords.txt\', encoding=\'utf8\').readlines()]
 44         text_seged = jieba.cut(text.strip())
 45         outstr = \'\'
 46         for word in text_seged:
 47             if word not in stop:
 48                 outstr += word
 49                 outstr += ""
 50         return outstr.strip()
 51 
 52     # 清洗文本,去除标点符号数字以及特殊符号
 53     def clean_text(self,content):
 54         text = re.sub(r\'[+——!,;/·。?、~@#¥%……&*“”《》:()[]【】〔〕]+\', \'\', content)
 55         text = re.sub(r\'[▲!"#$%&\\'()*+,-./:;<=>\\?@[\\]^_`{|}~]+\', \'\', text)
 56         text = re.sub(\'\d+\', \'\', text)
 57         text = re.sub(\'\s+\', \'\', text)
 58         return text
 59 
 60     def __str__(self):
 61         return self.text
 62 
 63     def compute_wordset(self):
 64         tokens = WordPunctTokenizer().tokenize(self.text)
 65         lowercase = [t.lower() for t in tokens]
 66         return set(lowercase) - {\',\', \'.\', \'!\', \';\', \':\', \'-\', \'\', None}
 67 
 68     def get_all_words(self):
 69         """ Return all words tokenized, in lowercase and without punctuation """
 70         return [w.lower() for w in word_tokenize(self.text)
 71                 if w not in string.punctuation]
 72 
 73     def read_sentences(self):
 74         lines = self.text.split(\'\n\')
 75         raw = [sentence for inner_list in lines
 76                for sentence in sent_tokenize(inner_list)]
 77         return [[w.lower() for w in word_tokenize(s) if w not in string.punctuation]
 78                 for s in raw]
 79 

 

5、通这上述的改造,我们的分类程序可以较好的支持中文了,接下来就可以进行数据训练了。项目是通过运行”train.py“类来进行训练操作,但在运行之前我们需要对该类做下改动,具体代码如下:

  1 from magpie import Magpie
  2 
  3 magpie = Magpie()
  4 magpie.train_word2vec(\'data/hep-categories\', vec_dim=3) #训练一个word2vec
  5 magpie.fit_scaler(\'data/hep-categories\') #生成scaler
  6 magpie.init_word_vectors(\'data/hep-categories\', vec_dim=3) #初始化词向量
  7 labels = [\'军事\',\'旅游\',\'政治\'] #定义所有类别
  8 magpie.train(\'data/hep-categories\', labels, test_ratio=0.2, epochs=20) #训练,20%数据作为测试数据,5轮
  9 
 10 #保存训练后的模型文件
 11 magpie.save_word2vec_model(\'save/embeddings/here\', overwrite=True)
 12 magpie.save_scaler(\'save/scaler/here\', overwrite=True)
 13 magpie.save_model(\'save/model/here.h5\')

 

6、运行”train.py“类来进行训练数据,截图如下:

image

 

7、模型训练成功后,接下来就可以进行模拟测试了。项目是通过运行”test.py“类来进行测试操作,但在运行之前我们需要对该类做下改动,具体代码如下:

  1 from magpie import Magpie
  2 
  3 magpie = Magpie(
  4     keras_model=\'save/model/here.h5\',
  5     word2vec_model=\'save/embeddings/here\',
  6     scaler=\'save/scaler/here\',
  7     labels=[\'旅游\', \'军事\', \'政治\']
  8 )
  9 
 10 #单条模拟测试数据
 11 text = \'特朗普在联合国大会发表演讲谈到这届美国*成绩时,称他已经取得了美国历史上几乎最大的成就。随后大会现场传出了嘲笑声,特朗普立即回应道:“这是真的。”\'
 12 mag1 = magpie.predict_from_text(text)
 13 print(mag1)
 14 
 15 \'\'\'
 16 #也可以通过从txt文件中读取测试数据进行批量测试
 17 mag2 = magpie.predict_from_file(\'data/hep-categories/1002413.txt\')
 18 print(mag2)
 19 \'\'\'

 

8、运行”test.py“类来进行测试数据,截图如下:

image

 

总结

1、文本分类在很多场景中都能应用,比如垃圾邮件分类、用户行为分析、文章分类等,通过本文简单的演示后聪明的你是不是有了一个更大的发现呢!

2、本文使用了Magpie开源库实现模型训练与测试,后台用Tensorflow来运算。并结合jieba分词进行中文切词处理。

3、Magpie本身是不支持中文文本内容的,在这里我加入了jieba分词库后使得整个分类程序有了较好的支持中文文本内容的能力。

4、本文测试分值跟训练数据的数量有一定关系,训练数据理论上是越多越好。

5、分享一句话:人工智能要有多少的智能,就必需要有多少的人工。

 

声明

本文为作者原创,转载请备注出处与保留原文地址,谢谢。如文章能给您带来帮助,请点下推荐或关注,感谢您的支持!