{"id":16387587,"url":"https://github.com/surmon-china/naivebayes","last_synced_at":"2025-03-16T16:31:05.422Z","repository":{"id":20183296,"uuid":"89076616","full_name":"surmon-china/naivebayes","owner":"surmon-china","description":"NaiveBayes classifier for JavaScript","archived":false,"fork":false,"pushed_at":"2023-03-07T17:15:16.000Z","size":537,"stargazers_count":142,"open_issues_count":8,"forks_count":8,"subscribers_count":6,"default_branch":"main","last_synced_at":"2024-10-12T04:26:53.286Z","etag":null,"topics":["bayes","classifier","javascript-library","machine-learning","machine-learning-algorithms","naive","naive-bayes","naive-bayes-algorithm","naive-bayes-classification","naive-bayes-classifier","naivebayes","node-ml","nodejs"],"latest_commit_sha":null,"homepage":"https://github.surmon.me/naivebayes","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/surmon-china.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2017-04-22T14:42:25.000Z","updated_at":"2024-06-27T22:51:35.000Z","dependencies_parsed_at":"2023-02-13T23:16:38.009Z","dependency_job_id":"dd8ebc32-b060-455d-9237-e8b1f2d3d9fb","html_url":"https://github.com/surmon-china/naivebayes","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/surmon-china%2Fnaivebayes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/surmon-china%2Fnaivebayes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/surmon-china%2Fnaivebayes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/surmon-china%2Fnaivebayes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/surmon-china","download_url":"https://codeload.github.com/surmon-china/naivebayes/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":221665860,"owners_count":16860320,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bayes","classifier","javascript-library","machine-learning","machine-learning-algorithms","naive","naive-bayes","naive-bayes-algorithm","naive-bayes-classification","naive-bayes-classifier","naivebayes","node-ml","nodejs"],"created_at":"2024-10-11T04:26:55.684Z","updated_at":"2024-10-27T10:54:58.474Z","avatar_url":"https://github.com/surmon-china.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n# naivebayes\n\n[![GitHub stars](https://img.shields.io/github/stars/surmon-china/naivebayes.svg?style=for-the-badge)](https://github.com/surmon-china/naivebayes/stargazers)\n\u0026nbsp;\n[![GitHub issues](https://img.shields.io/github/issues-raw/surmon-china/naivebayes.svg?style=for-the-badge)](https://github.com/surmon-china/naivebayes/issues)\n\u0026nbsp;\n[![npm](https://img.shields.io/npm/v/naivebayes?color=%23c7343a\u0026label=npm\u0026style=for-the-badge)](https://www.npmjs.com/package/naivebayes)\n\u0026nbsp;\n[![license](https://img.shields.io/github/license/mashape/apistatus.svg?style=for-the-badge)](/LICENSE)\n\n[![NPM](https://nodei.co/npm/naivebayes.png?downloads=true\u0026downloadRank=true\u0026stars=true)](https://nodei.co/npm/naivebayes/)\n\nNaive-Bayes classifier for JavaScript.\n\n适用于 JavaScript 的用于文本学习的朴素贝叶斯算法库。\n\n`naivebayes` takes a document (piece of text), and tells you what category that document belongs to.\n\n简单说：**它可以学习文本和标签，并告诉你新的未知文本应该属于什么标签/分类。**\n\n**核心公式：**\n\n```\n文本：[W1,W2,W3,W4,W5...Wn]\n分类：[C1,C2,C3,C4,C5...Cn]\n\nP(C|D) = P(D|C) * P(C) / P(D)\n\n= P(C|W1W2...Wn) = P(W1W2...Wn|C) * P(C) / P(W1W2...Wn)\n\n=\u003e Cn.forEach(C =\u003e P(W1W2...Wn|C))\n\n=\u003e Wn.forEach(W =\u003e P(W|C)\n```\n\n**[Web example | 使用浏览器进行在线分类学习](https://github.surmon.me/naivebayes)**\n\n## What can I use this for?\n\nYou can use this for categorizing any text content into any arbitrary set of **categories**. For example:\n\n- Is an email **spam**, or **not spam** ?\n- Is a news article about **technology**, **politics**, or **sports** ?\n- Is a piece of text expressing **positive** emotions, or **negative** emotions?\n\n它可以用于任何文本学习类项目。比如：\n- 判断未知邮件是否为垃圾邮件\n- 判断不同的未知文本风格对应的作者\n- 判断未知文本内容的分类，可以是任何你想要的维度\n- ...\n\n## Installing\n\n```\nnpm install naivebayes --save\n```\n\n## Usage\n\n### 基本方法\n\n```javascript\n// 导入\nconst NaiveBayes = require('naivebayes')\n\n// 实例化（创建分类器）\nconst classifier = new NaiveBayes()\n\n// 学习文本和分类，teach it positive phrases\nclassifier.learn('amazing, awesome movie!! Yeah!! Oh boy.', 'positive')\nclassifier.learn('Sweet, this is incredibly, amazing, perfect, great!!', 'positive')\n\n// 学习不同文本和分类，teach it a negative phrase\nclassifier.learn('terrible, shitty thing. Damn. Sucks!!', 'negative')\n\n// 判断文本归属，now ask it to categorize a document it has never seen before\nclassifier.categorize('awesome, cool, amazing!! Yay.')\n// =\u003e 'positive'\n\n// 导出学习数据，serialize the classifier's state as a JSON string.\nconst stateJson = classifier.toJson()\n\n// 导入学习数据，load the classifier back from its JSON representation.\nconst revivedClassifier = NaiveBayes.fromJson(stateJson)\n\n```\n\n### 实践场景\n\n```javascript\nconst NaiveBayes = require('naivebayes')\n\n// 使用第三方中文分词库\nconst Segment = require('segment')\nconst segment = new Segment()\n\n// 使用默认的识别模块及字典，载入字典文件需要1秒，仅初始化时执行一次即可\nsegment.useDefault()\n\n// 分词测试\nconsole.log('测试中文分词库', segment.doSegment('这是一个基于 Node.js 的中文分词模块。', { simple: true }))\n// 测试中文分词库 [ '这是', '一个', '基于', 'Node.js', '的', '中文', '分词', '模块', '。' ]\n\nconst classifier = new NaiveBayes({\n\n    // 自定义分词器\n    tokenizer(sentence) {\n\n        // 仅保留英文、中文、数字\n        const sanitized = sentence.replace(/[^(a-zA-Z\\u4e00-\\u9fa50-9_)+\\s]/g, ' ')\n\n        // 中英文分词\n        return segment.doSegment(sanitized, { simple: true })\n    }\n})\n\n// 利用词库进行一些复杂的测试\nclassifier.learn('你大爷的！', '脏话')\nclassifier.learn('跪下叫爸爸！！', '脏话')\nclassifier.learn('我去你妈的！！', '脏话')\nclassifier.learn('呵呵呵妈的智障！！', '脏话')\nclassifier.learn('妈妈，一起飞吧', '正常')\nclassifier.learn('妈妈，一起摇滚吧', '正常')\nclassifier.learn('给山和河起个名字，骑马的坐在马背上，放羊的跟在羊身后', '正常')\nclassifier.learn('金色的秋天正在向一望无际的原野告别', '正常')\nclassifier.learn('他们还看见他们所有的人站在一起，还没有一片树叶年轻', '正常')\nclassifier.learn('牛儿吃草卷起舌头，狐狸和土狼寻找着野兔子的窝', '正常')\nclassifier.learn('反正现在这里到处都是你的脚印', '正常')\nclassifier.learn('不毛之地已高楼林立，流亡之处已灯红酒绿', '正常')\nclassifier.learn('我想要怒放的生命', '正常')\nclassifier.learn('两种社会矛盾之一。同“敌我矛盾”相对。一般来说，是在人民利益根本一致的基础上的矛盾。它在不同的国家和各个国家的不同历史时期有着不同的内容。在中国社会主义革命和建设时期，“包括工人阶级内部，工农两个阶级之间，知识分子之间，农民阶级之间，工人、农民和知识分子之间的矛盾”。', '正常')\n\n// 测试\nconsole.log('预期：脏话，实际：', classifier.categorize('你大爷的吧')) // 脏话\nconsole.log('预期：脏话，实际：', classifier.categorize('你丫有病吧')) // 脏话\nconsole.log('预期：正常，实际：', classifier.categorize('妈妈，我饿了')) // 正常\nconsole.log('预期：正常，实际：', classifier.categorize('马克思主义'， true)) // { category: '正常', probability: xxx }\n\n// 获取对于各分类的概率数组\nconsole.log('预期：正常，实际：', classifier.probabilities('马克思主义'))\n// [{ category: 'xx', probability: xxx }, { ... }, ...]\n```\n\n## API\n\n### Class\n\n```javascript\nconst classifier = new NaiveBayes([options])\n```\n\nReturns an instance of a Naive-Bayes Classifier.\n\nPass in an optional `options` object to configure the instance. If you specify a `tokenizer` function in `options`, it will be used as the instance's tokenizer. It receives a (string) `text` argument - this is the string value that is passed in by you when you call `.learn()` or `.categorize()`. It must return an array of tokens.\n\n你可以自定义一个分词器，用于将被学习的文本进行处理后，返回一个数组；\n默认分词器仅保留中文、英文、数字字符，英文按照空格分割词汇，中文按照单个汉字分割词汇，[代码在此](/src/naivebayes.js#L21)。\n\nEg.\n\n```javascript\nconst classifier = new NaiveBayes({\n    tokenizer(text) { \n        return text.split(' ') \n    }\n})\n```\n\n### Learn\n\n```javascript\nclassifier.learn(text, category)\n```\n\n学习：使分类器学习一些新的内容，内容包括文本和文本对应的标签/分类；标签/分类可以是已经存在的；学习的样本越多，分类的准确率越高。\n\nTeach your classifier what `category` the `text` belongs to. The more you teach your classifier, the more reliable it becomes. It will use what it has learned to identify new documents that it hasn't seen before.\n\n### Probabilities\n\n```javascript\nclassifier.probabilities(text)\n```\n\n计算概率：返回一个由分类名称和分类对应的概率（计算后的）组成的数组，已经从大到小排序完毕，`classifier.categorize(text)` 使用的便是此数组中的最大值。\n\nReturns an array of `{ category, probability }` objects with probability calculated for each category. Its judgement is based on what you have taught it with `.learn()`.\n\n### Categorize\n\n```javascript\nclassifier.categorize(text ,[probability])\n```\n\n分类：确定一段文本所属的分类，`probability`参数用于标识是否返回概率，如果为`true`，则返回一个对象`{ category: xxx, probability: xxx }`，否则直接返回分类。\n\nReturns the `category` it thinks `text` belongs to. Its judgement is based on what you have taught it with `.learn()`.\n\n### ToJson\n\n```javascript\nclassifier.toJson()\n```\n\n导出：将类实例化之后进行的一系列学习成果导出为标准json格式（字符串），以便下次导入增量学习。\n\nReturns the JSON representation of a classifier. This is the same as `JSON.stringify(classifier.toJsonObject())`.\n\n### ToJsonObject\n\n```javascript\nclassifier.toJsonObject()\n```\n\n基本同上，异同：导出的是json对象，可直接用于运算。\n\nReturns a JSON-friendly representation of the classifier as an `object`.\n\n### FromJson\n\n```javascript\nconst classifier = NaiveBayes.fromJson(jsonObject)\n```\n\n导入：将上次的学习成果导入并实例化，格式为标准Json（字符串/对象）；当然你也可以将其他地方已学习的计算结果转化为 `NaiveBayes` 需要的json格式，然后初始化`NaiveBayes` 分类器，json对象的具体格式可以通过[这里的代码](/src/naivebayes.js#L7)一探究竟。\n\nReturns a classifier instance from the JSON representation. Use this with the JSON representation obtained from `classifier.toJson()`.\n\n## 相关库\n### 中文分词库：\n- [nodejieba](https://github.com/yanyiwu/nodejieba)\n- [node-segment](https://github.com/leizongmin/node-segment)\n- [segmentit (for javascript)](https://github.com/linonetwo/segmentit)\n- [china-address - 地址分词](https://github.com/booxood/china-address)\n- [word-picker](https://github.com/redhu/word-picker)\n\n### 英文分词库：\n- [tokenize-text](https://github.com/GitbookIO/tokenize-text)\n- [tokenizer](https://github.com/bredele/tokenizer)\n\n## Credits\nThis project was forked from [bayes](https://github.com/ttezel/bayes) by @Tolga Tezel 👍\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsurmon-china%2Fnaivebayes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsurmon-china%2Fnaivebayes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsurmon-china%2Fnaivebayes/lists"}