Changeset 13791 for branches/PerformanceComparison/HeuristicLab.OptimizationExpertSystem.Common/3.3/Recommenders/KNearestNeighborModel.cs
- Timestamp:
- 04/25/16 12:56:17 (8 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/PerformanceComparison/HeuristicLab.OptimizationExpertSystem.Common/3.3/Recommenders/KNearestNeighborModel.cs
r13787 r13791 20 20 #endregion 21 21 22 using HeuristicLab.Co mmon;22 using HeuristicLab.Collections; 23 23 using HeuristicLab.Optimization; 24 24 using System; … … 30 30 private readonly int K; 31 31 private readonly string[] characteristics; 32 private readonly Dictionary<IRun, Dictionary<IAlgorithm, double>> performance; 33 private readonly BidirectionalDictionary<int, IRun> problemInstanceMap; 34 private readonly double[] medianValues; 32 35 33 public KNearestNeighborModel(int k, string[] characteristics) {36 public KNearestNeighborModel(int k, Dictionary<IRun, Dictionary<IAlgorithm, double>> perfData, string[] characteristics) { 34 37 this.K = k; 38 this.performance = perfData; 35 39 this.characteristics = characteristics; 40 problemInstanceMap = new BidirectionalDictionary<int, IRun>(); 41 var i = 0; 42 foreach (var pi in perfData.Keys) { 43 problemInstanceMap.Add(i++, pi); 44 } 45 this.medianValues = KnowledgeCenter.GetMedianValues(perfData.Keys.OrderBy(problemInstanceMap.GetBySecond).ToArray(), characteristics); 36 46 } 37 47 38 public IEnumerable<Tuple<IAlgorithm, double>> GetRanking(KnowledgeCenter kc) { 39 var distances = kc.GetProblemDistances(characteristics); 48 public IEnumerable<Tuple<IAlgorithm, double>> GetRanking(IRun problemInstance) { 49 var features = KnowledgeCenter.GetFeatures(performance.Keys.OrderBy(problemInstanceMap.GetBySecond).ToArray(), characteristics, medianValues); 50 var feature = KnowledgeCenter.GetFeatures(new [] { problemInstance }, characteristics, medianValues)[0]; 51 var nearestK = features.Select((f, i) => new { ProblemInstanceIndex = i, Feature = f }) 52 .OrderBy(x => x.Feature.Select((f, i) => (f - feature[i]) * (f - feature[i])).Sum()) 53 .Take(K); 54 40 55 var performances = new Dictionary<IAlgorithm, List<double>>(); 41 for (var k = 0; k < K; k++) { 42 if (distances.Count == 0) break; 43 var min = distances.MinItems(x => x.Value).First(); 44 // lookup algorithm performances in min 45 var perfs = kc.GetAlgorithmPerformance(min.Key); 46 if (perfs.Count == 0) { 47 k--; 48 continue; 49 } 56 foreach (var next in nearestK) { 57 var perfs = performance[problemInstanceMap.GetByFirst(next.ProblemInstanceIndex)]; 58 if (perfs.Count == 0) continue; 59 50 60 foreach (var p in perfs) { 51 61 var ert = p.Value; … … 56 66 } else erts.Add(ert); 57 67 } 58 distances.Remove(min.Key);59 68 } 60 69
Note: See TracChangeset
for help on using the changeset viewer.