jbrukh / bayesian

Naive Bayesian Classification for Golang.
Other
805 stars 128 forks source link

JSON serialization #30

Open nnqq opened 4 years ago

nnqq commented 4 years ago

Hi. My edits:

2020/07/24 20:32:04 gob [One Two Three Four Five Six Seven Eight Nine Ten]
2020/07/24 20:32:04 gob size 816
2020/07/24 20:32:04 json [One Two Three Four Five Six Seven Eight Nine Ten]
2020/07/24 20:32:04 json size 611
package main

import (
    "github.com/jbrukh/bayesian"
    "log"
    "os"
    "path"
)

func write(ser bayesian.Serializer) {
    const (
        One   bayesian.Class = "One"
        Two   bayesian.Class = "Two"
        Three bayesian.Class = "Three"
        Four  bayesian.Class = "Four"
        Five  bayesian.Class = "Five"
        Six   bayesian.Class = "Six"
        Seven bayesian.Class = "Seven"
        Eight bayesian.Class = "Eight"
        Nine  bayesian.Class = "Nine"
        Ten   bayesian.Class = "Ten"
    )

    classifier := bayesian.NewClassifier(One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten)
    oneStuff := []string{"lorem", "ipsum", "dolor"}
    twoStuff := []string{"sit", "amet", "consectetur"}
    threeStuff := []string{"adipiscing", "elit", "sed"}
    fourStuff := []string{"do", "eiusmod", "tempor"}
    fiveStuff := []string{"incididunt", "ut", "labore"}
    sixStuff := []string{"et", "dolore", "magna"}
    sevenStuff := []string{"aliqua", "ut", "enim"}
    eightStuff := []string{"ad", "minim", "veniam"}
    nineStuff := []string{"quis", "nostrud", "exercitation"}
    tenStuff := []string{"ullamco", "laboris", "nisi"}

    classifier.Learn(oneStuff, One)
    classifier.Learn(twoStuff, Two)
    classifier.Learn(threeStuff, Three)
    classifier.Learn(fourStuff, Four)
    classifier.Learn(fiveStuff, Five)
    classifier.Learn(sixStuff, Six)
    classifier.Learn(sevenStuff, Seven)
    classifier.Learn(eightStuff, Eight)
    classifier.Learn(nineStuff, Nine)
    classifier.Learn(tenStuff, Ten)

    wd, err := os.Getwd()
    if err != nil {
        panic(err)
    }

    err = classifier.WriteToFile(path.Join(wd, "out_"+string(ser)), ser)
    if err != nil {
        panic(err)
    }
}

func read(ser bayesian.Serializer) {
    wd, err := os.Getwd()
    if err != nil {
        panic(err)
    }

    file := path.Join(wd, "out_"+string(ser))

    classifier, err := bayesian.NewClassifierFromFile(file, ser)
    if err != nil {
        panic(err)
    }

    f, err := os.Open(file)
    if err != nil {
        panic(err)
    }
    info, err := f.Stat()
    if err != nil {
        panic(err)
    }

    log.Println(ser, classifier.Classes)
    log.Println(ser, "size", info.Size())
}

func main() {
    write(bayesian.Gob)
    read(bayesian.Gob)

    write(bayesian.JSON)
    read(bayesian.JSON)
}