Exemplo n.º 1
0
        public IList <TPredictionResult> Predict(IDataFrame queryDataFrame, IPredictionModel model, int dependentFeatureIndex)
        {
            ValidateModel(model);
            var knnModel               = model as IKnnPredictionModel <TPredictionResult>;
            var results                = new ConcurrentBag <RowIndexDistanceDto <TPredictionResult> >();
            var normalizedData         = NormalizeData(queryDataFrame, knnModel, dependentFeatureIndex);
            var normalizedTrainingData = normalizedData.Item1;
            var queryMatrix            = normalizedData.Item2;

            Parallel.For(0, queryDataFrame.RowCount, queryRowIdx =>
            {
                var rowVector = queryMatrix.Row(queryRowIdx);
                var distances = new ConcurrentBag <RowIndexDistanceDto <TPredictionResult> >();
                for (int trainingRowIdx = 0; trainingRowIdx < normalizedTrainingData.RowCount; trainingRowIdx++)
                {
                    var trainingRow = normalizedTrainingData.Row(trainingRowIdx);
                    TPredictionResult dependentFeatureValue = knnModel.ExpectedTrainingOutcomes[trainingRowIdx];
                    double distance = DistanceMeasure.Distance(rowVector, trainingRow);
                    var distanceDto = new RowIndexDistanceDto <TPredictionResult>(trainingRowIdx, distance, dependentFeatureValue);
                    distances.Add(distanceDto);
                }
                var sortedDistances = distances.OrderBy(distDto => distDto.Distance).Take(knnModel.KNeighbors);
                var result          = new RowIndexDistanceDto <TPredictionResult>(queryRowIdx, 0, _resultHandler(sortedDistances, WeightingFunction));
                results.Add(result);
            });
            return(results.OrderBy(res => res.RowIndex).Select(res => res.DependentFeatureValue).ToList());
        }