• C# 文本分类之朴素贝叶斯分类


    贝叶斯分类是一类分类算法的总称,这类算法均以贝叶斯定理为基础,故统称为贝叶斯分类。而朴素贝叶斯分类是贝叶斯分类中最简单,也是常见的一种分类方法。引用一句每篇写到朴素贝叶斯分类文章基本都会介绍的一句话。

    对于机器学习和算法之类的,我是个小小白。很多东西都百思不得其解。

    写这个也是一个学习的过程,为此专门买了西瓜书等其他算法书籍。emmmm,该看不懂还是看不懂。

    我一开始的诉求很简单,就是想做个文本分类,查了一些文章,越看越懵,而且关于此方面的开发,大都是python写的,然后很多python又都是直接调包。。。。

    关于朴素贝叶斯分类在看了几篇文章后发现,嗯,最起码我能看懂。所以就照着写了下来。最后的成果的话,我感觉还行,最起码没有太离谱。反正就是一个入门的学习,再深入的话可能要掉头发。

    为了实现这个功能,简单的数据处理还是必要的,比如把北京、上海、广州、深圳定义为是城市,张三、李四、赵五定义为人名,长江、黄河、黄浦江定义为河流。这三个层次看起来还是比较好区分,最起码之间干系不大,但也不能绝对,比如有的人名叫长江等,这样的数据多了的话,会影响最终的预测结果。

    当然我这里处理的数据不是这些,所以还用到了JiebaNet来对数据进行分词处理。

    所以简述下这个流程就很简单,已有数据进行分类->分词处理->调用朴素贝叶斯分类算法->输入数据->预测结果。

    最后提一下,虽然说代码写完了,但是是基于怎么简单怎么来的思路来做的,我甚至一度怀疑使用我这个方法来做这件事可能从根本上就是不正确的,所以说,有需要参考下就行,我的思路可能并不正确,不要在这条路上浪费过多时间。

    实现功能:

      • 使用朴素贝叶斯分类实现文本分类

    开发环境:

    开发工具:Visual Studio 2022

    .NET Framework版本:4.7.2

    实现代码:

    1. /// <summary>
    2. /// 朴素贝叶斯分类
    3. /// </summary>
    4. public class NaiveBayes {
    5. Dictionary<string, string> _types;
    6. List<TrainItem> _trains;
    7. public NaiveBayes(Dictionary<string, string> types
    8. , List<TrainItem> trains) {
    9. _types = types;
    10. _trains = trains;
    11. typesScore = new Dictionary<string, double>();
    12. }
    13. /// <summary>
    14. /// 待分类文本关键词(可重复,重复词有助于分类)
    15. /// </summary>
    16. private List<string> keyList = new List<string>();
    17. /// <summary>
    18. /// 类别分数
    19. /// </summary>
    20. public Dictionary<string, double> typesScore { set; get; }
    21. /// <summary>
    22. /// 计算先验概率
    23. /// </summary>
    24. /// <param name="type"></param>
    25. /// <returns></returns>
    26. private double GetPrior(string type) {
    27. /*
    28. * 先验概率P(c)=“类c下的单词总数”/“整个训练样本的单词总数”
    29. */
    30. int typeCount = GetTrainSetCount(type);
    31. int allCount = GetTrainSetCount();
    32. double result = typeCount * 1.0 / allCount;
    33. return result;
    34. }
    35. /// <summary>
    36. /// 计算似然概率
    37. /// </summary>
    38. /// <param name="type"></param>
    39. /// <returns></returns>
    40. private double GetLikelihood(string type) {
    41. /*
    42. * P(X|c1)=P(x1|c1)P(x2|c1)...P(xn|c1)
    43. * P(x1|c1)="x1关键字在c1文档中出现过的次数之和+1"/"类c1下单词的总数(单词可重复)+总训练样本的不重复单词数"
    44. * 注:引入Laplace校准,它的思想非常简单,就是对没类别下所有划分的计数加1,解决 P(x1|c1)=0 的情况
    45. */
    46. int typeTermCount = GetTrainSetCount(type);
    47. int allTermCount = GetTrainSetCount();
    48. int sum = typeTermCount + allTermCount;
    49. double result = 1.0;
    50. int count = 0;
    51. //遍历待分类文本的关键字集合
    52. keyList.ForEach(x => {
    53. //计算 P(x1|c1)
    54. count = GetTrainSetCountForKey(type, x) + 1;
    55. result *= (count * 1.0 / sum);
    56. });
    57. return result;
    58. }
    59. /// <summary>
    60. /// 获取训练集中的关键字数量
    61. /// </summary>
    62. /// <param name="type">类别名称,为空则获取全部</param>
    63. /// <returns></returns>
    64. public int GetTrainSetCount(string type = null) {
    65. if(!string.IsNullOrEmpty(type)) {
    66. return _trains.Where(s => s.type == type).Count();
    67. }
    68. else {
    69. return _trains.Count();
    70. }
    71. }
    72. /// <summary>
    73. /// 获取训练集中某类别下某关键字数量
    74. /// </summary>
    75. /// <param name="type">类别</param>
    76. /// <param name="key">关键字</param>
    77. /// <returns></returns>
    78. public int GetTrainSetCountForKey(string type, string key) {
    79. int count = 0;
    80. //在可重复集合中寻找
    81. _trains.FindAll(s => s.type == type).ForEach(s => {
    82. count += s.textList.FindAll(t => t.Contains(key)).Count;
    83. });
    84. return count;
    85. }
    86. /// <summary>
    87. /// 获取最终分类结果
    88. /// </summary>
    89. /// <returns></returns>
    90. public string GetClassify(string content) {
    91. // _tempTermList = GetTermSegment(content);//分词
    92. var segmenter = new JiebaSegmenter();
    93. keyList = segmenter.CutForSearch(content).ToList();
    94. /*
    95. * P(C|X)=P(X|C)P(C)/P(X);后验概率=似然概率(条件概率)*先验概率/联合概率
    96. *
    97. * 其中,P(X)联合概率,为常量,所以只需要计算 P(X|C)P(C)
    98. *
    99. * 公式:P(X|C)P(C)
    100. * 其中:
    101. * P(X|C)=P(x1|c1)P(x2|c1)...P(xn|c1)
    102. * P(x1|c1)="x1关键字在c1文档中出现过的次数之和 +1"/"类c1下单词的总数(单词可重复)+总训练样本的不重复单词数"
    103. * P(c1)=类c1下总共有单词个数(可重复)/训练样本单词总数(可重复),
    104. */
    105. double likelihood = 0f;//似然概率
    106. double prior = 0f;//先验概率
    107. double probability = 0f; //后验概率
    108. //1 计算每个列别的概率值
    109. foreach(var type in _types.Keys) {
    110. //计算似然概率 P(X|c1)=P(x1|c1)P(x2|c1)...P(xn|c1)
    111. likelihood = GetLikelihood(type);
    112. //计算先验概率 P(c1)
    113. prior = GetPrior(type);
    114. //计算最中值:P(X|C)P(C)
    115. probability = likelihood * prior;
    116. //保存类的最终概率值
    117. NoteTypeScore(type, probability);
    118. }
    119. //2 获取最大概率的类型code
    120. string typeCode = GetMaxSoreType();
    121. if(string.Equals(typeCode, string.Empty))
    122. return "-1";
    123. return typeCode;
    124. }
    125. private string GetMaxSoreType() {
    126. //对字典中的值进行排序
    127. Dictionary<string, double> soretDic = typesScore
    128. .OrderByDescending(x => x.Value)
    129. .ToDictionary(x => x.Key, x => x.Value);
    130. //返回第一个分数最高的类型code
    131. return soretDic.First().Key;
    132. }
    133. /// <summary>
    134. /// 记录类型得分
    135. /// </summary>
    136. /// <param name="type"></param>
    137. /// <param name="sore"></param>
    138. private void NoteTypeScore(string type, double sore) {
    139. typesScore[type] = sore;
    140. }
    141. }
    142. public class TrainItem {
    143. public string type { get; set; }
    144. public List<string> textList { get; set; }
    145. // public SortedSet<string> textDistinctList = new SortedSet<string>();
    146. public TrainItem(string _type, List<string> _textList) {
    147. type = _type;
    148. textList = _textList;
    149. //textList.ForEach(s => textDistinctList.Add(s));
    150. }
    151. }
    1. Console.WriteLine("正在加载模型...");
    2. var split_kindname = Properties.Resource.品种.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
    3. var split_specname = Properties.Resource.规格.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
    4. var split_areaname = Properties.Resource.产地.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
    5. Dictionary<string, string> types = new Dictionary<string, string>
    6. {
    7. {"0","品种" },
    8. {"1","规格" },
    9. {"2","产地" },
    10. };
    11. List<TrainItem> trainSet = new List<TrainItem>
    12. {
    13. new TrainItem("0",split_kindname.ToList()),
    14. new TrainItem("1",split_specname.ToList()),
    15. new TrainItem("2",split_areaname.ToList()),
    16. };
    17. Console.WriteLine("模型加载完毕...\n");
    18. while(true) {
    19. Console.ForegroundColor = ConsoleColor.White;
    20. Console.WriteLine("\n请输入要检测的文本:\n");
    21. Console.ForegroundColor = ConsoleColor.Red;
    22. string input = Console.ReadLine();
    23. Console.WriteLine($"输入文本:{input}\n");
    24. Console.ForegroundColor = ConsoleColor.White;
    25. Console.WriteLine("正在预测结果...\n");
    26. NaiveBayes naiveBayes = new NaiveBayes(types, trainSet);
    27. string type = naiveBayes.GetClassify(input);
    28. Console.ForegroundColor = ConsoleColor.Green;
    29. if(naiveBayes.typesScore.Values.Distinct().Count() == 1) {
    30. Console.WriteLine($"预测结果:未知数据");
    31. }
    32. else {
    33. Console.WriteLine($"预测结果:{types[type]}");
    34. }
    35. }

    实现效果:

     

  • 相关阅读:
    Nginx之memcached_module模块解读
    新型人工智能技术让机器人的识别能力大幅提升
    mysql8.0英文OCP考试第131-140题
    【前端必学】PS切图详细教程3种方法(图层切图,切片,切图神器cutterman)
    Ajax+Axios+前后端分离+YApi+Vue-ElementUI组件+Vue路由+nginx【全详解】
    工业自动化编程与数字图像处理技术
    用Python上傳api資料
    【深度学习】Python爬取豆瓣实现影评分析
    UML 类图几种关系(依赖、关联、泛化、实现、聚合、组合)及其对应代码
    Mysql5.7开启SSL认证且支持Springboot客户端验证
  • 原文地址:https://blog.csdn.net/lwf3115841/article/details/127667929