카테고리 보관물: 컴퓨터언어

Go언어 FastText 모델 로딩해서 예측 수행하기 – Golang do prediction with built model

Facebook FastText로 만든 분류모델 (supervised model)을 로딩해서 prediction하는 간단한 코드입니다.

FastText 모델은 Python으로도 로딩해서 사용할 수 있습니다.

하지만 Python은 멀티쓰레드를 사용하기가 어려우니 빠른 속도를 위해서 Go언어나 다른 언어를 써야 할 때가 있으니 알아두면 좋습니다.

// FastText prediction
package main

import (
	"fmt"
	fasttext "github.com/bountylabs/go-fasttext"
)

func main() {
	model := fasttext.Open("//model/fasttext01.bin")
	fmt.Println("Prediction...")
	predictResult, err := model.Predict("분류할 입력 텍스트입니다.")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("Label: %s, Prob: %fs\n", predictResult[0].Label, predictResult[0].Probability)
}

FastText provide a command-line process to make a model. to apply the model to production, you may want write code for processing particular logic.

so, you need to know how cat load prebuilt FastText model and process prediction with Go language

Go언어 명령행 인수 처리 – Golang getting arguments from command line

Go언어에서 명령행 인수를 처리하는 방법입니다.

몇가지 방법이 더 있지만 여기에서는 flag 모듈를 사용합니다.

package main

import (
	"flag"
	"fmt"
)

func main() {
	file := flag.String("file", "default.txt", "Input file")
	maxcpu := flag.Int("maxcpu", 10, "Max CPU Count")
	isForce := flag.Bool("force", false, "Run force")

	flag.Parse()

	// 포인터 변수이므로 앞에 * 를 붙어 deference 해줘야 한다.
	fmt.Printf("file: %s\n", *file)
	fmt.Printf("maxcpu: %d\n", *maxcpu)
	fmt.Printf("force: %t\n", *isForce)
}

/* 테스트
C> go build exam_arguments.go
C> exam_arguments -file=test.csv -maxtrial=5 -force=true
*/

Go언어 CPU 수 알아내기

Go언어에서 CPU 수를 알아내는 코드입니다.

// OS, 아키텍쳐, CPU수, 고루틴 수를 출력한다.
package main

import (
	"fmt"
	"runtime"
)

func main() {
	fmt.Println("OS\t\t", runtime.GOOS)
	fmt.Println("ARCH\t\t", runtime.GOARCH)
	fmt.Println("CPU\t\t", runtime.NumCPU())
	fmt.Println("Goroutines\t", runtime.NumGoroutine())
}

Go언어 파일 목록 읽기

특정 디렉토리에 있는 파일 목록을 읽어오는 코드입니다.

요점

ioutil.ReadDir 함수를 사용하면 됩니다.

package main

import (
	"fmt"
	"io/ioutil"
	"log"
)

func main() {
	files, err := ioutil.ReadDir("/tmp/")
	if err != nil {
		log.Fatal(err)
	}

	for _, file := range files {
		fmt.Println(file.Name(), file.IsDir())
	}
}

How to retrieve a list of files from a particular directory.

Use “iotuil.ReadDir”

Go언어 csv.gz 읽기

csv파일은 gzip 압축이 되는 경우가 많습니다.

압축을 따로 풀지않고 gz 압축된 csv 파일을 직접 처리하는 것이 더 편할때가 많아졌습니다.

Go언어에서 gzip으로 압축된 csv 파일을 읽는 방법입니다.

package main

import (
	"compress/gzip"
	"encoding/csv"
	"fmt"
	"log"
	"os"
)

func main() {
	file, err := os.Open("data.csv.gz")

	if err != nil {
		log.Fatal(err)
	}

	defer file.Close()

	gzipReader, err := gzip.NewReader(file)

	if err != nil {
		log.Fatal(err)
	}

	defer gzipReader.Close()

	csvReader := csv.NewReader(gzipReader)
	record, err := csvReader.Read()

	if err != nil {
		log.Fatal(err)
	}

	for _, v := range record {
		fmt.Println(v)
	}
}