Example #1
0
        private bool OnSetPredictedServiceItem(Entity entity, ClassificationResult result)
        {
            ////TODO #CRM-34721 Devide into 2 packages: for Customer Center and Service Enterprise
            if (entity.FindEntityColumnValue("ServicePactId") == null)
            {
                return(true);
            }
            UserConnection userConnection = Get <UserConnection>("UserConnection");

            Guid.TryParse(result.Value, out var serviceItemId);
            Guid servicePactId = entity.GetTypedColumnValue <Guid>("ServicePactId");
            var  select        = (Select) new Select(userConnection)
                                 .Column(Column.Const(1))
                                 .From("ServiceInServicePact").As("sp")
                                 .InnerJoin("ServiceStatus").As("ss").On("sp", "StatusId").IsEqual("ss", "Id")
                                 .Where("sp", "ServiceItemId").IsEqual(Column.Parameter(serviceItemId, "Guid"))
                                 .And("sp", "ServicePactId").IsEqual(Column.Parameter(servicePactId, "Guid"))
                                 .And("ss", "Active").IsEqual(Column.Parameter(true, "Boolean"));

            try {
                return(select.ExecuteScalar <int>() > 0);
            } catch (Exception e) {
                return(false);
            }
        }
Example #2
0
        public double CrossValidate()
        {
            ExampleSet v_Set;   // validation set

            //Logging.Info("Retrieving validation set");
            v_Set = this.m_problem.ValidationSet;

            int numExample = v_Set.Examples.Count;
            int numCorrect = 0;

            //Logging.Info("Cross Validating on validation set");

            foreach (Example example in v_Set.Examples)
            {
                ClassificationResult result = new ClassificationResult();

                if (this.PredictText(example) == example.Label.Id)
                {
                    numCorrect++;
                }
            }

            double correctRatio = 1.0 * numCorrect / numExample;

            Logger.Info(string.Format("Correct ratio: {0}", correctRatio));

            return(correctRatio);
        }
        private ClassifierResult ComputeResult(string text, Document document, string documentPath, ClassifierDocumentType[] documentTypes, int evidencePage)
        {
            // example of unsuccessful classification
            if (documentTypes == null || !documentTypes.Any() || document.Pages.Length <= evidencePage)
            {
                return(null);
            }

            // take first word from the evidence page in the document and consider it as evidence for the classification
            var firstWord           = document.Pages[evidencePage].Sections[0].WordGroups[0].Words[0];
            var firstWordValueToken = new ResultsValueTokens(0, (float)document.Pages[evidencePage].Size.Width, (float)document.Pages[evidencePage].Size.Height, new[] { firstWord.Box });

            // return first document type, with evidecing based on the first word in the document
            var classificationResult = new ClassificationResult(
                // consider the first document type requested
                documentTypes.First().DocumentTypeId,
                // fill in document id from the Document Object Model information
                document.DocumentId,
                // simulate a 85% confidence
                0.85f,
                // take OCR confidence of the words used for evidencing
                firstWord.OcrConfidence,
                // build the evidencing information
                new ResultsContentReference(firstWord.IndexInText, firstWord.Text.Length, new[] { firstWordValueToken }),
                // consider the classification applying to the entire document (all pages)
                new ResultsDocumentBounds(document.Pages.Length, document.Length));

            return(new ClassifierResult
            {
                Classifications = new[] { classificationResult }
            });
        }
Example #4
0
        public ClassificationResult ClassifyData(string text)
        {
            var result = new ClassificationResult { Text = text };
            var stopWords = Helpers.GetStopWords();

            foreach (var token in new Document(text))
            {
                if (stopWords.Contains(token))
                {
                    continue;
                }

                var positiveCount = _positiveCorpus.GetTokenCount(token);
                var negativeCount = _negativeCorpus.GetTokenCount(token);

                var tokenProbability = calculateProbability(positiveCount, _positiveCorpus.EntryCount, negativeCount, _negativeCorpus.EntryCount);
                recordProbability(tokenProbability);

                result.TokenProbabilities.Add(new TokenProbability
                {
                    Token = token,
                    Probability = tokenProbability,
                    PositiveTotal = _positiveCorpus.EntryCount,
                    PositiveMatches = positiveCount,
                    NegativeTotal = _negativeCorpus.EntryCount,
                    NegativeMatches = negativeCount,
                    Sentiment = calculateSentiment(tokenProbability)
                });
            }

            result.OverallProbability = combineProbabilities();
            result.Sentiment = calculateSentiment(result.OverallProbability);

            return result;
        }
Example #5
0
        public void ClassifyNearestNeighbour()
        {
            foreach (var testObject in _testSet.Objects)
            {
                float finalValue = 0f;
                bool  first      = true;
                var   result     = new ClassificationResult {
                    Object = testObject
                };

                foreach (var trainingObject in _trainingSet.Objects)
                {
                    float tempValue = 0f;

                    for (int i = 0; i < testObject.FeaturesNumber; i++)
                    {
                        tempValue += (float)Math.Pow(testObject.Features[i] - trainingObject.Features[i], 2);
                    }

                    tempValue = (float)Math.Sqrt(tempValue);

                    if (first || tempValue < finalValue)
                    {
                        finalValue = tempValue;
                        result.AssignedClassName = trainingObject.ClassName;
                        first = false;
                    }
                }

                NearestNeighbourResult.ClassificationResults.Add(result);
            }
        }
Example #6
0
        public void ClassifyNearesMean()
        {
            Dictionary <string, float[]> classMeans = CountClassMeans();


            foreach (var testObject in _testSet.Objects)
            {
                var result = new ClassificationResult {
                    Object = testObject
                };
                float finalValue = 0f;

                foreach (var classMean in classMeans)
                {
                    float tempValue = 0f;

                    var currentMean = classMean.Value;

                    for (int i = 0; i < testObject.FeaturesNumber; i++)
                    {
                        tempValue += (float)Math.Pow(testObject.Features[i] - currentMean[i], 2);
                    }

                    tempValue = (float)Math.Sqrt(tempValue);

                    if (finalValue == 0f || tempValue < finalValue)
                    {
                        finalValue = tempValue;
                        result.AssignedClassName = classMean.Key;
                    }
                }

                NearestMeanResult.ClassificationResults.Add(result);
            }
        }
        /// <summary>
        /// Saves the predictions and updates column value if prediction is highly significant.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="results">The results.</param>
        /// <param name="targetColumnName">Name of the target column.</param>
        /// <param name="valueSelectorFunc">Function for select value from prediction list to be setted in target field.
        /// If <c>null</c> - high significance value will be selected.</param>
        protected virtual void SavePredictions(Entity entity, List <ClassificationResult> results,
                                               string targetColumnName,
                                               Func <IEnumerable <ClassificationResult>, ClassificationResult> valueSelectorFunc)
        {
            var connectionArg = new ConstructorArgument("userConnection", _userConnection);
            var saver         = ClassFactory.Get <MLPredictionSaver>(connectionArg);

            saver.SavePrediction(ModelId, ModelInstanceUId, entity.PrimaryColumnValue, results);
            ClassificationResult highSignificanceValue = null;

            if (valueSelectorFunc != null)
            {
                highSignificanceValue = valueSelectorFunc(results);
            }
            else
            {
                highSignificanceValue = results.FirstOrDefault(result => result.Significance == HighSignificance);
            }
            if (highSignificanceValue == null)
            {
                _log.InfoFormat("No significant value detected for '{0}' with record id '{1}'",
                                entity.Schema.Name, entity.PrimaryColumnValue);
                return;
            }
            _log.InfoFormat("Saving significant value '{2}' for '{0}' with record id '{1}'",
                            entity.Schema.Name, entity.PrimaryColumnValue, highSignificanceValue.Value);
            EntitySchemaColumn targetColumn = entity.Schema.GetSchemaColumnByPath(targetColumnName);

            entity.SetColumnValue(targetColumn.ColumnValueName, new Guid(highSignificanceValue.Value));
            entity.Save(false);
        }
Example #8
0
        public double CrossValidate(TextClassificationProblem problem)
        {
            ExampleSet v_Set;   // validation set

            //Logging.Info("Retrieving validation set");
            v_Set = problem.ValidationSet;

            int numExample = v_Set.Examples.Count;
            int numCorrect = 0;

            //Logging.Info("Cross Validating on validation set");

            foreach (TextExample example in v_Set.Examples)
            {
                ClassificationResult result = new ClassificationResult();
                this.Predict(problem, example, ref result);
                if (result.Vnb == example.Label.Name)
                {
                    numCorrect++;
                }
            }

            double correctRatio = 1.0 * numCorrect / numExample;

            Logger.Info(string.Format("Correct ratio: {0}", correctRatio));

            return(correctRatio);
        }
Example #9
0
        private async Task <ClassificationResult> DoMlNetClassifierAction(IFormFile file)
        {
            var client = _httpClientFactory.CreateClient(HttpClients.ApiGW);

            var fileContent = new StreamContent(file.OpenReadStream())
            {
                Headers =
                {
                    ContentLength = file.Length,
                    ContentType   = new MediaTypeHeaderValue(file.ContentType)
                }
            };

            var formDataContent = new MultipartFormDataContent();

            formDataContent.Add(fileContent, "file", file.FileName);

            var response = await client.PostAsync(API.Products.ImageClassifier.PostImage(_settings.ImageClassifierApiUrl, VERSION_API), formDataContent);

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();

                var scoredProduct = JsonConvert.DeserializeObject <ClassificationResult>(result);

                return(scoredProduct);
            }
            else
            {
                return(ClassificationResult.InvalidResult(response.StatusCode));
            }
        }
        private void btnSavePicture_Click(object sender, EventArgs e)
        {
            ClassificationResult result = lstResults.SelectedItems[0].Tag as ClassificationResult;

            if (result == null)
            {
                return;
            }

            SaveFileDialog savefile = new SaveFileDialog();

            // set a default file name
            savefile.FileName = result.Classifier.Name + "-" + DateTime.Now.ToFileTimeUtc() + ".png";
            // set filters - this can be done in properties as well
            savefile.Filter = "Image files (*.png)|*.png|All files (*.*)|*.*";

            if (savefile.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            Bitmap bitmap = resultsDrawingService.DrawResult(result, 1000);

            bitmap.Save(savefile.FileName, ImageFormat.Png);
        }
        /// <summary>
        /// Called when entity field need to be setted by predicted value.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="columnValueName">Name of the column value.</param>
        /// <param name="result">The predicted value.</param>
        /// <returns><c>true</c> - if value may be setted to field, else - <c>false</c>.</returns>
        public override bool OnSetupPredictedValue(Entity entity, string columnValueName,
                                                   ClassificationResult result)
        {
            if (!base.OnSetupPredictedValue(entity, columnValueName, result))
            {
                return(false);
            }
            if (columnValueName != "ServiceItemId")
            {
                return(true);
            }
            if (!Guid.TryParse(result.Value, out var serviceItemId))
            {
                return(false);
            }
            Guid servicePactId = entity.GetTypedColumnValue <Guid>("ServicePactId");
            var  select        = (Select) new Select(UserConnection)
                                 .Column(Column.Const(1))
                                 .From("ServiceInServicePact").As("sp")
                                 .InnerJoin("ServiceStatus").As("ss").On("sp", "StatusId").IsEqual("ss", "Id")
                                 .Where("sp", "ServiceItemId").IsEqual(Column.Parameter(serviceItemId, "Guid"))
                                 .And("sp", "ServicePactId").IsEqual(Column.Parameter(servicePactId, "Guid"))
                                 .And("ss", "Active").IsEqual(Column.Parameter(true, "Boolean"));

            try {
                return(select.ExecuteScalar <int>() > 0);
            } catch (Exception e) {
                Log.Error($"MLServicePredictedValueFilter.OnSetupPredictedValue throws exception {e}");
                return(false);
            }
        }
        private static void PlacePart(Point originOfTesselationPolygon, Part part, ClassificationResult result)
        {
            Part placedPart = part.Clone();

            placedPart.Place(originOfTesselationPolygon);

            result.Parts.Add(placedPart);
        }
Example #13
0
 private bool OnSetPredictedValue(Entity entity, string columnValueName, ClassificationResult result)
 {
     if (columnValueName == "ServiceItemId")
     {
         return(OnSetPredictedServiceItem(entity, result));
     }
     return(true);
 }
        private static ClassificationResult GetDirectedResult(INestingManager nestingManager, Part part, WorkingArea workingArea, List <Part> originalParts)
        {
            float areaX, areaY;

            if (!nestingManager.IsRectangle(workingArea, out areaX, out areaY))
            {
                throw new Exception("WorkingArea is not a rectangle!");
            }


            //Step 1: Calculate the tesselation polygon
            float boxX, boxY;

            nestingManager.GetRectangleBoxOfPart(part, out boxX, out boxY);
            int horizontalBoxes = (int)(areaX / boxX);
            int verticalBoxes   = (int)(areaY / boxY);

            ClassificationResult result = new ClassificationResult(ClassifierInformation);

            //Step 4: Calculate the remainder polygons
            List <WorkingArea> remainderPolygons = CalculateRemainderWorkingAreas(
                nestingManager,
                boxX,
                boxY,
                horizontalBoxes,
                verticalBoxes,
                areaX,
                areaY);

            //Step 5: Generate the reimainder polygons' problems
            foreach (WorkingArea remainderPolygon in remainderPolygons)
            {
                ClassificationResult subResult = GetMainResult(nestingManager, originalParts, remainderPolygon);

                if (!nestingManager.IsRectangle(remainderPolygon, out areaX, out areaY))
                {
                    throw new Exception("WorkingArea is not a rectangle!");
                }

                result.ExtraPolygons.Add(nestingManager.CalculateRectangle(areaX, areaY, remainderPolygon.Placement));

                result.AddSubResult(subResult, remainderPolygon.Placement);
            }

            for (int i = 0; i < horizontalBoxes; i++)
            {
                for (int j = 0; j < verticalBoxes; j++)
                {
                    Point placementPart = new Point(i * boxX, j * boxY);

                    PlaceGenericPart(nestingManager, placementPart, part, result);

                    result.ExtraPolygons.Add(nestingManager.CalculateRectangle(boxX, boxY, placementPart));
                }
            }

            return(result);
        }
Example #15
0
        public static ClassificationResult Classify(IExpression expr, string variable)
        {
            var classification = new ClassificationResult();

            Search(expr, e => e.DimensionKey.Key == variable, classification.SearchResult);
            classification.EquationType = FindType(classification.SearchResult);

            return(classification);
        }
Example #16
0
        //mouse released//
        private void jPanel2MouseReleased(MouseEvent evt)
        {
            currentX = evt.X;
            currentY = evt.Y;


            const double  SCALE = 0.1;
            BufferedImage bi    = new BufferedImage(32, 32, BufferedImage.TYPE_BYTE_GRAY);

            Graphics2D grph = (Graphics2D)bi.Graphics;

            grph.scale(SCALE, SCALE);

            grph.drawImage(canvas, 0, 0, null);
            grph.dispose();

            newPix = new double[32 * 32];
            pixels = bi.getRGB(0, 0, 32, 32, pixels, 0, 32);

            for (int i = 0; i < pixels.Length; i++)
            {
                newPix[i]  = 255 - (pixels[i] & 0xff);
                newPix[i] /= 255;
            }


            long start = DateTimeHelperClass.CurrentUnixTimeMillis();

            network.Input = newPix;
            network.calculate();
            Console.WriteLine("Execution time: " + (DateTimeHelperClass.CurrentUnixTimeMillis() - start) + " milliseconds");

            try
            {
                ImageIO.write(bi, "png", new File("number.png"));
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }

            double[] networkOutput = network.Output;
            int      maxNeuronIdx  = Utils.maxIdx(networkOutput);

            ClassificationResult max = new ClassificationResult(maxNeuronIdx, networkOutput[maxNeuronIdx]);


            Console.WriteLine("New calculation:");
            Console.WriteLine("Class: " + max.ClassIdx);
            Console.WriteLine("Probability: " + max.NeuronOutput);

            label.Text = Convert.ToString(max.ClassIdx);
        }
Example #17
0
        private static ClassificationResult ClassifyGeneric(
            INestingManager manager,
            List <Part> parts,
            WorkingArea workingArea)
        {
            float areaX, areaY;

            if (!manager.IsRectangle(workingArea, out areaX, out areaY))
            {
                throw new Exception("WorkingArea is not a rectangle!");
            }

            float boxX, boxY;

            manager.GetRectangleBoxOfParts(parts, out boxX, out boxY);

            if (boxX > areaX || boxY > areaY)
            {
                throw new Exception("Part does not fit inside Working area!");
            }

            //Calculate how many boxes could be fit in the area
            int horizontalBoxes = (int)(areaX / boxX);
            int verticalBoxes   = (int)(areaY / boxY);

            //We build the final result using the partial results and the calculated positions of the boxes
            ClassificationResult result = new ClassificationResult(ClassifierInformation)
            {
                WorkingArea = workingArea.Clone()
            };

            int partIndex = 0;

            //Place parts until we run out of space
            for (int i = 0; i < horizontalBoxes; i++)
            {
                for (int j = 0; j < verticalBoxes; j++)
                {
                    Point subResultOrigin = new Point(i * boxX, j * boxY);
                    result.ExtraPolygons.Add(manager.CalculateRectangle(boxX, boxY, subResultOrigin));

                    Part placedPart = parts[partIndex % parts.Count].Clone();

                    placedPart.Place(subResultOrigin);

                    result.Parts.Add(placedPart);

                    partIndex++;
                }
            }

            return(result);
        }
Example #18
0
        private static void PrintWrongResults(
            ClassificationResult classificationResult, LearningResult learningResult)
        {
            var nodeAndVectors = new[] {
                classificationResult.WronglyAcceptedNodes
                .Zip(classificationResult.WronglyAcceptedVectors, Tuple.Create),
                classificationResult.WronglyRejectedNodes
                .Zip(classificationResult.WronglyRejectedVectors, Tuple.Create)
            };
            var titles = new[] {
                "WronglyAcceptedNodes", "WronglyRejectedNodes"
            };

            for (int i = 0; i < nodeAndVectors.Length; i++)
            {
                Console.WriteLine("--------------- " + titles[i] + " ---------------");
                foreach (var nodeAndVector in nodeAndVectors[i])
                {
                    var node   = nodeAndVector.Item1;
                    var vector = nodeAndVector.Item2;
                    Console.WriteLine(node.Code);
                    Console.WriteLine(GetGoodAncestorNode(node).Code);
                    var groupPath  = learningResult.FeatureEncoder.GetGroupPathFromNode(node);
                    var groupIndex = learningResult.Classifier.GetGroupIndex(groupPath);
                    Console.WriteLine("Group: " + (groupIndex + 1) + " (" + groupPath + ")");
                    Console.WriteLine("IsAccepted: "
                                      + learningResult.Classifier.IsAccepted(vector, groupIndex));
                    Console.WriteLine("IsRejected: "
                                      + learningResult.Classifier.IsRejected(vector, groupIndex));
                    var featureStrings =
                        learningResult.FeatureEncoder.GetFeatureStringsByVector(vector);
                    foreach (var featureString in featureStrings)
                    {
                        Console.WriteLine(Beautify(featureString));
                    }
                    if (i == 1)
                    {
                        Console.WriteLine("------------- Rejcting Features -------------");
                        var negativeVector = vector
                                             & learningResult.Classifier.Units[groupIndex].Rejecting;
                        featureStrings =
                            learningResult.FeatureEncoder.GetFeatureStringsByVector(
                                negativeVector);
                        foreach (var featureString in featureStrings)
                        {
                            Console.WriteLine(Beautify(featureString));
                        }
                    }
                    Console.WriteLine("---------------------------------------------");
                }
            }
        }
Example #19
0
        public void PredictText(ExampleSet t_Set, Example text, ref ClassificationResult result)
        {
            double f;

            f = Calculate_F(t_Set, text.X);

            if (f >= 0)
            {
                result.ResultCategoryId = +1;
            }
            else
            {
                result.ResultCategoryId = -1;
            }
        }
        public async Task <IActionResult> ClassifyImage()
        {
            var    files  = Request.Form.Files;
            string output = await _classificationService
                            .ClassifyImageCharacters(files[0]);

            bool isDrug = await
                          _drugRegistryService
                          .IsDrug(output);

            ClassificationResult result =
                new ClassificationResult(output, isDrug);

            return(Ok(result));
        }
Example #21
0
        public void ClassifyKNearestNeighbour(uint k)
        {
            Dictionary <string, int> classCounter = _trainingSet.ClassNames.ToDictionary(className => className, className => 0);

            foreach (var testObject in _testSet.Objects)
            {
                IList <float> values = new List <float>();
                var           result = new ClassificationResult {
                    Object = testObject
                };

                foreach (string className in _trainingSet.ClassNames)
                {
                    classCounter[className] = 0;
                }

                foreach (var trainingObject in _trainingSet.Objects)
                {
                    float tempValue = 0f;

                    for (int i = 0; i < testObject.FeaturesNumber; i++)
                    {
                        tempValue += (float)Math.Pow(testObject.Features[i] - trainingObject.Features[i], 2);
                    }

                    tempValue = (float)Math.Sqrt(tempValue);
                    values.Add(tempValue);
                }

                IList <int> minValuesIndexes = new List <int>();

                for (int i = 0; i < k; i++)
                {
                    var lowestValue = values.Where(v => !minValuesIndexes.Contains(values.IndexOf(v))).Min();
                    minValuesIndexes.Add(values.IndexOf(lowestValue));
                }

                foreach (int index in minValuesIndexes)
                {
                    classCounter[_trainingSet.Objects[index].ClassName]++;
                }

                result.AssignedClassName = classCounter.First(c => c.Value == classCounter.Values.Max()).Key;

                KNearestNeighbourResult.ClassificationResults.Add(result);
            }
        }
Example #22
0
 public IEnumerable<ClassificationResult> ClasifyOpearations(IEnumerable<BankOperation> operations)
 {
     List<ClassificationResult> classificationResult = new List<ClassificationResult>();
     foreach (var currentOperation in operations)
     {
         var foundMatches = _definitionsToApply
             .Where(r1 => r1.DoMatch(currentOperation))
             .Select(r2 => new RuleMatch()
                 {
                     MatchedDefinition = r2.Definition,
                     Description = r2.GetCustomDescription()
                 });
         var subResult = new ClassificationResult() { BankOperation = currentOperation, Matches = foundMatches };
         classificationResult.Add(subResult);
     }
     return classificationResult;
 }
        public List <ClassificationResult> ClassifyAll()
        {
            ClassificationResult mainResult = GetMainResult(
                manager,
                classificationParameters.Parts,
                classificationParameters.WorkingArea);

            if (mainResult == null)
            {
                return(new List <ClassificationResult>());
            }

            return(new List <ClassificationResult>()
            {
                mainResult
            });
        }
Example #24
0
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return(false);
            }
            if (obj == this)
            {
                return(true);
            }
            if (!(obj is ClassificationResult))
            {
                return(false);
            }
            ClassificationResult that = (ClassificationResult)obj;

            return(this.ClassIdx == that.ClassIdx);
        }
Example #25
0
        public static ClassificationResult CalculateThreshold(List <SimilarityResult> similarityResults)
        {
            var result = new ClassificationResult()
            {
                Lines = new List <ClassificationResultLine>()
            };

            similarityResults = similarityResults.OrderBy(s => s.AvgDistFromReferences).ToList();
            for (int i = 0; i < similarityResults.Count - 1; i++)
            {
                var threshold = (similarityResults[i].AvgDistFromReferences + similarityResults[i + 1].AvgDistFromReferences) / 2;
                CalculateRates(similarityResults, threshold, out var far, out var frr);
                result.Lines.Add(new ClassificationResultLine {
                    Threshold = threshold, Far = far, Frr = frr, Aer = (far + frr) / 2
                });
            }
            result.Threshold = result.Lines.OrderBy(er => er.Aer).First().Threshold;
            return(result);
        }
Example #26
0
        private IClassificationResult RecognizeBlurryLineGesture(TrackedGesture inputData)
        {
            if (!CheckTokenCriterion(inputData.FrameList, 1))
            {
                return(null);
            }

            Vertex startPoint, endPoint;
            int    startPointIndex = FindFirstFrameIndexWithCorrectCount(inputData.FrameList, 1, true);
            int    endPointIndex   = FindFirstFrameIndexWithCorrectCount(inputData.FrameList, 1, false);

            Touch t = inputData.FrameList[startPointIndex][0];

            startPoint = new Vertex(t.x, t.y);

            int maxDistantBlobFrameIndex;
            //search endpoint es point with max distance from start point
            //accounts for misleading data and offers robust identification of lines with disadvantage of
            //more wrong positive classifications
            int maxDistantBlobIndex = GetBlobMaxDistantFromPointIndex(inputData.FrameList, startPoint, out maxDistantBlobFrameIndex);

            if (startPointIndex == -1 || endPointIndex == -1 ||
                startPointIndex == endPointIndex || maxDistantBlobFrameIndex == -1)
            {
                return(null);
            }


            t        = inputData.FrameList[endPointIndex][0];
            endPoint = new Vertex(t.x, t.y);


            IClassificationResult result = null;

            if (CheckMaxDistanceFromLineKriterion(inputData.FrameList, startPoint, endPoint, MAXDISTFROMLINE) &&
                MetricDistances.EuclideanDistance(startPoint, endPoint) > MINLINELENGTH)
            {
                //return RecognizeDirectionalLine(startPoint, endPoint);
                result = new ClassificationResult("line", 100.0, new Sample[] { new Sample(DateTime.Now, startPoint), new Sample(DateTime.Now, endPoint) },
                                                  new KeyValuePair <String, double>("angle", GetAngle(startPoint, endPoint)));
            }
            return(result);
        }
        /// <summary>
        /// Sets the predicted results to entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="columnValueName">Name of the column value.</param>
        /// <param name="classificationResults">The classification results.</param>
        /// <param name="onSetEntityValue">Function, that will be invoked before setting predicted value to entity.
        /// If it returns <c>false</c>, the value won't be set.</param>
        /// <returns><c>true</c> if the value was set, otherwise - <c>false</c>.</returns>
        protected virtual bool SetPredictedResultsToEntity(Entity entity, string columnValueName,
                                                           List <ClassificationResult> classificationResults,
                                                           Func <Entity, string, ClassificationResult, bool> onSetEntityValue)
        {
            var columnValue = entity.FindEntityColumnValue(columnValueName);
            ClassificationResult highlySignificantResult =
                classificationResults.FirstOrDefault(result => result.Significance == HighSignificance);

            if (highlySignificantResult == null)
            {
                return(false);
            }
            if (onSetEntityValue != null && !onSetEntityValue(entity, columnValueName, highlySignificantResult))
            {
                return(false);
            }
            entity.SetColumnValue(columnValue.Column, highlySignificantResult.Value);
            return(true);
        }
Example #28
0
        public List <ClassificationResult> ClassifyAll()
        {
            ClassifierInformation information = classifier.GetClassifierInformation();

            try
            {
                startTime = DateTime.UtcNow;

                List <ClassificationResult> temp = classifier.ClassifyAll();

                List <ClassificationResult> result = new List <ClassificationResult>();


                endTime = DateTime.UtcNow;


                foreach (ClassificationResult res in temp)
                {
                    res.TimeTaken = endTime - startTime;

                    float partsArea = res.Parts.Select(x => x.GetTotalArea()).Sum();

                    res.RemainingArea = res.WorkingArea.GetTotalArea() - partsArea;

                    result.Add(res);
                }

                return(result.OrderBy(x => x.RemainingArea).ToList());
            }
            catch (Exception ex)
            {
                ClassificationResult result = new ClassificationResult(information);
                result.Error     = ex;
                result.HasError  = true;
                endTime          = DateTime.UtcNow;
                result.TimeTaken = endTime - startTime;
                return(new List <ClassificationResult>()
                {
                    result
                });
            }
        }
        //Result selected
        private void lstResults_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            ListView item = sender as ListView;

            if (item == null || item.SelectedItems.Count == 0)
            {
                return;
            }

            ClassificationResult result = item.SelectedItems[0].Tag as ClassificationResult;

            if (result == null)
            {
                return;
            }

            Bitmap bitmap = resultsDrawingService.DrawResult(result, Math.Max(imgDrawArea.Size.Height, imgDrawArea.Size.Width));

            imgDrawArea.Image = bitmap;
        }
Example #30
0
        public async Task <IActionResult> PostImage(IFormFile file)
        {
            ClassificationResult result = null;

            if (_settings.UseMlNetClassifier)
            {
                _logger.LogInformation($"Beginning a ML.NET based classification");
                result = await DoMlNetClassifierAction(file);
            }
            else
            {
                _logger.LogInformation($"Beginning a Cognitive-service containerized Classification");
                result = await DoCognitiveClassifierAction(file);
            }

            if (!result.IsOk)
            {
                _logger.LogInformation($"Classification failed due to HTTP CODE {result.Code}");
                return(StatusCode((int)result.Code, "Request to inner container returned HTTP " + result.Code));
            }

            _logger.LogInformation($"Classification ended up with tag {result.Label} with a prob (0-1) of {result.Probability}");

            var client = _httpClientFactory.CreateClient(HttpClients.ApiGW);
            // Need to query products API for tag
            var ptagsResponse = await client.GetAsync(API.Products.GetByTag(_settings.ProductsApiUrl, VERSION_API, result.Label));

            if (ptagsResponse.StatusCode == HttpStatusCode.NotFound)
            {
                _logger.LogInformation($"Tag {result.Label} do not have any object associated");
                return(Ok(Enumerable.Empty <ClassifiedProductItem>()));
            }

            ptagsResponse.EnsureSuccessStatusCode();

            var suggestedProductsJson = await ptagsResponse.Content.ReadAsStringAsync();

            var suggestedProducts = JsonConvert.DeserializeObject <IEnumerable <ClassifiedProductItem> >(suggestedProductsJson);

            return(Ok(suggestedProducts));
        }
Example #31
0
        public ClassificationResult ClassifyOne()
        {
            //This classifier does not classify

            ClassificationResult result = new ClassificationResult(ClassifierInformation);

            result.WorkingArea = (WorkingArea)parameters.WorkingArea.Clone();

            List <Part> parts = new List <Part>();

            foreach (Part part in parameters.Parts)
            {
                Part classifiedPart = (Part)part.Clone();
                classifiedPart.Place(new Point(5, 5));
                parts.Add(classifiedPart);
            }

            result.Parts = parts;

            return(result);
        }
        public void CrossValidate(TextClassificationProblem problem, out double correctRatio, out double falsePositive, out double falseNegative)
        {
            ExampleSet v_Set;   // validation set

            //Logging.Info("Retrieving validation set");
            v_Set = problem.ValidationSet;

            int numExample = v_Set.Examples.Count;
            int numCorrect = 0;
            int numFP = 0, numFN = 0;

            //Logging.Info("Cross Validating on validation set");

            foreach (TextExample example in v_Set.Examples)
            {
                ClassificationResult result = new ClassificationResult();
                this.Predict(problem, example, ref result);
                string res = this.MinCostClassName(result);

                if (res == example.Label.Name)
                {
                    numCorrect++;
                }
                else if (res == className[0] && example.Label.Name == className[1])
                {
                    numFP++;
                }
                else if (res == className[1] && example.Label.Name == className[0])
                {
                    numFN++;
                }
            }

            correctRatio  = 1.0 * numCorrect / numExample;
            falsePositive = 1.0 * numFP / numExample;
            falseNegative = 1.0 * numFN / numExample;
            Logger.Info("Correct ratio: {0}", correctRatio);
            Logger.Info("False Positive: {0}", falsePositive);
            Logger.Info("False Negative: {0}", falseNegative);
        }
Example #33
0
        private static void PrintWrongResults(
                ClassificationResult classificationResult, LearningResult learningResult) {
            var nodeAndVectors = new[] {
                classificationResult.WronglyAcceptedNodes
                        .Zip(classificationResult.WronglyAcceptedVectors, Tuple.Create),
                classificationResult.WronglyRejectedNodes
                        .Zip(classificationResult.WronglyRejectedVectors, Tuple.Create)
            };
            var titles = new[] {
                "WronglyAcceptedNodes", "WronglyRejectedNodes"
            };

            for (int i = 0; i < nodeAndVectors.Length; i++) {
                Console.WriteLine("--------------- " + titles[i] + " ---------------");
                foreach (var nodeAndVector in nodeAndVectors[i]) {
                    var node = nodeAndVector.Item1;
                    var vector = nodeAndVector.Item2;
                    Console.WriteLine(node.Code);
                    Console.WriteLine(GetGoodAncestorNode(node).Code);
                    var groupPath = learningResult.FeatureEncoder.GetGroupPathFromNode(node);
                    var groupIndex = learningResult.Classifier.GetGroupIndex(groupPath);
                    Console.WriteLine("Group: " + (groupIndex + 1) + " (" + groupPath + ")");
                    Console.WriteLine("IsAccepted: "
                                      + learningResult.Classifier.IsAccepted(vector, groupIndex));
                    Console.WriteLine("IsRejected: "
                                      + learningResult.Classifier.IsRejected(vector, groupIndex));
                    var featureStrings =
                            learningResult.FeatureEncoder.GetFeatureStringsByVector(vector);
                    foreach (var featureString in featureStrings) {
                        Console.WriteLine(Beautify(featureString));
                    }
                    if (i == 1) {
                        Console.WriteLine("------------- Rejcting Features -------------");
                        var negativeVector = vector
                                             & learningResult.Classifier.Units[groupIndex].Rejecting;
                        featureStrings =
                                learningResult.FeatureEncoder.GetFeatureStringsByVector(
                                        negativeVector);
                        foreach (var featureString in featureStrings) {
                            Console.WriteLine(Beautify(featureString));
                        }
                    }
                    Console.WriteLine("---------------------------------------------");
                }
            }
        }