How to use TestLabels method of result Package

Best Testkube code snippet using result.TestLabels

mnist.go

Source:mnist.go Github

copy

Full Screen

1package main2import (3 "flag"4 "fmt"5 "github.com/moygit/rbf"6 "io"7 "log"8 "math"9 "os"10 "sort"11 "time"12)13const num_features = 78414type Config struct {15 numTrees int3216 depth int3217 leafSize int3218 numFeaturesToCompare int3219 numNeighbors int3220}21func main() {22 config := getConfig()23 train := readImagesFile("fashion/train_images.bin")24 test := readImagesFile("fashion/test_images.bin")25 trainLabels := readLabelsFile("fashion/train_labels.bin")26 testLabels := readLabelsFile("fashion/test_labels.bin")27 trainStartTime := time.Now().UnixNano()28 forest := rbf.TrainForest(train, config.numTrees, config.depth, config.leafSize, config.numFeaturesToCompare)29 //filename := fmt.Sprintf("mnist_forest_%d_%d_%d_%d.bin", config.numTrees, config.depth, config.leafSize, config.numFeaturesToCompare)30 //f, _ := os.Create(filename)31 //forest.WriteToWriter(f)32 //f.Close()33 //filename := fmt.Sprintf("mnist_forest_%d_%d_%d_%d.bin", config.numTrees, config.depth, config.leafSize, config.numFeaturesToCompare)34 //f, _ := os.Open(filename)35 //forest := rbf.ReadForestFromReader(f)36 //f.Close()37 evalStartTime := time.Now().UnixNano()38 //matchCount := evalL2(forest, train, test, trainLabels, testLabels, config.numNeighbors)39 matchCount := evalPlurality(forest, test, trainLabels, testLabels)40 evalFinishTime := time.Now().UnixNano()41 trainTime := float64(evalStartTime-trainStartTime) / (1000000.0 * 1000.0)42 evalTime := float64(evalFinishTime-evalStartTime) / 1000000.043 accuracy := float64(matchCount) / float64(len(testLabels))44 fmt.Printf("%d,%d,%d,%.3f,%.5f,%.5f\n", config.numTrees, config.leafSize, config.numFeaturesToCompare, trainTime, evalTime, accuracy)45}46func getConfig() Config {47 numTrees := flag.Int("t", -1, "number of trees")48 depth := flag.Int("d", -1, "depth")49 leafSize := flag.Int("l", -1, "leaf size")50 numFeaturesToCompare := flag.Int("n", -1, "number of features to compare")51 numNeighbors := flag.Int("k", -1, "number of neighbors to consider for plurality-select")52 flag.Parse()53 if *numTrees < 1 || *depth < 1 || *leafSize < 1 || *numFeaturesToCompare < 1 || *numNeighbors < 0 {54 flag.Usage()55 os.Exit(1)56 }57 return Config{int32(*numTrees), int32(*depth), int32(*leafSize), int32(*numFeaturesToCompare), int32(*numNeighbors)}58}59func readImagesFile(filename string) [][]byte {60 file, _ := os.Open(filename)61 defer file.Close()62 buf := make([]byte, getFileSize(file))63 if _, err := io.ReadFull(file, buf); err != nil {64 log.Panicf("error reading %s: %v\n", filename, err)65 }66 buf2d := make([][]byte, len(buf)/num_features)67 for i := range buf2d {68 buf2d[i] = buf[i*num_features : (i+1)*num_features]69 }70 return buf2d71}72func readLabelsFile(filename string) []byte {73 file, _ := os.Open(filename)74 defer file.Close()75 // file format is "label\nlabel\nlabel\n...", so we can just read in the whole file and then drop alternate bytes76 size := getFileSize(file)77 buf := make([]byte, size)78 if _, err := io.ReadFull(file, buf); err != nil {79 log.Panicf("error reading %s: %v\n", filename, err)80 }81 return buf82}83func getFileSize(file *os.File) int64 {84 info, err := file.Stat()85 if err != nil {86 panic(err)87 }88 return info.Size()89}90func evalL2(forest rbf.RandomBinaryForest, train, test [][]byte, trainLabels, testLabels []byte, numNeighbors int32) int {91 matchCount := 092 for i, image := range test {93 if evalOneImageL2(forest, train, image, trainLabels, testLabels[i], numNeighbors) {94 matchCount += 195 }96 }97 return matchCount98}99func evalPlurality(forest rbf.RandomBinaryForest, test [][]byte, trainLabels, testLabels []byte) int {100 matchCount := 0101 for i, image := range test {102 if evalOneImagePlurality(forest, image, trainLabels, testLabels[i]) {103 matchCount += 1104 }105 }106 return matchCount107}108func l2Dist(v1, v2 []byte) int {109 distSquared := 0110 for i := range v1 {111 diff := v1[i] - v2[i]112 distSquared += int(diff * diff)113 }114 return distSquared115}116func evalOneImageL2(forest rbf.RandomBinaryForest, train [][]byte, testImage []byte, trainLabels []byte, testLabel byte, numNeighbors int32) bool {117 // query forest118 resultsCount, allTreeResults := forest.FindPointAllResults(testImage)119 // combine all returned results into single slice120 allResults := make([]int32, resultsCount)121 for _, treeResults := range allTreeResults {122 for _, result := range treeResults {123 allResults = append(allResults, result)124 }125 }126 // order them by L2 distance to test point127 sort.Slice(allResults, func(i, j int) bool {128 return l2Dist(testImage, train[allResults[i]]) < l2Dist(testImage, train[allResults[j]])129 })130 // pick out the k nearest ones131 labelCounts := make([]int, 10)132 for _, index := range allResults[:numNeighbors] {133 labelCounts[trainLabels[index]] += 1134 }135 argmaxLabel := argmax(labelCounts)136 return byte(argmaxLabel) == testLabel137}138//func evalOneImageL2(forest rbf.RandomBinaryForest, train [][]byte, testImage []byte, trainLabels []byte, testLabel byte) bool {139// allResults := forest.FindPointDedupResults(testImage)140// minDist := math.MaxInt64141// minDistIndex := int32(-1)142// for index := range allResults {143// if dist := l2Dist(testImage, train[index]); dist < minDist {144// minDist = dist145// minDistIndex = index146// }147// }148// rbfLabel := trainLabels[minDistIndex]149// return rbfLabel == testLabel150//}151func evalOneImagePlurality(forest rbf.RandomBinaryForest, image []byte, trainLabels []byte, testLabel byte) bool {152 _, results := forest.FindPointAllResults(image)153 labelCounts := make([]int, 10)154 for _, resultRow := range results {155 for _, result := range resultRow {156 labelCounts[trainLabels[result]] += 1157 }158 }159 argmaxLabel := argmax(labelCounts)160 return byte(argmaxLabel) == testLabel161}162func argmax(values []int) int {163 maxLabelCount := math.MinInt64164 argmaxLabel := -1165 for label := 0; label < len(values); label++ {166 if values[label] > maxLabelCount {167 argmaxLabel = label168 maxLabelCount = values[label]169 }170 }171 return argmaxLabel172}173func printResults(trainStartTime, evalStartTime, evalFinishTime int64, matchCount, totalCount int) {174 fmt.Printf("Total training time: %.2f seconds\n", float64((evalStartTime-trainStartTime)/1000000)/1000.0)175 fmt.Printf("Total eval time: %.2f seconds\n", float64((evalFinishTime-evalStartTime)/1000000)/1000.0)176 fmt.Printf("Average eval time per image: %.3f milliseconds\n", float64((evalFinishTime-evalStartTime)/1000000)/float64(totalCount))177 fmt.Printf("Accuracy: %.2f%%\n", float64(matchCount*100)/float64(totalCount))178}...

Full Screen

Full Screen

deviceprofile_test.go

Source:deviceprofile_test.go Github

copy

Full Screen

1//2// Copyright (C) 2021 IOTech Ltd3//4// SPDX-License-Identifier: Apache-2.05package dtos6import (7 "gopkg.in/yaml.v3"8 "testing"9 "github.com/edgexfoundry/go-mod-core-contracts/v2/common"10 "github.com/edgexfoundry/go-mod-core-contracts/v2/models"11 "github.com/stretchr/testify/assert"12 "github.com/stretchr/testify/require"13)14var testLabels = []string{"MODBUS", "TEMP"}15var testAttributes = map[string]interface{}{16 "TestAttribute": "TestAttributeValue",17}18var testMappings = map[string]string{"0": "off", "1": "on"}19var testDeviceProfile = models.DeviceProfile{20 Name: TestDeviceProfileName,21 Manufacturer: TestManufacturer,22 Description: TestDescription,23 Model: TestModel,24 Labels: testLabels,25 DeviceResources: []models.DeviceResource{{26 Name: TestDeviceResourceName,27 Description: TestDescription,28 Tag: TestTag,29 Attributes: testAttributes,30 Properties: models.ResourceProperties{31 ValueType: common.ValueTypeInt16,32 ReadWrite: common.ReadWrite_RW,33 },34 }},35 DeviceCommands: []models.DeviceCommand{{36 Name: TestDeviceCommandName,37 ReadWrite: common.ReadWrite_RW,38 ResourceOperations: []models.ResourceOperation{{39 DeviceResource: TestDeviceResourceName,40 Mappings: testMappings,41 }},42 }},43}44func profileData() DeviceProfile {45 return DeviceProfile{46 DeviceProfileBasicInfo: DeviceProfileBasicInfo{47 Name: TestDeviceProfileName,48 Manufacturer: TestManufacturer,49 Description: TestDescription,50 Model: TestModel,51 Labels: testLabels,52 },53 DeviceResources: []DeviceResource{{54 Name: TestDeviceResourceName,55 Description: TestDescription,56 Tag: TestTag,57 Attributes: testAttributes,58 Properties: ResourceProperties{59 ValueType: common.ValueTypeInt16,60 ReadWrite: common.ReadWrite_RW,61 },62 }},63 DeviceCommands: []DeviceCommand{{64 Name: TestDeviceCommandName,65 ReadWrite: common.ReadWrite_RW,66 ResourceOperations: []ResourceOperation{{67 DeviceResource: TestDeviceResourceName,68 Mappings: testMappings,69 }},70 }},71 }72}73func TestFromDeviceProfileModelToDTO(t *testing.T) {74 result := FromDeviceProfileModelToDTO(testDeviceProfile)75 assert.Equal(t, profileData(), result, "FromDeviceProfileModelToDTO did not result in expected device profile DTO.")76}77func TestDeviceProfileDTOValidation(t *testing.T) {78 valid := profileData()79 duplicatedDeviceResource := profileData()80 duplicatedDeviceResource.DeviceResources = append(81 duplicatedDeviceResource.DeviceResources, DeviceResource{Name: TestDeviceResourceName})82 duplicatedDeviceCommand := profileData()83 duplicatedDeviceCommand.DeviceCommands = append(84 duplicatedDeviceCommand.DeviceCommands, DeviceCommand{Name: TestDeviceCommandName})85 mismatchedResource := profileData()86 mismatchedResource.DeviceCommands[0].ResourceOperations = append(87 mismatchedResource.DeviceCommands[0].ResourceOperations, ResourceOperation{DeviceResource: "missMatchedResource"})88 invalidReadWrite := profileData()89 invalidReadWrite.DeviceResources[0].Properties.ReadWrite = common.ReadWrite_R90 binaryWithWritePermission := profileData()91 binaryWithWritePermission.DeviceResources[0].Properties.ValueType = common.ValueTypeBinary92 binaryWithWritePermission.DeviceResources[0].Properties.ReadWrite = common.ReadWrite_RW93 tests := []struct {94 name string95 profile DeviceProfile96 expectError bool97 }{98 {"valid device profile", valid, false},99 {"duplicated device resource", duplicatedDeviceResource, true},100 {"duplicated device command", duplicatedDeviceCommand, true},101 {"mismatched resource", mismatchedResource, true},102 {"invalid ReadWrite permission", invalidReadWrite, true},103 {"write permission not support Binary value type", binaryWithWritePermission, true},104 }105 for _, tt := range tests {106 t.Run(tt.name, func(t *testing.T) {107 err := tt.profile.Validate()108 if tt.expectError {109 require.Error(t, err)110 } else {111 require.NoError(t, err)112 }113 })114 }115}116func TestAddDeviceProfile_UnmarshalYAML(t *testing.T) {117 valid := profileData()118 resultTestBytes, _ := yaml.Marshal(profileData())119 type args struct {120 data []byte121 }122 tests := []struct {123 name string124 expected DeviceProfile125 args args126 wantErr bool127 }{128 {"valid", valid, args{resultTestBytes}, false},129 {"invalid", DeviceProfile{}, args{[]byte("Invalid DeviceProfile")}, true},130 }131 for _, tt := range tests {132 t.Run(tt.name, func(t *testing.T) {133 var dp DeviceProfile134 err := yaml.Unmarshal(tt.args.data, &dp)135 if tt.wantErr {136 require.Error(t, err)137 } else {138 require.NoError(t, err)139 assert.Equal(t, tt.expected, dp, "Unmarshal did not result in expected DeviceProfileRequest.")140 }141 })142 }143}...

Full Screen

Full Screen

dataset.go

Source:dataset.go Github

copy

Full Screen

1package v12import (3 "bytes"4 "encoding/json"5 "fmt"6 "github.com/diegostock12/kubeml/ml/pkg/api"7 "github.com/pkg/errors"8 "io"9 "io/ioutil"10 "mime/multipart"11 "net/http"12 "os"13)14var (15 filenames = []string{"x-train", "y-train", "x-test", "y-test"}16)17type (18 // DatasetsGetter returns an object to interact with the19 // kubeml datasets20 DatasetsGetter interface {21 Datasets() DatasetInterface22 }23 // DatasetInterface has methods to work with dataset resources24 DatasetInterface interface {25 Create(name, trainData, trainLabels, testData, testLabels string) error26 Delete(name string) error27 Get(name string) (*api.DatasetSummary, error)28 List() ([]api.DatasetSummary, error)29 }30 // datasets implements DatasetInterface31 datasets struct {32 controllerUrl string33 httpClient *http.Client34 }35)36func newDatasets(c *V1) DatasetInterface {37 return &datasets{38 controllerUrl: c.controllerUrl,39 httpClient: c.httpClient,40 }41}42func (d *datasets) Create(name, trainData, trainLabels, testData, testLabels string) error {43 url := d.controllerUrl + "/dataset/" + name44 // Create the files to index the file name45 files := []string{trainData, trainLabels, testData, testLabels}46 body := new(bytes.Buffer)47 writer := multipart.NewWriter(body)48 // For each of the files add a multipart form field49 // with the specific filename and its contents50 for i, name := range files {51 file, err := os.Open(name)52 if err != nil {53 return errors.Wrap(err, fmt.Sprintf("could not open file %s", name))54 }55 defer file.Close()56 part, err := writer.CreateFormFile(filenames[i], file.Name())57 if err != nil {58 return errors.Wrap(err, fmt.Sprintf("could not write part from file %s", name))59 }60 _, err = io.Copy(part, file)61 if err != nil {62 return errors.Wrap(err, fmt.Sprintf("could not copy part from file %s", name))63 }64 fmt.Println("File", name, "added to the multipart form")65 }66 err := writer.Close()67 if err != nil {68 return errors.Wrap(err, "could not close writer")69 }70 resp, err := d.httpClient.Post(url, writer.FormDataContentType(), body)71 if err != nil {72 return errors.Wrap(err, "could not process creation request")73 }74 defer resp.Body.Close()75 var result map[string]string76 respBody, err := ioutil.ReadAll(resp.Body)77 if err != nil {78 return err79 }80 err = json.Unmarshal(respBody, &result)81 if resp.StatusCode != http.StatusOK {82 return errors.New(fmt.Sprintf("Could not complete task: %s", result["error"]))83 }84 fmt.Println(result["result"])85 return nil86}87func (d *datasets) Delete(name string) error {88 url := d.controllerUrl + "/dataset/" + name89 req, err := http.NewRequest(http.MethodDelete, url, nil)90 if err != nil {91 return errors.Wrap(err, "could not create request body")92 }93 resp, err := d.httpClient.Do(req)94 if err != nil {95 return errors.Wrap(err, "could not handle request")96 }97 defer resp.Body.Close()98 var result map[string]string99 respBody, err := ioutil.ReadAll(resp.Body)100 if err != nil {101 return err102 }103 err = json.Unmarshal(respBody, &result)104 if resp.StatusCode != http.StatusOK {105 return errors.New(fmt.Sprintf("Status code is not OK: %s", result["error"]))106 }107 fmt.Println(result["result"])108 return nil109}110func (d *datasets) Get(name string) (*api.DatasetSummary, error) {111 url := d.controllerUrl + "/dataset/" + name112 resp, err := d.httpClient.Get(url)113 if err != nil {114 return nil, errors.Wrap(err, "could not get perform http request")115 }116 defer resp.Body.Close()117 body, err := ioutil.ReadAll(resp.Body)118 if err != nil {119 return nil, errors.Wrap(err, "could not read responde body")120 }121 var dataset api.DatasetSummary122 err = json.Unmarshal(body, &dataset)123 if err != nil {124 return nil, errors.Wrap(err, "could not decode body")125 }126 return &dataset, nil127}128func (d *datasets) List() ([]api.DatasetSummary, error) {129 url := d.controllerUrl + "/dataset"130 resp, err := d.httpClient.Get(url)131 if err != nil {132 return nil, errors.Wrap(err, "could not get perform http request")133 }134 defer resp.Body.Close()135 body, err := ioutil.ReadAll(resp.Body)136 if err != nil {137 return nil, errors.Wrap(err, "could not read responde body")138 }139 var result []api.DatasetSummary140 err = json.Unmarshal(body, &result)141 if err != nil {142 return nil, errors.Wrap(err, "could not decode body")143 }144 return result, nil145}...

Full Screen

Full Screen

TestLabels

Using AI Code Generation

copy

Full Screen

1result := new Result()2result.TestLabels()3result := new Result()4result.TestLabels()5result := new Result()6result.TestLabels()7result := new Result()8result.TestLabels()9result := new Result()10result.TestLabels()11result := new Result()12result.TestLabels()13result := new Result()14result.TestLabels()15result := new Result()16result.TestLabels()17result := new Result()18result.TestLabels()19result := new Result()20result.TestLabels()21result := new Result()22result.TestLabels()23result := new Result()24result.TestLabels()25result := new Result()26result.TestLabels()27result := new Result()28result.TestLabels()29result := new Result()30result.TestLabels()31result := new Result()32result.TestLabels()33result := new Result()34result.TestLabels()35result := new Result()36result.TestLabels()37result := new Result()38result.TestLabels()

Full Screen

Full Screen

TestLabels

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("TestLabels")4 fmt.Println(result.TestLabels())5}6import (7func main() {8 fmt.Println("TestLabels")9 fmt.Println(result.TestLabels())10}11import (12func main() {13 fmt.Println("TestLabels")14 fmt.Println(result.TestLabels())15}16import (17func main() {18 fmt.Println("TestLabels")19 fmt.Println(result.TestLabels())20}21import (22func main() {23 fmt.Println("TestLabels")24 fmt.Println(result.TestLabels())25}26import (27func main() {28 fmt.Println("TestLabels")29 fmt.Println(result.TestLabels())30}31import (32func main() {33 fmt.Println("TestLabels")34 fmt.Println(result.TestLabels())35}36import (37func main() {38 fmt.Println("TestLabels")39 fmt.Println(result.TestLabels())40}41import (42func main() {43 fmt.Println("TestLabels")44 fmt.Println(result.TestLabels())45}46import (47func main() {48 fmt.Println("TestLabels")49 fmt.Println(result.TestLabels())50}51import (

Full Screen

Full Screen

TestLabels

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 result := text.NewResult()4 classifier := text.NewClassifier(result)5 classifier.Learn("i love this sandwich.", "pos")6 classifier.Learn("this is an amazing place!", "pos")7 classifier.Learn("I feel very good about these beers.", "pos")8 classifier.Learn("this is my best work.", "pos")9 classifier.Learn("what an awesome view", "pos")10 classifier.Learn("I do not like this restaurant", "neg")11 classifier.Learn("I am tired of this stuff.", "neg")12 classifier.Learn("I can't deal with this", "neg")13 classifier.Learn("he is my sworn enemy!", "neg")14 classifier.Learn("my boss is horrible.", "neg")15 classifier.Train()16 fmt.Println(classifier.Test("the beer was good."))17 fmt.Println(classifier.Test("I do not enjoy my job"))18 fmt.Println(classifier.Test("I ain't feeling dandy today."))19 fmt.Println(classifier.Test("I feel amazing!"))20 fmt.Println(classifier.Test("Gary is a friend of mine."))21 fmt.Println(classifier.Test("I can't believe I'm doing this."))22 fmt.Println(result.TestLabels())23}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful