public List <IProbScoreProxy> Predicting(IResults results, int scanNum) { List <IScore> scores = results.GetResult(scanNum); ISpectrum spectrum = results.GetSpectrum(scanNum); List <double[]> estimationList = new List <double[]>(); List <IProbScoreProxy> probabilities = new List <IProbScoreProxy>(); foreach (IScore score in scores) { List <SVMNode> X = new List <SVMNode>(); // store score value in X int idx = 0; foreach (MassType type in types) { SVMNode node = new SVMNode(); node.Index = idx; node.Value = score.GetScore(type); X.Add(node); idx++; } testingProblem.X.Add(X.ToArray()); } // prediction double[] target = testingProblem.PredictProbability(model, out estimationList); testingProblem.X.Clear(); // create new scores for (int i = 0; i < scores.Count; i++) { probabilities.Add(new ProbScoreProxy(scores[i], spectrum, estimationList[i][1])); } return(probabilities); }
public Tuple <List <double[]>, double[]> Predicting(List <IScore> scores) { List <double[]> estimationList = new List <double[]>(); foreach (IScore score in scores) { List <SVMNode> X = new List <SVMNode>(); // store score value in X int idx = 0; foreach (MassType type in types) { SVMNode node = new SVMNode(); node.Index = idx; node.Value = score.GetScore(type); X.Add(node); idx++; } testingProblem.X.Add(X.ToArray()); } double [] target = testingProblem.PredictProbability(model, out estimationList); testingProblem.X.Clear(); return(Tuple.Create(estimationList, target)); }
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); }
public static SvmResult TrainAndTestSvm(SVMProblem trainingSet, SVMProblem testSet) { // find the ratio of malignant:benign cases: double mbTrainRatio = trainingSet.Y.Where(x => x == 0).ToArray().Length *1F / trainingSet.Y.Count; Console.WriteLine($"MB TRAIN RATIO: {mbTrainRatio}"); double mbTestRatio = testSet.Y.Where(x => x == 0).ToArray().Length * 1F / testSet.Y.Count; Console.WriteLine($"MB TEST RATIO: {mbTestRatio}"); SVMParameter parameter = new SVMParameter { Type = SVMType.C_SVC, Kernel = SVMKernelType.RBF, C = double.Parse(Configuration.Get("C")), Gamma = double.Parse(Configuration.Get("Gamma")), Probability = true, WeightLabels = new[] { 0, 1 }, Weights = new[] { (1 - mbTrainRatio) / mbTrainRatio, 1 } }; //parameter = TrainingHelper.FindBestHyperparameters(trainingSet, parameter); Console.WriteLine($"Found best parameters: c={parameter.C},gamma={parameter.Gamma}"); SVMModel model = trainingSet.Train(parameter); SVM.SaveModel(model, Configuration.Get("ModelLocation")); // The following evaluation has code from: // https://csharp.hotexamples.com/examples/LibSVMsharp/SVMParameter/-/php-svmparameter-class-examples.html // Predict the instances in the test set double[] testResults = testSet.Predict(model); // Evaluate the test results double testAccuracy = testSet.EvaluateClassificationProblem(testResults, model.Labels, out var confusionMatrix); // Print the resutls Console.WriteLine("\nTest accuracy: " + testAccuracy); Console.WriteLine("\nConfusion matrix:\n"); // Print formatted confusion matrix Console.Write($"{"",6}"); for (int i = 0; i < model.Labels.Length; i++) { Console.Write($"{"(" + model.Labels[i] + ")",5}"); } Console.WriteLine(); for (int i = 0; i < confusionMatrix.GetLength(0); i++) { Console.Write($"{"(" + model.Labels[i] + ")",5}"); for (int j = 0; j < confusionMatrix.GetLength(1); j++) { Console.Write($"{confusionMatrix[i, j],5}"); } Console.WriteLine(); } double sensitivity = confusionMatrix[0, 0] * 1.0 / (confusionMatrix[0, 1] + confusionMatrix[0, 0]); double specificity = confusionMatrix[1, 1] * 1.0 / (confusionMatrix[1, 1] + confusionMatrix[1, 0]); double[] results = testSet.PredictProbability(model, out var probabilities); for (int i = 0; i < probabilities.Count; i++) { // ReSharper disable once CompareOfFloatsByEqualityOperator String x = results[i] != testSet.Y[i] ? "MISPREDICTION" :""; Console.WriteLine($"{results[i]} | {probabilities[i][0]} | {probabilities[i][1]} | {testSet.Y[i]} | {x}"); } return(new SvmResult() { C = parameter.C, Gamma = parameter.Gamma, TestAccuracy = testAccuracy, Sensitivity = sensitivity, Specificity = specificity }); }
private async Task PerformAnalysis(String path, Rectangle rectangle) { UShortArrayAsImage image = null; double[] pcaComponents = null; int tasksComplete = 0; UpdateStatus(path, startingImageStatusStr); List <Task> tasks = new List <Task>() { new Task(() => { var file = db.FileStorage.FindById($"images/{path}"); var ms = new MemoryStream(); file.CopyTo(ms); ms.Seek(0, 0); image = DicomFile.Open(ms).GetUshortImageInfo(); UpdateStatus(path, loadedImageStatusStr); }), new Task(() => { image = Normalization.GetNormalizedImage(image, rectangle, int.Parse(Configuration.Get("sizeImageToAnalyze"))); db.FileStorage.Upload($"images/{path}-cropped", $"{path}-cropped", image.GetPngAsMemoryStream()); UpdateStatus(path, croppedImageStatusStr); }), new Task(() => { image = Contrast.ApplyHistogramEqualization(image); db.FileStorage.Upload($"images/{path}-croppedContrast", $"{path}-croppedContrast", image.GetPngAsMemoryStream()); UpdateStatus(path, contrastImageStatusStr); }), new Task(() => { //PCA PCA pca = PCA.LoadModelFromFile(Configuration.Get("PcaModelLocation")); if (!int.TryParse(Configuration.Get("componentsToUse"), out int components)) { components = pca.Eigenvalues.Length; } pcaComponents = pca.GetComponentsFromImage(image, components); UpdateStatus(path, pcaImageStatusStr); }), new Task(() => { //SVM SVMProblem svmProblem = new SVMProblem(); // add all the components to an SVMNode[] SVMNode[] nodes = new SVMNode[pcaComponents.Length]; for (int i = 0; i < pcaComponents.Length; i++) { nodes[i] = new SVMNode(i + 1, pcaComponents[i]); } svmProblem.Add(nodes, 0); svmProblem = svmProblem.Normalize(SVMNormType.L2); SVMModel svmModel = SVM.LoadModel(Configuration.Get("ModelLocation")); double[] results = svmProblem.PredictProbability(svmModel, out var probabilities); var analysis = db.GetCollection <Analysis>("analysis"); Analysis currentAnalysis = analysis.FindOne(x => x.Id.ToString().Equals(path)); currentAnalysis.Certainty = results[0] == 0 ? probabilities[0][1] * 100 : probabilities[0][0] * 100; currentAnalysis.Diagnosis = results[0] == 0 ? DdsmImage.Pathologies.Benign : DdsmImage.Pathologies .Malignant; analysis.Update(currentAnalysis); UpdateStatus(path, svmImageStatusStr); }) }; foreach (Task task in tasks) { task.Start(); await task; // lets set percentage done: var analysis = db.GetCollection <Analysis>("analysis"); Analysis currentAnalysis = analysis.FindOne(x => x.Id.ToString().Equals(path)); currentAnalysis.PercentageDone = (++tasksComplete * 100) / tasks.Count; analysis.Update(currentAnalysis); } UpdateStatus(path, doneStatusStr); }