当前位置:   article > 正文

NLP自然语言处理相关技术说明及样例(附源码)_自然语言处理代码样例

自然语言处理代码样例

https://segmentfault.com/a/1190000010320214

1、简单概述

1.1 NLP概念

NLP(Natural Language Processing),自然语言处理,又称NLU(Natural Language Understanding)自然语言理解,是语言信息处理的分支,也是人工智能的核心课题,简单来说就是让计算机理解自然语言。

1.2 NLP涉及的内容及技术

自然语言处理研究包含的内容十分广泛,这里只列举出其中的其中的一部分(主要是在移动易系统中涉及到的),包括分词处理(Word-Segment),词性标注(Part-of-Speech tagging),句法分析(Parsing),信息检索(Infomation-Retrieval),文字校对(Text-Rroofing),词向量模型(WordVector-Model),语言模型(Language-Model),问答系统(Question-Answer-System)。如下逐一介绍。

2、前期准备

  1. Lucene使用经验

  2. python使用经验

  3. 相关工具包如下:

工具 版本 下载地址
哈工大LTP ltp4j download
berkeleylm berkeleylm 1.1.5 download
ElasticSearch elasticsearch-2.4.5 download

3、具体实现

3.1 分词(Word-Segment)

3.1.1 这里主要介绍中文分词的实现,实现中文分词的方法有许多种,例如StandfordCore NLP(具体实现参见【NLP】使用 Stanford NLP 进行中文分词 ),jieba分词,这里使用哈工大的语言技术平台LTP(包括后面的词性标注,句法分析)。具体步骤如下:

  • 首先下载LTP4J的jar包(download),

  • 下载完解压缩后的文件包为ltp4j-master,相应的jar包就在output文件夹下的jar文件夹中。

  • 下载编译好的C++动态链接库download,解压后如下所示:  

  • 将文件夹中的所有内容复制到jdk的bin目录下,如下所示:

  • 构建Java项目,将jar包导入到项目中,右键项目buildpath,为添加的jar包添加本来地库依赖,路劲即下载解压后的dll动态库文件路径,如下所示:

  • 接着便是中文分词的测试了,实现代码如下:

  1. package ccw.ltpdemo;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import edu.hit.ir.ltp4j.Segmentor;
  5. public class ltpSegmentDemo {
  6. public static void main(String[] args) {
  7. Segmentor segmentor = new Segmentor();
  8. if(segmentor.create("D:/NLP/ltp/ltp_data_v3.4.0/ltp_data_v3.4.0/cws.model")<0)
  9. {
  10. System.out.println("model load failed");
  11. }
  12. else
  13. {
  14. String sent = "这是中文分词测试";
  15. List<String> words = new ArrayList<String>();
  16. int size = segmentor.segment(sent, words);
  17. for(String word :words)
  18. {
  19. System.out.print(word+"\t");
  20. }
  21. segmentor.release();
  22. }
  23. }
  24. }

3.1.2 效果如下:

3.2 词性标注(Part-of-Speech tagging)

3.2.1 这里介绍如何通过ltp实现中文的词性标注,具体实现代码如下:

  1. package ccw.ltpdemo;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import edu.hit.ir.ltp4j.Postagger;
  5. public class ltpPostaggerDemo {
  6. public static void main(String[] args) {
  7. Postagger postagger = new Postagger();
  8. if(postagger.create("D:/NLP/ltp/ltp_data_v3.4.0/ltp_data_v3.4.0/pos.model")<0)
  9. {
  10. System.out.println("model load failed");
  11. }
  12. else
  13. {
  14. List<String> words = new ArrayList<String>();
  15. words.add("我");
  16. words.add("是");
  17. words.add("中国");
  18. words.add("人");
  19. List<String> values = new ArrayList<String>();
  20. int size = postagger.postag(words, values);
  21. for(int i = 0;i<words.size();i++)
  22. {
  23. System.out.print(words.get(i)+" "+values.get(i)+"\t");
  24. }
  25. postagger.release();
  26. }
  27. }
  28. }

3.2.2 实现效果如下: 

3.3 句法分析(Parsing)

3.3.1 这里介绍如何通过ltp实现对中文句子的句法分析,核心方法int size = Parser.parse(words,tags,heads,deprels),其中,words[]表示待分析的词序列,tags[]表示待分析的词的词性序列,heads[]表示结果依存弧,heads[i]代表第i个节点的父节点编号(其中第0个表示根节点root),deprels[]表示依存弧的关系类型,size表示返回结果中词的个数。实现代码如下:

  1. package ccw.ltpdemo;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import edu.hit.ir.ltp4j.Parser;
  5. public class ltpParserDemo {
  6. /**
  7. * @param args
  8. */
  9. public static void main(String[] args) {
  10. Parser parser = new Parser();
  11. if(parser.create("D:/NLP/ltp/ltp_data_v3.4.0/ltp_data_v3.4.0/parser.model")<0)
  12. {
  13. System.out.println("model load failed");
  14. }
  15. else
  16. {
  17. List<String> words = new ArrayList<String>();
  18. List<String> tags = new ArrayList<String>();
  19. words.add("我");tags.add("r");
  20. words.add("非常");tags.add("d");
  21. words.add("喜欢");tags.add("v");
  22. words.add("音乐");tags.add("n");
  23. List<Integer> heads = new ArrayList<Integer>();
  24. List<String> deprels = new ArrayList<String>();
  25. int size = Parser.parse(words,tags,heads,deprels);
  26. for(int i = 0;i<size;i++) {
  27. System.out.print(heads.get(i)+":"+deprels.get(i));
  28. if(i==size-1) {
  29. System.out.println();
  30. }
  31. else{
  32. System.out.print(" ");
  33. }
  34. }
  35. parser.release();
  36. }
  37. }
  38. }

3.3.2 实现效果如下: 

3.4 信息检索(Information-Retrieval)

信息检索(Information Retrieval)是用户进行信息查询和获取的主要方式,是查找信息的方法和手段。狭义的信息检索仅指信息查询(Information Search)。即用户根据需要,采用一定的方法,借助检索工具,从信息集合中找出所需要信息的查找过程。实现参见移动易实现全文搜索

3.5 文字校对(Text-Rroofing),语言模型(Language-Model)

3.5.1 N元模型(N-gram)

首先介绍N-gram模型,N-gram模型是自然语言处理中一个非常重要的概念,通常,在NLP中,基于一定的语料库, 可以通过N-gram来预计或者评估一个句子是否合理。对于一个句子T,假设T由词序列w1,w2,w3...wn组成,那么T出现的概率

  • P(T)=P(w1,w2,w3...wn)=P(w1)P(w2|w1)P(w3|w2,w1)...p(wn|wn-1,...w2,w1)
    此概率在参数巨大的情况下显然不容易计算,因此引入了马尔可夫链(即每个词出现的概率仅仅与它的前后几个词相关),这样可以大幅度缩小计算的长度,即

  • P(wi|w1,⋯,wi−1)=P(wi|wi−n+1,⋯,wi−1)
    特别的,当n取值较小时:

当n=1时,即每一个词出现的概率只由该词的词频决定,称为一元模型(unigram-model):

  • P(w1,w2,⋯,wm)=∏i=1mP(wi)
    设M表示语料库中的总字数,c(wi)表示wi在语料库中出现的次数,那么

  • P(wi)=C(wi)/M
    当n=2时,即每一个词出现的概率只由该词的前一个词以及后一个词决定,称为二元模型(bigram-model):

  • P(w1,w2,⋯,wm)=∏i=1mP(wi|wi−1) 
    设M表示语料库中的总字数,c(wi-1WI)表示wi-1wi在语料库中出现的次数,那么

  • P(wi|wi−1)=C(wi−1wi)/C(wi−1)
    当n=3时,称为三元模型(trigram-model):

  • P(w1,w2,⋯,wm)=∏i=1mP(wi|wi−2wi−1) 
    那么

  • P(wi|wi−1wi-2)=C(wi-2wi−1wi)/C(wi−2wi-1)

3.5.2 中文拼写纠错

接着介绍如何通过Lucene提供的spellChecker(拼写校正)模块实现中文字词的纠错,首先创建语料词库,如下所示:

然后在代码中创建索引并测试,具体实现代码如下:

  1. package ccw.spring.ccw.lucencedemo;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import java.util.Iterator;
  9. import org.apache.lucene.index.IndexReader;
  10. import org.apache.lucene.index.IndexWriterConfig;
  11. import org.apache.lucene.search.spell.LuceneDictionary;
  12. import org.apache.lucene.search.spell.PlainTextDictionary;
  13. import org.apache.lucene.search.spell.SpellChecker;
  14. import org.apache.lucene.search.suggest.InputIterator;
  15. import org.apache.lucene.store.Directory;
  16. import org.apache.lucene.store.FSDirectory;
  17. import org.apache.lucene.util.Version;
  18. public class Spellcheck {
  19. public static String directorypath;
  20. public static String origindirectorypath;
  21. public SpellChecker spellcheck;
  22. public LuceneDictionary dict;
  23. /**
  24. * 创建索引
  25. * a
  26. * @return
  27. * @throws IOException
  28. * boolean
  29. */
  30. public static void createIndex(String directorypath,String origindirectorypath) throws IOException
  31. {
  32. Directory directory = FSDirectory.open(new File(directorypath));
  33. SpellChecker spellchecker = new SpellChecker(directory);
  34. IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_9, null);
  35. PlainTextDictionary pdic = new PlainTextDictionary(new InputStreamReader(new FileInputStream(new File(origindirectorypath)),"utf-8"));
  36. spellchecker.indexDictionary(new PlainTextDictionary(new File(origindirectorypath)), config, false);
  37. directory.close();
  38. spellchecker.close();
  39. }
  40. public Spellcheck(String opath ,String path)
  41. {
  42. origindirectorypath = opath;
  43. directorypath = path;
  44. Directory directory;
  45. try {
  46. directory = FSDirectory.open(new File(directorypath));
  47. spellcheck = new SpellChecker(directory);
  48. IndexReader oriIndex = IndexReader.open(directory);
  49. dict = new LuceneDictionary(oriIndex,"name");
  50. }
  51. catch (IOException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. public void setAccuracy(float v)
  56. {
  57. spellcheck.setAccuracy(v);
  58. }
  59. public String[]search(String queryString, int suggestionsNumber)
  60. {
  61. String[]suggestions = null;
  62. try {
  63. if (exist(queryString))
  64. return null;
  65. suggestions = spellcheck.suggestSimilar(queryString,suggestionsNumber);
  66. }
  67. catch (IOException e)
  68. {
  69. e.printStackTrace();
  70. }
  71. return suggestions;
  72. }
  73. private boolean exist(String queryString) throws IOException {
  74. InputIterator ite = dict.getEntryIterator();
  75. while (ite.hasContexts())
  76. {
  77. if (ite.next().equals(queryString))
  78. return true;
  79. }
  80. return false;
  81. }
  82. public static void main(String[] args) throws IOException {
  83. String opath = "D:\\Lucene\\NLPLucene\\words.txt";
  84. String ipath = "D:\\Lucene\\NLPLucene\\index";
  85. Spellcheck.createIndex(ipath, opath);
  86. Spellcheck spellcheck = new Spellcheck(opath,ipath);
  87. //spellcheck.createSpellIndex();
  88. spellcheck.setAccuracy((float) 0.5);
  89. String [] result = spellcheck.search("麻辣糖", 15);
  90. if(result.length==0||null==result)
  91. {
  92. System.out.println("未发现错误");
  93. }
  94. else
  95. {
  96. System.out.println("你是不是要找:");
  97. for(String hit:result)
  98. {
  99. System.out.println(hit);
  100. }
  101. }
  102. }
  103. }

实现效果如下: 

3.5.3 中文语言模型训练

这里主要介绍中文语言模型的训练,中文语言模型的训练主要基于N-gram算法,目前开源的语言模型训练的工具主要有SRILM、KenLM、 berkeleylm 等几种,KenLm较SRILM性能上要好一些,用C++编写,支持单机大数据的训练。berkeleylm是用java写。本文主要介绍如何通过berkelylm实现中文语言模型的训练。

  • 首先需要下载berkeleylm的jar包(download),完成后将jar包导入到java项目中。

  • 然后准备训练的语料库,首先通过ltp将每一句文本分词,然后将分完词的语句写入txt文件,如下所示: 

  • 接着就是对语料库的训练,首先要读取分完词的文本,然后就是对每个词计算在给定上下文中出现的概率,这里的概率是对10取对数后计算得到的,最后将结果按照给定的格式存储,可以按照.arpa或者二进制.bin文件存储。文件格式如下: 
      

实现代码如下:

  1. package ccw.berkeleylm;
  2. import java.io.File;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import edu.berkeley.nlp.lm.ConfigOptions;
  6. import edu.berkeley.nlp.lm.StringWordIndexer;
  7. import edu.berkeley.nlp.lm.io.ArpaLmReader;
  8. import edu.berkeley.nlp.lm.io.LmReaders;
  9. import edu.berkeley.nlp.lm.util.Logger;
  10. public class demo {
  11. private static void usage() {
  12. System.err.println("Usage: <lmOrder> <ARPA lm output file> <textfiles>*");
  13. System.exit(1);
  14. }
  15. public void makelml(String [] argv)
  16. {
  17. if (argv.length < 2) {
  18. usage();
  19. }
  20. final int lmOrder = Integer.parseInt(argv[0]);
  21. final String outputFile = argv[1];
  22. final List<String> inputFiles = new ArrayList<String>();
  23. for (int i = 2; i < argv.length; ++i) {
  24. inputFiles.add(argv[i]);
  25. }
  26. if (inputFiles.isEmpty()) inputFiles.add("-");
  27. Logger.setGlobalLogger(new Logger.SystemLogger(System.out, System.err));
  28. Logger.startTrack("Reading text files " + inputFiles + " and writing to file " + outputFile);
  29. final StringWordIndexer wordIndexer = new StringWordIndexer();
  30. wordIndexer.setStartSymbol(ArpaLmReader.START_SYMBOL);
  31. wordIndexer.setEndSymbol(ArpaLmReader.END_SYMBOL);
  32. wordIndexer.setUnkSymbol(ArpaLmReader.UNK_SYMBOL);
  33. LmReaders.createKneserNeyLmFromTextFiles(inputFiles, wordIndexer, lmOrder, new File(outputFile), new ConfigOptions());
  34. Logger.endTrack();
  35. }
  36. public static void main(String[] args) {
  37. demo d = new demo();
  38. String inputfile = "D:\\NLP\\languagematerial\\quest.txt";
  39. String outputfile = "D:\\NLP\\languagematerial\\q.arpa";
  40. String s[]={"8",outputfile,inputfile};
  41. d.makelml(s);
  42. }
  43. }
  • 最后就是读取模型,然后判断句子的相似性,实现代码如下:

  1. package ccw.berkeleylm;
  2. import java.io.File;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import edu.berkeley.nlp.lm.ArrayEncodedProbBackoffLm;
  6. import edu.berkeley.nlp.lm.ConfigOptions;
  7. import edu.berkeley.nlp.lm.StringWordIndexer;
  8. import edu.berkeley.nlp.lm.io.LmReaders;
  9. public class readdemo {
  10. public static ArrayEncodedProbBackoffLm<String> getLm(boolean compress,String file) {
  11. final File lmFile = new File(file);
  12. final ConfigOptions configOptions = new ConfigOptions();
  13. configOptions.unknownWordLogProb = 0.0f;
  14. final ArrayEncodedProbBackoffLm<String> lm = LmReaders.readArrayEncodedLmFromArpa(lmFile.getPath(), compress, new StringWordIndexer(), configOptions,
  15. Integer.MAX_VALUE);
  16. return lm;
  17. }
  18. public static void main(String[] args) {
  19. readdemo read = new readdemo();
  20. LmReaders readers = new LmReaders();
  21. ArrayEncodedProbBackoffLm<String> model = (ArrayEncodedProbBackoffLm) readdemo.getLm(false, "D:\\NLP\\languagematerial\\q.arpa");
  22. String sentence = "是";
  23. String [] words = sentence.split(" ");
  24. List<String> list = new ArrayList<String>();
  25. for(String word : words)
  26. {
  27. System.out.println(word);
  28. list.add(word);
  29. }
  30. float score = model.getLogProb(list);
  31. System.out.println(score);
  32. }
  33. }

实现效果如下:

 

3.5.4 同义词词林

这里使用哈工大提供的同义词词林,词林提供三层编码,第一级大类用大写英文字母表示,第二级中类用小写字母表示,第三级小类用二位十进制整数表示,第四级词群用大写英文字母表示,第五级原子词群用二位十进制整数表示。编码表如下所示:

   

第八位的标记有三种,分别是“=“、”#“、”@“,=代表相等、同义,#代表不等、同类,@代表自我封闭、独立,它在词典中既没有同义词,也没有相关词。通过同义词词林可以比较两词的相似程度,代码实现如下:

  1. package cilin;
  2. import java.io.BufferedReader;
  3. import java.io.FileInputStream;
  4. import java.io.InputStreamReader;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import java.util.Vector;
  8. public class CiLin {
  9. public static HashMap<String, List<String>> keyWord_Identifier_HashMap;//<关键词,编号List集合>哈希
  10. public int zero_KeyWord_Depth = 12;
  11. public static HashMap<String, Integer> first_KeyWord_Depth_HashMap;//<第一层编号,深度>哈希
  12. public static HashMap<String, Integer> second_KeyWord_Depth_HashMap;//<前二层编号,深度>哈希
  13. public static HashMap<String, Integer> third_KeyWord_Depth_HashMap;//<前三层编号,深度>哈希
  14. public static HashMap<String, Integer> fourth_KeyWord_Depth_HashMap;//<前四层编号,深度>哈希
  15. //public HashMap<String, HashSet<String>> ciLin_Sort_keyWord_HashMap = new HashMap<String, HashSet<String>>();//<(同义词)编号,关键词Set集合>哈希
  16. static{
  17. keyWord_Identifier_HashMap = new HashMap<String, List<String>>();
  18. first_KeyWord_Depth_HashMap = new HashMap<String, Integer>();
  19. second_KeyWord_Depth_HashMap = new HashMap<String, Integer>();
  20. third_KeyWord_Depth_HashMap = new HashMap<String, Integer>();
  21. fourth_KeyWord_Depth_HashMap = new HashMap<String, Integer>();
  22. initCiLin();
  23. }
  24. //3.初始化词林相关
  25. public static void initCiLin(){
  26. int i;
  27. String str = null;
  28. String[] strs = null;
  29. List<String> list = null;
  30. BufferedReader inFile = null;
  31. try {
  32. //初始化<关键词, 编号set>哈希
  33. inFile = new BufferedReader(new InputStreamReader(new FileInputStream("cilin/keyWord_Identifier_HashMap.txt"), "utf-8"));// 读取文本
  34. while((str = inFile.readLine()) != null){
  35. strs = str.split(" ");
  36. list = new Vector<String>();
  37. for (i = 1; i < strs.length; i++)
  38. list.add(strs[i]);
  39. keyWord_Identifier_HashMap.put(strs[0], list);
  40. }
  41. //初始化<第一层编号,高度>哈希
  42. inFile.close();
  43. inFile = new BufferedReader(new InputStreamReader(new FileInputStream("cilin/first_KeyWord_Depth_HashMap.txt"), "utf-8"));// 读取文本
  44. while ((str = inFile.readLine()) != null){
  45. strs = str.split(" ");
  46. first_KeyWord_Depth_HashMap.put(strs[0], Integer.valueOf(strs[1]));
  47. }
  48. //初始化<前二层编号,高度>哈希
  49. inFile.close();
  50. inFile = new BufferedReader(new InputStreamReader(new FileInputStream("cilin/second_KeyWord_Depth_HashMap.txt"), "utf-8"));// 读取文本
  51. while ((str = inFile.readLine()) != null){
  52. strs = str.split(" ");
  53. second_KeyWord_Depth_HashMap.put(strs[0], Integer.valueOf(strs[1]));
  54. }
  55. //初始化<前三层编号,高度>哈希
  56. inFile.close();
  57. inFile = new BufferedReader(new InputStreamReader(new FileInputStream("cilin/third_KeyWord_Depth_HashMap.txt"), "utf-8"));// 读取文本
  58. while ((str = inFile.readLine()) != null){
  59. strs = str.split(" ");
  60. third_KeyWord_Depth_HashMap.put(strs[0], Integer.valueOf(strs[1]));
  61. }
  62. //初始化<前四层编号,高度>哈希
  63. inFile.close();
  64. inFile = new BufferedReader(new InputStreamReader(new FileInputStream("cilin/fourth_KeyWord_Depth_HashMap.txt"), "utf-8"));// 读取文本
  65. while ((str = inFile.readLine()) != null){
  66. strs = str.split(" ");
  67. fourth_KeyWord_Depth_HashMap.put(strs[0], Integer.valueOf(strs[1]));
  68. }
  69. inFile.close();
  70. } catch (Exception e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. //根据两个关键词计算相似度
  75. public static double calcWordsSimilarity(String key1, String key2){
  76. List<String> identifierList1 = null, identifierList2 = null;//词林编号list
  77. if(key1.equals(key2))
  78. return 1.0;
  79. if (!keyWord_Identifier_HashMap.containsKey(key1) || !keyWord_Identifier_HashMap.containsKey(key2)) {//其中有一个不在词林中,则返回相似度为0.1
  80. //System.out.println(key1 + " " + key2 + "有一个不在同义词词林中!");
  81. return 0.1;
  82. }
  83. identifierList1 = keyWord_Identifier_HashMap.get(key1);//取得第一个词的编号集合
  84. identifierList2 = keyWord_Identifier_HashMap.get(key2);//取得第二个词的编号集合
  85. return getMaxIdentifierSimilarity(identifierList1, identifierList2);
  86. }
  87. public static double getMaxIdentifierSimilarity(List<String> identifierList1, List<String> identifierList2){
  88. int i, j;
  89. double maxSimilarity = 0, similarity = 0;
  90. for(i = 0; i < identifierList1.size(); i++){
  91. j = 0;
  92. while(j < identifierList2.size()){
  93. similarity = getIdentifierSimilarity(identifierList1.get(i), identifierList2.get(j));
  94. System.out.println(identifierList1.get(i) + " " + identifierList2.get(j) + " " + similarity);
  95. if(similarity > maxSimilarity)
  96. maxSimilarity = similarity;
  97. if(maxSimilarity == 1.0)
  98. return maxSimilarity;
  99. j++;
  100. }
  101. }
  102. return maxSimilarity;
  103. }
  104. public static double getIdentifierSimilarity(String identifier1, String identifier2){
  105. int n = 0, k = 0;//n是分支层的节点总数, k是两个分支间的距离.
  106. //double a = 0.5, b = 0.6, c = 0.7, d = 0.96;
  107. double a = 0.65, b = 0.8, c = 0.9, d = 0.96;
  108. if(identifier1.equals(identifier2)){//在第五层相等
  109. if(identifier1.substring(7).equals("="))
  110. return 1.0;
  111. else
  112. return 0.5;
  113. }
  114. else if(identifier1.substring(0, 5).equals(identifier2.substring(0, 5))){//在第四层相等 Da13A01=
  115. n = fourth_KeyWord_Depth_HashMap.get(identifier1.substring(0, 5));
  116. k = Integer.valueOf(identifier1.substring(5, 7)) - Integer.valueOf(identifier2.substring(5, 7));
  117. if(k < 0) k = -k;
  118. return Math.cos(n * Math.PI / 180) * ((double)(n - k + 1) / n) * d;
  119. }
  120. else if(identifier1.substring(0, 4).equals(identifier2.substring(0, 4))){//在第三层相等 Da13A01=
  121. n = third_KeyWord_Depth_HashMap.get(identifier1.substring(0, 4));
  122. k = identifier1.substring(4, 5).charAt(0) - identifier2.substring(4, 5).charAt(0);
  123. if(k < 0) k = -k;
  124. return Math.cos(n * Math.PI / 180) * ((double)(n - k + 1) / n) * c;
  125. }
  126. else if(identifier1.substring(0, 2).equals(identifier2.substring(0, 2))){//在第二层相等
  127. n = second_KeyWord_Depth_HashMap.get(identifier1.substring(0, 2));
  128. k = Integer.valueOf(identifier1.substring(2, 4)) - Integer.valueOf(identifier2.substring(2, 4));
  129. if(k < 0) k = -k;
  130. return Math.cos(n * Math.PI / 180) * ((double)(n - k + 1) / n) * b;
  131. }
  132. else if(identifier1.substring(0, 1).equals(identifier2.substring(0, 1))){//在第一层相等
  133. n = first_KeyWord_Depth_HashMap.get(identifier1.substring(0, 1));
  134. k = identifier1.substring(1, 2).charAt(0) - identifier2.substring(1, 2).charAt(0);
  135. if(k < 0) k = -k;
  136. return Math.cos(n * Math.PI / 180) * ((double)(n - k + 1) / n) * a;
  137. }
  138. return 0.1;
  139. }
  140. }
  141. //测试
  142. public class Test {
  143. public static void main(String args[]) {
  144. String word1 = "相似", word2 = "相像";
  145. double sim = 0;
  146. sim = CiLin.calcWordsSimilarity(word1, word2);//计算两个词的相似度
  147. System.out.println(word1 + " " + word2 + "的相似度为:" + sim);
  148. }
  149. }

测试效果如下:

3.6 词向量模型(WordVector-Model)

3.6.1 词向量

词向量顾名思义,就是用一个向量的形式表示一个词。为什么这么做?自然语言理解问题转化为机器学习问题的第一步都是通过一种方法把这些符号数学化。词向量具有良好的语义特性,是表示词语特征的常用方式。词向量的每一维的值代表一个具有一定的语义和语法上解释的特征。

3.6.2 Word2vec

Word2vec是Google公司在2013年开放的一款用于训练词向量的软件工具。它根据给定的语料库,通过优化后的训练模型快速有效的将一个词语表达成向量形式,其核心架构包括CBOW和Skip-gram。Word2vec包含两种训练模型,分别是CBOW和Skip_gram(输入层、发射层、输出层),如下图所示: 

3.6.3 word2vec 训练词向量
  1. # coding:utf-8
  2. import sys
  3. reload(sys)
  4. sys.setdefaultencoding( "utf-8" )
  5. from gensim.models import Word2Vec
  6. import logging,gensim,os
  7. class TextLoader(object):
  8. def __init__(self):
  9. pass
  10. def __iter__(self):
  11. input = open('corpus-seg.txt','r')
  12. line = str(input.readline())
  13. counter = 0
  14. while line!=None and len(line) > 4:
  15. #print line
  16. segments = line.split(' ')
  17. yield segments
  18. line = str(input.readline())
  19. sentences = TextLoader()
  20. model = gensim.models.Word2Vec(sentences, workers=8)
  21. model.save('word2vector2.model')
  22. print 'ok'
  1. # coding:utf-8
  2. import sys
  3. reload(sys)
  4. sys.setdefaultencoding( "utf-8" )
  5. from gensim.models import Word2Vec
  6. import logging,gensim,os
  7. #模型的加载
  8. model = Word2Vec.load('word2vector.model')
  9. #比较两个词语的相似度,越高越好
  10. print('"唐山" 和 "中国" 的相似度:'+ str(model.similarity('唐山','中国')))
  11. print('"中国" 和 "祖国" 的相似度:'+ str(model.similarity('祖国','中国')))
  12. print('"中国" 和 "中国" 的相似度:'+ str(model.similarity('中国','中国')))
  13. #使用一些词语来限定,分为正向和负向的
  14. result = model.most_similar(positive=['中国', '城市'], negative=['学生'])
  15. print('同"中国"与"城市"二词接近,但是与"学生"不接近的词有:')
  16. for item in result:
  17. print(' "'+item[0]+'" 相似度:'+str(item[1]))
  18. result = model.most_similar(positive=['男人','权利'], negative=['女人'])
  19. print('同"男人"和"权利"接近,但是与"女人"不接近的词有:')
  20. for item in result:
  21. print(' "'+item[0]+'" 相似度:'+str(item[1]))
  22. result = model.most_similar(positive=['女人','法律'], negative=['男人'])
  23. print('同"女人"和"法律"接近,但是与"男人"不接近的词有:')
  24. for item in result:
  25. print(' "'+item[0]+'" 相似度:'+str(item[1]))
  26. #从一堆词里面找到不匹配的
  27. print("老师 学生 上课 校长 , 有哪个是不匹配的? word2vec结果说是:"+model.doesnt_match("老师 学生 上课 校长".split()))
  28. print("汽车 火车 单车 相机 , 有哪个是不匹配的? word2vec结果说是:"+model.doesnt_match("汽车 火车 单车 相机".split()))
  29. print("大米 白色 蓝色 绿色 红色 , 有哪个是不匹配的? word2vec结果说是:"+model.doesnt_match("大米 白色 蓝色 绿色 红色 ".split()))
  30. #直接查看某个词的向量
  31. print('中国的特征向量是:')
  32. print(model['中国'])

效果如下: 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/357130
推荐阅读
相关标签
  

闽ICP备14008679号