1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
4 | *
|
---|
5 | * This file is part of HeuristicLab.
|
---|
6 | *
|
---|
7 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
8 | * it under the terms of the GNU General Public License as published by
|
---|
9 | * the Free Software Foundation, either version 3 of the License, or
|
---|
10 | * (at your option) any later version.
|
---|
11 | *
|
---|
12 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
15 | * GNU General Public License for more details.
|
---|
16 | *
|
---|
17 | * You should have received a copy of the GNU General Public License
|
---|
18 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
19 | */
|
---|
20 | #endregion
|
---|
21 |
|
---|
22 | using HeuristicLab.Common;
|
---|
23 | using HeuristicLab.Optimization;
|
---|
24 | using System;
|
---|
25 | using System.Collections.Generic;
|
---|
26 | using System.Linq;
|
---|
27 |
|
---|
28 | namespace HeuristicLab.OptimizationExpertSystem.Common {
|
---|
29 | public class KNearestNeighborModel : IRecommendationModel {
|
---|
30 | private readonly int K;
|
---|
31 | private readonly string[] characteristics;
|
---|
32 |
|
---|
33 | public KNearestNeighborModel(int k, string[] characteristics) {
|
---|
34 | this.K = k;
|
---|
35 | this.characteristics = characteristics;
|
---|
36 | }
|
---|
37 |
|
---|
38 | public IEnumerable<Tuple<IAlgorithm, double>> GetRanking(KnowledgeCenter kc) {
|
---|
39 | var distances = kc.GetProblemDistances(characteristics);
|
---|
40 | 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 | }
|
---|
50 | foreach (var p in perfs) {
|
---|
51 | var ert = p.Value;
|
---|
52 | if (double.IsNaN(ert)) ert = int.MaxValue;
|
---|
53 | List<double> erts;
|
---|
54 | if (!performances.TryGetValue(p.Key, out erts)) {
|
---|
55 | performances[p.Key] = new List<double>() { ert }; ;
|
---|
56 | } else erts.Add(ert);
|
---|
57 | }
|
---|
58 | distances.Remove(min.Key);
|
---|
59 | }
|
---|
60 |
|
---|
61 | return performances.Select(x => new { Alg = x.Key, Perf = x.Value.Average() })
|
---|
62 | .OrderBy(x => x.Perf)
|
---|
63 | .Select(x => Tuple.Create(x.Alg, x.Perf));
|
---|
64 | }
|
---|
65 | }
|
---|
66 | }
|
---|