Introduce Ramda a practical functional library for JavaScript/TypeScript by Naive Bayes classifier script.
It's code after refactoring from refactoring tutorial from a book Refactoring JavaScript: Turning Bad Code Into Good Code
This repo refactor the original code into a functional programming style version by adopting Ramda.
- original code
https://github.com/MingJen/ChordTrain/blob/main/TypeScript/main.ts
- code after refactoring
https://github.com/guAnsunyata/ramda-classifier-example/blob/main/src/script/classifier.ts
https://github.com/guAnsunyata/ramda-classifier-example/blob/main/src/script/records-of.ts
https://github.com/guAnsunyata/ramda-classifier-example/blob/main/src/main.ts
Naive Bayes classifier
see classifier
Query records in specific parameters for calculating classifier probability
see record-of see test case of record-of
Test final result for refactoring code from the book
Make formula of Naive Bayes classifier more clear. Use query function in a declarative way to indicate the probability concepts. Rather than generating snapshot maps imperatively.
const categoryProbability = (category) =>
length(recordOf(category)) / length(records) + smooth
const attrProbability = (category, attr) =>
length(recordOf(category, attr)) / length(records)
Implementation of query function
export const recordsOf: RecordOf = (records) => (category, attr) =>
filter(
both(
matchCategory(category),
ifElse(always(!!attr), matchAttr(attr), always(true))
),
records
)
const matchCategory = (category) => pipe(prop('category'), equals(category))
const matchAttr = (attr) => pipe(prop('attrs'), find(equals(attr)))