经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
HanLP — 词性标注
来源:cnblogs  作者:VipSoft  时间:2024/2/2 9:17:03  对本文有异议


词性(Part-Of-Speech,POS)指的是单词的语法分类,也称为词类。同一个类别的词语具有相似的语法性质
所有词性的集合称为词性标注集
image

词性的用处

当下游应用遇到OOV时,可以通过OOV的词性猜测用法词性也可以直接用于抽取一些信息,比如抽取所有描述特定商品的形容词等

词性标注

词性标注指的是为句子中每个单词预测一个词性标签的任务

  • 汉语中一个单词多个词性的现象很常见(称作兼类词)
  • OOV是任何自然语言处理任务的难题

词性标注模型

联合模型

同时进行多个任务的模型称为联合模型(joint model)

  1. B-名词
  2. E-名词
  3. S-连词
  4. B-名词
  5. E-名词

流水线式

中文分词语料库远远多于词性标注语料库
实际工程上通常在大型分词语料库上训练分词器
然后与小型词性标注语料库上的词性标注模型灵活组合为一个异源的流水线式词法分析器
image

词性标注语料库与标注集

目前还没有一个被广泛接受的汉语词性划分标准
本节选取其中一些授权宽松,容易获得的语料库作为案例,介绍其规模、标注集等特点

《人民日报》语料库与PKU标注集
http://file.hankcs.com/corpus/pku98.zip
https://www.fujitsu.com/cn/about/resources/news/press-releases/2001/0829.html
语料库中的一句样例为:
1997年/t 12月/t 31日/t 午夜/t ,/w 聚集/v 在/p 日本/ns 东京/ns 增上寺/ns 的/u 善男信女/i 放飞/v 气球/n ,/w 祈祷/v 新年/t 好运/n 。

国家语委语料库与863标注集

国家语言文字工作委员会建设的大型语料库
国家语委语料库的标注规范《信息处理用现代汉语词类标记集规范》在2006年成为国家标准
其词类体系分为20个一级类、29个二级类

《诛仙》语料库与CTB标注集

哈工大张梅山老师公开了网络小说《诛仙》上的标注语料
远处/NN ,/PU 小竹峰/NR 诸/DT 人/NN 处/NN ,/PU 陆雪琪/NR 缓缓/AD 从/P 张小凡/NR 身上/NN 收回/VV 目光/NN ,/PU 落到/VV 了/AS 前方/NN 碧瑶/NR 的/DEG 身上/NN ,/PU 默默/AD 端详/VV 著/AS 她/PN 。/PU
《诛仙》语料库采用的标注集与CTB(Chinese Treebank,中文树库)相同,一共33种词类

序列标注模型应用于词性标注

HanLP中词性标注由POSTagger接口提供
image

训练集转换成 Sentence 对像
IOUtility.loadInstance

  1. /**
  2. * 将语料库中每行文字,字符、词性,转换成 Sentence,由具体的实现类去做 handler.process 处理
  3. * @param path
  4. * @param handler
  5. * @return
  6. * @throws IOException
  7. */
  8. public static int loadInstance(final String path, InstanceHandler handler) throws IOException {
  9. ConsoleLogger logger = new ConsoleLogger();
  10. int size = 0;
  11. File root = new File(path);
  12. File allFiles[];
  13. if (root.isDirectory()) {
  14. allFiles = root.listFiles(new FileFilter() {
  15. @Override
  16. public boolean accept(File pathname) {
  17. return pathname.isFile() && pathname.getName().endsWith(".txt");
  18. }
  19. });
  20. } else {
  21. allFiles = new File[]{root};
  22. }
  23. for (File file : allFiles) {
  24. BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
  25. String line;
  26. while ((line = br.readLine()) != null) {
  27. line = line.trim();
  28. if (line.length() == 0) {
  29. continue;
  30. }
  31. //line=迈向/v 充满/v 希望/n 的/u 新/a 世纪/n ——/w 一九九八年/t 新年/t 讲话/n (/w 附/v 图片/n 1/m 张/q )/w
  32. Sentence sentence = Sentence.create(line);
  33. //wordList[0].value="迈向"
  34. //wordList[0].label="v"
  35. if (sentence.wordList.size() == 0) continue;
  36. ++size;
  37. if (size % 1000 == 0) {
  38. logger.err("%c语料: %dk...", 13, size / 1000);
  39. }
  40. // debug
  41. // if (size == 100) break;
  42. if (handler.process(sentence)) break;
  43. }
  44. }
  45. return size;
  46. }

基于隐马尔可夫模型的词性标注
image
HanLP-1.7.5\src\main\java\com\hankcs\hanlp\model\hmm\HMMTrainer.java

  1. /***
  2. * HMM 训练
  3. * @param corpus data/test/pku98/199801-train.txt
  4. * @throws IOException
  5. */
  6. public void train(String corpus) throws IOException
  7. {
  8. final List<List<String[]>> sequenceList = new LinkedList<List<String[]>>();
  9. IOUtility.loadInstance(corpus, new InstanceHandler()
  10. {
  11. @Override
  12. public boolean process(Sentence sentence)
  13. {
  14. sequenceList.add(convertToSequence(sentence));
  15. return false;
  16. }
  17. });
  18. TagSet tagSet = getTagSet();
  19. List<int[][]> sampleList = new ArrayList<int[][]>(sequenceList.size());
  20. for (List<String[]> sequence : sequenceList)
  21. {
  22. int[][] sample = new int[2][sequence.size()];
  23. int i = 0;
  24. for (String[] os : sequence)
  25. {
  26. sample[0][i] = vocabulary.idOf(os[0]);
  27. assert sample[0][i] != -1;
  28. sample[1][i] = tagSet.add(os[1]);
  29. assert sample[1][i] != -1;
  30. ++i;
  31. }
  32. sampleList.add(sample);
  33. }
  34. model.train(sampleList);
  35. vocabulary.mutable = false;
  36. }

基于感知机的词性标注
image

  1. /**
  2. * 训练
  3. *
  4. * @param trainingFile 训练集
  5. * @param developFile 开发集
  6. * @param modelFile 模型保存路径
  7. * @param compressRatio 压缩比
  8. * @param maxIteration 最大迭代次数
  9. * @param threadNum 线程数
  10. * @return 一个包含模型和精度的结构
  11. * @throws IOException
  12. */
  13. public Result train(String trainingFile, String developFile,
  14. String modelFile, final double compressRatio,
  15. final int maxIteration, final int threadNum) throws IOException
  16. {
  17. if (developFile == null)
  18. {
  19. developFile = trainingFile;
  20. }
  21. // 加载训练语料
  22. TagSet tagSet = createTagSet();
  23. MutableFeatureMap mutableFeatureMap = new MutableFeatureMap(tagSet);
  24. ConsoleLogger logger = new ConsoleLogger();
  25. logger.start("开始加载训练集...\n");
  26. Instance[] instances = loadTrainInstances(trainingFile, mutableFeatureMap);
  27. tagSet.lock();
  28. logger.finish("\n加载完毕,实例一共%d句,特征总数%d\n", instances.length, mutableFeatureMap.size() * tagSet.size());
  29. // 开始训练
  30. ImmutableFeatureMap immutableFeatureMap = new ImmutableFeatureMap(mutableFeatureMap.featureIdMap, tagSet);
  31. mutableFeatureMap = null;
  32. double[] accuracy = null;
  33. if (threadNum == 1)
  34. {
  35. AveragedPerceptron model;
  36. model = new AveragedPerceptron(immutableFeatureMap);
  37. final double[] total = new double[model.parameter.length];
  38. final int[] timestamp = new int[model.parameter.length];
  39. int current = 0;
  40. for (int iter = 1; iter <= maxIteration; iter++)
  41. {
  42. Utility.shuffleArray(instances);
  43. for (Instance instance : instances)
  44. {
  45. ++current;
  46. int[] guessLabel = new int[instance.length()];
  47. model.viterbiDecode(instance, guessLabel);
  48. for (int i = 0; i < instance.length(); i++)
  49. {
  50. int[] featureVector = instance.getFeatureAt(i);
  51. int[] goldFeature = new int[featureVector.length];
  52. int[] predFeature = new int[featureVector.length];
  53. for (int j = 0; j < featureVector.length - 1; j++)
  54. {
  55. goldFeature[j] = featureVector[j] * tagSet.size() + instance.tagArray[i];
  56. predFeature[j] = featureVector[j] * tagSet.size() + guessLabel[i];
  57. }
  58. goldFeature[featureVector.length - 1] = (i == 0 ? tagSet.bosId() : instance.tagArray[i - 1]) * tagSet.size() + instance.tagArray[i];
  59. predFeature[featureVector.length - 1] = (i == 0 ? tagSet.bosId() : guessLabel[i - 1]) * tagSet.size() + guessLabel[i];
  60. model.update(goldFeature, predFeature, total, timestamp, current);
  61. }
  62. }
  63. // 在开发集上校验
  64. accuracy = trainingFile.equals(developFile) ? IOUtility.evaluate(instances, model) : evaluate(developFile, model);
  65. out.printf("Iter#%d - ", iter);
  66. printAccuracy(accuracy);
  67. }
  68. // 平均
  69. model.average(total, timestamp, current);
  70. accuracy = trainingFile.equals(developFile) ? IOUtility.evaluate(instances, model) : evaluate(developFile, model);
  71. out.print("AP - ");
  72. printAccuracy(accuracy);
  73. logger.start("以压缩比 %.2f 保存模型到 %s ... ", compressRatio, modelFile);
  74. model.save(modelFile, immutableFeatureMap.featureIdMap.entrySet(), compressRatio);
  75. logger.finish(" 保存完毕\n");
  76. if (compressRatio == 0) return new Result(model, accuracy);
  77. }
  78. else
  79. {
  80. // 多线程用Structure Perceptron
  81. StructuredPerceptron[] models = new StructuredPerceptron[threadNum];
  82. for (int i = 0; i < models.length; i++)
  83. {
  84. models[i] = new StructuredPerceptron(immutableFeatureMap);
  85. }
  86. TrainingWorker[] workers = new TrainingWorker[threadNum];
  87. int job = instances.length / threadNum;
  88. for (int iter = 1; iter <= maxIteration; iter++)
  89. {
  90. Utility.shuffleArray(instances);
  91. try
  92. {
  93. for (int i = 0; i < workers.length; i++)
  94. {
  95. workers[i] = new TrainingWorker(instances, i * job,
  96. i == workers.length - 1 ? instances.length : (i + 1) * job,
  97. models[i]);
  98. workers[i].start();
  99. }
  100. for (TrainingWorker worker : workers)
  101. {
  102. worker.join();
  103. }
  104. for (int j = 0; j < models[0].parameter.length; j++)
  105. {
  106. for (int i = 1; i < models.length; i++)
  107. {
  108. models[0].parameter[j] += models[i].parameter[j];
  109. }
  110. models[0].parameter[j] /= threadNum;
  111. }
  112. accuracy = trainingFile.equals(developFile) ? IOUtility.evaluate(instances, models[0]) : evaluate(developFile, models[0]);
  113. out.printf("Iter#%d - ", iter);
  114. printAccuracy(accuracy);
  115. }
  116. catch (InterruptedException e)
  117. {
  118. err.printf("线程同步异常,训练失败\n");
  119. e.printStackTrace();
  120. return null;
  121. }
  122. }
  123. logger.start("以压缩比 %.2f 保存模型到 %s ... ", compressRatio, modelFile);
  124. models[0].save(modelFile, immutableFeatureMap.featureIdMap.entrySet(), compressRatio, HanLP.Config.DEBUG);
  125. logger.finish(" 保存完毕\n");
  126. if (compressRatio == 0) return new Result(models[0], accuracy);
  127. }
  128. LinearModel model = new LinearModel(modelFile);
  129. if (compressRatio > 0)
  130. {
  131. accuracy = evaluate(developFile, model);
  132. out.printf("\n%.2f compressed model - ", compressRatio);
  133. printAccuracy(accuracy);
  134. }
  135. return new Result(model, accuracy);
  136. }

基于条件随机场的词性标注
image

词性标注评测
image
PosTagUtil.evaluate

  1. /**
  2. * 评估词性标注器的准确率
  3. *
  4. * @param tagger 词性标注器
  5. * @param corpus 测试集 data/test/pku98/199801-test.txt
  6. * @return Accuracy百分比
  7. */
  8. public static float evaluate(POSTagger tagger, String corpus)
  9. {
  10. int correct = 0, total = 0;
  11. IOUtil.LineIterator lineIterator = new IOUtil.LineIterator(corpus);
  12. //循环测试集中的每一行数据
  13. for (String line : lineIterator)
  14. {
  15. Sentence sentence = Sentence.create(line);
  16. if (sentence == null) continue;
  17. //将字符,词性,转成二维数组
  18. String[][] wordTagArray = sentence.toWordTagArray();
  19. //根据测试字符获得预测的词性
  20. String[] prediction = tagger.tag(wordTagArray[0]);
  21. //看预测词性的长度和测试词性长度是否相等
  22. assert prediction.length == wordTagArray[1].length;
  23. // 199801-test.txt 中的所有字符个数
  24. total += prediction.length;
  25. for (int i = 0; i < prediction.length; i++)
  26. {
  27. //预测词性 = 测试词性,预测正确的标签总数 + 1
  28. if (prediction[i].equals(wordTagArray[1][i])){
  29. ++correct;
  30. }
  31. }
  32. }
  33. if (total == 0) return 0;
  34. //准确率 = 预测正确标签总数 / 标签总数
  35. return correct / (float) total * 100;
  36. }

自定义词性

在工程上,许多用户希望将特定的一些词语打上自定义的标签,称为自定义词性

朴素实现

规则系统,用户将自己关心的词语以及自定义词性以词典的形式交给HanLP挂载

  1. CustomDictionary.insert("苹果", "手机品牌 1") CustomDictionary.insert("iPhone X", "手机型号 1") analyzer = PerceptronLexicalAnalyzer() analyzer.enableCustomDictionaryForcing(True) print(analyzer.analyze("你们苹果iPhone X保修吗?")) print(analyzer.analyze("多吃苹果有益健康"))

你们/r 苹果/手机品牌 iPhone X/手机型号 保修/v 吗/y ?/w
多/ad 吃/v 苹果/手机品牌 有益健康/i

标注语料

  1. PerceptronPOSTagger posTagger = trainPerceptronPOS(ZHUXIAN); // 训练 AbstractLexicalAnalyzer analyzer = new AbstractLexicalAnalyzer(new PerceptronSegmenter(), posTagger); // 包装 System.out.println(analyzer.analyze("陆雪琪的天琊神剑不做丝毫退避,直冲而上,瞬间,这两道奇光异宝撞到了一起。")); // 分词+标注

陆雪琪/NR 的/DEG 天琊神剑/NN 不/AD 做/VV 丝毫/NN 退避/VV ,/PU 直冲/VV 而/MSP 上/VV ,/PU 瞬间/NN ,/PU 这/DT 两/CD 道/M 奇光/NN 异宝/NN 撞/VV 到/VV 了/AS 一起/AD 。/PU

总结

隐马尔可夫模型、感知机和条件随机场三种词性标注器
为了实现自定义词性
依靠词典匹配虽然简单但非常死板,只能用于一词一义的情况
如果涉及兼类词,标注一份领域语料才是正确做法

原文链接:https://www.cnblogs.com/vipsoft/p/17998604

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号