示例#1
0
        protected override int Test(FeatureVector vector, out double[] details)
        {
            double[] votes_c          = new double[NoOfClasses];
            var      nearestNeighbors = new List <IdValuePair <double> >();

            for (int v_i = 0; v_i < TrainingVectors.Count; v_i++)
            {
                double distance = distanceFunc(TrainingVectors[v_i], vector);
                // If this neighbor is closer than our furthest neighbor, ...

                // If the list of nearest neighbors is empty OR this is the closest distance we'Ve seen,
                // then add neighbor as the closest neighbor (i.e. insert at position 0).
                if (nearestNeighbors.Count == 0 || distance < nearestNeighbors[0].Value)
                {
                    nearestNeighbors.Insert(0, new IdValuePair <double>(v_i, distance));
                    votes_c[TrainingVectors[v_i].Headers[Gold_i]]++;
                    // If we have too many neighbors, then remove the furthest one.
                    if (nearestNeighbors.Count > K)
                    {
                        votes_c[TrainingVectors[nearestNeighbors[nearestNeighbors.Count - 1].Id].Headers[Gold_i]]--;
                        nearestNeighbors.RemoveAt(nearestNeighbors.Count - 1);
                    }
                }
                else if (nearestNeighbors.Count < K || distance < nearestNeighbors[nearestNeighbors.Count - 1].Value)
                {
                    var newNeighbor = new IdValuePair <double>(v_i, distance);
                    int insert_b    = SearchHelper.FindInsertIndex(nearestNeighbors, newNeighbor);
                    if (insert_b <= K)
                    {
                        nearestNeighbors.Insert(insert_b, newNeighbor);
                        votes_c[TrainingVectors[v_i].Headers[Gold_i]]++;
                    }
                    // If we have too many neighbors, then remove the furthest one.
                    if (nearestNeighbors.Count > K)
                    {
                        votes_c[TrainingVectors[nearestNeighbors[nearestNeighbors.Count - 1].Id].Headers[Gold_i]]--;
                        nearestNeighbors.RemoveAt(nearestNeighbors.Count - 1);
                    }
                }
                Debug.Assert(nearestNeighbors.Count <= K);
            }
            if (nearestNeighbors.Count < K)
            {
                Console.Error.WriteLine("Warning: K nearest neighbors could not be found.");
            }

            details = NormalizationHelper.CreateNormalizedDistribution(votes_c);
            return(StatisticsHelper.ArgMax(votes_c));
        }
示例#2
0
 public int CompareTo(IdValuePair <T> that)
 {
     return(Value.CompareTo(that.Value));
 }
示例#3
0
        // Methods

        public int CompareTo(object obj)
        {
            IdValuePair <T> that = (IdValuePair <T>)obj;

            return(CompareTo(that));
        }