How to use the natural.BayesClassifier function in natural

To help you get started, we’ve selected a few natural examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github shiffman / A2Z-F18 / week10-sentiment / 03_classification_API / server.js View on Github external
function listen() {
  const host = server.address().address;
  const port = server.address().port;
  console.log('Example app listening at http://' + host + ':' + port);
}

// Do we already have a classifier "database"
const exists = fs.existsSync('classifier.json');

// If we do, load it
if (exists) {
  natural.BayesClassifier.load('classifier.json', null, loaded);
  // If not make a new one
} else {
  console.log('starting a new classifier');
  classifier = new natural.BayesClassifier();
}

// All set and loaded
function loaded(err, cf) {
  classifier = cf;
  console.log('Classifier loaded');
}

// This is a post for training
app.post('/train', training);

function training(req, res) {
  // Get the text and category
  const text = req.body.text;
  const category = req.body.category;
github NaturalNode / natural / examples / classification / store.js View on Github external
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var natural = require('natural'),
    classifier = new natural.BayesClassifier();


classifier.addDocument('my unit-tests failed.', 'software');
classifier.addDocument('tried the program, but it was buggy.', 'software');
classifier.addDocument('the drive has a 2TB capacity.', 'hardware');
classifier.addDocument('i need a new power supply.', 'hardware');

classifier.train();

classifier.save('classifier.json', function(err, classifier) {
	// the classifier is saved to the classifier.json file!
    });
github brian-ai / core / src / services / natural / index.js View on Github external
/* eslint-disable no-unused-expressions */
import { BayesClassifier } from 'natural'
import { NlpManager, NluManager } from 'node-nlp'
import logger from 'hoopa-logger'
import baseKnowledge from '../../brain/knowledge'

const LanguageProcessor = new NlpManager({ languages: 'en' })
const UnderstandingProcessor = new NluManager({ languages: 'en' })

const NLP = {
	Bayes: new BayesClassifier(),
	LanguageProcessor,
	UnderstandingProcessor,
	trainModel: (newKnowledge = null, bayes, manager) => {
		logger.info('Cognitive analysis (NLP & NLU), basic training...')
		const trainingContext = baseKnowledge.natural

		if (newKnowledge) {
			newKnowledge.map(token => trainingContext.push(token))
		}

		trainingContext.map(token => {
			UnderstandingProcessor.addDocument('en', token.input, token.class)
			manager.addDocument('en', token.input, token.class)
			if (token.answer) {
				manager.addAnswer('en', token.class, token.answer)
			}
github velniukas / nlp2json / server.js View on Github external
var natural = require('natural'),
  pos = require('pos'),
  wordnet = new natural.WordNet(),
  _ = require('underscore'),
  NGrams = natural.NGrams,
  classifier = new natural.BayesClassifier(),
  tokenizer = new natural.TreebankWordTokenizer(); // natural.WordTokenizer();

  natural.PorterStemmer.attach();

// load the classifier data and learn the schema
/*natural.BayesClassifier.load('./classifier.json', null, function(err, classifier) {
	// if the classifier hasn't been saved, then calculate it now
	if (err) {
		var traindata = require('./trainingdata.json');
		for (i in traindata)
		{
			classifier.addDocument(traindata[i].query, traindata[i].category);
		}
		classifier.train();
		classifier.save('classifier.json', function(err, classifier) {
github flickz / jobtweets / training.js View on Github external
const {BayesClassifier} = require('natural')
const {readFileSync} = require('fs')
const {join} = require('lodash')

const classifier = new BayesClassifier()

function train () {
  var data = readFileSync('training-data.json', 'utf-8')
  data = JSON.parse(data)

  for (let i = 0; i < data.length; i++) {
    // The keywords is an array but natural classifier works better with a string
    // so keywords are turned to string of text.
    let text = join(data[i].keywords, ',')
    classifier.addDocument(text, data[i].field)
  }
}

train()

classifier.events.on('trainedWithDocument', function (obj) {
github NaturalNode / natural / examples / classification / recall.js View on Github external
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var natural = require('natural'),
    classifier = new natural.BayesClassifier();

natural.BayesClassifier.load('classifier.json', null, function(err, classifier) {
	console.log(classifier.classify('did the tests pass?'));
    });
github silvia-odwyer / Onyx / discordBot.js View on Github external
});

                })
                .catch(err => { throw err });
        }
    }

    else if (cmd === "chat") {
        var randomNumber = getRandomNumber(0, happy_emoji.length - 1)
        msg.react(happy_emoji[randomNumber])
        var naturalLanguageSentences = require(`naturalLanguage.json`)
        var resser2 = naturalLanguageSentences["about"];
        msg.reply(resser2)
        var question = msg.content.slice(6, msg.content.length)
        var natural = require('natural');
        var classifier = new natural.BayesClassifier();

        classifier.addDocument("you your", "about");
        classifier.addDocument("think", "opinion");
        classifier.addDocument("Which better versus", "versus");
        classifier.addDocument("Do like", "like");
        classifier.addDocument("Can you help me", "help")
        classifier.addDocument("created coder silvia silv made", "created")
        classifier.addDocument("I", "user")
        classifier.train();

        var result = String(classifier.classify(question));

        var answer = naturalLanguageSentences[result];
        console.log(answer)
        var randomNumber = getRandomNumber(0, answer.length - 1)
        var randomAnswer = answer[randomNumber]
github handav / nlp-in-javascript-with-natural / 7-classify / example1.js View on Github external
var natural = require('natural');
var classifier = new natural.BayesClassifier();

var trainingData = [
    {text: 'RE: Canadian drugs now on sale', label: 'spam'}, 
    {text: 'Earn more from home', label: 'spam'},
    {text: 'Information now available!!!', label: 'spam'},
    {text: 'Earn easy cash', label: 'spam'},
    {text: 'Your business trip is confirmed for Monday the 4th', label: 'notspam'},
    {text: 'Project planning - next steps', label: 'notspam'},
    {text:'Birthday party next weekend', label: 'notspam'},
    {text: 'Drinks on Monday?', label: 'notspam'}
];

var testData = [
    {text: 'Drugs for cheap', label: 'spam'},
    {text: 'Next deadline due Monday', label: 'notspam'},
    {text: 'Meet me at home?', label: 'notspam'},
github GCE-NEIIST / GCE-NEIIST-webapp / server / services / thesis / thesis-services.js View on Github external
const natural = require("natural");
//const bClassifier = new natural.BayesClassifier();
const bClassifierThesis = new natural.BayesClassifier(null,0.1);
const thesesClassifier = require("./bn.js");
const tokenizer = new natural.CaseTokenizer();
const sw = require('stopword');
const ba_logger = require('../../log/ba_logger');
const threshold = 0.5;
var htmlparser = require("htmlparser2");
const fs = require('fs'),
  path = require('path'),
  filePath = path.join(__dirname, "../../files/tTrad.html");

const util = require('util');
var HashMap = require('hashmap');



let ThesisTypes = ["Projecto", "Dissertação", "Empresa"];
github mertkahyaoglu / tsa-webapp / routes.js View on Github external
var router    = require('express').Router();
var natural   = require('natural');
var Twitter   = require('twitter');
var config    = require('./config');
var trainData = require('./train');

var client = new Twitter(config);
var classifier = new natural.BayesClassifier();
var all_tweets = [];

function train() {
  trainData.forEach(function(item) {
    classifier.addDocument(item[0], item[1]);
  });
  classifier.train();
}

router.use(function(req, res, next) {
    next();
});

router.get('/', function(req, res) {
  res.render('index');
});

natural

General natural language (tokenizing, stemming (English, Russian, Spanish), part-of-speech tagging, sentiment analysis, classification, inflection, phonetics, tfidf, WordNet, jaro-winkler, Levenshtein distance, Dice's Coefficient) facilities for node.

MIT
Latest version published 1 month ago

Package Health Score

98 / 100
Full package analysis