是否有可能在Golang

时间:2016-06-30 16:47:48

标签: go pickle

我正在Golang做一些机器学习。我现在正在撞墙,我训练有素的分类器需要差不多半分钟才能训练,并希望保存分类器的实例,这样我就不必每次都从头开始训练。 Golang应该怎么做呢? 仅供参考我的分类器是一个结构

当我用python做这种类型的东西时,用泡菜很容易。有没有等价的?

1 个答案:

答案 0 :(得分:1)

尝试gobencoding/json整理您的物体。之后,您可以将字符串存储到文件中。

Here是使用json的示例:

package main

import (
    "encoding/json"
     "fmt"
     "os"
)

type Book struct {
    Title string
    Pages []*Page
}

type Page struct {
    pageNumber int // remember to Capitalize the fields you want to marshal
    Content    string
}

func main() {
    // First make a book with nested array of struct pointers
    myBook := &Book{Title: "this is a title", Pages: make([]*Page, 0)}
    for i := 0; i < 3; i++ {
        myBook.Pages = append(myBook.Pages, &Page{i + 1, "words"})
    }

    // Open a file and dump JSON to it!
    f1, err := os.Create("/tmp/file1")
    enc := json.NewEncoder(f1)
    err = enc.Encode(myBook)
    if err != nil {
        panic(err)
    }
    f1.Close()

    // Open the file and load the object back!
    f2, err := os.Open("/tmp/file1")
    dec := json.NewDecoder(f2)
    var v Book
    err = dec.Decode(&v)
    if err != nil {
        panic(err)
    }
    f2.Close()

    // Check
    fmt.Println(v.Title)            // Output: <this is a title>
    fmt.Println(v.Pages[1].Content) // Output: <words>

    // pageNumber is not capitalized so it was not marshaled
    fmt.Println(v.Pages[1].pageNumber) // Output: <0>

}