Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions MachineLearningInAction/MachineLearningInAction/NaiveBayes.fs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ module NaiveBayes =
label,
prop(total, size),
Map.map (fun token count -> prop(count, totTokens)) tokenCount)
|> Seq.toList

// Classifier function:
// the classifier is trained on the dataset,
Expand All @@ -112,16 +113,17 @@ module NaiveBayes =
// and returning the highest scoring label.
// Probabilities are log-transformed to avoid underflow.
// See "Chapter4.fsx" for an illustration.
let classifier frequency dataset words text =
let classifier frequency dataset words =
let estimator = train frequency dataset words
let tokenized = vocabulary text
estimator
|> Seq.map (fun (label, proba, tokens) ->
label,
tokens
|> Map.fold (fun p token value ->
if Set.exists (fun w -> w = token) tokenized
then p + log(value)
else p) (log proba))
|> Seq.maxBy snd
|> fst
fun text ->
let tokenized = vocabulary text
estimator
|> Seq.map (fun (label, proba, tokens) ->
label,
tokens
|> Map.fold (fun p token value ->
if Set.exists (fun w -> w = token) tokenized
then p + log(value)
else p) (log proba))
|> Seq.maxBy snd
|> fst