是否可以在Golang中腌制结构实例 [英] Is it possible to pickle instances of structs in Golang

查看:61
本文介绍了是否可以在Golang中腌制结构实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am doing some machine learning in Golang. I am now hitting a wall, my trained classifier takes almost half a minute to train and want to save that instance of the classifier so that I do not have to train in from scratch every time. How should someone go about doing this is Golang? FYI my classifier is a struct

当我使用python进行此类处理时,使用pickle非常简单.有等同的东西吗?

When I do this type of stuff with python, it's very easy with pickle. Is there an equivalent?

推荐答案

尝试 gob encoding/json 来编组对象.之后,您可以将字符串存储到文件中.

Try gob or encoding/json to marshal your objects. After that, you can store the string to a file.

此处是使用json的示例:

Here is an example to use 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>

}

这篇关于是否可以在Golang中腌制结构实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆