static void test_knn(string fn) { //string fn = @"C:\projects\local\GradeChecker\GradeChecker\bin\Debug\test.json"; try { var jss = new System.Web.Script.Serialization.JavaScriptSerializer(); List <Dictionary <string, object> > datas = jss.Deserialize <List <Dictionary <string, object> > >(System.IO.File.ReadAllText(fn)); string[] keys = testMQ.Properties.Resources.keys.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); Matrix <float> data; Matrix <int> response; load_data(datas.ToArray(), keys, out data, out response); using (KNearest model = new KNearest()) { model.Load("knn.xml"); for (int i = 0; i < data.Rows; i++) { float r = model.Predict(data.GetRow(i)); Dictionary <string, object> d = datas[i]; System.Console.WriteLine($"imei={d["imei"]}, VZW={d["VZW"]}, FD={grade_level[(int)r]}"); } } } catch (Exception) { } }
static void test_knn_1() { //Regex r = new Regex(@"^Color Temp: (\d+) K - Lux: (\d+) - R: (\d+) G: (\d+) B: (\d+) Rr: (\d+) Gr: (\d+) Br: (\d+) C: (\d+)\s*$"); //string[] lines = System.IO.File.ReadAllLines(@"data\test.txt"); //foreach(string s in lines) //{ // Match m = r.Match(s); // if (m.Success) // { // if (m.Groups.Count > 9) // { // } // } //} string s = "knn.xml"; if (System.IO.File.Exists(s)) { using (KNearest knn = new KNearest()) { knn.Load(s); //bool ok = knn.Train(data, Emgu.CV.ML.MlEnum.DataLayoutType.RowSample, response); Matrix <float> sample; test_data(out sample); float r = knn.Predict(sample); } } else { Matrix <float> data; Matrix <float> response; ReadMushroomData(out data, out response); // using (KNearest knn = new KNearest()) { knn.DefaultK = 3; knn.IsClassifier = true; bool ok = knn.Train(data, Emgu.CV.ML.MlEnum.DataLayoutType.RowSample, response); if (ok) { knn.Save("knn.xml"); //int cols = data.Cols; //Matrix<float> sample = new Matrix<float>(1, cols); Matrix <float> sample; test_data(out sample); float r = knn.Predict(sample); } } } }
public void SaveLoadTest() { float[] trainFeaturesData = { 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7 }; var trainFeatures = new Mat(6, 4, MatType.CV_32F, trainFeaturesData); int[] trainLabelsData = { 2, 3, 4, 5, 6, 7 }; var trainLabels = new Mat(1, 6, MatType.CV_32S, trainLabelsData); const string fileName = "knearest.yml"; if (File.Exists(fileName)) { File.Delete(fileName); } using (var model = KNearest.Create()) { model.Train(trainFeatures, SampleTypes.RowSample, trainLabels); model.Save(fileName); } Assert.True(File.Exists(fileName)); string content = File.ReadAllText(fileName); //Console.WriteLine(content); // Assert.DoesNotThrow using (var model2 = KNearest.Load(fileName)) { GC.KeepAlive(model2); } using (var model2 = KNearest.LoadFromString(content)) { GC.KeepAlive(model2); } }