Prediction by trained model
Author: hayato-akagiCreated May 26, 2025Updated May 26, 2025
Hi,
I want to know the best way to predict result by giving saved model (.gob) explain variables. As long as I explored, the only way I found was to prepare a template base.FixedDataGrid from the training data.
// buildTestInstance constructs a new test instance using the structure of the training data
func buildTestInstance(template base.FixedDataGrid, features []float64, dummyLabel string) (base.FixedDataGrid, error) {
original, ok := template.(*base.DenseInstances)
if !ok {
return nil, errors.New("template is not DenseInstances")
}
allAttrs := original.AllAttributes()
if len(features)+1 != len(allAttrs) {
return nil, errors.New("feature count mismatch")
}
inst := base.NewDenseInstances()
for _, attr := range allAttrs {
inst.AddAttribute(attr)
}
inst.AddClassAttribute(original.AllClassAttributes()[0])
inst.Extend(1)
for i, attr := range allAttrs {
spec, _ := inst.GetAttribute(attr)
switch a := attr.(type) {
case *base.FloatAttribute:
inst.Set(spec, 0, base.PackFloatToBytes(features[i]))
case *base.CategoricalAttribute:
inst.Set(spec, 0, a.GetSysValFromString(dummyLabel))
default:
return nil, errors.New("unsupported attribute type")
}
}
return inst, nil
}
// predict uses the trained classifier to predict the label of input features
func predict(classifier base.Classifier, template base.FixedDataGrid, features []float64) (string, error) {
inst, err := buildTestInstance(template, features, "dummy")
if err != nil {
return "", err
}
pred, err := classifier.Predict(inst)
if err != nil {
return "", err
}
return pred.RowString(0), nil
}
...
dataPath := "datasets/data.csv"
instances, err := base.ParseCSVToInstances(dataPath, true)
rf := ensemble.NewRandomForest(10, 3)
testFeatures := []float64{0.7, 2.1, 3.5}
label, err := predict(rf, instances, testFeatures)
...all sources: hayato-akagi/golearn_test
Are there any way to get label without instances?
If not, the dataset information (at least column names) will be necessary also when we want to run saved .gob model.
Source: sjwhitworth/golearn