【问题标题】:Is it possible to pickle instances of structs in Golang是否可以在 Golang 中腌制结构实例
【发布时间】:2016-11-02 21:38:15
【问题描述】:

我正在使用 Golang 进行一些机器学习。我现在碰壁了,我训练有素的分类器需要将近半分钟的时间来训练,并且想保存分类器的那个实例,这样我就不必每次都从头开始训练。 Golang 应该怎么做? 仅供参考,我的分类器是一个结构


当我用 python 做这类事情时,用 pickle 很容易。有没有等价物?

【问题讨论】:

  • 你看过像godoc.org/github.com/hydrogen18/stalecucumber这样的库吗?
  • Pickle 的 Golang 等价物是 gob
  • 好吧,pickle 只不过是一种任意的序列化格式。因此,您可以选择自己的任意格式。除了标准库外,您拥有encoding/gobencoding/jsonencoding/xml
  • 作为参考,如果需要与 Python 兼容,可以使用 godoc.org/github.com/kisielk/og-rek 保存和加载来自 Go 端的泡菜。

标签: go pickle


【解决方案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>

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2014-02-10
    • 2016-01-05
    • 2014-10-25
    • 1970-01-01
    相关资源
    最近更新 更多