Ejemplo n.º 1
0
        /// <summary>
        /// Get k nearest neighbors of an instance.
        /// </summary>
        /// <param name="testingInstance">The instance to be used as a reference based on which distances to all other instances are calculated. </param>
        /// <param name="k">Number of neighbors to be selected. </param>
        /// <returns>Instances that are nearest to the testingInstance by Euclidean distance. </returns>
        private IEnumerable <Instance> GetNeighbors(Instance testingInstance, int k)
        {
            Dictionary <Instance, double> distStats = new Dictionary <Instance, double>();

            TrainingInstances.ForEach(i => distStats.Add(i, EuclideanDistance(testingInstance, i)));
            distStats.Remove(testingInstance);
            distStats = distStats.OrderBy(kvp => kvp.Value).Take(k).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            foreach (KeyValuePair <Instance, double> kvp in distStats)
            {
                yield return(kvp.Key);
            }
        }