mirror of
https://github.com/sjwhitworth/golearn.git
synced 2025-04-28 13:48:56 +08:00
70 lines
2.1 KiB
Go
70 lines
2.1 KiB
Go
package main
|
|
|
|
// This example program demonstrates Instances
|
|
|
|
import (
|
|
"fmt"
|
|
base "github.com/sjwhitworth/golearn/base"
|
|
)
|
|
|
|
func main() {
|
|
|
|
// Instances can be read using ParseCsvToInstances
|
|
rawData, err := base.ParseCSVToInstances("../datasets/iris_headers.csv", true)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
// Instances can be printed, and you'll see a human-readable summary
|
|
// if you do so. The first section is a line like
|
|
// Instances with 150 row(s) and 5 attribute(s)
|
|
//
|
|
// It next prints all the attributes
|
|
// FloatAttribute(Sepal length)
|
|
// FloatAttribute(Sepal width)
|
|
// FloatAttribute(Petal length)
|
|
// FloatAttribute(Petal width)
|
|
// CategoricalAttribute([Iris-setosa Iris-versicolor Iris-viriginica])
|
|
// The final attribute has an asterisk (*) printed before it,
|
|
// meaning that it is the class variable. It then prints out up to
|
|
// 30 rows which correspond to those attributes.
|
|
// 5.10 3.50 1.40 0.20 Iris-setosa
|
|
// 4.90 3.00 1.40 0.20 Iris-setosa
|
|
fmt.Println(rawData)
|
|
|
|
// If two decimal places isn't enough, you can update the
|
|
// Precision field on any FloatAttribute
|
|
if attr, ok := rawData.GetAttr(0).(*base.FloatAttribute); !ok {
|
|
panic("Invalid cast")
|
|
} else {
|
|
attr.Precision = 4
|
|
}
|
|
// Now the first column has more precision
|
|
fmt.Println(rawData)
|
|
|
|
// We can update the set of Instances, although the API
|
|
// for doing so is not very sophisticated.
|
|
rawData.SetAttrStr(0, 0, "1.00")
|
|
rawData.SetAttrStr(0, rawData.ClassIndex, "Iris-unusual")
|
|
fmt.Println(rawData)
|
|
|
|
// There is a way of creating new Instances from scratch.
|
|
// Inside an Instance, everything's stored as float64
|
|
newData := make([]float64, 2)
|
|
newData[0] = 1.0
|
|
newData[1] = 0.0
|
|
|
|
// Let's create some attributes
|
|
attrs := make([]base.Attribute, 2)
|
|
attrs[0] = base.NewFloatAttribute()
|
|
attrs[0].SetName("Arbitrary Float Quantity")
|
|
attrs[1] = new(base.CategoricalAttribute)
|
|
attrs[1].SetName("Class")
|
|
// Insert a standard class
|
|
attrs[1].GetSysValFromString("A")
|
|
|
|
// Now let's create the final instances set
|
|
newInst := base.NewInstancesFromRaw(attrs, 1, newData)
|
|
fmt.Println(newInst)
|
|
}
|