private static void Train(string prefix) { SVMProblem trainingSet = SVMProblemHelper.Load(MnistDataPath + prefix + ".txt"); trainingSet = trainingSet.Normalize(SVMNormType.L2); SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.C_SVC; parameter.Kernel = SVMKernelType.RBF; parameter.C = 1; parameter.Gamma = 1; double[] crossValidationResults; int nFold = 5; trainingSet.CrossValidation(parameter, nFold, out crossValidationResults); double crossValidationAccuracy = trainingSet.EvaluateClassificationProblem(crossValidationResults); Console.WriteLine("\n\nCross validation accuracy: " + crossValidationAccuracy); SVMModel model = trainingSet.Train(parameter); SVM.SaveModel(model, MnistDataPath + "model.txt"); Console.WriteLine("\n\nModel ok!"); }
// for training the face, public void face_training(SVMProblem f_training) { SVMProblem trainingSet = SVMProblemHelper.Load(@"C:\Users\temp\Desktop\0921_towp.txt"); SVMProblem testSet = SVMProblemHelper.Load(@"C:\Users\temp\Desktop\0921_towpt.txt"); trainingSet = trainingSet.Normalize(SVMNormType.L2); testSet = testSet.Normalize(SVMNormType.L2); SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.NU_SVC; parameter.Kernel = SVMKernelType.SIGMOID; parameter.C = 1; parameter.Gamma = 1; parameter.Probability = true; double[] crossValidationResults; int nFold = 10; trainingSet.CrossValidation(parameter, nFold, out crossValidationResults); double crossValidationAccuracy = trainingSet.EvaluateClassificationProblem(crossValidationResults); SVMModel model = trainingSet.Train(parameter); double[] testResults = testSet.Predict(model); int[,] confusionMatrix; double testAccuracy = testSet.EvaluateClassificationProblem(testResults, model.Labels, out confusionMatrix); Training_result.Content = "testAccuracy:" + testAccuracy + "\nCross validation accuracy: " + crossValidationAccuracy + "\nCount " + trainingSet.Y.Count; Training_result.FontSize = 14; Training_result.FontStyle = FontStyles.Normal; Training_result.Foreground = Brushes.Red; Training_result.Background = Brushes.Black; index++; }
public void face_training(SVMProblem f_training) { SVMProblem trainingSet = SVMProblemHelper.Load(@"C:\Users\temp\Desktop\0921_towp.txt"); SVMProblem testSet = SVMProblemHelper.Load(@"C:\Users\temp\Desktop\0921_towpt.txt"); // f_training.Save(@"C:\Users\temp\Desktop\1005f.txt"); // trainingSet.Insert(index, f_training.X[0], 2); trainingSet.Add(f_training.X[0], 1); trainingSet.Save(@"C:\Users\temp\Desktop\flag.txt"); // trainingSet.Save(@"C:\Users\temp\Desktop\1005.txt"); // Console.WriteLine(); // SVMNode node = new SVMNode(); // node.Index = Convert.ToInt32(o); // node.Value = Convert.ToDouble(f_training.X); // nodes.Add(node); // trainingSet.Add(nodes.ToArray(), 1); // int number = randon.Next(0, trainingSet.X.Count); // int trainingsample = Convert.ToInt32(trainingSet.X.Count * 2 / 3); // int testingsample = Convert.ToInt32(trainingSet.X.Count / 3); trainingSet = trainingSet.Normalize(SVMNormType.L2); testSet = testSet.Normalize(SVMNormType.L2); SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.NU_SVC; parameter.Kernel = SVMKernelType.SIGMOID; parameter.C = 1; parameter.Gamma = 1; parameter.Probability = true; int nFold = 10; MainWindow main = new MainWindow(); double[] crossValidationResults; // output labels trainingSet.CrossValidation(parameter, nFold, out crossValidationResults); double crossValidationAccuracy = trainingSet.EvaluateClassificationProblem(crossValidationResults); SVMModel model = SVM.Train(trainingSet, parameter); // SVMModel model = trainingSet.Train(parameter); SVM.SaveModel(model, @"C:\Users\temp\Desktop\1005.txt"); double[] testResults = testSet.Predict(model); // Console.WriteLine(""); int[,] confusionMatrix; double testAccuracy = testSet.EvaluateClassificationProblem(testResults, model.Labels, out confusionMatrix); // Console.WriteLine("\n\nCross validation accuracy: " + crossValidationAccuracy); // Console.WriteLine("testAccuracy:" + testAccuracy); // Console.WriteLine(Convert.ToString(trainingSet.X.Count)); main.Training_result.Content = "testAccuracy:" + testAccuracy + "\nCross validation accuracy: " + crossValidationAccuracy + "\nCount " + trainingSet.X.Count; main.Training_result.FontSize = 14; main.Training_result.FontStyle = FontStyles.Normal; main.Training_result.Foreground = Brushes.Red; main.Training_result.Background = Brushes.Black; // Console.WriteLine(trainingSet1.Length); // trainingSet.Save(@"C:\Users\temp\Desktop\1005.txt"); index++; }
private static void TestOne(string prefix) { SVMModel model = SVM.LoadModel(MnistDataPath + "model.txt"); SVMProblem testSet = SVMProblemHelper.Load(MnistDataPath + prefix + ".txt"); testSet = testSet.Normalize(SVMNormType.L2); double[] testResults = testSet.Predict(model); Console.WriteLine("\nTest result: " + testResults[0].ToString()); }
//Coin SVM按鈕事件 private void button8_Click(object sender, EventArgs e) { StreamWriter Train_txt = new StreamWriter(@"train.txt"); StreamWriter Test_txt = new StreamWriter(@"test.txt"); for (int i = 0; i < 2000; i++) { if (CoinTrainingSet[i, 0] == 1) { Train_txt.WriteLine("1" + " 1:" + CoinTrainingSet[i, 1]); } else { Train_txt.WriteLine("-1" + " 1:" + CoinTrainingSet[i, 1]); } } for (int i = 0; i < 20000; i++) { if (i < 10000) { Test_txt.WriteLine("1" + " 1:" + RV_XY[i]); } else { Test_txt.WriteLine("-1" + " 1:" + RV_XY[i]); } } Train_txt.Close(); Test_txt.Close(); SVMProblem problem = SVMProblemHelper.Load(@"train.txt"); SVMProblem testProblem = SVMProblemHelper.Load(@"test.txt"); SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.C_SVC; parameter.Kernel = SVMKernelType.RBF; parameter.C = 1; parameter.Gamma = 0.0001; SVMModel model = SVM.Train(problem, parameter); double[] target = new double[testProblem.Length]; for (int i = 0; i < testProblem.Length; i++) { target[i] = SVM.Predict(model, testProblem.X[i]); } double accuracy = SVMHelper.EvaluateClassificationProblem(testProblem, target); label6.Text = accuracy.ToString(); }
private static void Test(string prefix) { SVMModel model = SVM.LoadModel(MnistDataPath + "model.txt"); SVMProblem testSet = SVMProblemHelper.Load(MnistDataPath + prefix + ".txt"); testSet = testSet.Normalize(SVMNormType.L2); double[] testResults = testSet.Predict(model); int[,] confusionMatrix; double testAccuracy = testSet.EvaluateClassificationProblem(testResults, model.Labels, out confusionMatrix); Console.WriteLine("\nTest accuracy: " + testAccuracy); }
//인식 하기 public static int SVM_Classification(SVMModel md) { int result = 0; SVMProblem testSet = SVMProblemHelper.Load("tmp.txt"); //인식데이터셋 열기 testSet = testSet.Normalize(SVMNormType.L2); double[] testResults = testSet.Predict(md); result = (int)testResults[0]; return(result); }
public void Evaluate(IEvolutionState state, Individual ind, int subpop, int threadnum) { if (!ind.Evaluated) { int imageIndex; var SVMTrainData = new StreamWriter(@"F:\Gesty\features\traindata" + threadnum + ".txt"); var SVMTestData = new StreamWriter(@"F:\Gesty\features\testdata" + threadnum + ".txt"); for (imageIndex = 0; imageIndex < imageList.Length; imageIndex++) { var image = new Image <Gray, Byte>(imageList[imageIndex]); var line = new StringBuilder(); image.CopyTo(currentImage[threadnum]); image.CopyTo(originalImage[threadnum]); image.Dispose(); ((GPIndividual)ind).Trees[0].Child.Eval(state, threadnum, Input, Stack, ((GPIndividual)ind), this); //int[] features = imageTransformer.GetSuperpixelFeatures(currentImage[threadnum]); int[] features = ImageTransformer.GetSquareSuperpixelFeatures(currentImage[threadnum], 25); line.Append((imageIndex / 213) + 1 + " "); for (int i = 1; i <= features.Length; i++) { line.Append(i + ":" + features[i - 1] + " "); } var lineString = line.ToString().Trim(); if (imageIndex % 2 == 0) { SVMTrainData.WriteLine(lineString); } else { SVMTestData.WriteLine(lineString); } } SVMTrainData.Close(); SVMTestData.Close(); var problem = SVMProblemHelper.Load(@"F:\Gesty\features\traindata" + threadnum + ".txt"); var testProblem = SVMProblemHelper.Load(@"F:\Gesty\features\testdata" + threadnum + ".txt"); var model = problem.Train(Parameter); double[] target = testProblem.Predict(model); double accuracy = testProblem.EvaluateClassificationProblem(target); var f = ((KozaFitness)ind.Fitness); f.SetStandardizedFitness(state, (float)(100 - accuracy)); ind.Evaluated = true; } }
//-------------------------------------------------------------------------------------- // private //--------------------------------------------------------------------------------------- /// <summary> /// 辞書ファイルを作成する /// </summary> /// <param name="input_learing_file"></param> /// <param name="gammma"></param> /// <param name="cost"></param> private void Training(string input_learing_file, float gammma, float cost) { //LibSVMのテスト //学習用のデータの読み込み SVMProblem problem = SVMProblemHelper.Load(input_learing_file); //SVMパラメータ SVMParameter parameter = new SVMParameter(); parameter.Type = LibSVMsharp.SVMType.C_SVC; parameter.Kernel = LibSVMsharp.SVMKernelType.RBF; parameter.C = cost; parameter.Gamma = gammma; //svmModelが上手く作れていない?ラベルが付けられてない!! libSVM_model = SVM.Train(problem, parameter); //辞書ファイルを出力(xmlファイル) string xml_name = @"model_" + input_learing_file; xml_name = xml_name.Replace(@".csv", @".xml"); SVM.SaveModel(libSVM_model, xml_name); //判定結果をファイルに出してみる SVMProblem testProblem = SVMProblemHelper.Load(input_learing_file); double[] target = new double[testProblem.Length]; string debug_file_str = @"debug_" + input_learing_file; using (StreamWriter w = new StreamWriter(debug_file_str)) { for (int i = 0; i < testProblem.Length; i++) { target[i] = SVM.Predict(libSVM_model, testProblem.X[i]); w.Write(target[i] + "\n"); Console.Out.WriteLine(@"{0} : {1}", i, target[i]); } } //正解率を出す。 double accuracy = SVMHelper.EvaluateClassificationProblem(testProblem, target); }
static void Main(string[] args) { SVMProblem problem = SVMProblemHelper.Load(@"Datasets\wine.txt"); problem = SVMProblemHelper.Normalize(problem, SVMNormType.L2); // Optional SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.C_SVC; parameter.Kernel = SVMKernelType.RBF; parameter.C = 1; parameter.Gamma = 1; // Do 10-fold cross validation double[] target; SVM.CrossValidation(problem, parameter, 10, out target); double crossValidationAccuracy = SVMHelper.EvaluateClassificationProblem(problem, target); // Train the model SVMModel model = SVM.Train(problem, parameter); double correct = 0; for (int i = 0; i < problem.Length; i++) { double y = SVM.Predict(model, problem.X[i]); if (y == problem.Y[i]) { correct++; } } double trainingAccuracy = correct / (double)problem.Length; Console.WriteLine("\nCross validation accuracy: " + crossValidationAccuracy); Console.WriteLine("\nTraining accuracy: " + trainingAccuracy); Console.ReadLine(); }
public static int predictSVM() { double[] results = { 99 }; //Variables.model = getExistingModel(); if (!Variables.newdata.Contains("null")) { SVMProblem newData = SVMProblemHelper.Load(Constants.NEWDATA_PATH); Console.Write("Predicted command:\n"); results = newData.Predict(Variables.model); /*foreach (var item in results) * { * Console.WriteLine(item.ToString()); * }*/ Console.WriteLine(results[0]); } else { Console.WriteLine("invalid new data"); } return((int)results[0]); }
//학습모델 생성 public static SVMModel SVM_GenModel(String dataset) { SVMProblem trainingSet = SVMProblemHelper.Load(dataset); //학습데이터셋 열기 trainingSet = trainingSet.Normalize(SVMNormType.L2); SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.C_SVC; parameter.Kernel = SVMKernelType.RBF; parameter.C = 1; parameter.Gamma = 1; double[] crossValidationResults; int nFold = 5; trainingSet.CrossValidation(parameter, nFold, out crossValidationResults); double crossValidationAccuracy = trainingSet.EvaluateClassificationProblem(crossValidationResults); SVMModel model = trainingSet.Train(parameter); // 학습된 모델 생성 SVM.SaveModel(model, "model_" + dataset); // 모델 저장 return(model); }
private void listBox2_SelectedIndexChanged(object sender, EventArgs e) { File.Create(parameter["hog_test_file"]).Dispose(); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); if (listBox2.SelectedIndex < 0) { return; } else { try { List <Mat> ListImage = new List <Mat>(); Mat img_display = new Mat(); string dir = listBox2.SelectedItem.ToString(); img_display = Cv2.ImRead(dir); pictureBox2.Image = img_display.ToBitmap(); // Process predict sw.Start(); Cv2.Resize(img_display, img_display, sizes2); ListImage.Add(img_display); FeatureExtraction.compute_hog_test(ListImage, sizes2, 100, parameter["hog_test_file"]); SVMProblem Test = SVMProblemHelper.Load(parameter["hog_test_file"]); double[] Target = Test.Predict(model_load); sw.Stop(); label13.Text = MAPPING[(int)(Target[0])].ToString(); label10.Text = sw.ElapsedMilliseconds.ToString() + " (ms)"; string time = sw.ElapsedMilliseconds.ToString(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
//学習ファイルの作成 public void TrainingExec(List <FaceFeature.FeatureValue> FeatureList) { //特徴量をMatに移し替える 2個で一つ //2個のfloat * LISTの大きさの配列 double[] feature_array = new double[2 * FeatureList.Count]; //特徴量をSVMで扱えるように配列に置き換える SetFeatureListToArray(FeatureList, ref feature_array); CvPoint2D32f[] feature_points = new CvPoint2D32f[feature_array.Length / 2]; int id = 0; for (int i = 0; i < feature_array.Length / 2; i++) { feature_points[id].X = (float)feature_array[i * 2]; feature_points[id].Y = (float)feature_array[i * 2 + 1]; id++; } CvMat dataMat = new CvMat(feature_points.Length, 2, MatrixType.F32C1, feature_points, true); //これがラベル番号 int[] id_array = new int[FeatureList.Count]; for (int i = 0; i < id_array.Length; i++) { id_array[i] = FeatureList[i].ID; } CvMat resMat = new CvMat(id_array.Length, 1, MatrixType.S32C1, id_array, true); // dataとresponsesの様子を描画 CvPoint2D32f[] points = new CvPoint2D32f[id_array.Length]; int idx = 0; for (int i = 0; i < id_array.Length; i++) { points[idx].X = (float)feature_array[i * 2]; points[idx].Y = (float)feature_array[i * 2 + 1]; idx++; } //学習データを図にする Debug_DrawInputFeature(points, id_array); //デバッグ用 学習させる特徴量を出力する OutPut_FeatureAndID(points, id_array); //LibSVMのテスト //学習用のデータの読み込み SVMProblem problem = SVMProblemHelper.Load(@"wine.txt"); SVMProblem testProblem = SVMProblemHelper.Load(@"wine.txt"); SVMParameter parameter = new SVMParameter(); parameter.Type = LibSVMsharp.SVMType.C_SVC; parameter.Kernel = LibSVMsharp.SVMKernelType.RBF; parameter.C = 1; parameter.Gamma = 1; SVMModel model = SVM.Train(problem, parameter); double[] target = new double[testProblem.Length]; for (int i = 0; i < testProblem.Length; i++) { target[i] = SVM.Predict(model, testProblem.X[i]); } double accuracy = SVMHelper.EvaluateClassificationProblem(testProblem, target); //SVMの用意 CvTermCriteria criteria = new CvTermCriteria(1000, 0.000001); CvSVMParams param = new CvSVMParams( OpenCvSharp.CPlusPlus.SVMType.CSvc, OpenCvSharp.CPlusPlus.SVMKernelType.Rbf, 10.0, // degree 100.0, // gamma 調整 1.0, // coeff0 10.0, // c 調整 0.5, // nu 0.1, // p null, criteria); //学習実行 svm.Train(dataMat, resMat, null, null, param); Debug_DispPredict(); }
private void btnTrain_Click(object sender, EventArgs e) { System.Diagnostics.Stopwatch time = new System.Diagnostics.Stopwatch(); parameter = load_json_file(parameter_file); try { File.Create(parameter["path_model"] + textBox3.Text + ".txt").Dispose(); File.Create(parameter["result_file"]).Dispose(); if (textBox3.Text == "") { MessageBox.Show("create model name"); } //if(SHOWRESULT.ContainsKey(txtModelName.Text)) //{ // MessageBox.Show("Model name already exits"); //} else { time.Start(); #region Creat file Model // Creat param SVM SVMProblem FileTrain = SVMProblemHelper.Load(parameter["hog_train_file"]); SVMParameter param = new SVMParameter(); param.Type = SVMType.C_SVC; if (parameter["kernel_svm"] == "RBF") { param.Kernel = SVMKernelType.RBF; } if (parameter["kernel_svm"] == "Linear") { param.Kernel = SVMKernelType.LINEAR; } if (parameter["kernel_svm"] == "Poly") { param.Kernel = SVMKernelType.POLY; } if (parameter["kernel_svm"] == "Sigmoid") { param.Kernel = SVMKernelType.SIGMOID; } // param.C = Convert.ToDouble(parameter["c"]); param.C = double.Parse(parameter["c"], CultureInfo.InvariantCulture); param.P = double.Parse(parameter["p"], CultureInfo.InvariantCulture); param.Gamma = double.Parse(parameter["gamma"], CultureInfo.InvariantCulture); param.Degree = Convert.ToInt16(parameter["degree"]); param.Nu = double.Parse(parameter["nu"], CultureInfo.InvariantCulture); param.Coef0 = double.Parse(parameter["coef0"], CultureInfo.InvariantCulture); param.Eps = double.Parse(parameter["eps"], CultureInfo.InvariantCulture); //Train model model = LibSVMsharp.SVM.Train(FileTrain, param); LibSVMsharp.SVM.SaveModel(model, parameter["path_model"] + textBox3.Text + ".txt"); time.Stop(); double train_time = time.ElapsedMilliseconds; #endregion #region Validation data SVMProblem Validation = SVMProblemHelper.Load(parameter["hog_val_file"]); double[] Target_validation = Validation.Predict(model); StreamWriter sw = new StreamWriter(parameter["result_file"], true, Encoding.UTF8); for (int i = 0; i < Target_validation.Length; i++) { string lines = Target_validation[i].ToString(); sw.WriteLine(lines); } sw.Close(); Accuracy = SVMHelper.EvaluateClassificationProblem(Validation, Target_validation); Accuracy = Math.Round(Accuracy, 3); // show result training textBox4.Text = (train_time / 1000).ToString(); textBox5.Text = Accuracy.ToString(); MessageBox.Show("Trainning sucessful"); #endregion } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public int SVM_face_recognition() { SVMProblem face_data = SVMProblemHelper.Load(@"C:\Users\temp\Desktop\Face_feature.txt"); face_data = face_data.Normalize(SVMNormType.L2); //using Libsvm package which has api to calculate the probabilty face_data.PredictProbability(face_recognition_model, out prolist); var ok = prolist.ToArray(); var v = ok[0]; // we have 13 person int maxconfidenceindex = 0; double maxconfidence = v[maxconfidenceindex]; double threshold = 0.25; for (int i = 0; i < v.Count(); i++) { if (v[i] > maxconfidence) { maxconfidenceindex = i; maxconfidence = v[i]; } } if (threshold < maxconfidence) { f1 = v[0]; f2 = v[1]; f3 = v[2]; f4 = v[3]; f5 = v[4]; /* * f6 = v[5]; * f7 = v[6]; * f8 = v[7]; * f9 = v[8]; * f10 = v[9]; * f11 = v[10]; * f12 = v[11]; * f13 = v[12]; */ double[] faceresult = face_data.Predict(face_recognition_model); facename = Convert.ToInt16(faceresult[0]); // facename =facemodel.Labels[maxconfidenceindex]; faceshow++; } int labelnum = face_recognition_model.Labels[maxconfidenceindex]; if (threshold > maxconfidence) { // Console.WriteLine("Unknow"); facename = 0; display.Content = "Unknow"; facefail++; } return(facename); }
/// <summary> /// Function which will run forever, continously classifying histogram batches into key events. /// </summary> public void run() { List <Histogram> temp = null; List <Histogram> hb; SVMProblem problem = SVMProblemHelper.Load(PipelineConstants.SVMFeaturesFile); SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.C_SVC; parameter.Kernel = SVMKernelType.RBF; parameter.C = 13.9; parameter.Gamma = .029; SVMModel model = SVM.Train(problem, parameter); string[] eventTrigger = { "standing", "leftShoulder", "rightShoulder", "leftHip", "rightHip" }; ScanCodeShort[] keyEvents = { ScanCodeShort.KEY_S, ScanCodeShort.KEY_I, ScanCodeShort.KEY_O, ScanCodeShort.KEY_K, ScanCodeShort.KEY_L }; // Continuously scan the histogram share point for new histogram data while (true) { hb = hsp.histBatch; // Compare references -- if the share point has a different reference, we're out of date if (temp != hb && hb != null) { temp = hb; int count = 1; // Convert histogram bins into SVM feature vectors List <SVMNode> nodes = new List <SVMNode>(); for (int i = 0; i < temp.Count; i++) { Histogram histObject = temp[i]; for (int j = 0; j < histObject.BucketCount; j++) { SVMNode node = new SVMNode(); node.Index = count++; node.Value = histObject[j].Count / SkeletonFrameWindowProcessor.WindowSize; nodes.Add(node); } } // Get a prediction double y = SVM.Predict(model, nodes.ToArray()); // Use a sliding of votes to filter out brief moments of misclassification votingWindow.Add(y); while (votingWindow.Count > VotingWindowSize) { votingWindow.RemoveAt(0); } // Neat one-liner taken from http://stackoverflow.com/a/8260598 // Group the votes, sorty by group size, select the largest, select the associated vote value double vote = votingWindow.GroupBy(v => v).OrderByDescending(g => g.Count()).First().Key; // Change the console title to make it clear what the classifier is seeing System.Console.Title = eventTrigger[(int)vote]; // Only trigger a keypress when the voted value changes // This has the result of holding a pose being equivalent to quickly dropping it // i.e., the gesture is invariant to duration if (vote != 0 && vote != previousVote) { SendInputWithAPI(keyEvents[(int)vote]); } previousVote = vote; } } }
// activity classification public void SVM_Classification() { testSet1 = SVMProblemHelper.Load(@"Dataset\ADLfall_test1.txt"); testSet1 = testSet1.Normalize(SVMNormType.L2); float sum; if (testSet1.Length != 0) { try { //var resut = model.Predict(testSet1.X[testSet1.Length - 1]); // p = Convert.ToInt16(resut); //predict the result using model, return result var result = testSet1.Predict(activity_model); p = Convert.ToInt16(result[0]); //put the result into enqueue myq.Enqueue(p); switch (p) { case 1: q++; break; case 2: w++; break; case 3: e++; break; case 4: r++; break; } } catch { } // if the collected data is larger than 30 if (myq.Count > 30) { // dequeue the old one myq.TryDequeue(out p); switch (p) { case 1: q--; break; case 2: w--; break; case 3: e--; break; case 4: r--; break; } // proportional sum = q + w + e + r; // activity.Content = ("Sit down:" + sit_down + "\n" + "Walking" + walkig + "\n" + "Standing" + standing + "\n" + "Fall event" + fallevent); activity.Content = ("Sit down: " + Math.Round(e / sum, 2) * 100 + "%" + "\n" + "Walking: " + Math.Round(q / sum, 2) * 100 + "%" + "\n" + "Standing: " + Math.Round(w / sum, 2) * 100 + "%" + "\n" + "Fall event: " + Math.Round(r / sum, 2) * 100 + "%"); // activity.Content = ("Sit down:" + Math.Round(h / sum, 2) + "\n" + "Walking" + Math.Round(w / sum, 2) + "\n" + "Standing" + Math.Round(q / sum, 2) + "\n" + "Fall event" + Math.Round(r / sum, 2)); if (e / sum > 0.5) { label.Content = ("You have sit down"); label.Foreground = Brushes.Red; } else if (q / sum > 0.5) { label.Content = "You are walking"; label.Foreground = Brushes.Red; } else if (w / sum > 0.5) { label.Content = "You are standing"; label.Foreground = Brushes.Red; } else if (r / sum > 0.5) { label.Content = "You fell down"; label.Foreground = Brushes.Red; } activity.FontSize = 20; activity.FontStyle = FontStyles.Normal; activity.Foreground = Brushes.Red; activity.Background = Brushes.Black; } } }
public static SVMProblem Normalize(this SVMProblem problem, SVMNormType type) { return(SVMProblemHelper.Normalize(problem, type)); }
static void Main(string[] args) { // Load the datasets: In this example I use the same datasets for training and testing which is not suggested SVMProblem trainingSet = SVMProblemHelper.Load(@"C:\Users\temp\Desktop\ADLfall_train.txt"); // SVMProblem testSet = SVMProblemHelper.Load(@"C:\Users\temp\Desktop\ADLfall_test.txt"); SVMProblem testSet1 = SVMProblemHelper.Load(@"C:\Users\temp\Desktop\ADLfall_test1.txt"); // SVMProblem testSet1 = SVMProblemHelper.Load(@"C:\Users\temp\Desktop\result.txt"); // Normalize the datasets if you want: L2 Norm => x / ||x|| trainingSet = trainingSet.Normalize(SVMNormType.L2); // testSet = testSet.Normalize(SVMNormType.L2); testSet1 = testSet1.Normalize(SVMNormType.L2); // Select the parameter set SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.C_SVC; parameter.Kernel = SVMKernelType.RBF; parameter.C = 32768.0; parameter.Gamma = 8.0; // Do cross validation to check this parameter set is correct for the dataset or not double[] crossValidationResults; // output labels int nFold = 5; // trainingSet1.CrossValidation(parameter, nFold, out crossValidationResults); // Evaluate the cross validation result // If it is not good enough, select the parameter set again // double crossValidationAccuracy = trainingSet.EvaluateClassificationProblem(crossValidationResults); // Train the model, If your parameter set gives good result on cross validation // SVMModel model = trainingSet.Train(parameter); // Save the model // SVM.SaveModel(model, @"Model\activity_recognition.txt"); SVMModel model = SVM.LoadModel(@"Model\activity_recognition.txt"); int p, q, w, e, r, ok = 0; double sum; q = 0; w = 0; e = 0; r = 0; // Predict the instances in the test set double[] testResults = testSet1.Predict(model); while (ok < testSet1.Length) { var resut = model.Predict(testSet1.X[ok]); // Console.WriteLine("resut111:" + resut); p = Convert.ToInt16(resut); switch (p) { case 1: q++; break; case 2: w++; break; case 3: e++; break; case 4: r++; break; } ok++; } sum = q + w + e + r; Console.WriteLine("result:" + Math.Round(q / sum, 2) + "," + Math.Round(w / sum, 2) + "," + Math.Round(e / sum, 2) + "," + Math.Round(r / sum, 2)); // Evaluate the test results int[,] confusionMatrix; double testAccuracy = testSet1.EvaluateClassificationProblem(testResults, model.Labels, out confusionMatrix); // Print the resutls // Console.WriteLine("\n\nCross validation accuracy: " + crossValidationAccuracy); Console.WriteLine("\nTest accuracy: " + testAccuracy); Console.WriteLine("\nConfusion matrix:\n"); // Print formatted confusion matrix Console.Write(String.Format("{0,6}", "")); for (int i = 0; i < model.Labels.Length; i++) { Console.Write(String.Format("{0,5}", "(" + model.Labels[i] + ")")); } Console.WriteLine(); for (int i = 0; i < confusionMatrix.GetLength(0); i++) { Console.Write(String.Format("{0,5}", "(" + model.Labels[i] + ")")); for (int j = 0; j < confusionMatrix.GetLength(1); j++) { Console.Write(String.Format("{0,5}", confusionMatrix[i, j])); } Console.WriteLine(); } Console.WriteLine("\n\nPress any key to quit..."); Console.ReadLine(); }
public static SVMProblem RemoveDuplicates(this SVMProblem problem) { return(SVMProblemHelper.RemoveDuplicates(problem)); }
//SVM按鈕事件 private void button5_Click(object sender, EventArgs e) { StreamWriter Train_txt = new StreamWriter(@"train.txt"); StreamWriter Test_txt = new StreamWriter(@"test.txt"); int[] get; for (int i = 0; i < TrainingSet.Count; i++) { get = TrainingSet[i]; if (get[0] == 1) { Train_txt.WriteLine("1" + " 1:" + get[1] + " 2:" + get[2] + " 3:" + get[3]); } else { Train_txt.WriteLine("-1" + " 1:" + get[1] + " 2:" + get[2] + " 3:" + get[3]); } } for (int i = 0; i < height; i++) { for (int j = 0; j < wide; j++) { Test_txt.WriteLine("1" + " 1:" + Image[0, j, i] + " 2:" + Image[1, j, i] + " 3:" + Image[2, j, i]); } } Train_txt.Close(); Test_txt.Close(); SVMProblem problem = SVMProblemHelper.Load(@"train.txt"); SVMProblem testProblem = SVMProblemHelper.Load(@"test.txt"); SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.C_SVC; parameter.Kernel = SVMKernelType.RBF; parameter.C = 1; parameter.Gamma = 0.0001; SVMModel model = SVM.Train(problem, parameter); double[] target = new double[testProblem.Length]; for (int i = 0; i < testProblem.Length; i++) { target[i] = SVM.Predict(model, testProblem.X[i]); } //改圖 Rectangle recta = new Rectangle(0, 0, wide, height); BmData = copy.LockBits(recta, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); IntPtr Scan = BmData.Scan0; int Offset = BmData.Stride - wide * 3; unsafe { byte *P = (byte *)(void *)Scan; for (int y = 0; y < height; y++, P += Offset) { for (int x = 0; x < wide; x++, P += 3) { if (target[y * wide + x] > 0) { P[2] = 255; P[1] = 255; P[0] = 255; } else { P[2] = 0; P[1] = 0; P[0] = 0; } } } } copy.UnlockBits(BmData); pictureBox3.Image = copy; }
public static bool trainProblem() { if (checkExistingDataset()) { SVMProblem problem = SVMProblemHelper.Load(Constants.DATA_PATH); SVMProblem randdata = SVMProblemHelper.Load(Constants.RAND_PATH); List <string> resultsstring = new List <string>(); List <SVMClass.SVMResult> ResultsList = new List <SVMClass.SVMResult>(); double C, gammasq; double Cmin = 1, Cmax = 10000, Cstep = 10; double gmin = 0.0001, gmax = 1000, gstep = 10; bool satisfied = false; while (!satisfied) { for (C = Cmin; C <= Cmax; C = C * Cstep) { for (gammasq = gmin; gammasq <= gmax; gammasq = gammasq * gstep) { SVMParameter tempparameter = new SVMParameter(); tempparameter.Type = SVMType.C_SVC; tempparameter.Kernel = SVMKernelType.RBF; tempparameter.C = C; tempparameter.Gamma = gammasq; SVMModel tempmodel = SVM.Train(problem, tempparameter); SVMProblem testData = SVMProblemHelper.Load(Constants.RAND_PATH); double[] results = testData.Predict(tempmodel); int[,] confusionMatrix; double testAccuracy = testData.EvaluateClassificationProblem(results, tempmodel.Labels, out confusionMatrix); // Do cross validation to check this parameter set is correct for the dataset or not double[] crossValidationResults; // output labels int nFold = 10; problem.CrossValidation(tempparameter, nFold, out crossValidationResults); // Evaluate the cross validation result // If it is not good enough, select the parameter set again double crossValidationAccuracy = problem.EvaluateClassificationProblem(crossValidationResults); SVMClass.SVMResult compiled = new SVMClass.SVMResult(); compiled.C = C; compiled.gamma = gammasq; compiled.testAcc = testAccuracy; compiled.crossValidAcc = crossValidationAccuracy; ResultsList.Add(compiled); } } // Evaluate the test results double maxTestAcc = ResultsList.Max(resultdata => resultdata.testAcc); //int maxTestAccIndex = ResultsList.FindIndex(resultdata => resultdata.testAcc.Equals(maxTestAcc)); double maxValidAcc = ResultsList.Max(resultdata => resultdata.crossValidAcc); //int maxValidAccIndex = ResultsList.FindIndex(resultdata => resultdata.crossValidAcc.Equals(maxValidAcc)); if (maxTestAcc < 95 || maxValidAcc < 95) { satisfied = false; Cstep--; gstep--; } else { satisfied = true; List <SVMClass.SVMResult> topResults = ResultsList.FindAll(resultdata => resultdata.testAcc.Equals(maxTestAcc)); List <SVMClass.SVMResult> topValid = ResultsList.FindAll(resultdata => resultdata.crossValidAcc.Equals(maxValidAcc)); while (topResults.Count > topValid.Count) { topResults.RemoveAt(ResultsList.FindIndex(resultsdata => resultsdata.crossValidAcc.Equals(ResultsList.Min(resultdata => resultdata.crossValidAcc)))); } double maxC = topResults.Max(resultdata => resultdata.C); int maxCIndex = topResults.FindIndex(resultdata => resultdata.C.Equals(maxC)); double bestgamma = topResults[maxCIndex].gamma; // maxC or not??? //double bestC = topResults[topResults.Count - 2].C; //topResults[maxCIndex].C; //double bestgamma = topResults[topResults.Count - 2].gamma;//topResults[maxCIndex].gamma; Console.WriteLine("Best C: " + maxC + " Best gammasq: " + bestgamma); Constants.C = maxC; Constants.gammasq = bestgamma; foreach (SVMClass.SVMResult resultdata in topResults) { Console.WriteLine(resultdata.C.ToString() + " " + resultdata.gamma.ToString()); } } } SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.C_SVC; parameter.Kernel = SVMKernelType.RBF; parameter.C = Constants.C; parameter.Gamma = Constants.gammasq; Variables.model = SVM.Train(problem, parameter); //File.WriteAllText(Constants.MODEL_PATH, String.Empty); //SVM.SaveModel(Variables.model, Constants.MODEL_PATH); Console.WriteLine("Trained and saved model.\n"); //return Variables.model; return(true); } else { MessageBox.Show("Invalid training data!"); return(false); } }
private void btnSVM_Click(object sender, EventArgs e) { SVMProblem problem = SVMProblemHelper.Load(@"train.txt"); //訓練樣本 SVMProblem testProblem = SVMProblemHelper.Load(@"train.txt"); //測試樣本 Image <Bgr, Byte> img = new Image <Bgr, Byte>(testProblem.Length, 128); //建立圖片 img.SetValue(255); //設為全白 double res = 0.0; //SVM的模板 SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.C_SVC; parameter.Kernel = SVMKernelType.LINEAR; //SVM模型 SVMModel model = SVM.Train(problem, parameter); double[] target = new double[testProblem.Length]; //上色 for (int i = img.Height - 1, k = 0; i > 0; --i) { for (int j = 0; j < img.Width; ++j) { if (k >= testProblem.Length) { break; } //SVM預測 res = SVM.Predict(model, testProblem.X[k]); target[k] = res; k++; if (res == 1) { for (int count = 100; count > 0; count--) { img[i - count, j] = new Bgr(255, 0, 0); } } else if (res == 2) { for (int count = 100; count > 0; count--) { img[i - count, j] = new Bgr(0, 255, 0); } } else if (res == 3) { for (int count = 100; count > 0; count--) { img[i - count, j] = new Bgr(0, 0, 255); } } else if (res == 4) { for (int count = 100; count > 0; count--) { img[i - count, j] = new Bgr(0, 0, 0); } } else if (res == 0) { for (int count = 100; count > 0; count--) { img[i - count, j] = new Bgr(127, 127, 127); } } } } //輸出圖片 ImageViewer output = new ImageViewer(img, "123"); output.Show(); //算出準確率 double accuracy = SVMHelper.EvaluateClassificationProblem(testProblem, target); lblAccuracy.Text = "準確率: " + accuracy; }
//public static SVMProblem RemoveDuplicates(this SVMProblem problem) //{ // //return SVMProblemHelper.RemoveDuplicates(problem); //} //public static SVMProblem Normalize(this SVMProblem problem, SVMNormType type) //{ // //return SVMProblemHelper.Normalize(problem, type); //} public static Dictionary <double, int> GetLabelsCount(this SVMProblem problem) { return(SVMProblemHelper.GetLabelsCount(problem)); }
static void Main(string[] args) { // Load the datasets: In this example I use the same datasets for training and testing which is not suggested SVMProblem trainingSet = SVMProblemHelper.Load(@"Dataset\wine.txt"); SVMProblem testSet = SVMProblemHelper.Load(@"Dataset\wine2.txt"); // Normalize the datasets if you want: L2 Norm => x / ||x|| trainingSet = trainingSet.Normalize(SVMNormType.L2); testSet = testSet.Normalize(SVMNormType.L2); // Select the parameter set SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.C_SVC; parameter.Kernel = SVMKernelType.RBF; parameter.C = 1; parameter.Gamma = 1; // Do cross validation to check this parameter set is correct for the dataset or not double[] crossValidationResults; // output labels int nFold = 5; trainingSet.CrossValidation(parameter, nFold, out crossValidationResults); // Evaluate the cross validation result // If it is not good enough, select the parameter set again double crossValidationAccuracy = trainingSet.EvaluateClassificationProblem(crossValidationResults); // Train the model, If your parameter set gives good result on cross validation SVMModel model = trainingSet.Train(parameter); // Save the model SVM.SaveModel(model, @"Model\wine_model.txt"); // Predict the instances in the test set double[] testResults = testSet.Predict(model); Console.WriteLine("aaa:" + testResults[0] + "\n"); /* * // Evaluate the test results * int[,] confusionMatrix; * double testAccuracy = testSet.EvaluateClassificationProblem(testResults, model.Labels, out confusionMatrix); * * * * * // Print the resutls * Console.WriteLine("\n\nCross validation accuracy: " + crossValidationAccuracy); * Console.WriteLine("\nTest accuracy: " + testAccuracy); * Console.WriteLine("\nConfusion matrix:\n"); * * // Print formatted confusion matrix * Console.Write(String.Format("{0,6}", "")); * for (int i = 0; i < model.Labels.Length; i++) * Console.Write(String.Format("{0,5}", "(" + model.Labels[i] + ")")); * Console.WriteLine(); * for (int i = 0; i < confusionMatrix.GetLength(0); i++) * { * Console.Write(String.Format("{0,5}", "(" + model.Labels[i] + ")")); * for (int j = 0; j < confusionMatrix.GetLength(1); j++) * Console.Write(String.Format("{0,5}", confusionMatrix[i,j])); * Console.WriteLine(); * } * * Console.WriteLine("\n\nPress any key to quit..."); * Console.ReadLine();*/ }
private void testSVM() { if (!holdCommandListener) { holdCommandListener = true; } string parentpath = System.AppDomain.CurrentDomain.BaseDirectory; string DATA_PATH = parentpath + "Datasets\\dataset - Copy (2).txt"; string MODEL_PATH = parentpath + "Model\\testmodel.txt"; string NEWDATA_PATH = parentpath + "Datasets\\testdata.txt"; string RESULTS_PATH = parentpath + "Datasets\\results.txt"; List <string> resultsstring = new List <string>(); SVMProblem testSet = SVMProblemHelper.Load(NEWDATA_PATH); SVMParameter testparameter = new SVMParameter(); testparameter.Type = SVMType.C_SVC; testparameter.Kernel = SVMKernelType.RBF; testparameter.C = 0.1; //Constants.C; testparameter.Gamma = 0.001; // Constants.gammasq; List <SVMClass.SVMResult> ResultsList = new List <SVMClass.SVMResult>(); SVMProblem problem = SVMProblemHelper.Load(DATA_PATH); double C = 0.001; double gammasq = 0.001; for (C = 1; C <= 1000; C = C * 10) { for (gammasq = 0.001; gammasq <= 1000; gammasq = gammasq * 10) { SVMParameter parameter = new SVMParameter(); parameter.Type = SVMType.C_SVC; parameter.Kernel = SVMKernelType.RBF; parameter.C = C; parameter.Gamma = gammasq; SVMModel model = SVM.Train(problem, parameter); //File.WriteAllText(MODEL_PATH, String.Empty); //SVM.SaveModel(model, MODEL_PATH); //Console.WriteLine("Trained and saved model.\n"); //model = SVM.LoadModel(MODEL_PATH); SVMProblem newData = SVMProblemHelper.Load(NEWDATA_PATH); //Console.Write("Predicted Result:\n"); double[] results = newData.Predict(model); //Console.Write(results[0]); int[,] confusionMatrix; double testAccuracy = newData.EvaluateClassificationProblem(results, model.Labels, out confusionMatrix); // Do cross validation to check this parameter set is correct for the dataset or not double[] crossValidationResults; // output labels int nFold = 10; problem.CrossValidation(parameter, nFold, out crossValidationResults); // Evaluate the cross validation result // If it is not good enough, select the parameter set again double crossValidationAccuracy = problem.EvaluateClassificationProblem(crossValidationResults); //Console.WriteLine("\n\nCross validation accuracy: " + crossValidationAccuracy); string temp = ""; string resultstring = "Predict accuracy: " + testAccuracy + " C: " + C + " gamma: " + gammasq + " Cross validation accuracy: " + crossValidationAccuracy; resultsstring.Add(resultstring); if (parameter.C == testparameter.C && parameter.Gamma == testparameter.Gamma) { resultsstring.Add("This one is same as separate test."); } foreach (double res in results) { temp += res.ToString() + " "; } resultsstring.Add(temp); SVMClass.SVMResult compiled = new SVMClass.SVMResult(); compiled.C = C; compiled.gamma = gammasq; compiled.testAcc = testAccuracy; compiled.crossValidAcc = crossValidationAccuracy; ResultsList.Add(compiled); } } File.WriteAllLines(RESULTS_PATH, resultsstring); SVMModel testmodel = SVM.Train(problem, testparameter); // Predict the instances in the test set double[] testResults = testSet.Predict(testmodel); foreach (double result in testResults) { Console.WriteLine(result); } // Evaluate the test results double maxTestAcc = ResultsList.Max(resultdata => resultdata.testAcc); int maxTestAccIndex = ResultsList.FindIndex(resultdata => resultdata.testAcc.Equals(maxTestAcc)); //double maxValidAcc = ResultsList.Max(resultdata => resultdata.crossValidAcc); //int maxValidAccIndex = ResultsList.FindIndex(resultdata => resultdata.crossValidAcc.Equals(maxValidAcc)); List <SVMClass.SVMResult> topResults = ResultsList.FindAll(resultdata => resultdata.testAcc.Equals(maxTestAcc)); double maxC = topResults.Max(resultdata => resultdata.C); int maxCIndex = topResults.FindIndex(resultdata => resultdata.C.Equals(maxC)); double bestC = topResults[topResults.Count - 2].C; //topResults[maxCIndex].C; double bestgamma = topResults[topResults.Count - 2].gamma; //topResults[maxCIndex].gamma; Console.WriteLine("Best C: " + bestC + " Best gammasq: " + bestgamma); foreach (SVMClass.SVMResult resultdata in topResults) { Console.WriteLine(resultdata.C.ToString() + " " + resultdata.gamma.ToString()); } //int[,] confusionMatrix; //double testAccuracy = testSet.EvaluateClassificationProblem(testResults, testmodel.Labels, out confusionMatrix); //Console.WriteLine("\n\nTest accuracy: " + testAccuracy); }
public static bool Save(this SVMProblem problem, string filename) { return(SVMProblemHelper.Save(problem, filename)); }
static void Main(string[] args) { SVMProblem testSet = SVMProblemHelper.Load(@"Dataset\wine.txt"); // Same as the training set SVMModel model = SVM.LoadModel(@"Model\wine_model.txt"); Console.WriteLine("Feature count in one instance: " + model.SV[0].Length + "\n\n"); // Test 1: Predict instances with SVMProblem's Predict extension method. sw.Start(); double[] target = testSet.Predict(model); sw.Stop(); double elapsedTimeInTest1 = (double)sw.ElapsedMilliseconds / (double)testSet.Length; Console.WriteLine("> Test 1: \nPredict instances with SVMProblem's Predict extension method.\n"); Console.WriteLine("\tAverage elapsed time of one prediction: " + elapsedTimeInTest1 + " ms\n"); // Test 2: Predict instances with RapidPreditor class which is an explicit implementation of the method used in Test 1. using (RapidPredictor predictor = new RapidPredictor(model)) // It needs to be Disposed { sw.Start(); target = new double[testSet.Length]; for (int i = 0; i < testSet.Length; i++) { target[i] = predictor.Predict(testSet.X[i]); } sw.Stop(); } double elapsedTimeInTest2 = (double)sw.ElapsedMilliseconds / (double)testSet.Length; Console.WriteLine("> Test 2: \nPredict instances with RapidPreditor class which is an explicit implementation of the method used in Test 1.\n"); Console.WriteLine("\tAverage elapsed time of one prediction: " + elapsedTimeInTest2 + " ms\n"); // Test 3: Predict instances with standard SVM.Predict method or SVMNode[]'s predict extension method. sw.Start(); target = new double[testSet.Length]; for (int i = 0; i < testSet.Length; i++) { target[i] = SVM.Predict(model, testSet.X[i]); } sw.Stop(); double elapsedTimeInTest3 = (double)sw.ElapsedMilliseconds / (double)testSet.Length; Console.WriteLine("> Test 3: \nPredict instances with standard SVM.Predict method or SVMNode[]'s Predict extension method.\n"); Console.WriteLine("\tAverage elapsed time of one prediction: " + elapsedTimeInTest3 + " ms\n"); // Print the results Console.WriteLine("\nExplanation:\n"); Console.WriteLine( "In standard SVM.Predict method, the SVMModel object is allocated and deallocated every time when the method called. " + "Also the SVMNode[]'s Predict extension methods directly calls the SVM.Predict. " + "However, the model is allocated once and is used to predict whole instances with its pointer in SVMProblem's " + "Predict extension method as implemented in the RapidPredictor class. You can take or modify this class in order " + "to use in your applications, if you have performance considerations. " + "I am not suggesting that SVMProblem's Predict extension method is used in real-time, because the model is allocated" + "in every method call."); Console.WriteLine("\n\nPress any key to quit..."); Console.ReadLine(); }