id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
164,800
sjwhitworth/golearn
trees/random.go
LoadWithPrefix
func (rt *RandomTree) LoadWithPrefix(reader *base.ClassifierDeserializer, prefix string) error { rt.Root = &DecisionTreeNode{} return rt.Root.LoadWithPrefix(reader, prefix) }
go
func (rt *RandomTree) LoadWithPrefix(reader *base.ClassifierDeserializer, prefix string) error { rt.Root = &DecisionTreeNode{} return rt.Root.LoadWithPrefix(reader, prefix) }
[ "func", "(", "rt", "*", "RandomTree", ")", "LoadWithPrefix", "(", "reader", "*", "base", ".", "ClassifierDeserializer", ",", "prefix", "string", ")", "error", "{", "rt", ".", "Root", "=", "&", "DecisionTreeNode", "{", "}", "\n", "return", "rt", ".", "Root", ".", "LoadWithPrefix", "(", "reader", ",", "prefix", ")", "\n", "}" ]
// LoadWithPrefix retrives this random tree from disk with a given prefix.
[ "LoadWithPrefix", "retrives", "this", "random", "tree", "from", "disk", "with", "a", "given", "prefix", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/random.go#L119-L122
164,801
sjwhitworth/golearn
trees/random.go
GetMetadata
func (rt *RandomTree) GetMetadata() base.ClassifierMetadataV1 { return base.ClassifierMetadataV1{ FormatVersion: 1, ClassifierName: "KNN", ClassifierVersion: "1.0", ClassifierMetadata: nil, } }
go
func (rt *RandomTree) GetMetadata() base.ClassifierMetadataV1 { return base.ClassifierMetadataV1{ FormatVersion: 1, ClassifierName: "KNN", ClassifierVersion: "1.0", ClassifierMetadata: nil, } }
[ "func", "(", "rt", "*", "RandomTree", ")", "GetMetadata", "(", ")", "base", ".", "ClassifierMetadataV1", "{", "return", "base", ".", "ClassifierMetadataV1", "{", "FormatVersion", ":", "1", ",", "ClassifierName", ":", "\"", "\"", ",", "ClassifierVersion", ":", "\"", "\"", ",", "ClassifierMetadata", ":", "nil", ",", "}", "\n", "}" ]
// GetMetadata returns required serialization metadata
[ "GetMetadata", "returns", "required", "serialization", "metadata" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/random.go#L125-L132
164,802
sjwhitworth/golearn
base/serialize.go
GetNamedFile
func (f *FunctionalTarReader) GetNamedFile(name string) ([]byte, error) { tr := f.Regenerate() var returnCandidate []byte = nil for { hdr, err := tr.Next() if err == io.EOF { break } else if err != nil { return nil, err } if hdr.Name == name { ret, err := ioutil.ReadAll(tr) if err != nil { return nil, WrapError(err) } if int64(len(ret)) != hdr.Size { if int64(len(ret)) < hdr.Size { log.Printf("Size mismatch, got %d byte(s) for %s, expected %d (err was %s)", len(ret), hdr.Name, hdr.Size, err) } else { return nil, WrapError(fmt.Errorf("Size mismatch, expected %d byte(s) for %s, got %d", len(ret), hdr.Name, hdr.Size)) } } if err != nil { return nil, err } returnCandidate = ret } } if returnCandidate == nil { return nil, WrapError(fmt.Errorf("Not found (looking for %s)", name)) } return returnCandidate, nil }
go
func (f *FunctionalTarReader) GetNamedFile(name string) ([]byte, error) { tr := f.Regenerate() var returnCandidate []byte = nil for { hdr, err := tr.Next() if err == io.EOF { break } else if err != nil { return nil, err } if hdr.Name == name { ret, err := ioutil.ReadAll(tr) if err != nil { return nil, WrapError(err) } if int64(len(ret)) != hdr.Size { if int64(len(ret)) < hdr.Size { log.Printf("Size mismatch, got %d byte(s) for %s, expected %d (err was %s)", len(ret), hdr.Name, hdr.Size, err) } else { return nil, WrapError(fmt.Errorf("Size mismatch, expected %d byte(s) for %s, got %d", len(ret), hdr.Name, hdr.Size)) } } if err != nil { return nil, err } returnCandidate = ret } } if returnCandidate == nil { return nil, WrapError(fmt.Errorf("Not found (looking for %s)", name)) } return returnCandidate, nil }
[ "func", "(", "f", "*", "FunctionalTarReader", ")", "GetNamedFile", "(", "name", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "tr", ":=", "f", ".", "Regenerate", "(", ")", "\n\n", "var", "returnCandidate", "[", "]", "byte", "=", "nil", "\n", "for", "{", "hdr", ",", "err", ":=", "tr", ".", "Next", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "hdr", ".", "Name", "==", "name", "{", "ret", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "tr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "WrapError", "(", "err", ")", "\n", "}", "\n", "if", "int64", "(", "len", "(", "ret", ")", ")", "!=", "hdr", ".", "Size", "{", "if", "int64", "(", "len", "(", "ret", ")", ")", "<", "hdr", ".", "Size", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "len", "(", "ret", ")", ",", "hdr", ".", "Name", ",", "hdr", ".", "Size", ",", "err", ")", "\n", "}", "else", "{", "return", "nil", ",", "WrapError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "ret", ")", ",", "hdr", ".", "Name", ",", "hdr", ".", "Size", ")", ")", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "returnCandidate", "=", "ret", "\n", "}", "\n", "}", "\n", "if", "returnCandidate", "==", "nil", "{", "return", "nil", ",", "WrapError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n", "return", "returnCandidate", ",", "nil", "\n", "}" ]
// GetNamedFile returns a file named a given thing from the tar file. If there's more than one // entry, the most recent is returned.
[ "GetNamedFile", "returns", "a", "file", "named", "a", "given", "thing", "from", "the", "tar", "file", ".", "If", "there", "s", "more", "than", "one", "entry", "the", "most", "recent", "is", "returned", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L35-L69
164,803
sjwhitworth/golearn
base/serialize.go
ReadMetadataAtPrefix
func (c *ClassifierDeserializer) ReadMetadataAtPrefix(prefix string) (ClassifierMetadataV1, error) { var ret ClassifierMetadataV1 err := c.GetJSONForKey(c.Prefix(prefix, "METADATA"), &ret) return ret, err }
go
func (c *ClassifierDeserializer) ReadMetadataAtPrefix(prefix string) (ClassifierMetadataV1, error) { var ret ClassifierMetadataV1 err := c.GetJSONForKey(c.Prefix(prefix, "METADATA"), &ret) return ret, err }
[ "func", "(", "c", "*", "ClassifierDeserializer", ")", "ReadMetadataAtPrefix", "(", "prefix", "string", ")", "(", "ClassifierMetadataV1", ",", "error", ")", "{", "var", "ret", "ClassifierMetadataV1", "\n", "err", ":=", "c", ".", "GetJSONForKey", "(", "c", ".", "Prefix", "(", "prefix", ",", "\"", "\"", ")", ",", "&", "ret", ")", "\n", "return", "ret", ",", "err", "\n", "}" ]
// ReadMetadataAtPrefix reads the METADATA file after prefix. If an error is returned, the first value is undefined.
[ "ReadMetadataAtPrefix", "reads", "the", "METADATA", "file", "after", "prefix", ".", "If", "an", "error", "is", "returned", "the", "first", "value", "is", "undefined", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L110-L114
164,804
sjwhitworth/golearn
base/serialize.go
ReadSerializedClassifierStub
func ReadSerializedClassifierStub(filePath string) (*ClassifierDeserializer, error) { f, err := os.Open(filePath) if err != nil { return nil, DescribeError("Can't open file", err) } gzr, err := gzip.NewReader(f) if err != nil { return nil, DescribeError("Can't decompress", err) } regenerateFunc := func() *tar.Reader { f.Seek(0, os.SEEK_SET) gzr.Reset(f) tz := tar.NewReader(gzr) return tz } tz := NewFunctionalTarReader(regenerateFunc) // Check that the serialization format is right // Retrieve the MANIFEST and verify manifestBytes, err := tz.GetNamedFile("CLS_MANIFEST") if err != nil { return nil, DescribeError("Error reading CLS_MANIFEST", err) } if !reflect.DeepEqual(manifestBytes, []byte(SerializationFormatVersion)) { return nil, fmt.Errorf("Unsupported CLS_MANIFEST: %s", string(manifestBytes)) } // // Parse METADATA // var metadata ClassifierMetadataV1 ret := &ClassifierDeserializer{ f, gzr, tz, &metadata, } metadata, err = ret.ReadMetadataAtPrefix("") if err != nil { return nil, fmt.Errorf("Error whilst reading METADATA: %s", err) } ret.Metadata = &metadata // Check that we can understand this archive if metadata.FormatVersion != 1 { return nil, fmt.Errorf("METADATA: wrong format_version for this version of golearn") } return ret, nil }
go
func ReadSerializedClassifierStub(filePath string) (*ClassifierDeserializer, error) { f, err := os.Open(filePath) if err != nil { return nil, DescribeError("Can't open file", err) } gzr, err := gzip.NewReader(f) if err != nil { return nil, DescribeError("Can't decompress", err) } regenerateFunc := func() *tar.Reader { f.Seek(0, os.SEEK_SET) gzr.Reset(f) tz := tar.NewReader(gzr) return tz } tz := NewFunctionalTarReader(regenerateFunc) // Check that the serialization format is right // Retrieve the MANIFEST and verify manifestBytes, err := tz.GetNamedFile("CLS_MANIFEST") if err != nil { return nil, DescribeError("Error reading CLS_MANIFEST", err) } if !reflect.DeepEqual(manifestBytes, []byte(SerializationFormatVersion)) { return nil, fmt.Errorf("Unsupported CLS_MANIFEST: %s", string(manifestBytes)) } // // Parse METADATA // var metadata ClassifierMetadataV1 ret := &ClassifierDeserializer{ f, gzr, tz, &metadata, } metadata, err = ret.ReadMetadataAtPrefix("") if err != nil { return nil, fmt.Errorf("Error whilst reading METADATA: %s", err) } ret.Metadata = &metadata // Check that we can understand this archive if metadata.FormatVersion != 1 { return nil, fmt.Errorf("METADATA: wrong format_version for this version of golearn") } return ret, nil }
[ "func", "ReadSerializedClassifierStub", "(", "filePath", "string", ")", "(", "*", "ClassifierDeserializer", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "DescribeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "gzr", ",", "err", ":=", "gzip", ".", "NewReader", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "DescribeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "regenerateFunc", ":=", "func", "(", ")", "*", "tar", ".", "Reader", "{", "f", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "\n", "gzr", ".", "Reset", "(", "f", ")", "\n", "tz", ":=", "tar", ".", "NewReader", "(", "gzr", ")", "\n", "return", "tz", "\n", "}", "\n\n", "tz", ":=", "NewFunctionalTarReader", "(", "regenerateFunc", ")", "\n\n", "// Check that the serialization format is right", "// Retrieve the MANIFEST and verify", "manifestBytes", ",", "err", ":=", "tz", ".", "GetNamedFile", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "DescribeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "reflect", ".", "DeepEqual", "(", "manifestBytes", ",", "[", "]", "byte", "(", "SerializationFormatVersion", ")", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "manifestBytes", ")", ")", "\n", "}", "\n\n", "//", "// Parse METADATA", "//", "var", "metadata", "ClassifierMetadataV1", "\n", "ret", ":=", "&", "ClassifierDeserializer", "{", "f", ",", "gzr", ",", "tz", ",", "&", "metadata", ",", "}", "\n\n", "metadata", ",", "err", "=", "ret", ".", "ReadMetadataAtPrefix", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "ret", ".", "Metadata", "=", "&", "metadata", "\n\n", "// Check that we can understand this archive", "if", "metadata", ".", "FormatVersion", "!=", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "ret", ",", "nil", "\n", "}" ]
// ReadSerializedClassifierStub is the counterpart of CreateSerializedClassifierStub. // It's used inside SaveableClassifiers to read information from a perviously saved // model file.
[ "ReadSerializedClassifierStub", "is", "the", "counterpart", "of", "CreateSerializedClassifierStub", ".", "It", "s", "used", "inside", "SaveableClassifiers", "to", "read", "information", "from", "a", "perviously", "saved", "model", "file", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L119-L173
164,805
sjwhitworth/golearn
base/serialize.go
GetBytesForKey
func (c *ClassifierDeserializer) GetBytesForKey(key string) ([]byte, error) { return c.tarReader.GetNamedFile(key) }
go
func (c *ClassifierDeserializer) GetBytesForKey(key string) ([]byte, error) { return c.tarReader.GetNamedFile(key) }
[ "func", "(", "c", "*", "ClassifierDeserializer", ")", "GetBytesForKey", "(", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "c", ".", "tarReader", ".", "GetNamedFile", "(", "key", ")", "\n", "}" ]
// GetBytesForKey returns the bytes at a given location in the output.
[ "GetBytesForKey", "returns", "the", "bytes", "at", "a", "given", "location", "in", "the", "output", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L176-L178
164,806
sjwhitworth/golearn
base/serialize.go
GetJSONForKey
func (c *ClassifierDeserializer) GetJSONForKey(key string, v interface{}) error { b, err := c.GetBytesForKey(key) if err != nil { return err } return json.Unmarshal(b, v) }
go
func (c *ClassifierDeserializer) GetJSONForKey(key string, v interface{}) error { b, err := c.GetBytesForKey(key) if err != nil { return err } return json.Unmarshal(b, v) }
[ "func", "(", "c", "*", "ClassifierDeserializer", ")", "GetJSONForKey", "(", "key", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "b", ",", "err", ":=", "c", ".", "GetBytesForKey", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "json", ".", "Unmarshal", "(", "b", ",", "v", ")", "\n", "}" ]
// GetJSONForKey deserializes a JSON key in the output file.
[ "GetJSONForKey", "deserializes", "a", "JSON", "key", "in", "the", "output", "file", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L189-L195
164,807
sjwhitworth/golearn
base/serialize.go
GetInstancesForKey
func (c *ClassifierDeserializer) GetInstancesForKey(key string) (FixedDataGrid, error) { return DeserializeInstancesFromTarReader(c.tarReader, key) }
go
func (c *ClassifierDeserializer) GetInstancesForKey(key string) (FixedDataGrid, error) { return DeserializeInstancesFromTarReader(c.tarReader, key) }
[ "func", "(", "c", "*", "ClassifierDeserializer", ")", "GetInstancesForKey", "(", "key", "string", ")", "(", "FixedDataGrid", ",", "error", ")", "{", "return", "DeserializeInstancesFromTarReader", "(", "c", ".", "tarReader", ",", "key", ")", "\n", "}" ]
// GetInstancesForKey deserializes some instances stored in a classifier output file
[ "GetInstancesForKey", "deserializes", "some", "instances", "stored", "in", "a", "classifier", "output", "file" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L198-L200
164,808
sjwhitworth/golearn
base/serialize.go
GetU64ForKey
func (c *ClassifierDeserializer) GetU64ForKey(key string) (uint64, error) { b, err := c.GetBytesForKey(key) if err != nil { return 0, err } return UnpackBytesToU64(b), nil }
go
func (c *ClassifierDeserializer) GetU64ForKey(key string) (uint64, error) { b, err := c.GetBytesForKey(key) if err != nil { return 0, err } return UnpackBytesToU64(b), nil }
[ "func", "(", "c", "*", "ClassifierDeserializer", ")", "GetU64ForKey", "(", "key", "string", ")", "(", "uint64", ",", "error", ")", "{", "b", ",", "err", ":=", "c", ".", "GetBytesForKey", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "UnpackBytesToU64", "(", "b", ")", ",", "nil", "\n", "}" ]
// GetUInt64ForKey returns a int64 stored at a given key
[ "GetUInt64ForKey", "returns", "a", "int64", "stored", "at", "a", "given", "key" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L203-L209
164,809
sjwhitworth/golearn
base/serialize.go
GetAttributeForKey
func (c *ClassifierDeserializer) GetAttributeForKey(key string) (Attribute, error) { b, err := c.GetBytesForKey(key) if err != nil { return nil, WrapError(err) } attr, err := DeserializeAttribute(b) if err != nil { return nil, WrapError(err) } return attr, nil }
go
func (c *ClassifierDeserializer) GetAttributeForKey(key string) (Attribute, error) { b, err := c.GetBytesForKey(key) if err != nil { return nil, WrapError(err) } attr, err := DeserializeAttribute(b) if err != nil { return nil, WrapError(err) } return attr, nil }
[ "func", "(", "c", "*", "ClassifierDeserializer", ")", "GetAttributeForKey", "(", "key", "string", ")", "(", "Attribute", ",", "error", ")", "{", "b", ",", "err", ":=", "c", ".", "GetBytesForKey", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "WrapError", "(", "err", ")", "\n", "}", "\n", "attr", ",", "err", ":=", "DeserializeAttribute", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "WrapError", "(", "err", ")", "\n", "}", "\n", "return", "attr", ",", "nil", "\n", "}" ]
// GetAttributeForKey returns an Attribute stored at a given key
[ "GetAttributeForKey", "returns", "an", "Attribute", "stored", "at", "a", "given", "key" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L212-L222
164,810
sjwhitworth/golearn
base/serialize.go
GetAttributesForKey
func (c *ClassifierDeserializer) GetAttributesForKey(key string) ([]Attribute, error) { attrCountKey := c.Prefix(key, "ATTR_COUNT") attrCount, err := c.GetU64ForKey(attrCountKey) if err != nil { return nil, DescribeError("Unable to read ATTR_COUNT", err) } ret := make([]Attribute, attrCount) for i := range ret { attrKey := c.Prefix(key, fmt.Sprintf("%d", i)) ret[i], err = c.GetAttributeForKey(attrKey) if err != nil { return nil, DescribeError("Unable to read Attribute", err) } } return ret, nil }
go
func (c *ClassifierDeserializer) GetAttributesForKey(key string) ([]Attribute, error) { attrCountKey := c.Prefix(key, "ATTR_COUNT") attrCount, err := c.GetU64ForKey(attrCountKey) if err != nil { return nil, DescribeError("Unable to read ATTR_COUNT", err) } ret := make([]Attribute, attrCount) for i := range ret { attrKey := c.Prefix(key, fmt.Sprintf("%d", i)) ret[i], err = c.GetAttributeForKey(attrKey) if err != nil { return nil, DescribeError("Unable to read Attribute", err) } } return ret, nil }
[ "func", "(", "c", "*", "ClassifierDeserializer", ")", "GetAttributesForKey", "(", "key", "string", ")", "(", "[", "]", "Attribute", ",", "error", ")", "{", "attrCountKey", ":=", "c", ".", "Prefix", "(", "key", ",", "\"", "\"", ")", "\n", "attrCount", ",", "err", ":=", "c", ".", "GetU64ForKey", "(", "attrCountKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "DescribeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "attrCount", ")", "\n\n", "for", "i", ":=", "range", "ret", "{", "attrKey", ":=", "c", ".", "Prefix", "(", "key", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ")", ")", "\n", "ret", "[", "i", "]", ",", "err", "=", "c", ".", "GetAttributeForKey", "(", "attrKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "DescribeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// GetAttributesForKey returns an Attribute list stored at a given key
[ "GetAttributesForKey", "returns", "an", "Attribute", "list", "stored", "at", "a", "given", "key" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L225-L243
164,811
sjwhitworth/golearn
base/serialize.go
Close
func (c *ClassifierSerializer) Close() error { // Finally, close and flush the various levels if err := c.tarWriter.Flush(); err != nil { return fmt.Errorf("Could not flush tar: %s", err) } if err := c.tarWriter.Close(); err != nil { return fmt.Errorf("Could not close tar: %s", err) } if err := c.gzipWriter.Flush(); err != nil { return fmt.Errorf("Could not flush gz: %s", err) } if err := c.gzipWriter.Close(); err != nil { return fmt.Errorf("Could not close gz: %s", err) } if err := c.fileWriter.Sync(); err != nil { return fmt.Errorf("Could not close file writer: %s", err) } if err := c.fileWriter.Close(); err != nil { return fmt.Errorf("Could not close file writer: %s", err) } return nil }
go
func (c *ClassifierSerializer) Close() error { // Finally, close and flush the various levels if err := c.tarWriter.Flush(); err != nil { return fmt.Errorf("Could not flush tar: %s", err) } if err := c.tarWriter.Close(); err != nil { return fmt.Errorf("Could not close tar: %s", err) } if err := c.gzipWriter.Flush(); err != nil { return fmt.Errorf("Could not flush gz: %s", err) } if err := c.gzipWriter.Close(); err != nil { return fmt.Errorf("Could not close gz: %s", err) } if err := c.fileWriter.Sync(); err != nil { return fmt.Errorf("Could not close file writer: %s", err) } if err := c.fileWriter.Close(); err != nil { return fmt.Errorf("Could not close file writer: %s", err) } return nil }
[ "func", "(", "c", "*", "ClassifierSerializer", ")", "Close", "(", ")", "error", "{", "// Finally, close and flush the various levels", "if", "err", ":=", "c", ".", "tarWriter", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "tarWriter", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "gzipWriter", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "gzipWriter", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "fileWriter", ".", "Sync", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "fileWriter", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Close finalizes the Classifier serialization session.
[ "Close", "finalizes", "the", "Classifier", "serialization", "session", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L260-L288
164,812
sjwhitworth/golearn
base/serialize.go
WriteBytesForKey
func (c *ClassifierSerializer) WriteBytesForKey(key string, b []byte) error { // // Write header for key // hdr := &tar.Header{ Name: key, Size: int64(len(b)), } if err := c.tarWriter.WriteHeader(hdr); err != nil { return fmt.Errorf("Could not write header for '%s': %s", key, err) } // // Write data // if _, err := c.tarWriter.Write(b); err != nil { return fmt.Errorf("Could not write data for '%s': %s", key, err) } c.tarWriter.Flush() c.gzipWriter.Flush() c.fileWriter.Sync() return nil }
go
func (c *ClassifierSerializer) WriteBytesForKey(key string, b []byte) error { // // Write header for key // hdr := &tar.Header{ Name: key, Size: int64(len(b)), } if err := c.tarWriter.WriteHeader(hdr); err != nil { return fmt.Errorf("Could not write header for '%s': %s", key, err) } // // Write data // if _, err := c.tarWriter.Write(b); err != nil { return fmt.Errorf("Could not write data for '%s': %s", key, err) } c.tarWriter.Flush() c.gzipWriter.Flush() c.fileWriter.Sync() return nil }
[ "func", "(", "c", "*", "ClassifierSerializer", ")", "WriteBytesForKey", "(", "key", "string", ",", "b", "[", "]", "byte", ")", "error", "{", "//", "// Write header for key", "//", "hdr", ":=", "&", "tar", ".", "Header", "{", "Name", ":", "key", ",", "Size", ":", "int64", "(", "len", "(", "b", ")", ")", ",", "}", "\n\n", "if", "err", ":=", "c", ".", "tarWriter", ".", "WriteHeader", "(", "hdr", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ",", "err", ")", "\n", "}", "\n", "//", "// Write data", "//", "if", "_", ",", "err", ":=", "c", ".", "tarWriter", ".", "Write", "(", "b", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ",", "err", ")", "\n", "}", "\n\n", "c", ".", "tarWriter", ".", "Flush", "(", ")", "\n", "c", ".", "gzipWriter", ".", "Flush", "(", ")", "\n", "c", ".", "fileWriter", ".", "Sync", "(", ")", "\n", "return", "nil", "\n", "}" ]
// WriteBytesForKey creates a new entry in the serializer file with some user-defined bytes.
[ "WriteBytesForKey", "creates", "a", "new", "entry", "in", "the", "serializer", "file", "with", "some", "user", "-", "defined", "bytes", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L291-L315
164,813
sjwhitworth/golearn
base/serialize.go
WriteU64ForKey
func (c *ClassifierSerializer) WriteU64ForKey(key string, v uint64) error { b := PackU64ToBytes(v) return c.WriteBytesForKey(key, b) }
go
func (c *ClassifierSerializer) WriteU64ForKey(key string, v uint64) error { b := PackU64ToBytes(v) return c.WriteBytesForKey(key, b) }
[ "func", "(", "c", "*", "ClassifierSerializer", ")", "WriteU64ForKey", "(", "key", "string", ",", "v", "uint64", ")", "error", "{", "b", ":=", "PackU64ToBytes", "(", "v", ")", "\n", "return", "c", ".", "WriteBytesForKey", "(", "key", ",", "b", ")", "\n", "}" ]
// WriteU64ForKey creates a new entry in the serializer file with the bytes of a uint64
[ "WriteU64ForKey", "creates", "a", "new", "entry", "in", "the", "serializer", "file", "with", "the", "bytes", "of", "a", "uint64" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L318-L321
164,814
sjwhitworth/golearn
base/serialize.go
WriteJSONForKey
func (c *ClassifierSerializer) WriteJSONForKey(key string, v interface{}) error { b, err := json.Marshal(v) if err != nil { return err } return c.WriteBytesForKey(key, b) }
go
func (c *ClassifierSerializer) WriteJSONForKey(key string, v interface{}) error { b, err := json.Marshal(v) if err != nil { return err } return c.WriteBytesForKey(key, b) }
[ "func", "(", "c", "*", "ClassifierSerializer", ")", "WriteJSONForKey", "(", "key", "string", ",", "v", "interface", "{", "}", ")", "error", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "c", ".", "WriteBytesForKey", "(", "key", ",", "b", ")", "\n\n", "}" ]
// WriteJSONForKey creates a new entry in the file with an interface serialized as JSON.
[ "WriteJSONForKey", "creates", "a", "new", "entry", "in", "the", "file", "with", "an", "interface", "serialized", "as", "JSON", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L324-L333
164,815
sjwhitworth/golearn
base/serialize.go
WriteAttributeForKey
func (c *ClassifierSerializer) WriteAttributeForKey(key string, a Attribute) error { b, err := SerializeAttribute(a) if err != nil { return WrapError(err) } return c.WriteBytesForKey(key, b) }
go
func (c *ClassifierSerializer) WriteAttributeForKey(key string, a Attribute) error { b, err := SerializeAttribute(a) if err != nil { return WrapError(err) } return c.WriteBytesForKey(key, b) }
[ "func", "(", "c", "*", "ClassifierSerializer", ")", "WriteAttributeForKey", "(", "key", "string", ",", "a", "Attribute", ")", "error", "{", "b", ",", "err", ":=", "SerializeAttribute", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "WrapError", "(", "err", ")", "\n", "}", "\n", "return", "c", ".", "WriteBytesForKey", "(", "key", ",", "b", ")", "\n", "}" ]
// WriteAttributeForKey creates a new entry in the file containing a serialized representation of Attribute
[ "WriteAttributeForKey", "creates", "a", "new", "entry", "in", "the", "file", "containing", "a", "serialized", "representation", "of", "Attribute" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L336-L342
164,816
sjwhitworth/golearn
base/serialize.go
WriteAttributesForKey
func (c *ClassifierSerializer) WriteAttributesForKey(key string, attrs []Attribute) error { attrCountKey := c.Prefix(key, "ATTR_COUNT") err := c.WriteU64ForKey(attrCountKey, uint64(len(attrs))) if err != nil { return DescribeError("Unable to write ATTR_COUNT", err) } for i, a := range attrs { attrKey := c.Prefix(key, fmt.Sprintf("%d", i)) err = c.WriteAttributeForKey(attrKey, a) if err != nil { return DescribeError("Unable to write Attribute", err) } } return nil }
go
func (c *ClassifierSerializer) WriteAttributesForKey(key string, attrs []Attribute) error { attrCountKey := c.Prefix(key, "ATTR_COUNT") err := c.WriteU64ForKey(attrCountKey, uint64(len(attrs))) if err != nil { return DescribeError("Unable to write ATTR_COUNT", err) } for i, a := range attrs { attrKey := c.Prefix(key, fmt.Sprintf("%d", i)) err = c.WriteAttributeForKey(attrKey, a) if err != nil { return DescribeError("Unable to write Attribute", err) } } return nil }
[ "func", "(", "c", "*", "ClassifierSerializer", ")", "WriteAttributesForKey", "(", "key", "string", ",", "attrs", "[", "]", "Attribute", ")", "error", "{", "attrCountKey", ":=", "c", ".", "Prefix", "(", "key", ",", "\"", "\"", ")", "\n", "err", ":=", "c", ".", "WriteU64ForKey", "(", "attrCountKey", ",", "uint64", "(", "len", "(", "attrs", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "DescribeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "for", "i", ",", "a", ":=", "range", "attrs", "{", "attrKey", ":=", "c", ".", "Prefix", "(", "key", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ")", ")", "\n", "err", "=", "c", ".", "WriteAttributeForKey", "(", "attrKey", ",", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "DescribeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// WriteAttributesForKey does the same as WriteAttributeForKey, just with more than one Attribute.
[ "WriteAttributesForKey", "does", "the", "same", "as", "WriteAttributeForKey", "just", "with", "more", "than", "one", "Attribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L345-L360
164,817
sjwhitworth/golearn
base/serialize.go
WriteInstancesForKey
func (c *ClassifierSerializer) WriteInstancesForKey(key string, g FixedDataGrid, includeData bool) error { fmt.Sprintf("%v", c) return SerializeInstancesToTarWriter(g, c.tarWriter, key, includeData) }
go
func (c *ClassifierSerializer) WriteInstancesForKey(key string, g FixedDataGrid, includeData bool) error { fmt.Sprintf("%v", c) return SerializeInstancesToTarWriter(g, c.tarWriter, key, includeData) }
[ "func", "(", "c", "*", "ClassifierSerializer", ")", "WriteInstancesForKey", "(", "key", "string", ",", "g", "FixedDataGrid", ",", "includeData", "bool", ")", "error", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ")", "\n", "return", "SerializeInstancesToTarWriter", "(", "g", ",", "c", ".", "tarWriter", ",", "key", ",", "includeData", ")", "\n", "}" ]
// WriteInstances for key creates a new entry in the file containing some training instances
[ "WriteInstances", "for", "key", "creates", "a", "new", "entry", "in", "the", "file", "containing", "some", "training", "instances" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L363-L366
164,818
sjwhitworth/golearn
base/serialize.go
WriteMetadataAtPrefix
func (c *ClassifierSerializer) WriteMetadataAtPrefix(prefix string, metadata ClassifierMetadataV1) error { return c.WriteJSONForKey(c.Prefix(prefix, "METADATA"), &metadata) }
go
func (c *ClassifierSerializer) WriteMetadataAtPrefix(prefix string, metadata ClassifierMetadataV1) error { return c.WriteJSONForKey(c.Prefix(prefix, "METADATA"), &metadata) }
[ "func", "(", "c", "*", "ClassifierSerializer", ")", "WriteMetadataAtPrefix", "(", "prefix", "string", ",", "metadata", "ClassifierMetadataV1", ")", "error", "{", "return", "c", ".", "WriteJSONForKey", "(", "c", ".", "Prefix", "(", "prefix", ",", "\"", "\"", ")", ",", "&", "metadata", ")", "\n", "}" ]
// WriteMetadataAtPrefix outputs a METADATA entry in the right place
[ "WriteMetadataAtPrefix", "outputs", "a", "METADATA", "entry", "in", "the", "right", "place" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L377-L379
164,819
sjwhitworth/golearn
base/serialize.go
CreateSerializedClassifierStub
func CreateSerializedClassifierStub(filePath string, metadata ClassifierMetadataV1) (*ClassifierSerializer, error) { // Open the filePath f, err := os.OpenFile(filePath, os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0600) if err != nil { return nil, err } var hdr *tar.Header gzWriter := gzip.NewWriter(f) tw := tar.NewWriter(gzWriter) ret := ClassifierSerializer{ gzipWriter: gzWriter, fileWriter: f, tarWriter: tw, } // // Write the MANIFEST entry // hdr = &tar.Header{ Name: "CLS_MANIFEST", Size: int64(len(SerializationFormatVersion)), } if err := tw.WriteHeader(hdr); err != nil { return nil, fmt.Errorf("Could not write CLS_MANIFEST header: %s", err) } if _, err := tw.Write([]byte(SerializationFormatVersion)); err != nil { return nil, fmt.Errorf("Could not write CLS_MANIFEST contents: %s", err) } // // Write the METADATA entry // err = ret.WriteMetadataAtPrefix("", metadata) if err != nil { return nil, fmt.Errorf("JSON marshal error: %s", err) } return &ret, nil }
go
func CreateSerializedClassifierStub(filePath string, metadata ClassifierMetadataV1) (*ClassifierSerializer, error) { // Open the filePath f, err := os.OpenFile(filePath, os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0600) if err != nil { return nil, err } var hdr *tar.Header gzWriter := gzip.NewWriter(f) tw := tar.NewWriter(gzWriter) ret := ClassifierSerializer{ gzipWriter: gzWriter, fileWriter: f, tarWriter: tw, } // // Write the MANIFEST entry // hdr = &tar.Header{ Name: "CLS_MANIFEST", Size: int64(len(SerializationFormatVersion)), } if err := tw.WriteHeader(hdr); err != nil { return nil, fmt.Errorf("Could not write CLS_MANIFEST header: %s", err) } if _, err := tw.Write([]byte(SerializationFormatVersion)); err != nil { return nil, fmt.Errorf("Could not write CLS_MANIFEST contents: %s", err) } // // Write the METADATA entry // err = ret.WriteMetadataAtPrefix("", metadata) if err != nil { return nil, fmt.Errorf("JSON marshal error: %s", err) } return &ret, nil }
[ "func", "CreateSerializedClassifierStub", "(", "filePath", "string", ",", "metadata", "ClassifierMetadataV1", ")", "(", "*", "ClassifierSerializer", ",", "error", ")", "{", "// Open the filePath", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "filePath", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_TRUNC", "|", "os", ".", "O_CREATE", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "hdr", "*", "tar", ".", "Header", "\n", "gzWriter", ":=", "gzip", ".", "NewWriter", "(", "f", ")", "\n", "tw", ":=", "tar", ".", "NewWriter", "(", "gzWriter", ")", "\n\n", "ret", ":=", "ClassifierSerializer", "{", "gzipWriter", ":", "gzWriter", ",", "fileWriter", ":", "f", ",", "tarWriter", ":", "tw", ",", "}", "\n\n", "//", "// Write the MANIFEST entry", "//", "hdr", "=", "&", "tar", ".", "Header", "{", "Name", ":", "\"", "\"", ",", "Size", ":", "int64", "(", "len", "(", "SerializationFormatVersion", ")", ")", ",", "}", "\n", "if", "err", ":=", "tw", ".", "WriteHeader", "(", "hdr", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "tw", ".", "Write", "(", "[", "]", "byte", "(", "SerializationFormatVersion", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "//", "// Write the METADATA entry", "//", "err", "=", "ret", ".", "WriteMetadataAtPrefix", "(", "\"", "\"", ",", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "&", "ret", ",", "nil", "\n\n", "}" ]
// CreateSerializedClassifierStub generates a file to serialize into // and writes the METADATA header.
[ "CreateSerializedClassifierStub", "generates", "a", "file", "to", "serialize", "into", "and", "writes", "the", "METADATA", "header", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize.go#L383-L426
164,820
sjwhitworth/golearn
perceptron/average.go
Predict
func (p *AveragePerceptron) Predict(what base.FixedDataGrid) base.FixedDataGrid { if !p.trained { panic("Cannot call Predict on an untrained AveragePerceptron") } data := processData(what) allAttrs := base.CheckCompatible(what, p.TrainingData) if allAttrs == nil { // Don't have the same Attributes return nil } // Remove the Attributes which aren't numeric allNumericAttrs := make([]base.Attribute, 0) for _, a := range allAttrs { if fAttr, ok := a.(*base.FloatAttribute); ok { allNumericAttrs = append(allNumericAttrs, fAttr) } } ret := base.GeneratePredictionVector(what) classAttr := ret.AllClassAttributes()[0] classSpec, err := ret.GetAttribute(classAttr) if err != nil { panic(err) } for i, datum := range data { result := p.score(datum) if result > 0.0 { ret.Set(classSpec, i, base.PackU64ToBytes(1)) } else { ret.Set(classSpec, 1, []byte{0, 0, 0, 0, 0, 0, 0, 0}) } } return ret }
go
func (p *AveragePerceptron) Predict(what base.FixedDataGrid) base.FixedDataGrid { if !p.trained { panic("Cannot call Predict on an untrained AveragePerceptron") } data := processData(what) allAttrs := base.CheckCompatible(what, p.TrainingData) if allAttrs == nil { // Don't have the same Attributes return nil } // Remove the Attributes which aren't numeric allNumericAttrs := make([]base.Attribute, 0) for _, a := range allAttrs { if fAttr, ok := a.(*base.FloatAttribute); ok { allNumericAttrs = append(allNumericAttrs, fAttr) } } ret := base.GeneratePredictionVector(what) classAttr := ret.AllClassAttributes()[0] classSpec, err := ret.GetAttribute(classAttr) if err != nil { panic(err) } for i, datum := range data { result := p.score(datum) if result > 0.0 { ret.Set(classSpec, i, base.PackU64ToBytes(1)) } else { ret.Set(classSpec, 1, []byte{0, 0, 0, 0, 0, 0, 0, 0}) } } return ret }
[ "func", "(", "p", "*", "AveragePerceptron", ")", "Predict", "(", "what", "base", ".", "FixedDataGrid", ")", "base", ".", "FixedDataGrid", "{", "if", "!", "p", ".", "trained", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "data", ":=", "processData", "(", "what", ")", "\n\n", "allAttrs", ":=", "base", ".", "CheckCompatible", "(", "what", ",", "p", ".", "TrainingData", ")", "\n", "if", "allAttrs", "==", "nil", "{", "// Don't have the same Attributes", "return", "nil", "\n", "}", "\n\n", "// Remove the Attributes which aren't numeric", "allNumericAttrs", ":=", "make", "(", "[", "]", "base", ".", "Attribute", ",", "0", ")", "\n", "for", "_", ",", "a", ":=", "range", "allAttrs", "{", "if", "fAttr", ",", "ok", ":=", "a", ".", "(", "*", "base", ".", "FloatAttribute", ")", ";", "ok", "{", "allNumericAttrs", "=", "append", "(", "allNumericAttrs", ",", "fAttr", ")", "\n", "}", "\n", "}", "\n\n", "ret", ":=", "base", ".", "GeneratePredictionVector", "(", "what", ")", "\n", "classAttr", ":=", "ret", ".", "AllClassAttributes", "(", ")", "[", "0", "]", "\n", "classSpec", ",", "err", ":=", "ret", ".", "GetAttribute", "(", "classAttr", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "for", "i", ",", "datum", ":=", "range", "data", "{", "result", ":=", "p", ".", "score", "(", "datum", ")", "\n", "if", "result", ">", "0.0", "{", "ret", ".", "Set", "(", "classSpec", ",", "i", ",", "base", ".", "PackU64ToBytes", "(", "1", ")", ")", "\n", "}", "else", "{", "ret", ".", "Set", "(", "classSpec", ",", "1", ",", "[", "]", "byte", "{", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", "}", ")", "\n", "}", "\n", "}", "\n\n", "return", "ret", "\n", "}" ]
// param base.IFixedDataGrid // return base.IFixedDataGrid
[ "param", "base", ".", "IFixedDataGrid", "return", "base", ".", "IFixedDataGrid" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/perceptron/average.go#L101-L140
164,821
sjwhitworth/golearn
linear_models/linearsvc.go
Copy
func (p *LinearSVCParams) Copy() *LinearSVCParams { ret := &LinearSVCParams{ p.SolverType, nil, p.C, p.Eps, p.WeightClassesAutomatically, p.Dual, } if p.ClassWeights != nil { ret.ClassWeights = make([]float64, len(p.ClassWeights)) copy(ret.ClassWeights, p.ClassWeights) } return ret }
go
func (p *LinearSVCParams) Copy() *LinearSVCParams { ret := &LinearSVCParams{ p.SolverType, nil, p.C, p.Eps, p.WeightClassesAutomatically, p.Dual, } if p.ClassWeights != nil { ret.ClassWeights = make([]float64, len(p.ClassWeights)) copy(ret.ClassWeights, p.ClassWeights) } return ret }
[ "func", "(", "p", "*", "LinearSVCParams", ")", "Copy", "(", ")", "*", "LinearSVCParams", "{", "ret", ":=", "&", "LinearSVCParams", "{", "p", ".", "SolverType", ",", "nil", ",", "p", ".", "C", ",", "p", ".", "Eps", ",", "p", ".", "WeightClassesAutomatically", ",", "p", ".", "Dual", ",", "}", "\n", "if", "p", ".", "ClassWeights", "!=", "nil", "{", "ret", ".", "ClassWeights", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "p", ".", "ClassWeights", ")", ")", "\n", "copy", "(", "ret", ".", "ClassWeights", ",", "p", ".", "ClassWeights", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Copy return s a copy of these parameters
[ "Copy", "return", "s", "a", "copy", "of", "these", "parameters" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/linear_models/linearsvc.go#L40-L54
164,822
sjwhitworth/golearn
linear_models/linearsvc.go
SetKindFromStrings
func (p *LinearSVCParams) SetKindFromStrings(loss, penalty string) error { var ret error p.SolverType = 0 // Loss validation if loss == "l1" { } else if loss == "l2" { } else { return fmt.Errorf("loss must be \"l1\" or \"l2\"") } // Penalty validation if penalty == "l2" { if loss == "l1" { if !p.Dual { ret = fmt.Errorf("Important: changed to dual form") } p.SolverType = L2R_L1LOSS_SVC_DUAL p.Dual = true } else { if p.Dual { p.SolverType = L2R_L2LOSS_SVC_DUAL } else { p.SolverType = L2R_L2LOSS_SVC } } } else if penalty == "l1" { if loss == "l2" { if p.Dual { ret = fmt.Errorf("Important: changed to primary form") } p.Dual = false p.SolverType = L1R_L2LOSS_SVC } else { return fmt.Errorf("Must have L2 loss with L1 penalty") } } else { return fmt.Errorf("Penalty must be \"l1\" or \"l2\"") } // Final validation if p.SolverType == 0 { return fmt.Errorf("Invalid parameter combination") } return ret }
go
func (p *LinearSVCParams) SetKindFromStrings(loss, penalty string) error { var ret error p.SolverType = 0 // Loss validation if loss == "l1" { } else if loss == "l2" { } else { return fmt.Errorf("loss must be \"l1\" or \"l2\"") } // Penalty validation if penalty == "l2" { if loss == "l1" { if !p.Dual { ret = fmt.Errorf("Important: changed to dual form") } p.SolverType = L2R_L1LOSS_SVC_DUAL p.Dual = true } else { if p.Dual { p.SolverType = L2R_L2LOSS_SVC_DUAL } else { p.SolverType = L2R_L2LOSS_SVC } } } else if penalty == "l1" { if loss == "l2" { if p.Dual { ret = fmt.Errorf("Important: changed to primary form") } p.Dual = false p.SolverType = L1R_L2LOSS_SVC } else { return fmt.Errorf("Must have L2 loss with L1 penalty") } } else { return fmt.Errorf("Penalty must be \"l1\" or \"l2\"") } // Final validation if p.SolverType == 0 { return fmt.Errorf("Invalid parameter combination") } return ret }
[ "func", "(", "p", "*", "LinearSVCParams", ")", "SetKindFromStrings", "(", "loss", ",", "penalty", "string", ")", "error", "{", "var", "ret", "error", "\n", "p", ".", "SolverType", "=", "0", "\n", "// Loss validation", "if", "loss", "==", "\"", "\"", "{", "}", "else", "if", "loss", "==", "\"", "\"", "{", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ")", "\n", "}", "\n\n", "// Penalty validation", "if", "penalty", "==", "\"", "\"", "{", "if", "loss", "==", "\"", "\"", "{", "if", "!", "p", ".", "Dual", "{", "ret", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ".", "SolverType", "=", "L2R_L1LOSS_SVC_DUAL", "\n", "p", ".", "Dual", "=", "true", "\n", "}", "else", "{", "if", "p", ".", "Dual", "{", "p", ".", "SolverType", "=", "L2R_L2LOSS_SVC_DUAL", "\n", "}", "else", "{", "p", ".", "SolverType", "=", "L2R_L2LOSS_SVC", "\n", "}", "\n", "}", "\n", "}", "else", "if", "penalty", "==", "\"", "\"", "{", "if", "loss", "==", "\"", "\"", "{", "if", "p", ".", "Dual", "{", "ret", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ".", "Dual", "=", "false", "\n", "p", ".", "SolverType", "=", "L1R_L2LOSS_SVC", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ")", "\n", "}", "\n\n", "// Final validation", "if", "p", ".", "SolverType", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// SetKindFromStrings configures the solver kind from strings. // Penalty and Loss parameters can either be l1 or l2.
[ "SetKindFromStrings", "configures", "the", "solver", "kind", "from", "strings", ".", "Penalty", "and", "Loss", "parameters", "can", "either", "be", "l1", "or", "l2", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/linear_models/linearsvc.go#L58-L102
164,823
sjwhitworth/golearn
linear_models/linearsvc.go
convertToNativeFormat
func (p *LinearSVCParams) convertToNativeFormat() *Parameter { return NewParameter(p.SolverType, p.C, p.Eps) }
go
func (p *LinearSVCParams) convertToNativeFormat() *Parameter { return NewParameter(p.SolverType, p.C, p.Eps) }
[ "func", "(", "p", "*", "LinearSVCParams", ")", "convertToNativeFormat", "(", ")", "*", "Parameter", "{", "return", "NewParameter", "(", "p", ".", "SolverType", ",", "p", ".", "C", ",", "p", ".", "Eps", ")", "\n", "}" ]
// convertToNativeFormat converts the LinearSVCParams given into a format // for liblinear.
[ "convertToNativeFormat", "converts", "the", "LinearSVCParams", "given", "into", "a", "format", "for", "liblinear", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/linear_models/linearsvc.go#L106-L108
164,824
sjwhitworth/golearn
linear_models/linearsvc.go
NewLinearSVCFromParams
func NewLinearSVCFromParams(params *LinearSVCParams) (*LinearSVC, error) { // Construct model lr := LinearSVC{} lr.param = params.convertToNativeFormat() lr.Param = params lr.model = nil return &lr, nil }
go
func NewLinearSVCFromParams(params *LinearSVCParams) (*LinearSVC, error) { // Construct model lr := LinearSVC{} lr.param = params.convertToNativeFormat() lr.Param = params lr.model = nil return &lr, nil }
[ "func", "NewLinearSVCFromParams", "(", "params", "*", "LinearSVCParams", ")", "(", "*", "LinearSVC", ",", "error", ")", "{", "// Construct model", "lr", ":=", "LinearSVC", "{", "}", "\n", "lr", ".", "param", "=", "params", ".", "convertToNativeFormat", "(", ")", "\n", "lr", ".", "Param", "=", "params", "\n", "lr", ".", "model", "=", "nil", "\n", "return", "&", "lr", ",", "nil", "\n", "}" ]
// NewLinearSVCFromParams constructs a LinearSVC from the given LinearSVCParams structure.
[ "NewLinearSVCFromParams", "constructs", "a", "LinearSVC", "from", "the", "given", "LinearSVCParams", "structure", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/linear_models/linearsvc.go#L139-L146
164,825
sjwhitworth/golearn
linear_models/linearsvc.go
Save
func (lr *LinearSVC) Save(filePath string) error { writer, err := base.CreateSerializedClassifierStub(filePath, lr.GetMetadata()) if err != nil { return err } defer func() { writer.Close() }() fmt.Printf("writer: %v", writer) return lr.SaveWithPrefix(writer, "") }
go
func (lr *LinearSVC) Save(filePath string) error { writer, err := base.CreateSerializedClassifierStub(filePath, lr.GetMetadata()) if err != nil { return err } defer func() { writer.Close() }() fmt.Printf("writer: %v", writer) return lr.SaveWithPrefix(writer, "") }
[ "func", "(", "lr", "*", "LinearSVC", ")", "Save", "(", "filePath", "string", ")", "error", "{", "writer", ",", "err", ":=", "base", ".", "CreateSerializedClassifierStub", "(", "filePath", ",", "lr", ".", "GetMetadata", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "writer", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\"", ",", "writer", ")", "\n", "return", "lr", ".", "SaveWithPrefix", "(", "writer", ",", "\"", "\"", ")", "\n", "}" ]
// Save outputs this classifier
[ "Save", "outputs", "this", "classifier" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/linear_models/linearsvc.go#L239-L249
164,826
sjwhitworth/golearn
metrics/pairwise/cosine.go
Dot
func (c *Cosine) Dot(vectorX *mat.Dense, vectorY *mat.Dense) float64 { subVector := new(mat.Dense) subVector.MulElem(vectorX, vectorY) result := mat.Sum(subVector) return result }
go
func (c *Cosine) Dot(vectorX *mat.Dense, vectorY *mat.Dense) float64 { subVector := new(mat.Dense) subVector.MulElem(vectorX, vectorY) result := mat.Sum(subVector) return result }
[ "func", "(", "c", "*", "Cosine", ")", "Dot", "(", "vectorX", "*", "mat", ".", "Dense", ",", "vectorY", "*", "mat", ".", "Dense", ")", "float64", "{", "subVector", ":=", "new", "(", "mat", ".", "Dense", ")", "\n", "subVector", ".", "MulElem", "(", "vectorX", ",", "vectorY", ")", "\n", "result", ":=", "mat", ".", "Sum", "(", "subVector", ")", "\n\n", "return", "result", "\n", "}" ]
// Dot computes dot value of vectorX and vectorY.
[ "Dot", "computes", "dot", "value", "of", "vectorX", "and", "vectorY", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/metrics/pairwise/cosine.go#L16-L22
164,827
sjwhitworth/golearn
base/binary.go
MarshalJSON
func (b *BinaryAttribute) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{ "type": "binary", "name": b.Name, }) }
go
func (b *BinaryAttribute) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{ "type": "binary", "name": b.Name, }) }
[ "func", "(", "b", "*", "BinaryAttribute", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "b", ".", "Name", ",", "}", ")", "\n", "}" ]
// MarshalJSON returns a JSON version of this BinaryAttribute for serialisation.
[ "MarshalJSON", "returns", "a", "JSON", "version", "of", "this", "BinaryAttribute", "for", "serialisation", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/binary.go#L15-L20
164,828
sjwhitworth/golearn
base/binary.go
GetSysValFromString
func (b *BinaryAttribute) GetSysValFromString(userVal string) []byte { f, err := strconv.ParseFloat(userVal, 64) if err != nil { panic(err) } ret := make([]byte, 1) if f > 0 { ret[0] = 1 } return ret }
go
func (b *BinaryAttribute) GetSysValFromString(userVal string) []byte { f, err := strconv.ParseFloat(userVal, 64) if err != nil { panic(err) } ret := make([]byte, 1) if f > 0 { ret[0] = 1 } return ret }
[ "func", "(", "b", "*", "BinaryAttribute", ")", "GetSysValFromString", "(", "userVal", "string", ")", "[", "]", "byte", "{", "f", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "userVal", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "ret", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "if", "f", ">", "0", "{", "ret", "[", "0", "]", "=", "1", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// GetSysValFromString returns either 1 or 0 in a single byte.
[ "GetSysValFromString", "returns", "either", "1", "or", "0", "in", "a", "single", "byte", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/binary.go#L51-L61
164,829
sjwhitworth/golearn
base/binary.go
Equals
func (b *BinaryAttribute) Equals(other Attribute) bool { if a, ok := other.(*BinaryAttribute); !ok { return false } else { return a.Name == b.Name } }
go
func (b *BinaryAttribute) Equals(other Attribute) bool { if a, ok := other.(*BinaryAttribute); !ok { return false } else { return a.Name == b.Name } }
[ "func", "(", "b", "*", "BinaryAttribute", ")", "Equals", "(", "other", "Attribute", ")", "bool", "{", "if", "a", ",", "ok", ":=", "other", ".", "(", "*", "BinaryAttribute", ")", ";", "!", "ok", "{", "return", "false", "\n", "}", "else", "{", "return", "a", ".", "Name", "==", "b", ".", "Name", "\n", "}", "\n", "}" ]
// Equals checks for equality with another BinaryAttribute.
[ "Equals", "checks", "for", "equality", "with", "another", "BinaryAttribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/binary.go#L72-L78
164,830
sjwhitworth/golearn
base/binary.go
Compatible
func (b *BinaryAttribute) Compatible(other Attribute) bool { if _, ok := other.(*BinaryAttribute); !ok { return false } else { return true } }
go
func (b *BinaryAttribute) Compatible(other Attribute) bool { if _, ok := other.(*BinaryAttribute); !ok { return false } else { return true } }
[ "func", "(", "b", "*", "BinaryAttribute", ")", "Compatible", "(", "other", "Attribute", ")", "bool", "{", "if", "_", ",", "ok", ":=", "other", ".", "(", "*", "BinaryAttribute", ")", ";", "!", "ok", "{", "return", "false", "\n", "}", "else", "{", "return", "true", "\n", "}", "\n", "}" ]
// Compatible checks whether this Attribute can be represented // in the same pond as another.
[ "Compatible", "checks", "whether", "this", "Attribute", "can", "be", "represented", "in", "the", "same", "pond", "as", "another", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/binary.go#L82-L88
164,831
sjwhitworth/golearn
base/categorical.go
MarshalJSON
func (Attr *CategoricalAttribute) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{ "type": "categorical", "name": Attr.Name, "attr": map[string]interface{}{ "values": Attr.values, }, }) }
go
func (Attr *CategoricalAttribute) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{ "type": "categorical", "name": Attr.Name, "attr": map[string]interface{}{ "values": Attr.values, }, }) }
[ "func", "(", "Attr", "*", "CategoricalAttribute", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "Attr", ".", "Name", ",", "\"", "\"", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "Attr", ".", "values", ",", "}", ",", "}", ")", "\n", "}" ]
// MarshalJSON returns a JSON version of this Attribute.
[ "MarshalJSON", "returns", "a", "JSON", "version", "of", "this", "Attribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/categorical.go#L17-L25
164,832
sjwhitworth/golearn
base/categorical.go
UnmarshalJSON
func (Attr *CategoricalAttribute) UnmarshalJSON(data []byte) error { var d map[string]interface{} err := json.Unmarshal(data, &d) if err != nil { return err } for _, v := range d["values"].([]interface{}) { Attr.values = append(Attr.values, v.(string)) } return nil }
go
func (Attr *CategoricalAttribute) UnmarshalJSON(data []byte) error { var d map[string]interface{} err := json.Unmarshal(data, &d) if err != nil { return err } for _, v := range d["values"].([]interface{}) { Attr.values = append(Attr.values, v.(string)) } return nil }
[ "func", "(", "Attr", "*", "CategoricalAttribute", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "d", "map", "[", "string", "]", "interface", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "d", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "d", "[", "\"", "\"", "]", ".", "(", "[", "]", "interface", "{", "}", ")", "{", "Attr", ".", "values", "=", "append", "(", "Attr", ".", "values", ",", "v", ".", "(", "string", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON returns a JSON version of this Attribute.
[ "UnmarshalJSON", "returns", "a", "JSON", "version", "of", "this", "Attribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/categorical.go#L28-L38
164,833
sjwhitworth/golearn
base/categorical.go
GetSysVal
func (Attr *CategoricalAttribute) GetSysVal(userVal string) []byte { for idx, val := range Attr.values { if val == userVal { return PackU64ToBytes(uint64(idx)) } } return nil }
go
func (Attr *CategoricalAttribute) GetSysVal(userVal string) []byte { for idx, val := range Attr.values { if val == userVal { return PackU64ToBytes(uint64(idx)) } } return nil }
[ "func", "(", "Attr", "*", "CategoricalAttribute", ")", "GetSysVal", "(", "userVal", "string", ")", "[", "]", "byte", "{", "for", "idx", ",", "val", ":=", "range", "Attr", ".", "values", "{", "if", "val", "==", "userVal", "{", "return", "PackU64ToBytes", "(", "uint64", "(", "idx", ")", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetSysVal returns the system representation of userVal as an index into the Values slice // If the userVal can't be found, it returns nothing.
[ "GetSysVal", "returns", "the", "system", "representation", "of", "userVal", "as", "an", "index", "into", "the", "Values", "slice", "If", "the", "userVal", "can", "t", "be", "found", "it", "returns", "nothing", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/categorical.go#L70-L77
164,834
sjwhitworth/golearn
base/categorical.go
String
func (Attr *CategoricalAttribute) String() string { return fmt.Sprintf("CategoricalAttribute(\"%s\", %s)", Attr.Name, Attr.values) }
go
func (Attr *CategoricalAttribute) String() string { return fmt.Sprintf("CategoricalAttribute(\"%s\", %s)", Attr.Name, Attr.values) }
[ "func", "(", "Attr", "*", "CategoricalAttribute", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "Attr", ".", "Name", ",", "Attr", ".", "values", ")", "\n", "}" ]
// String returns a human-readable summary of this Attribute. // // Returns a string containing the list of human-readable values this // CategoricalAttribute can take.
[ "String", "returns", "a", "human", "-", "readable", "summary", "of", "this", "Attribute", ".", "Returns", "a", "string", "containing", "the", "list", "of", "human", "-", "readable", "values", "this", "CategoricalAttribute", "can", "take", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/categorical.go#L121-L123
164,835
sjwhitworth/golearn
base/categorical.go
Compatible
func (Attr *CategoricalAttribute) Compatible(other Attribute) bool { attribute, ok := other.(*CategoricalAttribute) if !ok { return false } // Check that this CategoricalAttribute has the same // values as the other, in the same order if len(attribute.values) != len(Attr.values) { return false } for i, a := range Attr.values { if a != attribute.values[i] { return false } } return true }
go
func (Attr *CategoricalAttribute) Compatible(other Attribute) bool { attribute, ok := other.(*CategoricalAttribute) if !ok { return false } // Check that this CategoricalAttribute has the same // values as the other, in the same order if len(attribute.values) != len(Attr.values) { return false } for i, a := range Attr.values { if a != attribute.values[i] { return false } } return true }
[ "func", "(", "Attr", "*", "CategoricalAttribute", ")", "Compatible", "(", "other", "Attribute", ")", "bool", "{", "attribute", ",", "ok", ":=", "other", ".", "(", "*", "CategoricalAttribute", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n\n", "// Check that this CategoricalAttribute has the same", "// values as the other, in the same order", "if", "len", "(", "attribute", ".", "values", ")", "!=", "len", "(", "Attr", ".", "values", ")", "{", "return", "false", "\n", "}", "\n\n", "for", "i", ",", "a", ":=", "range", "Attr", ".", "values", "{", "if", "a", "!=", "attribute", ".", "values", "[", "i", "]", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// Compatible checks that this CategoricalAttribute has the same // values as another, in the same order.
[ "Compatible", "checks", "that", "this", "CategoricalAttribute", "has", "the", "same", "values", "as", "another", "in", "the", "same", "order", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/categorical.go#L171-L190
164,836
sjwhitworth/golearn
pca/pca.go
FitTransform
func (pca *PCA) FitTransform(X *mat.Dense) *mat.Dense { return pca.Fit(X).Transform(X) }
go
func (pca *PCA) FitTransform(X *mat.Dense) *mat.Dense { return pca.Fit(X).Transform(X) }
[ "func", "(", "pca", "*", "PCA", ")", "FitTransform", "(", "X", "*", "mat", ".", "Dense", ")", "*", "mat", ".", "Dense", "{", "return", "pca", ".", "Fit", "(", "X", ")", ".", "Transform", "(", "X", ")", "\n", "}" ]
// Fit PCA model and transform data // Need return is base.FixedDataGrid
[ "Fit", "PCA", "model", "and", "transform", "data", "Need", "return", "is", "base", ".", "FixedDataGrid" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/pca/pca.go#L20-L22
164,837
sjwhitworth/golearn
pca/pca.go
Fit
func (pca *PCA) Fit(X *mat.Dense) *PCA { // Mean to input data M := mean(X) X = matrixSubVector(X, M) // Get SVD decomposition from data pca.svd = &mat.SVD{} ok := pca.svd.Factorize(X, mat.SVDThin) if !ok { panic("Unable to factorize") } if pca.Num_components < 0 { panic("Number of components can't be less than zero") } return pca }
go
func (pca *PCA) Fit(X *mat.Dense) *PCA { // Mean to input data M := mean(X) X = matrixSubVector(X, M) // Get SVD decomposition from data pca.svd = &mat.SVD{} ok := pca.svd.Factorize(X, mat.SVDThin) if !ok { panic("Unable to factorize") } if pca.Num_components < 0 { panic("Number of components can't be less than zero") } return pca }
[ "func", "(", "pca", "*", "PCA", ")", "Fit", "(", "X", "*", "mat", ".", "Dense", ")", "*", "PCA", "{", "// Mean to input data", "M", ":=", "mean", "(", "X", ")", "\n", "X", "=", "matrixSubVector", "(", "X", ",", "M", ")", "\n\n", "// Get SVD decomposition from data", "pca", ".", "svd", "=", "&", "mat", ".", "SVD", "{", "}", "\n", "ok", ":=", "pca", ".", "svd", ".", "Factorize", "(", "X", ",", "mat", ".", "SVDThin", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "pca", ".", "Num_components", "<", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "pca", "\n", "}" ]
// Fit PCA model
[ "Fit", "PCA", "model" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/pca/pca.go#L25-L41
164,838
sjwhitworth/golearn
pca/pca.go
Transform
func (pca *PCA) Transform(X *mat.Dense) *mat.Dense { if pca.svd == nil { panic("You should to fit PCA model first") } num_samples, num_features := X.Dims() vTemp := new(mat.Dense) pca.svd.VTo(vTemp) //Compute to full data if pca.Num_components == 0 || pca.Num_components > num_features { return compute(X, vTemp) } X = compute(X, vTemp) result := mat.NewDense(num_samples, pca.Num_components, nil) result.Copy(X) return result }
go
func (pca *PCA) Transform(X *mat.Dense) *mat.Dense { if pca.svd == nil { panic("You should to fit PCA model first") } num_samples, num_features := X.Dims() vTemp := new(mat.Dense) pca.svd.VTo(vTemp) //Compute to full data if pca.Num_components == 0 || pca.Num_components > num_features { return compute(X, vTemp) } X = compute(X, vTemp) result := mat.NewDense(num_samples, pca.Num_components, nil) result.Copy(X) return result }
[ "func", "(", "pca", "*", "PCA", ")", "Transform", "(", "X", "*", "mat", ".", "Dense", ")", "*", "mat", ".", "Dense", "{", "if", "pca", ".", "svd", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "num_samples", ",", "num_features", ":=", "X", ".", "Dims", "(", ")", "\n\n", "vTemp", ":=", "new", "(", "mat", ".", "Dense", ")", "\n", "pca", ".", "svd", ".", "VTo", "(", "vTemp", ")", "\n", "//Compute to full data", "if", "pca", ".", "Num_components", "==", "0", "||", "pca", ".", "Num_components", ">", "num_features", "{", "return", "compute", "(", "X", ",", "vTemp", ")", "\n", "}", "\n\n", "X", "=", "compute", "(", "X", ",", "vTemp", ")", "\n", "result", ":=", "mat", ".", "NewDense", "(", "num_samples", ",", "pca", ".", "Num_components", ",", "nil", ")", "\n", "result", ".", "Copy", "(", "X", ")", "\n", "return", "result", "\n", "}" ]
// Need return is base.FixedDataGrid
[ "Need", "return", "is", "base", ".", "FixedDataGrid" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/pca/pca.go#L44-L62
164,839
sjwhitworth/golearn
pca/pca.go
mean
func mean(matrix *mat.Dense) *mat.Dense { rows, cols := matrix.Dims() meanVector := make([]float64, cols) for i := 0; i < cols; i++ { sum := mat.Sum(matrix.ColView(i)) meanVector[i] = sum / float64(rows) } return mat.NewDense(1, cols, meanVector) }
go
func mean(matrix *mat.Dense) *mat.Dense { rows, cols := matrix.Dims() meanVector := make([]float64, cols) for i := 0; i < cols; i++ { sum := mat.Sum(matrix.ColView(i)) meanVector[i] = sum / float64(rows) } return mat.NewDense(1, cols, meanVector) }
[ "func", "mean", "(", "matrix", "*", "mat", ".", "Dense", ")", "*", "mat", ".", "Dense", "{", "rows", ",", "cols", ":=", "matrix", ".", "Dims", "(", ")", "\n", "meanVector", ":=", "make", "(", "[", "]", "float64", ",", "cols", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "cols", ";", "i", "++", "{", "sum", ":=", "mat", ".", "Sum", "(", "matrix", ".", "ColView", "(", "i", ")", ")", "\n", "meanVector", "[", "i", "]", "=", "sum", "/", "float64", "(", "rows", ")", "\n", "}", "\n", "return", "mat", ".", "NewDense", "(", "1", ",", "cols", ",", "meanVector", ")", "\n", "}" ]
//Helpful private functions //Compute mean of the columns of input matrix
[ "Helpful", "private", "functions", "Compute", "mean", "of", "the", "columns", "of", "input", "matrix" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/pca/pca.go#L67-L75
164,840
sjwhitworth/golearn
base/util.go
PackU64ToBytesInline
func PackU64ToBytesInline(val uint64, ret []byte) { ret[7] = byte(val & (0xFF << 56) >> 56) ret[6] = byte(val & (0xFF << 48) >> 48) ret[5] = byte(val & (0xFF << 40) >> 40) ret[4] = byte(val & (0xFF << 32) >> 32) ret[3] = byte(val & (0xFF << 24) >> 24) ret[2] = byte(val & (0xFF << 16) >> 16) ret[1] = byte(val & (0xFF << 8) >> 8) ret[0] = byte(val & (0xFF << 0) >> 0) }
go
func PackU64ToBytesInline(val uint64, ret []byte) { ret[7] = byte(val & (0xFF << 56) >> 56) ret[6] = byte(val & (0xFF << 48) >> 48) ret[5] = byte(val & (0xFF << 40) >> 40) ret[4] = byte(val & (0xFF << 32) >> 32) ret[3] = byte(val & (0xFF << 24) >> 24) ret[2] = byte(val & (0xFF << 16) >> 16) ret[1] = byte(val & (0xFF << 8) >> 8) ret[0] = byte(val & (0xFF << 0) >> 0) }
[ "func", "PackU64ToBytesInline", "(", "val", "uint64", ",", "ret", "[", "]", "byte", ")", "{", "ret", "[", "7", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "56", ")", ">>", "56", ")", "\n", "ret", "[", "6", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "48", ")", ">>", "48", ")", "\n", "ret", "[", "5", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "40", ")", ">>", "40", ")", "\n", "ret", "[", "4", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "32", ")", ">>", "32", ")", "\n", "ret", "[", "3", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "24", ")", ">>", "24", ")", "\n", "ret", "[", "2", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "16", ")", ">>", "16", ")", "\n", "ret", "[", "1", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "8", ")", ">>", "8", ")", "\n", "ret", "[", "0", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "0", ")", ">>", "0", ")", "\n", "}" ]
// PackU64ToBytesInline fills ret with the byte values of // val. Ret must have length at least 8.
[ "PackU64ToBytesInline", "fills", "ret", "with", "the", "byte", "values", "of", "val", ".", "Ret", "must", "have", "length", "at", "least", "8", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util.go#L10-L19
164,841
sjwhitworth/golearn
base/util.go
PackFloatToBytesInline
func PackFloatToBytesInline(val float64, ret []byte) { PackU64ToBytesInline(math.Float64bits(val), ret) }
go
func PackFloatToBytesInline(val float64, ret []byte) { PackU64ToBytesInline(math.Float64bits(val), ret) }
[ "func", "PackFloatToBytesInline", "(", "val", "float64", ",", "ret", "[", "]", "byte", ")", "{", "PackU64ToBytesInline", "(", "math", ".", "Float64bits", "(", "val", ")", ",", "ret", ")", "\n", "}" ]
// PackFloatToBytesInline fills ret with the byte values of // the float64 argument. ret must be at least 8 bytes in size.
[ "PackFloatToBytesInline", "fills", "ret", "with", "the", "byte", "values", "of", "the", "float64", "argument", ".", "ret", "must", "be", "at", "least", "8", "bytes", "in", "size", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util.go#L23-L25
164,842
sjwhitworth/golearn
base/util.go
PackU64ToBytes
func PackU64ToBytes(val uint64) []byte { ret := make([]byte, 8) ret[7] = byte(val & (0xFF << 56) >> 56) ret[6] = byte(val & (0xFF << 48) >> 48) ret[5] = byte(val & (0xFF << 40) >> 40) ret[4] = byte(val & (0xFF << 32) >> 32) ret[3] = byte(val & (0xFF << 24) >> 24) ret[2] = byte(val & (0xFF << 16) >> 16) ret[1] = byte(val & (0xFF << 8) >> 8) ret[0] = byte(val & (0xFF << 0) >> 0) return ret }
go
func PackU64ToBytes(val uint64) []byte { ret := make([]byte, 8) ret[7] = byte(val & (0xFF << 56) >> 56) ret[6] = byte(val & (0xFF << 48) >> 48) ret[5] = byte(val & (0xFF << 40) >> 40) ret[4] = byte(val & (0xFF << 32) >> 32) ret[3] = byte(val & (0xFF << 24) >> 24) ret[2] = byte(val & (0xFF << 16) >> 16) ret[1] = byte(val & (0xFF << 8) >> 8) ret[0] = byte(val & (0xFF << 0) >> 0) return ret }
[ "func", "PackU64ToBytes", "(", "val", "uint64", ")", "[", "]", "byte", "{", "ret", ":=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "ret", "[", "7", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "56", ")", ">>", "56", ")", "\n", "ret", "[", "6", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "48", ")", ">>", "48", ")", "\n", "ret", "[", "5", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "40", ")", ">>", "40", ")", "\n", "ret", "[", "4", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "32", ")", ">>", "32", ")", "\n", "ret", "[", "3", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "24", ")", ">>", "24", ")", "\n", "ret", "[", "2", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "16", ")", ">>", "16", ")", "\n", "ret", "[", "1", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "8", ")", ">>", "8", ")", "\n", "ret", "[", "0", "]", "=", "byte", "(", "val", "&", "(", "0xFF", "<<", "0", ")", ">>", "0", ")", "\n", "return", "ret", "\n", "}" ]
// PackU64ToBytes allocates a return value of appropriate length // and fills it with the values of val.
[ "PackU64ToBytes", "allocates", "a", "return", "value", "of", "appropriate", "length", "and", "fills", "it", "with", "the", "values", "of", "val", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util.go#L29-L40
164,843
sjwhitworth/golearn
base/util.go
UnpackBytesToU64
func UnpackBytesToU64(val []byte) uint64 { pb := unsafe.Pointer(&val[0]) return *(*uint64)(pb) }
go
func UnpackBytesToU64(val []byte) uint64 { pb := unsafe.Pointer(&val[0]) return *(*uint64)(pb) }
[ "func", "UnpackBytesToU64", "(", "val", "[", "]", "byte", ")", "uint64", "{", "pb", ":=", "unsafe", ".", "Pointer", "(", "&", "val", "[", "0", "]", ")", "\n", "return", "*", "(", "*", "uint64", ")", "(", "pb", ")", "\n", "}" ]
// UnpackBytesToU64 converst a given byte slice into // a uint64 value.
[ "UnpackBytesToU64", "converst", "a", "given", "byte", "slice", "into", "a", "uint64", "value", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util.go#L44-L47
164,844
sjwhitworth/golearn
base/util.go
UnpackBytesToFloat
func UnpackBytesToFloat(val []byte) float64 { pb := unsafe.Pointer(&val[0]) return *(*float64)(pb) }
go
func UnpackBytesToFloat(val []byte) float64 { pb := unsafe.Pointer(&val[0]) return *(*float64)(pb) }
[ "func", "UnpackBytesToFloat", "(", "val", "[", "]", "byte", ")", "float64", "{", "pb", ":=", "unsafe", ".", "Pointer", "(", "&", "val", "[", "0", "]", ")", "\n", "return", "*", "(", "*", "float64", ")", "(", "pb", ")", "\n", "}" ]
// UnpackBytesToFloat converts a given byte slice into an // equivalent float64.
[ "UnpackBytesToFloat", "converts", "a", "given", "byte", "slice", "into", "an", "equivalent", "float64", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util.go#L57-L60
164,845
sjwhitworth/golearn
evaluation/confusion.go
GetTruePositives
func GetTruePositives(class string, c ConfusionMatrix) float64 { return float64(c[class][class]) }
go
func GetTruePositives(class string, c ConfusionMatrix) float64 { return float64(c[class][class]) }
[ "func", "GetTruePositives", "(", "class", "string", ",", "c", "ConfusionMatrix", ")", "float64", "{", "return", "float64", "(", "c", "[", "class", "]", "[", "class", "]", ")", "\n", "}" ]
// GetTruePositives returns the number of times an entry is // predicted successfully in a given ConfusionMatrix.
[ "GetTruePositives", "returns", "the", "number", "of", "times", "an", "entry", "is", "predicted", "successfully", "in", "a", "given", "ConfusionMatrix", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L42-L44
164,846
sjwhitworth/golearn
evaluation/confusion.go
GetFalsePositives
func GetFalsePositives(class string, c ConfusionMatrix) float64 { ret := 0.0 for k := range c { if k == class { continue } ret += float64(c[k][class]) } return ret }
go
func GetFalsePositives(class string, c ConfusionMatrix) float64 { ret := 0.0 for k := range c { if k == class { continue } ret += float64(c[k][class]) } return ret }
[ "func", "GetFalsePositives", "(", "class", "string", ",", "c", "ConfusionMatrix", ")", "float64", "{", "ret", ":=", "0.0", "\n", "for", "k", ":=", "range", "c", "{", "if", "k", "==", "class", "{", "continue", "\n", "}", "\n", "ret", "+=", "float64", "(", "c", "[", "k", "]", "[", "class", "]", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// GetFalsePositives returns the number of times an entry is // incorrectly predicted as having a given class.
[ "GetFalsePositives", "returns", "the", "number", "of", "times", "an", "entry", "is", "incorrectly", "predicted", "as", "having", "a", "given", "class", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L48-L57
164,847
sjwhitworth/golearn
evaluation/confusion.go
GetFalseNegatives
func GetFalseNegatives(class string, c ConfusionMatrix) float64 { ret := 0.0 for k := range c[class] { if k == class { continue } ret += float64(c[class][k]) } return ret }
go
func GetFalseNegatives(class string, c ConfusionMatrix) float64 { ret := 0.0 for k := range c[class] { if k == class { continue } ret += float64(c[class][k]) } return ret }
[ "func", "GetFalseNegatives", "(", "class", "string", ",", "c", "ConfusionMatrix", ")", "float64", "{", "ret", ":=", "0.0", "\n", "for", "k", ":=", "range", "c", "[", "class", "]", "{", "if", "k", "==", "class", "{", "continue", "\n", "}", "\n", "ret", "+=", "float64", "(", "c", "[", "class", "]", "[", "k", "]", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// GetFalseNegatives returns the number of times an entry is // incorrectly predicted as something other than the given class.
[ "GetFalseNegatives", "returns", "the", "number", "of", "times", "an", "entry", "is", "incorrectly", "predicted", "as", "something", "other", "than", "the", "given", "class", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L61-L70
164,848
sjwhitworth/golearn
evaluation/confusion.go
GetTrueNegatives
func GetTrueNegatives(class string, c ConfusionMatrix) float64 { ret := 0.0 for k := range c { if k == class { continue } for l := range c[k] { if l == class { continue } ret += float64(c[k][l]) } } return ret }
go
func GetTrueNegatives(class string, c ConfusionMatrix) float64 { ret := 0.0 for k := range c { if k == class { continue } for l := range c[k] { if l == class { continue } ret += float64(c[k][l]) } } return ret }
[ "func", "GetTrueNegatives", "(", "class", "string", ",", "c", "ConfusionMatrix", ")", "float64", "{", "ret", ":=", "0.0", "\n", "for", "k", ":=", "range", "c", "{", "if", "k", "==", "class", "{", "continue", "\n", "}", "\n", "for", "l", ":=", "range", "c", "[", "k", "]", "{", "if", "l", "==", "class", "{", "continue", "\n", "}", "\n", "ret", "+=", "float64", "(", "c", "[", "k", "]", "[", "l", "]", ")", "\n", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// GetTrueNegatives returns the number of times an entry is // correctly predicted as something other than the given class.
[ "GetTrueNegatives", "returns", "the", "number", "of", "times", "an", "entry", "is", "correctly", "predicted", "as", "something", "other", "than", "the", "given", "class", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L74-L88
164,849
sjwhitworth/golearn
evaluation/confusion.go
GetPrecision
func GetPrecision(class string, c ConfusionMatrix) float64 { // Fraction of retrieved instances that are relevant truePositives := GetTruePositives(class, c) falsePositives := GetFalsePositives(class, c) return truePositives / (truePositives + falsePositives) }
go
func GetPrecision(class string, c ConfusionMatrix) float64 { // Fraction of retrieved instances that are relevant truePositives := GetTruePositives(class, c) falsePositives := GetFalsePositives(class, c) return truePositives / (truePositives + falsePositives) }
[ "func", "GetPrecision", "(", "class", "string", ",", "c", "ConfusionMatrix", ")", "float64", "{", "// Fraction of retrieved instances that are relevant", "truePositives", ":=", "GetTruePositives", "(", "class", ",", "c", ")", "\n", "falsePositives", ":=", "GetFalsePositives", "(", "class", ",", "c", ")", "\n", "return", "truePositives", "/", "(", "truePositives", "+", "falsePositives", ")", "\n", "}" ]
// GetPrecision returns the fraction of of the total predictions // for a given class which were correct.
[ "GetPrecision", "returns", "the", "fraction", "of", "of", "the", "total", "predictions", "for", "a", "given", "class", "which", "were", "correct", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L92-L97
164,850
sjwhitworth/golearn
evaluation/confusion.go
GetRecall
func GetRecall(class string, c ConfusionMatrix) float64 { // Fraction of relevant instances that are retrieved truePositives := GetTruePositives(class, c) falseNegatives := GetFalseNegatives(class, c) return truePositives / (truePositives + falseNegatives) }
go
func GetRecall(class string, c ConfusionMatrix) float64 { // Fraction of relevant instances that are retrieved truePositives := GetTruePositives(class, c) falseNegatives := GetFalseNegatives(class, c) return truePositives / (truePositives + falseNegatives) }
[ "func", "GetRecall", "(", "class", "string", ",", "c", "ConfusionMatrix", ")", "float64", "{", "// Fraction of relevant instances that are retrieved", "truePositives", ":=", "GetTruePositives", "(", "class", ",", "c", ")", "\n", "falseNegatives", ":=", "GetFalseNegatives", "(", "class", ",", "c", ")", "\n", "return", "truePositives", "/", "(", "truePositives", "+", "falseNegatives", ")", "\n", "}" ]
// GetRecall returns the fraction of the total occurrences of a // given class which were predicted.
[ "GetRecall", "returns", "the", "fraction", "of", "the", "total", "occurrences", "of", "a", "given", "class", "which", "were", "predicted", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L101-L106
164,851
sjwhitworth/golearn
evaluation/confusion.go
GetMicroPrecision
func GetMicroPrecision(c ConfusionMatrix) float64 { truePositives := 0.0 falsePositives := 0.0 for k := range c { truePositives += GetTruePositives(k, c) falsePositives += GetFalsePositives(k, c) } return truePositives / (truePositives + falsePositives) }
go
func GetMicroPrecision(c ConfusionMatrix) float64 { truePositives := 0.0 falsePositives := 0.0 for k := range c { truePositives += GetTruePositives(k, c) falsePositives += GetFalsePositives(k, c) } return truePositives / (truePositives + falsePositives) }
[ "func", "GetMicroPrecision", "(", "c", "ConfusionMatrix", ")", "float64", "{", "truePositives", ":=", "0.0", "\n", "falsePositives", ":=", "0.0", "\n", "for", "k", ":=", "range", "c", "{", "truePositives", "+=", "GetTruePositives", "(", "k", ",", "c", ")", "\n", "falsePositives", "+=", "GetFalsePositives", "(", "k", ",", "c", ")", "\n", "}", "\n", "return", "truePositives", "/", "(", "truePositives", "+", "falsePositives", ")", "\n", "}" ]
// GetMicroPrecision assesses Classifier performance across // all classes using the total true positives and false positives.
[ "GetMicroPrecision", "assesses", "Classifier", "performance", "across", "all", "classes", "using", "the", "total", "true", "positives", "and", "false", "positives", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L134-L142
164,852
sjwhitworth/golearn
evaluation/confusion.go
GetMacroPrecision
func GetMacroPrecision(c ConfusionMatrix) float64 { precisionVals := 0.0 for k := range c { precisionVals += GetPrecision(k, c) } return precisionVals / float64(len(c)) }
go
func GetMacroPrecision(c ConfusionMatrix) float64 { precisionVals := 0.0 for k := range c { precisionVals += GetPrecision(k, c) } return precisionVals / float64(len(c)) }
[ "func", "GetMacroPrecision", "(", "c", "ConfusionMatrix", ")", "float64", "{", "precisionVals", ":=", "0.0", "\n", "for", "k", ":=", "range", "c", "{", "precisionVals", "+=", "GetPrecision", "(", "k", ",", "c", ")", "\n", "}", "\n", "return", "precisionVals", "/", "float64", "(", "len", "(", "c", ")", ")", "\n", "}" ]
// GetMacroPrecision assesses Classifier performance across all // classes by averaging the precision measures achieved for each class.
[ "GetMacroPrecision", "assesses", "Classifier", "performance", "across", "all", "classes", "by", "averaging", "the", "precision", "measures", "achieved", "for", "each", "class", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L146-L152
164,853
sjwhitworth/golearn
evaluation/confusion.go
GetMicroRecall
func GetMicroRecall(c ConfusionMatrix) float64 { truePositives := 0.0 falseNegatives := 0.0 for k := range c { truePositives += GetTruePositives(k, c) falseNegatives += GetFalseNegatives(k, c) } return truePositives / (truePositives + falseNegatives) }
go
func GetMicroRecall(c ConfusionMatrix) float64 { truePositives := 0.0 falseNegatives := 0.0 for k := range c { truePositives += GetTruePositives(k, c) falseNegatives += GetFalseNegatives(k, c) } return truePositives / (truePositives + falseNegatives) }
[ "func", "GetMicroRecall", "(", "c", "ConfusionMatrix", ")", "float64", "{", "truePositives", ":=", "0.0", "\n", "falseNegatives", ":=", "0.0", "\n", "for", "k", ":=", "range", "c", "{", "truePositives", "+=", "GetTruePositives", "(", "k", ",", "c", ")", "\n", "falseNegatives", "+=", "GetFalseNegatives", "(", "k", ",", "c", ")", "\n", "}", "\n", "return", "truePositives", "/", "(", "truePositives", "+", "falseNegatives", ")", "\n", "}" ]
// GetMicroRecall assesses Classifier performance across all // classes using the total true positives and false negatives.
[ "GetMicroRecall", "assesses", "Classifier", "performance", "across", "all", "classes", "using", "the", "total", "true", "positives", "and", "false", "negatives", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L156-L164
164,854
sjwhitworth/golearn
evaluation/confusion.go
GetMacroRecall
func GetMacroRecall(c ConfusionMatrix) float64 { recallVals := 0.0 for k := range c { recallVals += GetRecall(k, c) } return recallVals / float64(len(c)) }
go
func GetMacroRecall(c ConfusionMatrix) float64 { recallVals := 0.0 for k := range c { recallVals += GetRecall(k, c) } return recallVals / float64(len(c)) }
[ "func", "GetMacroRecall", "(", "c", "ConfusionMatrix", ")", "float64", "{", "recallVals", ":=", "0.0", "\n", "for", "k", ":=", "range", "c", "{", "recallVals", "+=", "GetRecall", "(", "k", ",", "c", ")", "\n", "}", "\n", "return", "recallVals", "/", "float64", "(", "len", "(", "c", ")", ")", "\n", "}" ]
// GetMacroRecall assesses Classifier performance across all classes // by averaging the recall measures achieved for each class
[ "GetMacroRecall", "assesses", "Classifier", "performance", "across", "all", "classes", "by", "averaging", "the", "recall", "measures", "achieved", "for", "each", "class" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L168-L174
164,855
sjwhitworth/golearn
evaluation/confusion.go
GetSummary
func GetSummary(c ConfusionMatrix) string { var buffer bytes.Buffer w := new(tabwriter.Writer) w.Init(&buffer, 0, 8, 0, '\t', 0) fmt.Fprintln(w, "Reference Class\tTrue Positives\tFalse Positives\tTrue Negatives\tPrecision\tRecall\tF1 Score") fmt.Fprintln(w, "---------------\t--------------\t---------------\t--------------\t---------\t------\t--------") for k := range c { tp := GetTruePositives(k, c) fp := GetFalsePositives(k, c) tn := GetTrueNegatives(k, c) prec := GetPrecision(k, c) rec := GetRecall(k, c) f1 := GetF1Score(k, c) fmt.Fprintf(w, "%s\t%.0f\t%.0f\t%.0f\t%.4f\t%.4f\t%.4f\n", k, tp, fp, tn, prec, rec, f1) } w.Flush() buffer.WriteString(fmt.Sprintf("Overall accuracy: %.4f\n", GetAccuracy(c))) return buffer.String() }
go
func GetSummary(c ConfusionMatrix) string { var buffer bytes.Buffer w := new(tabwriter.Writer) w.Init(&buffer, 0, 8, 0, '\t', 0) fmt.Fprintln(w, "Reference Class\tTrue Positives\tFalse Positives\tTrue Negatives\tPrecision\tRecall\tF1 Score") fmt.Fprintln(w, "---------------\t--------------\t---------------\t--------------\t---------\t------\t--------") for k := range c { tp := GetTruePositives(k, c) fp := GetFalsePositives(k, c) tn := GetTrueNegatives(k, c) prec := GetPrecision(k, c) rec := GetRecall(k, c) f1 := GetF1Score(k, c) fmt.Fprintf(w, "%s\t%.0f\t%.0f\t%.0f\t%.4f\t%.4f\t%.4f\n", k, tp, fp, tn, prec, rec, f1) } w.Flush() buffer.WriteString(fmt.Sprintf("Overall accuracy: %.4f\n", GetAccuracy(c))) return buffer.String() }
[ "func", "GetSummary", "(", "c", "ConfusionMatrix", ")", "string", "{", "var", "buffer", "bytes", ".", "Buffer", "\n", "w", ":=", "new", "(", "tabwriter", ".", "Writer", ")", "\n", "w", ".", "Init", "(", "&", "buffer", ",", "0", ",", "8", ",", "0", ",", "'\\t'", ",", "0", ")", "\n\n", "fmt", ".", "Fprintln", "(", "w", ",", "\"", "\\t", "\\t", "\\t", "\\t", "\\t", "\\t", "\"", ")", "\n", "fmt", ".", "Fprintln", "(", "w", ",", "\"", "\\t", "\\t", "\\t", "\\t", "\\t", "\\t", "\"", ")", "\n", "for", "k", ":=", "range", "c", "{", "tp", ":=", "GetTruePositives", "(", "k", ",", "c", ")", "\n", "fp", ":=", "GetFalsePositives", "(", "k", ",", "c", ")", "\n", "tn", ":=", "GetTrueNegatives", "(", "k", ",", "c", ")", "\n", "prec", ":=", "GetPrecision", "(", "k", ",", "c", ")", "\n", "rec", ":=", "GetRecall", "(", "k", ",", "c", ")", "\n", "f1", ":=", "GetF1Score", "(", "k", ",", "c", ")", "\n\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\\t", "\\t", "\\t", "\\t", "\\t", "\\n", "\"", ",", "k", ",", "tp", ",", "fp", ",", "tn", ",", "prec", ",", "rec", ",", "f1", ")", "\n", "}", "\n", "w", ".", "Flush", "(", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "GetAccuracy", "(", "c", ")", ")", ")", "\n\n", "return", "buffer", ".", "String", "(", ")", "\n", "}" ]
// GetSummary returns a table of precision, recall, true positive, // false positive, and true negatives for each class for a given // ConfusionMatrix
[ "GetSummary", "returns", "a", "table", "of", "precision", "recall", "true", "positive", "false", "positive", "and", "true", "negatives", "for", "each", "class", "for", "a", "given", "ConfusionMatrix" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L179-L200
164,856
sjwhitworth/golearn
evaluation/confusion.go
ShowConfusionMatrix
func ShowConfusionMatrix(c ConfusionMatrix) string { var buffer bytes.Buffer w := new(tabwriter.Writer) w.Init(&buffer, 0, 8, 0, '\t', 0) ref := make([]string, 0) fmt.Fprintf(w, "Reference Class\t") for k := range c { fmt.Fprintf(w, "%s\t", k) ref = append(ref, k) } fmt.Fprintf(w, "\n") fmt.Fprintf(w, "---------------\t") for _, v := range ref { for t := 0; t < len(v); t++ { fmt.Fprintf(w, "-") } fmt.Fprintf(w, "\t") } fmt.Fprintf(w, "\n") for _, v := range ref { fmt.Fprintf(w, "%s\t", v) for _, v2 := range ref { fmt.Fprintf(w, "%d\t", c[v][v2]) } fmt.Fprintf(w, "\n") } w.Flush() return buffer.String() }
go
func ShowConfusionMatrix(c ConfusionMatrix) string { var buffer bytes.Buffer w := new(tabwriter.Writer) w.Init(&buffer, 0, 8, 0, '\t', 0) ref := make([]string, 0) fmt.Fprintf(w, "Reference Class\t") for k := range c { fmt.Fprintf(w, "%s\t", k) ref = append(ref, k) } fmt.Fprintf(w, "\n") fmt.Fprintf(w, "---------------\t") for _, v := range ref { for t := 0; t < len(v); t++ { fmt.Fprintf(w, "-") } fmt.Fprintf(w, "\t") } fmt.Fprintf(w, "\n") for _, v := range ref { fmt.Fprintf(w, "%s\t", v) for _, v2 := range ref { fmt.Fprintf(w, "%d\t", c[v][v2]) } fmt.Fprintf(w, "\n") } w.Flush() return buffer.String() }
[ "func", "ShowConfusionMatrix", "(", "c", "ConfusionMatrix", ")", "string", "{", "var", "buffer", "bytes", ".", "Buffer", "\n", "w", ":=", "new", "(", "tabwriter", ".", "Writer", ")", "\n", "w", ".", "Init", "(", "&", "buffer", ",", "0", ",", "8", ",", "0", ",", "'\\t'", ",", "0", ")", "\n\n", "ref", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\"", ")", "\n", "for", "k", ":=", "range", "c", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\"", ",", "k", ")", "\n", "ref", "=", "append", "(", "ref", ",", "k", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\"", ")", "\n", "for", "_", ",", "v", ":=", "range", "ref", "{", "for", "t", ":=", "0", ";", "t", "<", "len", "(", "v", ")", ";", "t", "++", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\"", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\"", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n\n", "for", "_", ",", "v", ":=", "range", "ref", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\"", ",", "v", ")", "\n", "for", "_", ",", "v2", ":=", "range", "ref", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\"", ",", "c", "[", "v", "]", "[", "v2", "]", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "}", "\n", "w", ".", "Flush", "(", ")", "\n\n", "return", "buffer", ".", "String", "(", ")", "\n", "}" ]
// ShowConfusionMatrix return a human-readable version of a given // ConfusionMatrix.
[ "ShowConfusionMatrix", "return", "a", "human", "-", "readable", "version", "of", "a", "given", "ConfusionMatrix", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/confusion.go#L204-L236
164,857
sjwhitworth/golearn
base/spec.go
String
func (a *AttributeSpec) String() string { return fmt.Sprintf("AttributeSpec(Attribute: '%s', Pond: %d/%d)", a.attr, a.pond, a.position) }
go
func (a *AttributeSpec) String() string { return fmt.Sprintf("AttributeSpec(Attribute: '%s', Pond: %d/%d)", a.attr, a.pond, a.position) }
[ "func", "(", "a", "*", "AttributeSpec", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "a", ".", "attr", ",", "a", ".", "pond", ",", "a", ".", "position", ")", "\n", "}" ]
// String returns a human-readable description of this AttributeSpec.
[ "String", "returns", "a", "human", "-", "readable", "description", "of", "this", "AttributeSpec", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/spec.go#L39-L41
164,858
sjwhitworth/golearn
base/util_attributes.go
NonClassFloatAttributes
func NonClassFloatAttributes(d DataGrid) []Attribute { classAttrs := d.AllClassAttributes() allAttrs := d.AllAttributes() ret := make([]Attribute, 0) for _, a := range allAttrs { matched := false if _, ok := a.(*FloatAttribute); !ok { continue } for _, b := range classAttrs { if a.Equals(b) { matched = true break } } if !matched { ret = append(ret, a) } } return ret }
go
func NonClassFloatAttributes(d DataGrid) []Attribute { classAttrs := d.AllClassAttributes() allAttrs := d.AllAttributes() ret := make([]Attribute, 0) for _, a := range allAttrs { matched := false if _, ok := a.(*FloatAttribute); !ok { continue } for _, b := range classAttrs { if a.Equals(b) { matched = true break } } if !matched { ret = append(ret, a) } } return ret }
[ "func", "NonClassFloatAttributes", "(", "d", "DataGrid", ")", "[", "]", "Attribute", "{", "classAttrs", ":=", "d", ".", "AllClassAttributes", "(", ")", "\n", "allAttrs", ":=", "d", ".", "AllAttributes", "(", ")", "\n", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "0", ")", "\n", "for", "_", ",", "a", ":=", "range", "allAttrs", "{", "matched", ":=", "false", "\n", "if", "_", ",", "ok", ":=", "a", ".", "(", "*", "FloatAttribute", ")", ";", "!", "ok", "{", "continue", "\n", "}", "\n", "for", "_", ",", "b", ":=", "range", "classAttrs", "{", "if", "a", ".", "Equals", "(", "b", ")", "{", "matched", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "matched", "{", "ret", "=", "append", "(", "ret", ",", "a", ")", "\n", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// This file contains utility functions relating to Attributes and Attribute specifications. // NonClassFloatAttributes returns all FloatAttributes which // aren't designated as a class Attribute.
[ "This", "file", "contains", "utility", "functions", "relating", "to", "Attributes", "and", "Attribute", "specifications", ".", "NonClassFloatAttributes", "returns", "all", "FloatAttributes", "which", "aren", "t", "designated", "as", "a", "class", "Attribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util_attributes.go#L12-L32
164,859
sjwhitworth/golearn
base/util_attributes.go
NonClassAttributes
func NonClassAttributes(d DataGrid) []Attribute { classAttrs := d.AllClassAttributes() allAttrs := d.AllAttributes() return AttributeDifferenceReferences(allAttrs, classAttrs) }
go
func NonClassAttributes(d DataGrid) []Attribute { classAttrs := d.AllClassAttributes() allAttrs := d.AllAttributes() return AttributeDifferenceReferences(allAttrs, classAttrs) }
[ "func", "NonClassAttributes", "(", "d", "DataGrid", ")", "[", "]", "Attribute", "{", "classAttrs", ":=", "d", ".", "AllClassAttributes", "(", ")", "\n", "allAttrs", ":=", "d", ".", "AllAttributes", "(", ")", "\n", "return", "AttributeDifferenceReferences", "(", "allAttrs", ",", "classAttrs", ")", "\n", "}" ]
// NonClassAttrs returns all Attributes which aren't designated as a // class Attribute.
[ "NonClassAttrs", "returns", "all", "Attributes", "which", "aren", "t", "designated", "as", "a", "class", "Attribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util_attributes.go#L36-L40
164,860
sjwhitworth/golearn
base/util_attributes.go
ResolveAttributes
func ResolveAttributes(d DataGrid, attrs []Attribute) []AttributeSpec { ret := make([]AttributeSpec, len(attrs)) n := len(attrs) for i := 0; i < n; i++ { a := attrs[i] spec, err := d.GetAttribute(a) if err != nil { panic(fmt.Errorf("Error resolving Attribute %s: %s", a, err)) } ret[i] = spec } sort.Sort(byPosition(ret)) return ret }
go
func ResolveAttributes(d DataGrid, attrs []Attribute) []AttributeSpec { ret := make([]AttributeSpec, len(attrs)) n := len(attrs) for i := 0; i < n; i++ { a := attrs[i] spec, err := d.GetAttribute(a) if err != nil { panic(fmt.Errorf("Error resolving Attribute %s: %s", a, err)) } ret[i] = spec } sort.Sort(byPosition(ret)) return ret }
[ "func", "ResolveAttributes", "(", "d", "DataGrid", ",", "attrs", "[", "]", "Attribute", ")", "[", "]", "AttributeSpec", "{", "ret", ":=", "make", "(", "[", "]", "AttributeSpec", ",", "len", "(", "attrs", ")", ")", "\n", "n", ":=", "len", "(", "attrs", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "a", ":=", "attrs", "[", "i", "]", "\n", "spec", ",", "err", ":=", "d", ".", "GetAttribute", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "a", ",", "err", ")", ")", "\n", "}", "\n", "ret", "[", "i", "]", "=", "spec", "\n", "}", "\n\n", "sort", ".", "Sort", "(", "byPosition", "(", "ret", ")", ")", "\n\n", "return", "ret", "\n", "}" ]
// ResolveAttributes returns AttributeSpecs describing // all of the Attributes.
[ "ResolveAttributes", "returns", "AttributeSpecs", "describing", "all", "of", "the", "Attributes", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util_attributes.go#L44-L59
164,861
sjwhitworth/golearn
base/conversion.go
ConvertRowToMat64
func ConvertRowToMat64(attrs []Attribute, f FixedDataGrid, r int) (*mat.Dense, error) { err := checkAllAttributesAreFloat(attrs) if err != nil { return nil, err } // Allocate the return value ret := mat.NewDense(1, len(attrs), nil) // Resolve all the attributes attrSpecs := ResolveAttributes(f, attrs) // Get the results for i, a := range attrSpecs { ret.Set(0, i, UnpackBytesToFloat(f.Get(a, r))) } // Return the result return ret, nil }
go
func ConvertRowToMat64(attrs []Attribute, f FixedDataGrid, r int) (*mat.Dense, error) { err := checkAllAttributesAreFloat(attrs) if err != nil { return nil, err } // Allocate the return value ret := mat.NewDense(1, len(attrs), nil) // Resolve all the attributes attrSpecs := ResolveAttributes(f, attrs) // Get the results for i, a := range attrSpecs { ret.Set(0, i, UnpackBytesToFloat(f.Get(a, r))) } // Return the result return ret, nil }
[ "func", "ConvertRowToMat64", "(", "attrs", "[", "]", "Attribute", ",", "f", "FixedDataGrid", ",", "r", "int", ")", "(", "*", "mat", ".", "Dense", ",", "error", ")", "{", "err", ":=", "checkAllAttributesAreFloat", "(", "attrs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Allocate the return value", "ret", ":=", "mat", ".", "NewDense", "(", "1", ",", "len", "(", "attrs", ")", ",", "nil", ")", "\n\n", "// Resolve all the attributes", "attrSpecs", ":=", "ResolveAttributes", "(", "f", ",", "attrs", ")", "\n\n", "// Get the results", "for", "i", ",", "a", ":=", "range", "attrSpecs", "{", "ret", ".", "Set", "(", "0", ",", "i", ",", "UnpackBytesToFloat", "(", "f", ".", "Get", "(", "a", ",", "r", ")", ")", ")", "\n", "}", "\n\n", "// Return the result", "return", "ret", ",", "nil", "\n", "}" ]
// ConvertRowToMat64 takes a list of Attributes, a FixedDataGrid // and a row number, and returns the float values of that row // in a mat.Dense format.
[ "ConvertRowToMat64", "takes", "a", "list", "of", "Attributes", "a", "FixedDataGrid", "and", "a", "row", "number", "and", "returns", "the", "float", "values", "of", "that", "row", "in", "a", "mat", ".", "Dense", "format", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/conversion.go#L22-L42
164,862
sjwhitworth/golearn
base/conversion.go
ConvertAllRowsToMat64
func ConvertAllRowsToMat64(attrs []Attribute, f FixedDataGrid) ([]*mat.Dense, error) { // Check for floats err := checkAllAttributesAreFloat(attrs) if err != nil { return nil, err } // Return value _, rows := f.Size() ret := make([]*mat.Dense, rows) // Resolve all attributes attrSpecs := ResolveAttributes(f, attrs) // Set the values in each return value for i := 0; i < rows; i++ { cur := mat.NewDense(1, len(attrs), nil) for j, a := range attrSpecs { cur.Set(0, j, UnpackBytesToFloat(f.Get(a, i))) } ret[i] = cur } return ret, nil }
go
func ConvertAllRowsToMat64(attrs []Attribute, f FixedDataGrid) ([]*mat.Dense, error) { // Check for floats err := checkAllAttributesAreFloat(attrs) if err != nil { return nil, err } // Return value _, rows := f.Size() ret := make([]*mat.Dense, rows) // Resolve all attributes attrSpecs := ResolveAttributes(f, attrs) // Set the values in each return value for i := 0; i < rows; i++ { cur := mat.NewDense(1, len(attrs), nil) for j, a := range attrSpecs { cur.Set(0, j, UnpackBytesToFloat(f.Get(a, i))) } ret[i] = cur } return ret, nil }
[ "func", "ConvertAllRowsToMat64", "(", "attrs", "[", "]", "Attribute", ",", "f", "FixedDataGrid", ")", "(", "[", "]", "*", "mat", ".", "Dense", ",", "error", ")", "{", "// Check for floats", "err", ":=", "checkAllAttributesAreFloat", "(", "attrs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Return value", "_", ",", "rows", ":=", "f", ".", "Size", "(", ")", "\n", "ret", ":=", "make", "(", "[", "]", "*", "mat", ".", "Dense", ",", "rows", ")", "\n\n", "// Resolve all attributes", "attrSpecs", ":=", "ResolveAttributes", "(", "f", ",", "attrs", ")", "\n\n", "// Set the values in each return value", "for", "i", ":=", "0", ";", "i", "<", "rows", ";", "i", "++", "{", "cur", ":=", "mat", ".", "NewDense", "(", "1", ",", "len", "(", "attrs", ")", ",", "nil", ")", "\n", "for", "j", ",", "a", ":=", "range", "attrSpecs", "{", "cur", ".", "Set", "(", "0", ",", "j", ",", "UnpackBytesToFloat", "(", "f", ".", "Get", "(", "a", ",", "i", ")", ")", ")", "\n", "}", "\n", "ret", "[", "i", "]", "=", "cur", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// ConvertAllRowsToMat64 takes a list of Attributes and returns a vector // of all rows in a mat.Dense format.
[ "ConvertAllRowsToMat64", "takes", "a", "list", "of", "Attributes", "and", "returns", "a", "vector", "of", "all", "rows", "in", "a", "mat", ".", "Dense", "format", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/conversion.go#L46-L70
164,863
sjwhitworth/golearn
base/csv.go
ParseCSVGetRowsFromReader
func ParseCSVGetRowsFromReader(r io.ReadSeeker) (int, error) { r.Seek(0, 0) reader := csv.NewReader(r) counter := 0 for { _, err := reader.Read() if err == io.EOF { break } else if err != nil { return 0, err } counter++ } return counter, nil }
go
func ParseCSVGetRowsFromReader(r io.ReadSeeker) (int, error) { r.Seek(0, 0) reader := csv.NewReader(r) counter := 0 for { _, err := reader.Read() if err == io.EOF { break } else if err != nil { return 0, err } counter++ } return counter, nil }
[ "func", "ParseCSVGetRowsFromReader", "(", "r", "io", ".", "ReadSeeker", ")", "(", "int", ",", "error", ")", "{", "r", ".", "Seek", "(", "0", ",", "0", ")", "\n", "reader", ":=", "csv", ".", "NewReader", "(", "r", ")", "\n", "counter", ":=", "0", "\n", "for", "{", "_", ",", "err", ":=", "reader", ".", "Read", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "counter", "++", "\n", "}", "\n", "return", "counter", ",", "nil", "\n", "}" ]
// ParseCSVGetRowsFromReader returns the number of rows in a given reader.
[ "ParseCSVGetRowsFromReader", "returns", "the", "number", "of", "rows", "in", "a", "given", "reader", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/csv.go#L14-L28
164,864
sjwhitworth/golearn
base/csv.go
ParseCSVEstimateFilePrecisionFromReader
func ParseCSVEstimateFilePrecisionFromReader(r io.ReadSeeker) (int, error) { // Creat a basic regexp rexp := regexp.MustCompile("[0-9]+(.[0-9]+)?") // Scan through the file line-by-line maxL := 0 r.Seek(0, 0) scanner := bufio.NewScanner(r) lineCount := 0 for scanner.Scan() { if lineCount > 5 { break } line := scanner.Text() if len(line) == 0 { continue } if line[0] == '@' { continue } if line[0] == '%' { continue } matches := rexp.FindAllString(line, -1) for _, m := range matches { p := strings.Split(m, ".") if len(p) == 2 { l := len(p[len(p)-1]) if l > maxL { maxL = l } } } lineCount++ } return maxL, nil }
go
func ParseCSVEstimateFilePrecisionFromReader(r io.ReadSeeker) (int, error) { // Creat a basic regexp rexp := regexp.MustCompile("[0-9]+(.[0-9]+)?") // Scan through the file line-by-line maxL := 0 r.Seek(0, 0) scanner := bufio.NewScanner(r) lineCount := 0 for scanner.Scan() { if lineCount > 5 { break } line := scanner.Text() if len(line) == 0 { continue } if line[0] == '@' { continue } if line[0] == '%' { continue } matches := rexp.FindAllString(line, -1) for _, m := range matches { p := strings.Split(m, ".") if len(p) == 2 { l := len(p[len(p)-1]) if l > maxL { maxL = l } } } lineCount++ } return maxL, nil }
[ "func", "ParseCSVEstimateFilePrecisionFromReader", "(", "r", "io", ".", "ReadSeeker", ")", "(", "int", ",", "error", ")", "{", "// Creat a basic regexp", "rexp", ":=", "regexp", ".", "MustCompile", "(", "\"", "\"", ")", "\n\n", "// Scan through the file line-by-line", "maxL", ":=", "0", "\n\n", "r", ".", "Seek", "(", "0", ",", "0", ")", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "r", ")", "\n", "lineCount", ":=", "0", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "if", "lineCount", ">", "5", "{", "break", "\n", "}", "\n", "line", ":=", "scanner", ".", "Text", "(", ")", "\n", "if", "len", "(", "line", ")", "==", "0", "{", "continue", "\n", "}", "\n", "if", "line", "[", "0", "]", "==", "'@'", "{", "continue", "\n", "}", "\n", "if", "line", "[", "0", "]", "==", "'%'", "{", "continue", "\n", "}", "\n", "matches", ":=", "rexp", ".", "FindAllString", "(", "line", ",", "-", "1", ")", "\n", "for", "_", ",", "m", ":=", "range", "matches", "{", "p", ":=", "strings", ".", "Split", "(", "m", ",", "\"", "\"", ")", "\n", "if", "len", "(", "p", ")", "==", "2", "{", "l", ":=", "len", "(", "p", "[", "len", "(", "p", ")", "-", "1", "]", ")", "\n", "if", "l", ">", "maxL", "{", "maxL", "=", "l", "\n", "}", "\n", "}", "\n", "}", "\n", "lineCount", "++", "\n", "}", "\n", "return", "maxL", ",", "nil", "\n", "}" ]
// ParseCSVEstimateFilePrecisionFromReader determines what the maximum number of // digits occuring anywhere after the decimal point within the reader.
[ "ParseCSVEstimateFilePrecisionFromReader", "determines", "what", "the", "maximum", "number", "of", "digits", "occuring", "anywhere", "after", "the", "decimal", "point", "within", "the", "reader", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/csv.go#L32-L69
164,865
sjwhitworth/golearn
base/csv.go
ParseCSVGetAttributesFromReader
func ParseCSVGetAttributesFromReader(r io.ReadSeeker, hasHeaders bool) []Attribute { attrs := ParseCSVSniffAttributeTypesFromReader(r, hasHeaders) names := ParseCSVSniffAttributeNamesFromReader(r, hasHeaders) for i, attr := range attrs { attr.SetName(names[i]) } return attrs }
go
func ParseCSVGetAttributesFromReader(r io.ReadSeeker, hasHeaders bool) []Attribute { attrs := ParseCSVSniffAttributeTypesFromReader(r, hasHeaders) names := ParseCSVSniffAttributeNamesFromReader(r, hasHeaders) for i, attr := range attrs { attr.SetName(names[i]) } return attrs }
[ "func", "ParseCSVGetAttributesFromReader", "(", "r", "io", ".", "ReadSeeker", ",", "hasHeaders", "bool", ")", "[", "]", "Attribute", "{", "attrs", ":=", "ParseCSVSniffAttributeTypesFromReader", "(", "r", ",", "hasHeaders", ")", "\n", "names", ":=", "ParseCSVSniffAttributeNamesFromReader", "(", "r", ",", "hasHeaders", ")", "\n", "for", "i", ",", "attr", ":=", "range", "attrs", "{", "attr", ".", "SetName", "(", "names", "[", "i", "]", ")", "\n", "}", "\n", "return", "attrs", "\n", "}" ]
// ParseCSVGetAttributesFromReader returns an ordered slice of appropriate-ly typed // and named Attributes.
[ "ParseCSVGetAttributesFromReader", "returns", "an", "ordered", "slice", "of", "appropriate", "-", "ly", "typed", "and", "named", "Attributes", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/csv.go#L73-L80
164,866
sjwhitworth/golearn
base/csv.go
ParseCSVSniffAttributeNamesFromReader
func ParseCSVSniffAttributeNamesFromReader(r io.ReadSeeker, hasHeaders bool) []string { r.Seek(0, 0) reader := csv.NewReader(r) headers, err := reader.Read() if err != nil { panic(err) } if hasHeaders { for i, h := range headers { headers[i] = strings.TrimSpace(h) } return headers } for i := range headers { headers[i] = fmt.Sprintf("%d", i) } return headers }
go
func ParseCSVSniffAttributeNamesFromReader(r io.ReadSeeker, hasHeaders bool) []string { r.Seek(0, 0) reader := csv.NewReader(r) headers, err := reader.Read() if err != nil { panic(err) } if hasHeaders { for i, h := range headers { headers[i] = strings.TrimSpace(h) } return headers } for i := range headers { headers[i] = fmt.Sprintf("%d", i) } return headers }
[ "func", "ParseCSVSniffAttributeNamesFromReader", "(", "r", "io", ".", "ReadSeeker", ",", "hasHeaders", "bool", ")", "[", "]", "string", "{", "r", ".", "Seek", "(", "0", ",", "0", ")", "\n", "reader", ":=", "csv", ".", "NewReader", "(", "r", ")", "\n", "headers", ",", "err", ":=", "reader", ".", "Read", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "if", "hasHeaders", "{", "for", "i", ",", "h", ":=", "range", "headers", "{", "headers", "[", "i", "]", "=", "strings", ".", "TrimSpace", "(", "h", ")", "\n", "}", "\n", "return", "headers", "\n", "}", "\n\n", "for", "i", ":=", "range", "headers", "{", "headers", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ")", "\n", "}", "\n", "return", "headers", "\n\n", "}" ]
// ParseCSVSniffAttributeNamesFromReader returns a slice containing the top row // of a given reader with CSV-contents, or placeholders if hasHeaders is false.
[ "ParseCSVSniffAttributeNamesFromReader", "returns", "a", "slice", "containing", "the", "top", "row", "of", "a", "given", "reader", "with", "CSV", "-", "contents", "or", "placeholders", "if", "hasHeaders", "is", "false", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/csv.go#L84-L105
164,867
sjwhitworth/golearn
base/csv.go
ParseCSVSniffAttributeTypesFromReader
func ParseCSVSniffAttributeTypesFromReader(r io.ReadSeeker, hasHeaders bool) []Attribute { var attrs []Attribute // Create the CSV reader r.Seek(0, 0) reader := csv.NewReader(r) if hasHeaders { // Skip the headers _, err := reader.Read() if err != nil { panic(err) } } // Read the first line of the file columns, err := reader.Read() if err != nil { panic(err) } for _, entry := range columns { // Match the Attribute type with regular expressions entry = strings.Trim(entry, " ") matched, err := regexp.MatchString("^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$", entry) if err != nil { panic(err) } if matched { attrs = append(attrs, NewFloatAttribute("")) } else { attrs = append(attrs, new(CategoricalAttribute)) } } // Estimate file precision maxP, err := ParseCSVEstimateFilePrecisionFromReader(r) if err != nil { panic(err) } for _, a := range attrs { if f, ok := a.(*FloatAttribute); ok { f.Precision = maxP } } return attrs }
go
func ParseCSVSniffAttributeTypesFromReader(r io.ReadSeeker, hasHeaders bool) []Attribute { var attrs []Attribute // Create the CSV reader r.Seek(0, 0) reader := csv.NewReader(r) if hasHeaders { // Skip the headers _, err := reader.Read() if err != nil { panic(err) } } // Read the first line of the file columns, err := reader.Read() if err != nil { panic(err) } for _, entry := range columns { // Match the Attribute type with regular expressions entry = strings.Trim(entry, " ") matched, err := regexp.MatchString("^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$", entry) if err != nil { panic(err) } if matched { attrs = append(attrs, NewFloatAttribute("")) } else { attrs = append(attrs, new(CategoricalAttribute)) } } // Estimate file precision maxP, err := ParseCSVEstimateFilePrecisionFromReader(r) if err != nil { panic(err) } for _, a := range attrs { if f, ok := a.(*FloatAttribute); ok { f.Precision = maxP } } return attrs }
[ "func", "ParseCSVSniffAttributeTypesFromReader", "(", "r", "io", ".", "ReadSeeker", ",", "hasHeaders", "bool", ")", "[", "]", "Attribute", "{", "var", "attrs", "[", "]", "Attribute", "\n\n", "// Create the CSV reader", "r", ".", "Seek", "(", "0", ",", "0", ")", "\n", "reader", ":=", "csv", ".", "NewReader", "(", "r", ")", "\n", "if", "hasHeaders", "{", "// Skip the headers", "_", ",", "err", ":=", "reader", ".", "Read", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "// Read the first line of the file", "columns", ",", "err", ":=", "reader", ".", "Read", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "entry", ":=", "range", "columns", "{", "// Match the Attribute type with regular expressions", "entry", "=", "strings", ".", "Trim", "(", "entry", ",", "\"", "\"", ")", "\n", "matched", ",", "err", ":=", "regexp", ".", "MatchString", "(", "\"", "\\\\", "\"", ",", "entry", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "if", "matched", "{", "attrs", "=", "append", "(", "attrs", ",", "NewFloatAttribute", "(", "\"", "\"", ")", ")", "\n", "}", "else", "{", "attrs", "=", "append", "(", "attrs", ",", "new", "(", "CategoricalAttribute", ")", ")", "\n", "}", "\n", "}", "\n\n", "// Estimate file precision", "maxP", ",", "err", ":=", "ParseCSVEstimateFilePrecisionFromReader", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "a", ":=", "range", "attrs", "{", "if", "f", ",", "ok", ":=", "a", ".", "(", "*", "FloatAttribute", ")", ";", "ok", "{", "f", ".", "Precision", "=", "maxP", "\n", "}", "\n", "}", "\n\n", "return", "attrs", "\n", "}" ]
// ParseCSVSniffAttributeTypesFromReader returns a slice of appropriately-typed Attributes. // // The type of a given attribute is determined by looking at the first data row // of the CSV.
[ "ParseCSVSniffAttributeTypesFromReader", "returns", "a", "slice", "of", "appropriately", "-", "typed", "Attributes", ".", "The", "type", "of", "a", "given", "attribute", "is", "determined", "by", "looking", "at", "the", "first", "data", "row", "of", "the", "CSV", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/csv.go#L111-L156
164,868
sjwhitworth/golearn
base/csv.go
ParseCSVToInstancesFromReader
func ParseCSVToInstancesFromReader(r io.ReadSeeker, hasHeaders bool) (instances *DenseInstances, err error) { // Read the number of rows in the file rowCount, err := ParseCSVGetRowsFromReader(r) if err != nil { return nil, err } if hasHeaders { rowCount-- } // Read the row headers attrs := ParseCSVGetAttributesFromReader(r, hasHeaders) specs := make([]AttributeSpec, len(attrs)) // Allocate the Instances to return instances = NewDenseInstances() for i, a := range attrs { spec := instances.AddAttribute(a) specs[i] = spec } instances.Extend(rowCount) err = ParseCSVBuildInstancesFromReader(r, attrs, hasHeaders, instances) if err != nil { return nil, err } instances.AddClassAttribute(attrs[len(attrs)-1]) return instances, nil }
go
func ParseCSVToInstancesFromReader(r io.ReadSeeker, hasHeaders bool) (instances *DenseInstances, err error) { // Read the number of rows in the file rowCount, err := ParseCSVGetRowsFromReader(r) if err != nil { return nil, err } if hasHeaders { rowCount-- } // Read the row headers attrs := ParseCSVGetAttributesFromReader(r, hasHeaders) specs := make([]AttributeSpec, len(attrs)) // Allocate the Instances to return instances = NewDenseInstances() for i, a := range attrs { spec := instances.AddAttribute(a) specs[i] = spec } instances.Extend(rowCount) err = ParseCSVBuildInstancesFromReader(r, attrs, hasHeaders, instances) if err != nil { return nil, err } instances.AddClassAttribute(attrs[len(attrs)-1]) return instances, nil }
[ "func", "ParseCSVToInstancesFromReader", "(", "r", "io", ".", "ReadSeeker", ",", "hasHeaders", "bool", ")", "(", "instances", "*", "DenseInstances", ",", "err", "error", ")", "{", "// Read the number of rows in the file", "rowCount", ",", "err", ":=", "ParseCSVGetRowsFromReader", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "hasHeaders", "{", "rowCount", "--", "\n", "}", "\n\n", "// Read the row headers", "attrs", ":=", "ParseCSVGetAttributesFromReader", "(", "r", ",", "hasHeaders", ")", "\n", "specs", ":=", "make", "(", "[", "]", "AttributeSpec", ",", "len", "(", "attrs", ")", ")", "\n", "// Allocate the Instances to return", "instances", "=", "NewDenseInstances", "(", ")", "\n", "for", "i", ",", "a", ":=", "range", "attrs", "{", "spec", ":=", "instances", ".", "AddAttribute", "(", "a", ")", "\n", "specs", "[", "i", "]", "=", "spec", "\n", "}", "\n", "instances", ".", "Extend", "(", "rowCount", ")", "\n\n", "err", "=", "ParseCSVBuildInstancesFromReader", "(", "r", ",", "attrs", ",", "hasHeaders", ",", "instances", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "instances", ".", "AddClassAttribute", "(", "attrs", "[", "len", "(", "attrs", ")", "-", "1", "]", ")", "\n\n", "return", "instances", ",", "nil", "\n", "}" ]
// ParseCSVToInstancesFromReader reads the reader containing CSV and returns // the read Instances.
[ "ParseCSVToInstancesFromReader", "reads", "the", "reader", "containing", "CSV", "and", "returns", "the", "read", "Instances", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/csv.go#L200-L230
164,869
sjwhitworth/golearn
base/csv.go
ParseMatchAttributes
func ParseMatchAttributes(attrs, templateAttrs []Attribute) { for i, a := range attrs { for _, b := range templateAttrs { if a.Equals(b) { attrs[i] = b } else if a.GetName() == b.GetName() { attrs[i] = b } } } }
go
func ParseMatchAttributes(attrs, templateAttrs []Attribute) { for i, a := range attrs { for _, b := range templateAttrs { if a.Equals(b) { attrs[i] = b } else if a.GetName() == b.GetName() { attrs[i] = b } } } }
[ "func", "ParseMatchAttributes", "(", "attrs", ",", "templateAttrs", "[", "]", "Attribute", ")", "{", "for", "i", ",", "a", ":=", "range", "attrs", "{", "for", "_", ",", "b", ":=", "range", "templateAttrs", "{", "if", "a", ".", "Equals", "(", "b", ")", "{", "attrs", "[", "i", "]", "=", "b", "\n", "}", "else", "if", "a", ".", "GetName", "(", ")", "==", "b", ".", "GetName", "(", ")", "{", "attrs", "[", "i", "]", "=", "b", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// ParseUtilsMatchAttrs tries to match the set of Attributes read from one file with // those read from another, and writes the matching Attributes back to the original set.
[ "ParseUtilsMatchAttrs", "tries", "to", "match", "the", "set", "of", "Attributes", "read", "from", "one", "file", "with", "those", "read", "from", "another", "and", "writes", "the", "matching", "Attributes", "back", "to", "the", "original", "set", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/csv.go#L234-L244
164,870
sjwhitworth/golearn
base/csv.go
ParseCSVToTemplatedInstancesFromReader
func ParseCSVToTemplatedInstancesFromReader(r io.ReadSeeker, hasHeaders bool, template *DenseInstances) (instances *DenseInstances, err error) { // Read the number of rows in the file rowCount, err := ParseCSVGetRowsFromReader(r) if err != nil { return nil, err } if hasHeaders { rowCount-- } // Read the row headers attrs := ParseCSVGetAttributesFromReader(r, hasHeaders) templateAttrs := template.AllAttributes() ParseMatchAttributes(attrs, templateAttrs) // Allocate the Instances to return instances = CopyDenseInstances(template, templateAttrs) instances.Extend(rowCount) err = ParseCSVBuildInstancesFromReader(r, attrs, hasHeaders, instances) if err != nil { return nil, err } for _, a := range template.AllClassAttributes() { err = instances.AddClassAttribute(a) if err != nil { return nil, err } } return instances, nil }
go
func ParseCSVToTemplatedInstancesFromReader(r io.ReadSeeker, hasHeaders bool, template *DenseInstances) (instances *DenseInstances, err error) { // Read the number of rows in the file rowCount, err := ParseCSVGetRowsFromReader(r) if err != nil { return nil, err } if hasHeaders { rowCount-- } // Read the row headers attrs := ParseCSVGetAttributesFromReader(r, hasHeaders) templateAttrs := template.AllAttributes() ParseMatchAttributes(attrs, templateAttrs) // Allocate the Instances to return instances = CopyDenseInstances(template, templateAttrs) instances.Extend(rowCount) err = ParseCSVBuildInstancesFromReader(r, attrs, hasHeaders, instances) if err != nil { return nil, err } for _, a := range template.AllClassAttributes() { err = instances.AddClassAttribute(a) if err != nil { return nil, err } } return instances, nil }
[ "func", "ParseCSVToTemplatedInstancesFromReader", "(", "r", "io", ".", "ReadSeeker", ",", "hasHeaders", "bool", ",", "template", "*", "DenseInstances", ")", "(", "instances", "*", "DenseInstances", ",", "err", "error", ")", "{", "// Read the number of rows in the file", "rowCount", ",", "err", ":=", "ParseCSVGetRowsFromReader", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "hasHeaders", "{", "rowCount", "--", "\n", "}", "\n\n", "// Read the row headers", "attrs", ":=", "ParseCSVGetAttributesFromReader", "(", "r", ",", "hasHeaders", ")", "\n", "templateAttrs", ":=", "template", ".", "AllAttributes", "(", ")", "\n", "ParseMatchAttributes", "(", "attrs", ",", "templateAttrs", ")", "\n\n", "// Allocate the Instances to return", "instances", "=", "CopyDenseInstances", "(", "template", ",", "templateAttrs", ")", "\n", "instances", ".", "Extend", "(", "rowCount", ")", "\n\n", "err", "=", "ParseCSVBuildInstancesFromReader", "(", "r", ",", "attrs", ",", "hasHeaders", ",", "instances", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "a", ":=", "range", "template", ".", "AllClassAttributes", "(", ")", "{", "err", "=", "instances", ".", "AddClassAttribute", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "instances", ",", "nil", "\n", "}" ]
// ParseCSVToTemplatedInstancesFromReader reads the reader containing CSV and returns // the read Instances, using another already read DenseInstances as a template.
[ "ParseCSVToTemplatedInstancesFromReader", "reads", "the", "reader", "containing", "CSV", "and", "returns", "the", "read", "Instances", "using", "another", "already", "read", "DenseInstances", "as", "a", "template", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/csv.go#L248-L281
164,871
sjwhitworth/golearn
base/csv.go
ParseCSVToInstancesWithAttributeGroupsFromReader
func ParseCSVToInstancesWithAttributeGroupsFromReader(r io.ReadSeeker, attrGroups, classAttrGroups map[string]string, attrOverrides map[int]Attribute, hasHeaders bool) (instances *DenseInstances, err error) { // Read row count rowCount, err := ParseCSVGetRowsFromReader(r) if err != nil { return nil, err } // Read the row headers attrs := ParseCSVGetAttributesFromReader(r, hasHeaders) for i := range attrs { if a, ok := attrOverrides[i]; ok { attrs[i] = a } } specs := make([]AttributeSpec, len(attrs)) // Allocate the Instances to return instances = NewDenseInstances() // // Create all AttributeGroups agsToCreate := make(map[string]int) combinedAgs := make(map[string]string) for a := range attrGroups { agsToCreate[attrGroups[a]] = 0 combinedAgs[a] = attrGroups[a] } for a := range classAttrGroups { agsToCreate[classAttrGroups[a]] = 8 combinedAgs[a] = classAttrGroups[a] } // Decide the sizes for _, a := range attrs { if ag, ok := combinedAgs[a.GetName()]; ok { if _, ok := a.(*BinaryAttribute); ok { agsToCreate[ag] = 0 } else { agsToCreate[ag] = 8 } } } // Create them for i := range agsToCreate { size := agsToCreate[i] err = instances.CreateAttributeGroup(i, size) if err != nil { panic(err) } } // Add the Attributes to them for i, a := range attrs { var spec AttributeSpec if ag, ok := combinedAgs[a.GetName()]; ok { spec, err = instances.AddAttributeToAttributeGroup(a, ag) if err != nil { panic(err) } specs[i] = spec } else { spec = instances.AddAttribute(a) } specs[i] = spec if _, ok := classAttrGroups[a.GetName()]; ok { err = instances.AddClassAttribute(a) if err != nil { panic(err) } } } // Allocate instances.Extend(rowCount) err = ParseCSVBuildInstancesFromReader(r, attrs, hasHeaders, instances) if err != nil { return nil, err } return instances, nil }
go
func ParseCSVToInstancesWithAttributeGroupsFromReader(r io.ReadSeeker, attrGroups, classAttrGroups map[string]string, attrOverrides map[int]Attribute, hasHeaders bool) (instances *DenseInstances, err error) { // Read row count rowCount, err := ParseCSVGetRowsFromReader(r) if err != nil { return nil, err } // Read the row headers attrs := ParseCSVGetAttributesFromReader(r, hasHeaders) for i := range attrs { if a, ok := attrOverrides[i]; ok { attrs[i] = a } } specs := make([]AttributeSpec, len(attrs)) // Allocate the Instances to return instances = NewDenseInstances() // // Create all AttributeGroups agsToCreate := make(map[string]int) combinedAgs := make(map[string]string) for a := range attrGroups { agsToCreate[attrGroups[a]] = 0 combinedAgs[a] = attrGroups[a] } for a := range classAttrGroups { agsToCreate[classAttrGroups[a]] = 8 combinedAgs[a] = classAttrGroups[a] } // Decide the sizes for _, a := range attrs { if ag, ok := combinedAgs[a.GetName()]; ok { if _, ok := a.(*BinaryAttribute); ok { agsToCreate[ag] = 0 } else { agsToCreate[ag] = 8 } } } // Create them for i := range agsToCreate { size := agsToCreate[i] err = instances.CreateAttributeGroup(i, size) if err != nil { panic(err) } } // Add the Attributes to them for i, a := range attrs { var spec AttributeSpec if ag, ok := combinedAgs[a.GetName()]; ok { spec, err = instances.AddAttributeToAttributeGroup(a, ag) if err != nil { panic(err) } specs[i] = spec } else { spec = instances.AddAttribute(a) } specs[i] = spec if _, ok := classAttrGroups[a.GetName()]; ok { err = instances.AddClassAttribute(a) if err != nil { panic(err) } } } // Allocate instances.Extend(rowCount) err = ParseCSVBuildInstancesFromReader(r, attrs, hasHeaders, instances) if err != nil { return nil, err } return instances, nil }
[ "func", "ParseCSVToInstancesWithAttributeGroupsFromReader", "(", "r", "io", ".", "ReadSeeker", ",", "attrGroups", ",", "classAttrGroups", "map", "[", "string", "]", "string", ",", "attrOverrides", "map", "[", "int", "]", "Attribute", ",", "hasHeaders", "bool", ")", "(", "instances", "*", "DenseInstances", ",", "err", "error", ")", "{", "// Read row count", "rowCount", ",", "err", ":=", "ParseCSVGetRowsFromReader", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Read the row headers", "attrs", ":=", "ParseCSVGetAttributesFromReader", "(", "r", ",", "hasHeaders", ")", "\n", "for", "i", ":=", "range", "attrs", "{", "if", "a", ",", "ok", ":=", "attrOverrides", "[", "i", "]", ";", "ok", "{", "attrs", "[", "i", "]", "=", "a", "\n", "}", "\n", "}", "\n\n", "specs", ":=", "make", "(", "[", "]", "AttributeSpec", ",", "len", "(", "attrs", ")", ")", "\n", "// Allocate the Instances to return", "instances", "=", "NewDenseInstances", "(", ")", "\n\n", "//", "// Create all AttributeGroups", "agsToCreate", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "combinedAgs", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "a", ":=", "range", "attrGroups", "{", "agsToCreate", "[", "attrGroups", "[", "a", "]", "]", "=", "0", "\n", "combinedAgs", "[", "a", "]", "=", "attrGroups", "[", "a", "]", "\n", "}", "\n", "for", "a", ":=", "range", "classAttrGroups", "{", "agsToCreate", "[", "classAttrGroups", "[", "a", "]", "]", "=", "8", "\n", "combinedAgs", "[", "a", "]", "=", "classAttrGroups", "[", "a", "]", "\n", "}", "\n\n", "// Decide the sizes", "for", "_", ",", "a", ":=", "range", "attrs", "{", "if", "ag", ",", "ok", ":=", "combinedAgs", "[", "a", ".", "GetName", "(", ")", "]", ";", "ok", "{", "if", "_", ",", "ok", ":=", "a", ".", "(", "*", "BinaryAttribute", ")", ";", "ok", "{", "agsToCreate", "[", "ag", "]", "=", "0", "\n", "}", "else", "{", "agsToCreate", "[", "ag", "]", "=", "8", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Create them", "for", "i", ":=", "range", "agsToCreate", "{", "size", ":=", "agsToCreate", "[", "i", "]", "\n", "err", "=", "instances", ".", "CreateAttributeGroup", "(", "i", ",", "size", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Add the Attributes to them", "for", "i", ",", "a", ":=", "range", "attrs", "{", "var", "spec", "AttributeSpec", "\n", "if", "ag", ",", "ok", ":=", "combinedAgs", "[", "a", ".", "GetName", "(", ")", "]", ";", "ok", "{", "spec", ",", "err", "=", "instances", ".", "AddAttributeToAttributeGroup", "(", "a", ",", "ag", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "specs", "[", "i", "]", "=", "spec", "\n", "}", "else", "{", "spec", "=", "instances", ".", "AddAttribute", "(", "a", ")", "\n", "}", "\n", "specs", "[", "i", "]", "=", "spec", "\n", "if", "_", ",", "ok", ":=", "classAttrGroups", "[", "a", ".", "GetName", "(", ")", "]", ";", "ok", "{", "err", "=", "instances", ".", "AddClassAttribute", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "// Allocate", "instances", ".", "Extend", "(", "rowCount", ")", "\n\n", "err", "=", "ParseCSVBuildInstancesFromReader", "(", "r", ",", "attrs", ",", "hasHeaders", ",", "instances", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "instances", ",", "nil", "\n\n", "}" ]
// ParseCSVToInstancesWithAttributeGroupsFromReader reads the CSV file given by filepath, // and returns the read DenseInstances, but also makes sure to group any Attributes // specified in the first argument and also any class Attributes specified in the second
[ "ParseCSVToInstancesWithAttributeGroupsFromReader", "reads", "the", "CSV", "file", "given", "by", "filepath", "and", "returns", "the", "read", "DenseInstances", "but", "also", "makes", "sure", "to", "group", "any", "Attributes", "specified", "in", "the", "first", "argument", "and", "also", "any", "class", "Attributes", "specified", "in", "the", "second" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/csv.go#L286-L368
164,872
sjwhitworth/golearn
filters/chimerge.go
NewChiMergeFilter
func NewChiMergeFilter(d base.FixedDataGrid, significance float64) *ChiMergeFilter { _, rows := d.Size() return &ChiMergeFilter{ AbstractDiscretizeFilter{ make(map[base.Attribute]bool), false, d, }, make(map[base.Attribute][]*FrequencyTableEntry), significance, 2, rows, } }
go
func NewChiMergeFilter(d base.FixedDataGrid, significance float64) *ChiMergeFilter { _, rows := d.Size() return &ChiMergeFilter{ AbstractDiscretizeFilter{ make(map[base.Attribute]bool), false, d, }, make(map[base.Attribute][]*FrequencyTableEntry), significance, 2, rows, } }
[ "func", "NewChiMergeFilter", "(", "d", "base", ".", "FixedDataGrid", ",", "significance", "float64", ")", "*", "ChiMergeFilter", "{", "_", ",", "rows", ":=", "d", ".", "Size", "(", ")", "\n", "return", "&", "ChiMergeFilter", "{", "AbstractDiscretizeFilter", "{", "make", "(", "map", "[", "base", ".", "Attribute", "]", "bool", ")", ",", "false", ",", "d", ",", "}", ",", "make", "(", "map", "[", "base", ".", "Attribute", "]", "[", "]", "*", "FrequencyTableEntry", ")", ",", "significance", ",", "2", ",", "rows", ",", "}", "\n", "}" ]
// NewChiMergeFilter creates a ChiMergeFilter with some helpful intialisations.
[ "NewChiMergeFilter", "creates", "a", "ChiMergeFilter", "with", "some", "helpful", "intialisations", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/filters/chimerge.go#L23-L36
164,873
sjwhitworth/golearn
filters/chimerge.go
Transform
func (c *ChiMergeFilter) Transform(a base.Attribute, n base.Attribute, field []byte) []byte { // Do we use this Attribute? if !c.attrs[a] { return field } // Find the Attribute value in the table table := c.tables[a] dis := 0 val := base.UnpackBytesToFloat(field) for j, k := range table { if k.Value < val { dis = j continue } break } return base.PackU64ToBytes(uint64(dis)) }
go
func (c *ChiMergeFilter) Transform(a base.Attribute, n base.Attribute, field []byte) []byte { // Do we use this Attribute? if !c.attrs[a] { return field } // Find the Attribute value in the table table := c.tables[a] dis := 0 val := base.UnpackBytesToFloat(field) for j, k := range table { if k.Value < val { dis = j continue } break } return base.PackU64ToBytes(uint64(dis)) }
[ "func", "(", "c", "*", "ChiMergeFilter", ")", "Transform", "(", "a", "base", ".", "Attribute", ",", "n", "base", ".", "Attribute", ",", "field", "[", "]", "byte", ")", "[", "]", "byte", "{", "// Do we use this Attribute?", "if", "!", "c", ".", "attrs", "[", "a", "]", "{", "return", "field", "\n", "}", "\n", "// Find the Attribute value in the table", "table", ":=", "c", ".", "tables", "[", "a", "]", "\n", "dis", ":=", "0", "\n", "val", ":=", "base", ".", "UnpackBytesToFloat", "(", "field", ")", "\n", "for", "j", ",", "k", ":=", "range", "table", "{", "if", "k", ".", "Value", "<", "val", "{", "dis", "=", "j", "\n", "continue", "\n", "}", "\n", "break", "\n", "}", "\n\n", "return", "base", ".", "PackU64ToBytes", "(", "uint64", "(", "dis", ")", ")", "\n", "}" ]
// Transform returns the byte sequence after discretisation
[ "Transform", "returns", "the", "byte", "sequence", "after", "discretisation" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/filters/chimerge.go#L166-L184
164,874
sjwhitworth/golearn
kdtree/heap.go
maximum
func (h *heap) maximum() heapNode { if len(h.tree) == 0 { return heapNode{} } return h.tree[0] }
go
func (h *heap) maximum() heapNode { if len(h.tree) == 0 { return heapNode{} } return h.tree[0] }
[ "func", "(", "h", "*", "heap", ")", "maximum", "(", ")", "heapNode", "{", "if", "len", "(", "h", ".", "tree", ")", "==", "0", "{", "return", "heapNode", "{", "}", "\n", "}", "\n\n", "return", "h", ".", "tree", "[", "0", "]", "\n", "}" ]
// maximum return the max heapNode in the heap.
[ "maximum", "return", "the", "max", "heapNode", "in", "the", "heap", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/kdtree/heap.go#L21-L27
164,875
sjwhitworth/golearn
kdtree/heap.go
extractMax
func (h *heap) extractMax() { if len(h.tree) == 0 { return } h.tree[0] = h.tree[len(h.tree)-1] h.tree = h.tree[:len(h.tree)-1] target := 1 for true { largest := target if target*2-1 >= len(h.tree) { break } if h.tree[target*2-1].length > h.tree[target-1].length { largest = target * 2 } if target*2 < len(h.tree) { if h.tree[target*2].length > h.tree[largest-1].length { largest = target*2 + 1 } } if largest == target { break } h.tree[largest-1], h.tree[target-1] = h.tree[target-1], h.tree[largest-1] target = largest } }
go
func (h *heap) extractMax() { if len(h.tree) == 0 { return } h.tree[0] = h.tree[len(h.tree)-1] h.tree = h.tree[:len(h.tree)-1] target := 1 for true { largest := target if target*2-1 >= len(h.tree) { break } if h.tree[target*2-1].length > h.tree[target-1].length { largest = target * 2 } if target*2 < len(h.tree) { if h.tree[target*2].length > h.tree[largest-1].length { largest = target*2 + 1 } } if largest == target { break } h.tree[largest-1], h.tree[target-1] = h.tree[target-1], h.tree[largest-1] target = largest } }
[ "func", "(", "h", "*", "heap", ")", "extractMax", "(", ")", "{", "if", "len", "(", "h", ".", "tree", ")", "==", "0", "{", "return", "\n", "}", "\n\n", "h", ".", "tree", "[", "0", "]", "=", "h", ".", "tree", "[", "len", "(", "h", ".", "tree", ")", "-", "1", "]", "\n", "h", ".", "tree", "=", "h", ".", "tree", "[", ":", "len", "(", "h", ".", "tree", ")", "-", "1", "]", "\n\n", "target", ":=", "1", "\n", "for", "true", "{", "largest", ":=", "target", "\n", "if", "target", "*", "2", "-", "1", ">=", "len", "(", "h", ".", "tree", ")", "{", "break", "\n", "}", "\n", "if", "h", ".", "tree", "[", "target", "*", "2", "-", "1", "]", ".", "length", ">", "h", ".", "tree", "[", "target", "-", "1", "]", ".", "length", "{", "largest", "=", "target", "*", "2", "\n", "}", "\n\n", "if", "target", "*", "2", "<", "len", "(", "h", ".", "tree", ")", "{", "if", "h", ".", "tree", "[", "target", "*", "2", "]", ".", "length", ">", "h", ".", "tree", "[", "largest", "-", "1", "]", ".", "length", "{", "largest", "=", "target", "*", "2", "+", "1", "\n", "}", "\n", "}", "\n\n", "if", "largest", "==", "target", "{", "break", "\n", "}", "\n", "h", ".", "tree", "[", "largest", "-", "1", "]", ",", "h", ".", "tree", "[", "target", "-", "1", "]", "=", "h", ".", "tree", "[", "target", "-", "1", "]", ",", "h", ".", "tree", "[", "largest", "-", "1", "]", "\n", "target", "=", "largest", "\n", "}", "\n", "}" ]
// extractMax remove the Max heapNode in the heap.
[ "extractMax", "remove", "the", "Max", "heapNode", "in", "the", "heap", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/kdtree/heap.go#L30-L60
164,876
sjwhitworth/golearn
kdtree/heap.go
insert
func (h *heap) insert(value []float64, length float64, srcRowNo int) { node := heapNode{} node.length = length node.srcRowNo = srcRowNo node.value = make([]float64, len(value)) copy(node.value, value) h.tree = append(h.tree, node) target := len(h.tree) for target != 1 { if h.tree[(target/2)-1].length >= h.tree[target-1].length { break } h.tree[target-1], h.tree[(target/2)-1] = h.tree[(target/2)-1], h.tree[target-1] target /= 2 } }
go
func (h *heap) insert(value []float64, length float64, srcRowNo int) { node := heapNode{} node.length = length node.srcRowNo = srcRowNo node.value = make([]float64, len(value)) copy(node.value, value) h.tree = append(h.tree, node) target := len(h.tree) for target != 1 { if h.tree[(target/2)-1].length >= h.tree[target-1].length { break } h.tree[target-1], h.tree[(target/2)-1] = h.tree[(target/2)-1], h.tree[target-1] target /= 2 } }
[ "func", "(", "h", "*", "heap", ")", "insert", "(", "value", "[", "]", "float64", ",", "length", "float64", ",", "srcRowNo", "int", ")", "{", "node", ":=", "heapNode", "{", "}", "\n", "node", ".", "length", "=", "length", "\n", "node", ".", "srcRowNo", "=", "srcRowNo", "\n", "node", ".", "value", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "value", ")", ")", "\n", "copy", "(", "node", ".", "value", ",", "value", ")", "\n", "h", ".", "tree", "=", "append", "(", "h", ".", "tree", ",", "node", ")", "\n\n", "target", ":=", "len", "(", "h", ".", "tree", ")", "\n", "for", "target", "!=", "1", "{", "if", "h", ".", "tree", "[", "(", "target", "/", "2", ")", "-", "1", "]", ".", "length", ">=", "h", ".", "tree", "[", "target", "-", "1", "]", ".", "length", "{", "break", "\n", "}", "\n", "h", ".", "tree", "[", "target", "-", "1", "]", ",", "h", ".", "tree", "[", "(", "target", "/", "2", ")", "-", "1", "]", "=", "h", ".", "tree", "[", "(", "target", "/", "2", ")", "-", "1", "]", ",", "h", ".", "tree", "[", "target", "-", "1", "]", "\n", "target", "/=", "2", "\n", "}", "\n", "}" ]
// insert put a new heapNode into heap.
[ "insert", "put", "a", "new", "heapNode", "into", "heap", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/kdtree/heap.go#L63-L79
164,877
sjwhitworth/golearn
trees/gini.go
computeGini
func computeGini(s map[string]int) float64 { // Compute probability map p := make(map[string]float64) for i := range s { if p[i] == 0 { continue } p[i] = 1.0 / float64(p[i]) } // Compute overall sum sum := 0.0 for i := range p { sum += p[i] * p[i] } return 1.0 - sum }
go
func computeGini(s map[string]int) float64 { // Compute probability map p := make(map[string]float64) for i := range s { if p[i] == 0 { continue } p[i] = 1.0 / float64(p[i]) } // Compute overall sum sum := 0.0 for i := range p { sum += p[i] * p[i] } return 1.0 - sum }
[ "func", "computeGini", "(", "s", "map", "[", "string", "]", "int", ")", "float64", "{", "// Compute probability map", "p", ":=", "make", "(", "map", "[", "string", "]", "float64", ")", "\n", "for", "i", ":=", "range", "s", "{", "if", "p", "[", "i", "]", "==", "0", "{", "continue", "\n", "}", "\n", "p", "[", "i", "]", "=", "1.0", "/", "float64", "(", "p", "[", "i", "]", ")", "\n", "}", "\n", "// Compute overall sum", "sum", ":=", "0.0", "\n", "for", "i", ":=", "range", "p", "{", "sum", "+=", "p", "[", "i", "]", "*", "p", "[", "i", "]", "\n", "}", "\n\n", "return", "1.0", "-", "sum", "\n", "}" ]
// // Utility functions // // computeGini computes the Gini impurity measure
[ "Utility", "functions", "computeGini", "computes", "the", "Gini", "impurity", "measure" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/gini.go#L72-L88
164,878
sjwhitworth/golearn
trees/gini.go
computeAverageGiniIndex
func computeAverageGiniIndex(s map[string]map[string]int) float64 { // Figure out the total number of things in this map total := 0 for i := range s { for j := range s[i] { total += s[i][j] } } sum := 0.0 for i := range s { subtotal := 0.0 for j := range s[i] { subtotal += float64(s[i][j]) } cf := subtotal / float64(total) cf *= computeGini(s[i]) sum += cf } return sum }
go
func computeAverageGiniIndex(s map[string]map[string]int) float64 { // Figure out the total number of things in this map total := 0 for i := range s { for j := range s[i] { total += s[i][j] } } sum := 0.0 for i := range s { subtotal := 0.0 for j := range s[i] { subtotal += float64(s[i][j]) } cf := subtotal / float64(total) cf *= computeGini(s[i]) sum += cf } return sum }
[ "func", "computeAverageGiniIndex", "(", "s", "map", "[", "string", "]", "map", "[", "string", "]", "int", ")", "float64", "{", "// Figure out the total number of things in this map", "total", ":=", "0", "\n", "for", "i", ":=", "range", "s", "{", "for", "j", ":=", "range", "s", "[", "i", "]", "{", "total", "+=", "s", "[", "i", "]", "[", "j", "]", "\n", "}", "\n", "}", "\n\n", "sum", ":=", "0.0", "\n", "for", "i", ":=", "range", "s", "{", "subtotal", ":=", "0.0", "\n", "for", "j", ":=", "range", "s", "[", "i", "]", "{", "subtotal", "+=", "float64", "(", "s", "[", "i", "]", "[", "j", "]", ")", "\n", "}", "\n", "cf", ":=", "subtotal", "/", "float64", "(", "total", ")", "\n", "cf", "*=", "computeGini", "(", "s", "[", "i", "]", ")", "\n", "sum", "+=", "cf", "\n", "}", "\n", "return", "sum", "\n", "}" ]
// computeGiniImpurity computes the average Gini index of a // proposed split
[ "computeGiniImpurity", "computes", "the", "average", "Gini", "index", "of", "a", "proposed", "split" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/gini.go#L92-L113
164,879
sjwhitworth/golearn
trees/id3.go
String
func (d *DecisionTreeRule) String() string { if d.SplitAttr == nil { return fmt.Sprintf("INVALID:DecisionTreeRule(SplitAttr is nil)") } if _, ok := d.SplitAttr.(*base.FloatAttribute); ok { return fmt.Sprintf("DecisionTreeRule(%s <= %f)", d.SplitAttr.GetName(), d.SplitVal) } return fmt.Sprintf("DecisionTreeRule(%s)", d.SplitAttr.GetName()) }
go
func (d *DecisionTreeRule) String() string { if d.SplitAttr == nil { return fmt.Sprintf("INVALID:DecisionTreeRule(SplitAttr is nil)") } if _, ok := d.SplitAttr.(*base.FloatAttribute); ok { return fmt.Sprintf("DecisionTreeRule(%s <= %f)", d.SplitAttr.GetName(), d.SplitVal) } return fmt.Sprintf("DecisionTreeRule(%s)", d.SplitAttr.GetName()) }
[ "func", "(", "d", "*", "DecisionTreeRule", ")", "String", "(", ")", "string", "{", "if", "d", ".", "SplitAttr", "==", "nil", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "d", ".", "SplitAttr", ".", "(", "*", "base", ".", "FloatAttribute", ")", ";", "ok", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "d", ".", "SplitAttr", ".", "GetName", "(", ")", ",", "d", ".", "SplitVal", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "d", ".", "SplitAttr", ".", "GetName", "(", ")", ")", "\n", "}" ]
// String prints a human-readable summary of this thing.
[ "String", "prints", "a", "human", "-", "readable", "summary", "of", "this", "thing", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/id3.go#L91-L101
164,880
sjwhitworth/golearn
trees/id3.go
Save
func (d *DecisionTreeNode) Save(filePath string) error { metadata := base.ClassifierMetadataV1{ FormatVersion: 1, ClassifierName: "test", ClassifierVersion: "1", } serializer, err := base.CreateSerializedClassifierStub(filePath, metadata) if err != nil { return err } err = d.SaveWithPrefix(serializer, "") if err != nil { return err } return serializer.Close() }
go
func (d *DecisionTreeNode) Save(filePath string) error { metadata := base.ClassifierMetadataV1{ FormatVersion: 1, ClassifierName: "test", ClassifierVersion: "1", } serializer, err := base.CreateSerializedClassifierStub(filePath, metadata) if err != nil { return err } err = d.SaveWithPrefix(serializer, "") if err != nil { return err } return serializer.Close() }
[ "func", "(", "d", "*", "DecisionTreeNode", ")", "Save", "(", "filePath", "string", ")", "error", "{", "metadata", ":=", "base", ".", "ClassifierMetadataV1", "{", "FormatVersion", ":", "1", ",", "ClassifierName", ":", "\"", "\"", ",", "ClassifierVersion", ":", "\"", "\"", ",", "}", "\n", "serializer", ",", "err", ":=", "base", ".", "CreateSerializedClassifierStub", "(", "filePath", ",", "metadata", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "d", ".", "SaveWithPrefix", "(", "serializer", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "serializer", ".", "Close", "(", ")", "\n", "}" ]
// Save sends the classification tree to an output file
[ "Save", "sends", "the", "classification", "tree", "to", "an", "output", "file" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/id3.go#L119-L134
164,881
sjwhitworth/golearn
trees/id3.go
Load
func (d *DecisionTreeNode) Load(filePath string) error { reader, err := base.ReadSerializedClassifierStub(filePath) if err != nil { return err } return d.LoadWithPrefix(reader, "") }
go
func (d *DecisionTreeNode) Load(filePath string) error { reader, err := base.ReadSerializedClassifierStub(filePath) if err != nil { return err } return d.LoadWithPrefix(reader, "") }
[ "func", "(", "d", "*", "DecisionTreeNode", ")", "Load", "(", "filePath", "string", ")", "error", "{", "reader", ",", "err", ":=", "base", ".", "ReadSerializedClassifierStub", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "d", ".", "LoadWithPrefix", "(", "reader", ",", "\"", "\"", ")", "\n", "}" ]
// Load reads from the classifier from an output file
[ "Load", "reads", "from", "the", "classifier", "from", "an", "output", "file" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/id3.go#L155-L163
164,882
sjwhitworth/golearn
trees/id3.go
LoadWithPrefix
func (d *DecisionTreeNode) LoadWithPrefix(reader *base.ClassifierDeserializer, prefix string) error { b, err := reader.GetBytesForKey(reader.Prefix(prefix, "tree")) if err != nil { return err } err = json.Unmarshal(b, d) if err != nil { return err } a, err := reader.GetAttributeForKey(reader.Prefix(prefix, "treeClassAttr")) if err != nil { return err } d.ClassAttr = a return nil }
go
func (d *DecisionTreeNode) LoadWithPrefix(reader *base.ClassifierDeserializer, prefix string) error { b, err := reader.GetBytesForKey(reader.Prefix(prefix, "tree")) if err != nil { return err } err = json.Unmarshal(b, d) if err != nil { return err } a, err := reader.GetAttributeForKey(reader.Prefix(prefix, "treeClassAttr")) if err != nil { return err } d.ClassAttr = a return nil }
[ "func", "(", "d", "*", "DecisionTreeNode", ")", "LoadWithPrefix", "(", "reader", "*", "base", ".", "ClassifierDeserializer", ",", "prefix", "string", ")", "error", "{", "b", ",", "err", ":=", "reader", ".", "GetBytesForKey", "(", "reader", ".", "Prefix", "(", "prefix", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "b", ",", "d", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "a", ",", "err", ":=", "reader", ".", "GetAttributeForKey", "(", "reader", ".", "Prefix", "(", "prefix", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "d", ".", "ClassAttr", "=", "a", "\n\n", "return", "nil", "\n", "}" ]
// LoadWithPrefix reads from the classifier from part of another model
[ "LoadWithPrefix", "reads", "from", "the", "classifier", "from", "part", "of", "another", "model" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/id3.go#L166-L186
164,883
sjwhitworth/golearn
trees/id3.go
Prune
func (d *DecisionTreeNode) Prune(using base.FixedDataGrid) { // If you're a leaf, you're already pruned if d.Children == nil { return } if d.SplitRule == nil { return } // Recursively prune children of this node sub := base.DecomposeOnAttributeValues(using, d.SplitRule.SplitAttr) for k := range d.Children { if sub[k] == nil { continue } subH, subV := sub[k].Size() if subH == 0 || subV == 0 { continue } d.Children[k].Prune(sub[k]) } // Get a baseline accuracy predictions, _ := d.Predict(using) baselineAccuracy := computeAccuracy(predictions, using) // Speculatively remove the children and re-evaluate tmpChildren := d.Children d.Children = nil predictions, _ = d.Predict(using) newAccuracy := computeAccuracy(predictions, using) // Keep the children removed if better, else restore if newAccuracy < baselineAccuracy { d.Children = tmpChildren } }
go
func (d *DecisionTreeNode) Prune(using base.FixedDataGrid) { // If you're a leaf, you're already pruned if d.Children == nil { return } if d.SplitRule == nil { return } // Recursively prune children of this node sub := base.DecomposeOnAttributeValues(using, d.SplitRule.SplitAttr) for k := range d.Children { if sub[k] == nil { continue } subH, subV := sub[k].Size() if subH == 0 || subV == 0 { continue } d.Children[k].Prune(sub[k]) } // Get a baseline accuracy predictions, _ := d.Predict(using) baselineAccuracy := computeAccuracy(predictions, using) // Speculatively remove the children and re-evaluate tmpChildren := d.Children d.Children = nil predictions, _ = d.Predict(using) newAccuracy := computeAccuracy(predictions, using) // Keep the children removed if better, else restore if newAccuracy < baselineAccuracy { d.Children = tmpChildren } }
[ "func", "(", "d", "*", "DecisionTreeNode", ")", "Prune", "(", "using", "base", ".", "FixedDataGrid", ")", "{", "// If you're a leaf, you're already pruned", "if", "d", ".", "Children", "==", "nil", "{", "return", "\n", "}", "\n", "if", "d", ".", "SplitRule", "==", "nil", "{", "return", "\n", "}", "\n\n", "// Recursively prune children of this node", "sub", ":=", "base", ".", "DecomposeOnAttributeValues", "(", "using", ",", "d", ".", "SplitRule", ".", "SplitAttr", ")", "\n", "for", "k", ":=", "range", "d", ".", "Children", "{", "if", "sub", "[", "k", "]", "==", "nil", "{", "continue", "\n", "}", "\n", "subH", ",", "subV", ":=", "sub", "[", "k", "]", ".", "Size", "(", ")", "\n", "if", "subH", "==", "0", "||", "subV", "==", "0", "{", "continue", "\n", "}", "\n", "d", ".", "Children", "[", "k", "]", ".", "Prune", "(", "sub", "[", "k", "]", ")", "\n", "}", "\n\n", "// Get a baseline accuracy", "predictions", ",", "_", ":=", "d", ".", "Predict", "(", "using", ")", "\n", "baselineAccuracy", ":=", "computeAccuracy", "(", "predictions", ",", "using", ")", "\n\n", "// Speculatively remove the children and re-evaluate", "tmpChildren", ":=", "d", ".", "Children", "\n", "d", ".", "Children", "=", "nil", "\n\n", "predictions", ",", "_", "=", "d", ".", "Predict", "(", "using", ")", "\n", "newAccuracy", ":=", "computeAccuracy", "(", "predictions", ",", "using", ")", "\n\n", "// Keep the children removed if better, else restore", "if", "newAccuracy", "<", "baselineAccuracy", "{", "d", ".", "Children", "=", "tmpChildren", "\n", "}", "\n", "}" ]
// Prune eliminates branches which hurt accuracy
[ "Prune", "eliminates", "branches", "which", "hurt", "accuracy" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/id3.go#L315-L352
164,884
sjwhitworth/golearn
trees/id3.go
Predict
func (d *DecisionTreeNode) Predict(what base.FixedDataGrid) (base.FixedDataGrid, error) { predictions := base.GeneratePredictionVector(what) classAttr := getClassAttr(predictions) classAttrSpec, err := predictions.GetAttribute(classAttr) if err != nil { panic(err) } predAttrs := base.AttributeDifferenceReferences(what.AllAttributes(), predictions.AllClassAttributes()) predAttrSpecs := base.ResolveAttributes(what, predAttrs) what.MapOverRows(predAttrSpecs, func(row [][]byte, rowNo int) (bool, error) { cur := d for { if cur.Children == nil { predictions.Set(classAttrSpec, rowNo, classAttr.GetSysValFromString(cur.Class)) break } else { splitVal := cur.SplitRule.SplitVal at := cur.SplitRule.SplitAttr ats, err := what.GetAttribute(at) if err != nil { //predictions.Set(classAttrSpec, rowNo, classAttr.GetSysValFromString(cur.Class)) //break panic(err) } var classVar string if _, ok := ats.GetAttribute().(*base.FloatAttribute); ok { // If it's a numeric Attribute (e.g. FloatAttribute) check that // the value of the current node is greater than the old one classVal := base.UnpackBytesToFloat(what.Get(ats, rowNo)) if classVal > splitVal { classVar = "1" } else { classVar = "0" } } else { classVar = ats.GetAttribute().GetStringFromSysVal(what.Get(ats, rowNo)) } if next, ok := cur.Children[classVar]; ok { cur = next } else { // Suspicious of this var bestChild string for c := range cur.Children { bestChild = c if c > classVar { break } } cur = cur.Children[bestChild] } } } return true, nil }) return predictions, nil }
go
func (d *DecisionTreeNode) Predict(what base.FixedDataGrid) (base.FixedDataGrid, error) { predictions := base.GeneratePredictionVector(what) classAttr := getClassAttr(predictions) classAttrSpec, err := predictions.GetAttribute(classAttr) if err != nil { panic(err) } predAttrs := base.AttributeDifferenceReferences(what.AllAttributes(), predictions.AllClassAttributes()) predAttrSpecs := base.ResolveAttributes(what, predAttrs) what.MapOverRows(predAttrSpecs, func(row [][]byte, rowNo int) (bool, error) { cur := d for { if cur.Children == nil { predictions.Set(classAttrSpec, rowNo, classAttr.GetSysValFromString(cur.Class)) break } else { splitVal := cur.SplitRule.SplitVal at := cur.SplitRule.SplitAttr ats, err := what.GetAttribute(at) if err != nil { //predictions.Set(classAttrSpec, rowNo, classAttr.GetSysValFromString(cur.Class)) //break panic(err) } var classVar string if _, ok := ats.GetAttribute().(*base.FloatAttribute); ok { // If it's a numeric Attribute (e.g. FloatAttribute) check that // the value of the current node is greater than the old one classVal := base.UnpackBytesToFloat(what.Get(ats, rowNo)) if classVal > splitVal { classVar = "1" } else { classVar = "0" } } else { classVar = ats.GetAttribute().GetStringFromSysVal(what.Get(ats, rowNo)) } if next, ok := cur.Children[classVar]; ok { cur = next } else { // Suspicious of this var bestChild string for c := range cur.Children { bestChild = c if c > classVar { break } } cur = cur.Children[bestChild] } } } return true, nil }) return predictions, nil }
[ "func", "(", "d", "*", "DecisionTreeNode", ")", "Predict", "(", "what", "base", ".", "FixedDataGrid", ")", "(", "base", ".", "FixedDataGrid", ",", "error", ")", "{", "predictions", ":=", "base", ".", "GeneratePredictionVector", "(", "what", ")", "\n", "classAttr", ":=", "getClassAttr", "(", "predictions", ")", "\n", "classAttrSpec", ",", "err", ":=", "predictions", ".", "GetAttribute", "(", "classAttr", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "predAttrs", ":=", "base", ".", "AttributeDifferenceReferences", "(", "what", ".", "AllAttributes", "(", ")", ",", "predictions", ".", "AllClassAttributes", "(", ")", ")", "\n", "predAttrSpecs", ":=", "base", ".", "ResolveAttributes", "(", "what", ",", "predAttrs", ")", "\n", "what", ".", "MapOverRows", "(", "predAttrSpecs", ",", "func", "(", "row", "[", "]", "[", "]", "byte", ",", "rowNo", "int", ")", "(", "bool", ",", "error", ")", "{", "cur", ":=", "d", "\n", "for", "{", "if", "cur", ".", "Children", "==", "nil", "{", "predictions", ".", "Set", "(", "classAttrSpec", ",", "rowNo", ",", "classAttr", ".", "GetSysValFromString", "(", "cur", ".", "Class", ")", ")", "\n", "break", "\n", "}", "else", "{", "splitVal", ":=", "cur", ".", "SplitRule", ".", "SplitVal", "\n", "at", ":=", "cur", ".", "SplitRule", ".", "SplitAttr", "\n", "ats", ",", "err", ":=", "what", ".", "GetAttribute", "(", "at", ")", "\n", "if", "err", "!=", "nil", "{", "//predictions.Set(classAttrSpec, rowNo, classAttr.GetSysValFromString(cur.Class))", "//break", "panic", "(", "err", ")", "\n", "}", "\n\n", "var", "classVar", "string", "\n", "if", "_", ",", "ok", ":=", "ats", ".", "GetAttribute", "(", ")", ".", "(", "*", "base", ".", "FloatAttribute", ")", ";", "ok", "{", "// If it's a numeric Attribute (e.g. FloatAttribute) check that", "// the value of the current node is greater than the old one", "classVal", ":=", "base", ".", "UnpackBytesToFloat", "(", "what", ".", "Get", "(", "ats", ",", "rowNo", ")", ")", "\n", "if", "classVal", ">", "splitVal", "{", "classVar", "=", "\"", "\"", "\n", "}", "else", "{", "classVar", "=", "\"", "\"", "\n", "}", "\n", "}", "else", "{", "classVar", "=", "ats", ".", "GetAttribute", "(", ")", ".", "GetStringFromSysVal", "(", "what", ".", "Get", "(", "ats", ",", "rowNo", ")", ")", "\n", "}", "\n", "if", "next", ",", "ok", ":=", "cur", ".", "Children", "[", "classVar", "]", ";", "ok", "{", "cur", "=", "next", "\n", "}", "else", "{", "// Suspicious of this", "var", "bestChild", "string", "\n", "for", "c", ":=", "range", "cur", ".", "Children", "{", "bestChild", "=", "c", "\n", "if", "c", ">", "classVar", "{", "break", "\n", "}", "\n", "}", "\n", "cur", "=", "cur", ".", "Children", "[", "bestChild", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}", ")", "\n", "return", "predictions", ",", "nil", "\n", "}" ]
// Predict outputs a base.Instances containing predictions from this tree
[ "Predict", "outputs", "a", "base", ".", "Instances", "containing", "predictions", "from", "this", "tree" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/id3.go#L355-L411
164,885
sjwhitworth/golearn
trees/id3.go
NewID3DecisionTree
func NewID3DecisionTree(prune float64) *ID3DecisionTree { return &ID3DecisionTree{ base.BaseClassifier{}, nil, prune, new(InformationGainRuleGenerator), } }
go
func NewID3DecisionTree(prune float64) *ID3DecisionTree { return &ID3DecisionTree{ base.BaseClassifier{}, nil, prune, new(InformationGainRuleGenerator), } }
[ "func", "NewID3DecisionTree", "(", "prune", "float64", ")", "*", "ID3DecisionTree", "{", "return", "&", "ID3DecisionTree", "{", "base", ".", "BaseClassifier", "{", "}", ",", "nil", ",", "prune", ",", "new", "(", "InformationGainRuleGenerator", ")", ",", "}", "\n", "}" ]
// NewID3DecisionTree returns a new ID3DecisionTree with the specified test-prune // ratio and InformationGain as the rule generator. // If the ratio is less than 0.001, the tree isn't pruned.
[ "NewID3DecisionTree", "returns", "a", "new", "ID3DecisionTree", "with", "the", "specified", "test", "-", "prune", "ratio", "and", "InformationGain", "as", "the", "rule", "generator", ".", "If", "the", "ratio", "is", "less", "than", "0", ".", "001", "the", "tree", "isn", "t", "pruned", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/id3.go#L516-L523
164,886
sjwhitworth/golearn
trees/id3.go
NewID3DecisionTreeFromRule
func NewID3DecisionTreeFromRule(prune float64, rule RuleGenerator) *ID3DecisionTree { return &ID3DecisionTree{ base.BaseClassifier{}, nil, prune, rule, } }
go
func NewID3DecisionTreeFromRule(prune float64, rule RuleGenerator) *ID3DecisionTree { return &ID3DecisionTree{ base.BaseClassifier{}, nil, prune, rule, } }
[ "func", "NewID3DecisionTreeFromRule", "(", "prune", "float64", ",", "rule", "RuleGenerator", ")", "*", "ID3DecisionTree", "{", "return", "&", "ID3DecisionTree", "{", "base", ".", "BaseClassifier", "{", "}", ",", "nil", ",", "prune", ",", "rule", ",", "}", "\n", "}" ]
// NewID3DecisionTreeFromRule returns a new ID3DecisionTree with the specified test-prun // ratio and the given rule gnereator.
[ "NewID3DecisionTreeFromRule", "returns", "a", "new", "ID3DecisionTree", "with", "the", "specified", "test", "-", "prun", "ratio", "and", "the", "given", "rule", "gnereator", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/id3.go#L527-L534
164,887
sjwhitworth/golearn
trees/id3.go
Fit
func (t *ID3DecisionTree) Fit(on base.FixedDataGrid) error { if t.PruneSplit > 0.001 { trainData, testData := base.InstancesTrainTestSplit(on, t.PruneSplit) t.Root = InferID3Tree(trainData, t.Rule) t.Root.Prune(testData) } else { t.Root = InferID3Tree(on, t.Rule) } return nil }
go
func (t *ID3DecisionTree) Fit(on base.FixedDataGrid) error { if t.PruneSplit > 0.001 { trainData, testData := base.InstancesTrainTestSplit(on, t.PruneSplit) t.Root = InferID3Tree(trainData, t.Rule) t.Root.Prune(testData) } else { t.Root = InferID3Tree(on, t.Rule) } return nil }
[ "func", "(", "t", "*", "ID3DecisionTree", ")", "Fit", "(", "on", "base", ".", "FixedDataGrid", ")", "error", "{", "if", "t", ".", "PruneSplit", ">", "0.001", "{", "trainData", ",", "testData", ":=", "base", ".", "InstancesTrainTestSplit", "(", "on", ",", "t", ".", "PruneSplit", ")", "\n", "t", ".", "Root", "=", "InferID3Tree", "(", "trainData", ",", "t", ".", "Rule", ")", "\n", "t", ".", "Root", ".", "Prune", "(", "testData", ")", "\n", "}", "else", "{", "t", ".", "Root", "=", "InferID3Tree", "(", "on", ",", "t", ".", "Rule", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Fit builds the ID3 decision tree
[ "Fit", "builds", "the", "ID3", "decision", "tree" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/id3.go#L537-L546
164,888
sjwhitworth/golearn
trees/id3.go
Predict
func (t *ID3DecisionTree) Predict(what base.FixedDataGrid) (base.FixedDataGrid, error) { return t.Root.Predict(what) }
go
func (t *ID3DecisionTree) Predict(what base.FixedDataGrid) (base.FixedDataGrid, error) { return t.Root.Predict(what) }
[ "func", "(", "t", "*", "ID3DecisionTree", ")", "Predict", "(", "what", "base", ".", "FixedDataGrid", ")", "(", "base", ".", "FixedDataGrid", ",", "error", ")", "{", "return", "t", ".", "Root", ".", "Predict", "(", "what", ")", "\n", "}" ]
// Predict outputs predictions from the ID3 decision tree
[ "Predict", "outputs", "predictions", "from", "the", "ID3", "decision", "tree" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/id3.go#L549-L551
164,889
sjwhitworth/golearn
filters/binary.go
NewBinaryConvertFilter
func NewBinaryConvertFilter() *BinaryConvertFilter { ret := &BinaryConvertFilter{ make([]base.Attribute, 0), make([]base.FilteredAttribute, 0), make(map[base.Attribute]bool), make(map[base.Attribute]map[uint64]base.Attribute), } return ret }
go
func NewBinaryConvertFilter() *BinaryConvertFilter { ret := &BinaryConvertFilter{ make([]base.Attribute, 0), make([]base.FilteredAttribute, 0), make(map[base.Attribute]bool), make(map[base.Attribute]map[uint64]base.Attribute), } return ret }
[ "func", "NewBinaryConvertFilter", "(", ")", "*", "BinaryConvertFilter", "{", "ret", ":=", "&", "BinaryConvertFilter", "{", "make", "(", "[", "]", "base", ".", "Attribute", ",", "0", ")", ",", "make", "(", "[", "]", "base", ".", "FilteredAttribute", ",", "0", ")", ",", "make", "(", "map", "[", "base", ".", "Attribute", "]", "bool", ")", ",", "make", "(", "map", "[", "base", ".", "Attribute", "]", "map", "[", "uint64", "]", "base", ".", "Attribute", ")", ",", "}", "\n", "return", "ret", "\n", "}" ]
// NewBinaryConvertFilter creates a blank BinaryConvertFilter
[ "NewBinaryConvertFilter", "creates", "a", "blank", "BinaryConvertFilter" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/filters/binary.go#L24-L32
164,890
sjwhitworth/golearn
filters/binary.go
Transform
func (b *BinaryConvertFilter) Transform(a base.Attribute, n base.Attribute, attrBytes []byte) []byte { ret := make([]byte, 1) // Check for CategoricalAttribute if _, ok := a.(*base.CategoricalAttribute); ok { // Unpack byte value val := base.UnpackBytesToU64(attrBytes) // If it's a two-valued one, check for non-zero if b.twoValuedCategoricalAttributes[a] { if val > 0 { ret[0] = 1 } else { ret[0] = 0 } } else if an, ok := b.nValuedCategoricalAttributeMap[a]; ok { // If it's an n-valued one, check the new Attribute maps onto // the unpacked value if af, ok := an[val]; ok { if af.Equals(n) { ret[0] = 1 } else { ret[0] = 0 } } else { panic("Categorical value not defined!") } } else { panic(fmt.Sprintf("Not a recognised Attribute %v", a)) } } else if _, ok := a.(*base.BinaryAttribute); ok { // Binary: just return the original value ret = attrBytes } else if _, ok := a.(*base.FloatAttribute); ok { // Float: check for non-zero val := base.UnpackBytesToFloat(attrBytes) if val > 0 { ret[0] = 1 } else { ret[0] = 0 } } else { panic(fmt.Sprintf("Unrecognised Attribute: %v", a)) } return ret }
go
func (b *BinaryConvertFilter) Transform(a base.Attribute, n base.Attribute, attrBytes []byte) []byte { ret := make([]byte, 1) // Check for CategoricalAttribute if _, ok := a.(*base.CategoricalAttribute); ok { // Unpack byte value val := base.UnpackBytesToU64(attrBytes) // If it's a two-valued one, check for non-zero if b.twoValuedCategoricalAttributes[a] { if val > 0 { ret[0] = 1 } else { ret[0] = 0 } } else if an, ok := b.nValuedCategoricalAttributeMap[a]; ok { // If it's an n-valued one, check the new Attribute maps onto // the unpacked value if af, ok := an[val]; ok { if af.Equals(n) { ret[0] = 1 } else { ret[0] = 0 } } else { panic("Categorical value not defined!") } } else { panic(fmt.Sprintf("Not a recognised Attribute %v", a)) } } else if _, ok := a.(*base.BinaryAttribute); ok { // Binary: just return the original value ret = attrBytes } else if _, ok := a.(*base.FloatAttribute); ok { // Float: check for non-zero val := base.UnpackBytesToFloat(attrBytes) if val > 0 { ret[0] = 1 } else { ret[0] = 0 } } else { panic(fmt.Sprintf("Unrecognised Attribute: %v", a)) } return ret }
[ "func", "(", "b", "*", "BinaryConvertFilter", ")", "Transform", "(", "a", "base", ".", "Attribute", ",", "n", "base", ".", "Attribute", ",", "attrBytes", "[", "]", "byte", ")", "[", "]", "byte", "{", "ret", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "// Check for CategoricalAttribute", "if", "_", ",", "ok", ":=", "a", ".", "(", "*", "base", ".", "CategoricalAttribute", ")", ";", "ok", "{", "// Unpack byte value", "val", ":=", "base", ".", "UnpackBytesToU64", "(", "attrBytes", ")", "\n", "// If it's a two-valued one, check for non-zero", "if", "b", ".", "twoValuedCategoricalAttributes", "[", "a", "]", "{", "if", "val", ">", "0", "{", "ret", "[", "0", "]", "=", "1", "\n", "}", "else", "{", "ret", "[", "0", "]", "=", "0", "\n", "}", "\n", "}", "else", "if", "an", ",", "ok", ":=", "b", ".", "nValuedCategoricalAttributeMap", "[", "a", "]", ";", "ok", "{", "// If it's an n-valued one, check the new Attribute maps onto", "// the unpacked value", "if", "af", ",", "ok", ":=", "an", "[", "val", "]", ";", "ok", "{", "if", "af", ".", "Equals", "(", "n", ")", "{", "ret", "[", "0", "]", "=", "1", "\n", "}", "else", "{", "ret", "[", "0", "]", "=", "0", "\n", "}", "\n", "}", "else", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "a", ")", ")", "\n", "}", "\n", "}", "else", "if", "_", ",", "ok", ":=", "a", ".", "(", "*", "base", ".", "BinaryAttribute", ")", ";", "ok", "{", "// Binary: just return the original value", "ret", "=", "attrBytes", "\n", "}", "else", "if", "_", ",", "ok", ":=", "a", ".", "(", "*", "base", ".", "FloatAttribute", ")", ";", "ok", "{", "// Float: check for non-zero", "val", ":=", "base", ".", "UnpackBytesToFloat", "(", "attrBytes", ")", "\n", "if", "val", ">", "0", "{", "ret", "[", "0", "]", "=", "1", "\n", "}", "else", "{", "ret", "[", "0", "]", "=", "0", "\n", "}", "\n", "}", "else", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "a", ")", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Transform converts the given byte sequence using the old Attribute into the new // byte sequence. // // If the old Attribute has a categorical value of at most two items, then a zero or // non-zero byte sequence is returned. // // If the old Attribute has a categorical value of at most n-items, then a non-zero // or zero byte sequence is returned based on the value of the new Attribute passed in. // // If the old Attribute is a float, it's value's unpacked and we check for non-zeroness // // If the old Attribute is a BinaryAttribute, just return the input
[ "Transform", "converts", "the", "given", "byte", "sequence", "using", "the", "old", "Attribute", "into", "the", "new", "byte", "sequence", ".", "If", "the", "old", "Attribute", "has", "a", "categorical", "value", "of", "at", "most", "two", "items", "then", "a", "zero", "or", "non", "-", "zero", "byte", "sequence", "is", "returned", ".", "If", "the", "old", "Attribute", "has", "a", "categorical", "value", "of", "at", "most", "n", "-", "items", "then", "a", "non", "-", "zero", "or", "zero", "byte", "sequence", "is", "returned", "based", "on", "the", "value", "of", "the", "new", "Attribute", "passed", "in", ".", "If", "the", "old", "Attribute", "is", "a", "float", "it", "s", "value", "s", "unpacked", "and", "we", "check", "for", "non", "-", "zeroness", "If", "the", "old", "Attribute", "is", "a", "BinaryAttribute", "just", "return", "the", "input" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/filters/binary.go#L62-L105
164,891
sjwhitworth/golearn
base/serialize_instances.go
SerializeInstancesToCSV
func SerializeInstancesToCSV(inst FixedDataGrid, path string) error { f, err := os.OpenFile(path, os.O_RDWR, 0600) if err != nil { return err } defer func() { f.Sync() f.Close() }() return SerializeInstancesToCSVStream(inst, f) }
go
func SerializeInstancesToCSV(inst FixedDataGrid, path string) error { f, err := os.OpenFile(path, os.O_RDWR, 0600) if err != nil { return err } defer func() { f.Sync() f.Close() }() return SerializeInstancesToCSVStream(inst, f) }
[ "func", "SerializeInstancesToCSV", "(", "inst", "FixedDataGrid", ",", "path", "string", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ",", "os", ".", "O_RDWR", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "f", ".", "Sync", "(", ")", "\n", "f", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n\n", "return", "SerializeInstancesToCSVStream", "(", "inst", ",", "f", ")", "\n", "}" ]
// SerializesInstancesToCSV converts a FixedDataGrid into a CSV file format.
[ "SerializesInstancesToCSV", "converts", "a", "FixedDataGrid", "into", "a", "CSV", "file", "format", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize_instances.go#L32-L43
164,892
sjwhitworth/golearn
base/serialize_instances.go
SerializeInstancesToCSVStream
func SerializeInstancesToCSVStream(inst FixedDataGrid, f io.Writer) error { // Create the CSV writer w := csv.NewWriter(f) colCount, _ := inst.Size() // Write out Attribute headers // Start with the regular Attributes normalAttrs := NonClassAttributes(inst) classAttrs := inst.AllClassAttributes() allAttrs := make([]Attribute, colCount) n := copy(allAttrs, normalAttrs) copy(allAttrs[n:], classAttrs) headerRow := make([]string, colCount) for i, v := range allAttrs { headerRow[i] = v.GetName() } w.Write(headerRow) specs := ResolveAttributes(inst, allAttrs) curRow := make([]string, colCount) inst.MapOverRows(specs, func(row [][]byte, rowNo int) (bool, error) { for i, v := range row { attr := allAttrs[i] curRow[i] = attr.GetStringFromSysVal(v) } w.Write(curRow) return true, nil }) w.Flush() return nil }
go
func SerializeInstancesToCSVStream(inst FixedDataGrid, f io.Writer) error { // Create the CSV writer w := csv.NewWriter(f) colCount, _ := inst.Size() // Write out Attribute headers // Start with the regular Attributes normalAttrs := NonClassAttributes(inst) classAttrs := inst.AllClassAttributes() allAttrs := make([]Attribute, colCount) n := copy(allAttrs, normalAttrs) copy(allAttrs[n:], classAttrs) headerRow := make([]string, colCount) for i, v := range allAttrs { headerRow[i] = v.GetName() } w.Write(headerRow) specs := ResolveAttributes(inst, allAttrs) curRow := make([]string, colCount) inst.MapOverRows(specs, func(row [][]byte, rowNo int) (bool, error) { for i, v := range row { attr := allAttrs[i] curRow[i] = attr.GetStringFromSysVal(v) } w.Write(curRow) return true, nil }) w.Flush() return nil }
[ "func", "SerializeInstancesToCSVStream", "(", "inst", "FixedDataGrid", ",", "f", "io", ".", "Writer", ")", "error", "{", "// Create the CSV writer", "w", ":=", "csv", ".", "NewWriter", "(", "f", ")", "\n\n", "colCount", ",", "_", ":=", "inst", ".", "Size", "(", ")", "\n\n", "// Write out Attribute headers", "// Start with the regular Attributes", "normalAttrs", ":=", "NonClassAttributes", "(", "inst", ")", "\n", "classAttrs", ":=", "inst", ".", "AllClassAttributes", "(", ")", "\n", "allAttrs", ":=", "make", "(", "[", "]", "Attribute", ",", "colCount", ")", "\n", "n", ":=", "copy", "(", "allAttrs", ",", "normalAttrs", ")", "\n", "copy", "(", "allAttrs", "[", "n", ":", "]", ",", "classAttrs", ")", "\n", "headerRow", ":=", "make", "(", "[", "]", "string", ",", "colCount", ")", "\n", "for", "i", ",", "v", ":=", "range", "allAttrs", "{", "headerRow", "[", "i", "]", "=", "v", ".", "GetName", "(", ")", "\n", "}", "\n", "w", ".", "Write", "(", "headerRow", ")", "\n\n", "specs", ":=", "ResolveAttributes", "(", "inst", ",", "allAttrs", ")", "\n", "curRow", ":=", "make", "(", "[", "]", "string", ",", "colCount", ")", "\n", "inst", ".", "MapOverRows", "(", "specs", ",", "func", "(", "row", "[", "]", "[", "]", "byte", ",", "rowNo", "int", ")", "(", "bool", ",", "error", ")", "{", "for", "i", ",", "v", ":=", "range", "row", "{", "attr", ":=", "allAttrs", "[", "i", "]", "\n", "curRow", "[", "i", "]", "=", "attr", ".", "GetStringFromSysVal", "(", "v", ")", "\n", "}", "\n", "w", ".", "Write", "(", "curRow", ")", "\n", "return", "true", ",", "nil", "\n", "}", ")", "\n\n", "w", ".", "Flush", "(", ")", "\n", "return", "nil", "\n", "}" ]
// SerializeInstancesToCSVStream outputs a FixedDataGrid into a CSV file format, via the io.Writer stream.
[ "SerializeInstancesToCSVStream", "outputs", "a", "FixedDataGrid", "into", "a", "CSV", "file", "format", "via", "the", "io", ".", "Writer", "stream", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize_instances.go#L46-L78
164,893
sjwhitworth/golearn
base/serialize_instances.go
DeserializeInstances
func DeserializeInstances(f io.ReadSeeker) (ret *DenseInstances, err error) { // Recovery function defer func() { if r := recover(); r != nil { if _, ok := r.(runtime.Error); ok { panic(r) } err = r.(error) } }() // Open the .gz layer gzReader, err := gzip.NewReader(f) if err != nil { panic(WrapError(err)) } regenerateTarReader := func() *tar.Reader { f.Seek(0, os.SEEK_SET) gzReader.Reset(f) tr := tar.NewReader(gzReader) return tr } tr := NewFunctionalTarReader(regenerateTarReader) ret, deSerializeErr := DeserializeInstancesFromTarReader(tr, "") if err = gzReader.Close(); err != nil { return ret, fmt.Errorf("Error closing gzip stream: %s", err) } return ret, deSerializeErr }
go
func DeserializeInstances(f io.ReadSeeker) (ret *DenseInstances, err error) { // Recovery function defer func() { if r := recover(); r != nil { if _, ok := r.(runtime.Error); ok { panic(r) } err = r.(error) } }() // Open the .gz layer gzReader, err := gzip.NewReader(f) if err != nil { panic(WrapError(err)) } regenerateTarReader := func() *tar.Reader { f.Seek(0, os.SEEK_SET) gzReader.Reset(f) tr := tar.NewReader(gzReader) return tr } tr := NewFunctionalTarReader(regenerateTarReader) ret, deSerializeErr := DeserializeInstancesFromTarReader(tr, "") if err = gzReader.Close(); err != nil { return ret, fmt.Errorf("Error closing gzip stream: %s", err) } return ret, deSerializeErr }
[ "func", "DeserializeInstances", "(", "f", "io", ".", "ReadSeeker", ")", "(", "ret", "*", "DenseInstances", ",", "err", "error", ")", "{", "// Recovery function", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "r", ".", "(", "runtime", ".", "Error", ")", ";", "ok", "{", "panic", "(", "r", ")", "\n", "}", "\n", "err", "=", "r", ".", "(", "error", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Open the .gz layer", "gzReader", ",", "err", ":=", "gzip", ".", "NewReader", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "WrapError", "(", "err", ")", ")", "\n", "}", "\n", "regenerateTarReader", ":=", "func", "(", ")", "*", "tar", ".", "Reader", "{", "f", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "\n", "gzReader", ".", "Reset", "(", "f", ")", "\n", "tr", ":=", "tar", ".", "NewReader", "(", "gzReader", ")", "\n", "return", "tr", "\n", "}", "\n\n", "tr", ":=", "NewFunctionalTarReader", "(", "regenerateTarReader", ")", "\n\n", "ret", ",", "deSerializeErr", ":=", "DeserializeInstancesFromTarReader", "(", "tr", ",", "\"", "\"", ")", "\n\n", "if", "err", "=", "gzReader", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "ret", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "ret", ",", "deSerializeErr", "\n", "}" ]
// DeserializeInstances returns a DenseInstances using a given io.Reader.
[ "DeserializeInstances", "returns", "a", "DenseInstances", "using", "a", "given", "io", ".", "Reader", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize_instances.go#L187-L220
164,894
sjwhitworth/golearn
base/serialize_instances.go
SerializeInstances
func SerializeInstances(inst FixedDataGrid, f io.Writer) error { // Create a .tar.gz container gzWriter := gzip.NewWriter(f) tw := tar.NewWriter(gzWriter) serializeErr := SerializeInstancesToTarWriter(inst, tw, "", true) // Finally, close and flush the various levels if err := tw.Flush(); err != nil { return fmt.Errorf("Could not flush tar: %s", err) } if err := tw.Close(); err != nil { return fmt.Errorf("Could not close tar: %s", err) } if err := gzWriter.Flush(); err != nil { return fmt.Errorf("Could not flush gz: %s", err) } if err := gzWriter.Close(); err != nil { return fmt.Errorf("Could not close gz: %s", err) } return serializeErr }
go
func SerializeInstances(inst FixedDataGrid, f io.Writer) error { // Create a .tar.gz container gzWriter := gzip.NewWriter(f) tw := tar.NewWriter(gzWriter) serializeErr := SerializeInstancesToTarWriter(inst, tw, "", true) // Finally, close and flush the various levels if err := tw.Flush(); err != nil { return fmt.Errorf("Could not flush tar: %s", err) } if err := tw.Close(); err != nil { return fmt.Errorf("Could not close tar: %s", err) } if err := gzWriter.Flush(); err != nil { return fmt.Errorf("Could not flush gz: %s", err) } if err := gzWriter.Close(); err != nil { return fmt.Errorf("Could not close gz: %s", err) } return serializeErr }
[ "func", "SerializeInstances", "(", "inst", "FixedDataGrid", ",", "f", "io", ".", "Writer", ")", "error", "{", "// Create a .tar.gz container", "gzWriter", ":=", "gzip", ".", "NewWriter", "(", "f", ")", "\n", "tw", ":=", "tar", ".", "NewWriter", "(", "gzWriter", ")", "\n\n", "serializeErr", ":=", "SerializeInstancesToTarWriter", "(", "inst", ",", "tw", ",", "\"", "\"", ",", "true", ")", "\n", "// Finally, close and flush the various levels", "if", "err", ":=", "tw", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "tw", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "gzWriter", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "gzWriter", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "serializeErr", "\n", "}" ]
// SerializeInstances stores a FixedDataGrid into an efficient format to the given io.Writer stream.
[ "SerializeInstances", "stores", "a", "FixedDataGrid", "into", "an", "efficient", "format", "to", "the", "given", "io", ".", "Writer", "stream", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize_instances.go#L223-L247
164,895
sjwhitworth/golearn
ensemble/multisvc.go
NewMultiLinearSVC
func NewMultiLinearSVC(loss, penalty string, dual bool, C float64, eps float64, weights map[string]float64) *MultiLinearSVC { // Set up the training parameters params := &linear_models.LinearSVCParams{0, nil, C, eps, false, dual} err := params.SetKindFromStrings(loss, penalty) if err != nil { panic(err) } // Return me... ret := &MultiLinearSVC{ parameters: params, weights: weights, } ret.initializeOneVsAllModel() return ret }
go
func NewMultiLinearSVC(loss, penalty string, dual bool, C float64, eps float64, weights map[string]float64) *MultiLinearSVC { // Set up the training parameters params := &linear_models.LinearSVCParams{0, nil, C, eps, false, dual} err := params.SetKindFromStrings(loss, penalty) if err != nil { panic(err) } // Return me... ret := &MultiLinearSVC{ parameters: params, weights: weights, } ret.initializeOneVsAllModel() return ret }
[ "func", "NewMultiLinearSVC", "(", "loss", ",", "penalty", "string", ",", "dual", "bool", ",", "C", "float64", ",", "eps", "float64", ",", "weights", "map", "[", "string", "]", "float64", ")", "*", "MultiLinearSVC", "{", "// Set up the training parameters", "params", ":=", "&", "linear_models", ".", "LinearSVCParams", "{", "0", ",", "nil", ",", "C", ",", "eps", ",", "false", ",", "dual", "}", "\n", "err", ":=", "params", ".", "SetKindFromStrings", "(", "loss", ",", "penalty", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "// Return me...", "ret", ":=", "&", "MultiLinearSVC", "{", "parameters", ":", "params", ",", "weights", ":", "weights", ",", "}", "\n\n", "ret", ".", "initializeOneVsAllModel", "(", ")", "\n", "return", "ret", "\n", "}" ]
// NewMultiLinearSVC creates a new MultiLinearSVC using the OneVsAllModel. // The loss and penalty arguments can be "l1" or "l2". Typical values are // "l1" for the loss and "l2" for the penalty. The dual parameter controls // whether the system solves the dual or primal SVM form, true should be used // in most cases. C is the penalty term, normally 1.0. eps is the convergence // term, typically 1e-4.
[ "NewMultiLinearSVC", "creates", "a", "new", "MultiLinearSVC", "using", "the", "OneVsAllModel", ".", "The", "loss", "and", "penalty", "arguments", "can", "be", "l1", "or", "l2", ".", "Typical", "values", "are", "l1", "for", "the", "loss", "and", "l2", "for", "the", "penalty", ".", "The", "dual", "parameter", "controls", "whether", "the", "system", "solves", "the", "dual", "or", "primal", "SVM", "form", "true", "should", "be", "used", "in", "most", "cases", ".", "C", "is", "the", "penalty", "term", "normally", "1", ".", "0", ".", "eps", "is", "the", "convergence", "term", "typically", "1e", "-", "4", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/ensemble/multisvc.go#L25-L41
164,896
sjwhitworth/golearn
ensemble/multisvc.go
Predict
func (m *MultiLinearSVC) Predict(from base.FixedDataGrid) (base.FixedDataGrid, error) { return m.m.Predict(from) }
go
func (m *MultiLinearSVC) Predict(from base.FixedDataGrid) (base.FixedDataGrid, error) { return m.m.Predict(from) }
[ "func", "(", "m", "*", "MultiLinearSVC", ")", "Predict", "(", "from", "base", ".", "FixedDataGrid", ")", "(", "base", ".", "FixedDataGrid", ",", "error", ")", "{", "return", "m", ".", "m", ".", "Predict", "(", "from", ")", "\n", "}" ]
// Predict issues predictions from the MultiLinearSVC. Each underlying LinearSVC is // used to predict whether an instance takes on a class or some other class, and the // model which definitively reports a given class is the one chosen. The result is // undefined if all underlying models predict that the instance originates from some // other class.
[ "Predict", "issues", "predictions", "from", "the", "MultiLinearSVC", ".", "Each", "underlying", "LinearSVC", "is", "used", "to", "predict", "whether", "an", "instance", "takes", "on", "a", "class", "or", "some", "other", "class", "and", "the", "model", "which", "definitively", "reports", "a", "given", "class", "is", "the", "one", "chosen", ".", "The", "result", "is", "undefined", "if", "all", "underlying", "models", "predict", "that", "the", "instance", "originates", "from", "some", "other", "class", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/ensemble/multisvc.go#L81-L83
164,897
sjwhitworth/golearn
clustering/em.go
NewExpectationMaximization
func NewExpectationMaximization(n_comps int) (*ExpectationMaximization, error) { if n_comps < 1 { return nil, InsufficientComponentsError } return &ExpectationMaximization{n_comps: n_comps, eps: 0.001}, nil }
go
func NewExpectationMaximization(n_comps int) (*ExpectationMaximization, error) { if n_comps < 1 { return nil, InsufficientComponentsError } return &ExpectationMaximization{n_comps: n_comps, eps: 0.001}, nil }
[ "func", "NewExpectationMaximization", "(", "n_comps", "int", ")", "(", "*", "ExpectationMaximization", ",", "error", ")", "{", "if", "n_comps", "<", "1", "{", "return", "nil", ",", "InsufficientComponentsError", "\n", "}", "\n\n", "return", "&", "ExpectationMaximization", "{", "n_comps", ":", "n_comps", ",", "eps", ":", "0.001", "}", ",", "nil", "\n", "}" ]
// Number of Gaussians to fit in the mixture
[ "Number", "of", "Gaussians", "to", "fit", "in", "the", "mixture" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L33-L39
164,898
sjwhitworth/golearn
clustering/em.go
Predict
func (em *ExpectationMaximization) Predict(inst base.FixedDataGrid) (ClusterMap, error) { if !em.fitted { return nil, NoTrainingDataError } _, n_obs := inst.Size() n_feats := len(em.attrs) // Numeric attrs attrSpecs := base.ResolveAttributes(inst, em.attrs) // Build the input matrix X := mat.NewDense(n_obs, n_feats, nil) inst.MapOverRows(attrSpecs, func(row [][]byte, i int) (bool, error) { for j, r := range row { X.Set(i, j, base.UnpackBytesToFloat(r)) } return true, nil }) // Vector of predictions preds := estimateLogProb(X, em.Params, em.n_comps) clusterMap := make(map[int][]int) for ix, pred := range vecToInts(preds) { clusterMap[pred] = append(clusterMap[pred], ix) } return ClusterMap(clusterMap), nil }
go
func (em *ExpectationMaximization) Predict(inst base.FixedDataGrid) (ClusterMap, error) { if !em.fitted { return nil, NoTrainingDataError } _, n_obs := inst.Size() n_feats := len(em.attrs) // Numeric attrs attrSpecs := base.ResolveAttributes(inst, em.attrs) // Build the input matrix X := mat.NewDense(n_obs, n_feats, nil) inst.MapOverRows(attrSpecs, func(row [][]byte, i int) (bool, error) { for j, r := range row { X.Set(i, j, base.UnpackBytesToFloat(r)) } return true, nil }) // Vector of predictions preds := estimateLogProb(X, em.Params, em.n_comps) clusterMap := make(map[int][]int) for ix, pred := range vecToInts(preds) { clusterMap[pred] = append(clusterMap[pred], ix) } return ClusterMap(clusterMap), nil }
[ "func", "(", "em", "*", "ExpectationMaximization", ")", "Predict", "(", "inst", "base", ".", "FixedDataGrid", ")", "(", "ClusterMap", ",", "error", ")", "{", "if", "!", "em", ".", "fitted", "{", "return", "nil", ",", "NoTrainingDataError", "\n", "}", "\n\n", "_", ",", "n_obs", ":=", "inst", ".", "Size", "(", ")", "\n", "n_feats", ":=", "len", "(", "em", ".", "attrs", ")", "\n\n", "// Numeric attrs", "attrSpecs", ":=", "base", ".", "ResolveAttributes", "(", "inst", ",", "em", ".", "attrs", ")", "\n\n", "// Build the input matrix", "X", ":=", "mat", ".", "NewDense", "(", "n_obs", ",", "n_feats", ",", "nil", ")", "\n", "inst", ".", "MapOverRows", "(", "attrSpecs", ",", "func", "(", "row", "[", "]", "[", "]", "byte", ",", "i", "int", ")", "(", "bool", ",", "error", ")", "{", "for", "j", ",", "r", ":=", "range", "row", "{", "X", ".", "Set", "(", "i", ",", "j", ",", "base", ".", "UnpackBytesToFloat", "(", "r", ")", ")", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}", ")", "\n\n", "// Vector of predictions", "preds", ":=", "estimateLogProb", "(", "X", ",", "em", ".", "Params", ",", "em", ".", "n_comps", ")", "\n\n", "clusterMap", ":=", "make", "(", "map", "[", "int", "]", "[", "]", "int", ")", "\n", "for", "ix", ",", "pred", ":=", "range", "vecToInts", "(", "preds", ")", "{", "clusterMap", "[", "pred", "]", "=", "append", "(", "clusterMap", "[", "pred", "]", ",", "ix", ")", "\n", "}", "\n\n", "return", "ClusterMap", "(", "clusterMap", ")", ",", "nil", "\n", "}" ]
// Predict method - returns a ClusterMap of components and row ids
[ "Predict", "method", "-", "returns", "a", "ClusterMap", "of", "components", "and", "row", "ids" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L89-L118
164,899
sjwhitworth/golearn
clustering/em.go
expectation
func expectation(X *mat.Dense, p Params, n_comps int) mat.Vector { y_new := estimateLogProb(X, p, n_comps) return y_new }
go
func expectation(X *mat.Dense, p Params, n_comps int) mat.Vector { y_new := estimateLogProb(X, p, n_comps) return y_new }
[ "func", "expectation", "(", "X", "*", "mat", ".", "Dense", ",", "p", "Params", ",", "n_comps", "int", ")", "mat", ".", "Vector", "{", "y_new", ":=", "estimateLogProb", "(", "X", ",", "p", ",", "n_comps", ")", "\n", "return", "y_new", "\n", "}" ]
// EM-specific functions // Expectation step
[ "EM", "-", "specific", "functions", "Expectation", "step" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L122-L125