[5624] | 1 | #region License Information
|
---|
| 2 | /* HeuristicLab
|
---|
[15583] | 3 | * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
[5624] | 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 System;
|
---|
| 23 | using System.Collections.Generic;
|
---|
| 24 | using System.IO;
|
---|
| 25 | using System.Linq;
|
---|
| 26 | using System.Text;
|
---|
| 27 | using HeuristicLab.Common;
|
---|
| 28 | using HeuristicLab.Core;
|
---|
| 29 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
[5861] | 30 | using HeuristicLab.Problems.DataAnalysis;
|
---|
[8609] | 31 | using LibSVM;
|
---|
[5624] | 32 |
|
---|
| 33 | namespace HeuristicLab.Algorithms.DataAnalysis {
|
---|
| 34 | /// <summary>
|
---|
[5626] | 35 | /// Represents a support vector machine model.
|
---|
[5624] | 36 | /// </summary>
|
---|
| 37 | [StorableClass]
|
---|
[5626] | 38 | [Item("SupportVectorMachineModel", "Represents a support vector machine model.")]
|
---|
[13941] | 39 | public sealed class SupportVectorMachineModel : ClassificationModel, ISupportVectorMachineModel {
|
---|
| 40 | public override IEnumerable<string> VariablesUsedForPrediction {
|
---|
[13921] | 41 | get { return allowedInputVariables; }
|
---|
| 42 | }
|
---|
[5624] | 43 |
|
---|
[13921] | 44 |
|
---|
[8609] | 45 | private svm_model model;
|
---|
[5624] | 46 | /// <summary>
|
---|
| 47 | /// Gets or sets the SVM model.
|
---|
| 48 | /// </summary>
|
---|
[8609] | 49 | public svm_model Model {
|
---|
[5624] | 50 | get { return model; }
|
---|
| 51 | set {
|
---|
| 52 | if (value != model) {
|
---|
| 53 | if (value == null) throw new ArgumentNullException();
|
---|
| 54 | model = value;
|
---|
| 55 | OnChanged(EventArgs.Empty);
|
---|
| 56 | }
|
---|
| 57 | }
|
---|
| 58 | }
|
---|
| 59 |
|
---|
| 60 | /// <summary>
|
---|
| 61 | /// Gets or sets the range transformation for the model.
|
---|
| 62 | /// </summary>
|
---|
[8609] | 63 | private RangeTransform rangeTransform;
|
---|
| 64 | public RangeTransform RangeTransform {
|
---|
[5624] | 65 | get { return rangeTransform; }
|
---|
| 66 | set {
|
---|
| 67 | if (value != rangeTransform) {
|
---|
| 68 | if (value == null) throw new ArgumentNullException();
|
---|
| 69 | rangeTransform = value;
|
---|
| 70 | OnChanged(EventArgs.Empty);
|
---|
| 71 | }
|
---|
| 72 | }
|
---|
| 73 | }
|
---|
[5649] | 74 |
|
---|
[5690] | 75 | public Dataset SupportVectors {
|
---|
| 76 | get {
|
---|
[8609] | 77 | var data = new double[Model.sv_coef.Length, allowedInputVariables.Count()];
|
---|
| 78 | for (int i = 0; i < Model.sv_coef.Length; i++) {
|
---|
| 79 | var sv = Model.SV[i];
|
---|
[5690] | 80 | for (int j = 0; j < sv.Length; j++) {
|
---|
[8609] | 81 | data[i, j] = sv[j].value;
|
---|
[5690] | 82 | }
|
---|
| 83 | }
|
---|
| 84 | return new Dataset(allowedInputVariables, data);
|
---|
| 85 | }
|
---|
| 86 | }
|
---|
| 87 |
|
---|
[5649] | 88 | [Storable]
|
---|
| 89 | private string[] allowedInputVariables;
|
---|
[5690] | 90 | [Storable]
|
---|
| 91 | private double[] classValues; // only for SVM classification models
|
---|
[5649] | 92 |
|
---|
| 93 | [StorableConstructor]
|
---|
| 94 | private SupportVectorMachineModel(bool deserializing) : base(deserializing) { }
|
---|
| 95 | private SupportVectorMachineModel(SupportVectorMachineModel original, Cloner cloner)
|
---|
| 96 | : base(original, cloner) {
|
---|
| 97 | // only using a shallow copy here! (gkronber)
|
---|
| 98 | this.model = original.model;
|
---|
| 99 | this.rangeTransform = original.rangeTransform;
|
---|
[5690] | 100 | this.allowedInputVariables = (string[])original.allowedInputVariables.Clone();
|
---|
| 101 | if (original.classValues != null)
|
---|
| 102 | this.classValues = (double[])original.classValues.Clone();
|
---|
[5649] | 103 | }
|
---|
[8609] | 104 | public SupportVectorMachineModel(svm_model model, RangeTransform rangeTransform, string targetVariable, IEnumerable<string> allowedInputVariables, IEnumerable<double> classValues)
|
---|
[5690] | 105 | : this(model, rangeTransform, targetVariable, allowedInputVariables) {
|
---|
| 106 | this.classValues = classValues.ToArray();
|
---|
| 107 | }
|
---|
[8609] | 108 | public SupportVectorMachineModel(svm_model model, RangeTransform rangeTransform, string targetVariable, IEnumerable<string> allowedInputVariables)
|
---|
[13941] | 109 | : base(targetVariable) {
|
---|
[5649] | 110 | this.name = ItemName;
|
---|
| 111 | this.description = ItemDescription;
|
---|
| 112 | this.model = model;
|
---|
| 113 | this.rangeTransform = rangeTransform;
|
---|
| 114 | this.allowedInputVariables = allowedInputVariables.ToArray();
|
---|
| 115 | }
|
---|
| 116 |
|
---|
| 117 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
| 118 | return new SupportVectorMachineModel(this, cloner);
|
---|
| 119 | }
|
---|
| 120 |
|
---|
[5626] | 121 | #region IRegressionModel Members
|
---|
[12509] | 122 | public IEnumerable<double> GetEstimatedValues(IDataset dataset, IEnumerable<int> rows) {
|
---|
[5649] | 123 | return GetEstimatedValuesHelper(dataset, rows);
|
---|
[5626] | 124 | }
|
---|
[13941] | 125 | public IRegressionSolution CreateRegressionSolution(IRegressionProblemData problemData) {
|
---|
[8528] | 126 | return new SupportVectorRegressionSolution(this, new RegressionProblemData(problemData));
|
---|
[6603] | 127 | }
|
---|
[5626] | 128 | #endregion
|
---|
[6603] | 129 |
|
---|
[5626] | 130 | #region IClassificationModel Members
|
---|
[13941] | 131 | public override IEnumerable<double> GetEstimatedClassValues(IDataset dataset, IEnumerable<int> rows) {
|
---|
[5690] | 132 | if (classValues == null) throw new NotSupportedException();
|
---|
| 133 | // return the original class value instead of the predicted value of the model
|
---|
| 134 | // svm classification only works for integer classes
|
---|
| 135 | foreach (var estimated in GetEstimatedValuesHelper(dataset, rows)) {
|
---|
| 136 | // find closest class
|
---|
| 137 | double bestDist = double.MaxValue;
|
---|
| 138 | double bestClass = -1;
|
---|
| 139 | for (int i = 0; i < classValues.Length; i++) {
|
---|
| 140 | double d = Math.Abs(estimated - classValues[i]);
|
---|
| 141 | if (d < bestDist) {
|
---|
| 142 | bestDist = d;
|
---|
| 143 | bestClass = classValues[i];
|
---|
| 144 | if (d.IsAlmost(0.0)) break; // exact match no need to look further
|
---|
| 145 | }
|
---|
| 146 | }
|
---|
| 147 | yield return bestClass;
|
---|
| 148 | }
|
---|
[5626] | 149 | }
|
---|
[6604] | 150 |
|
---|
[13941] | 151 | public override IClassificationSolution CreateClassificationSolution(IClassificationProblemData problemData) {
|
---|
[8528] | 152 | return new SupportVectorClassificationSolution(this, new ClassificationProblemData(problemData));
|
---|
[6604] | 153 | }
|
---|
[5626] | 154 | #endregion
|
---|
[12509] | 155 | private IEnumerable<double> GetEstimatedValuesHelper(IDataset dataset, IEnumerable<int> rows) {
|
---|
[7180] | 156 | // calculate predictions for the currently requested rows
|
---|
[15854] | 157 | svm_problem problem = SupportVectorMachineUtil.CreateSvmProblem(dataset, allowedInputVariables, rows);
|
---|
[8609] | 158 | svm_problem scaledProblem = rangeTransform.Scale(problem);
|
---|
[5624] | 159 |
|
---|
[8609] | 160 | for (int i = 0; i < problem.l; i++) {
|
---|
| 161 | yield return svm.svm_predict(Model, scaledProblem.x[i]);
|
---|
[5690] | 162 | }
|
---|
[5624] | 163 | }
|
---|
[6566] | 164 |
|
---|
[5624] | 165 | #region events
|
---|
| 166 | public event EventHandler Changed;
|
---|
| 167 | private void OnChanged(EventArgs e) {
|
---|
| 168 | var handlers = Changed;
|
---|
| 169 | if (handlers != null)
|
---|
| 170 | handlers(this, e);
|
---|
| 171 | }
|
---|
| 172 | #endregion
|
---|
| 173 |
|
---|
| 174 | #region persistence
|
---|
| 175 | [Storable]
|
---|
| 176 | private string ModelAsString {
|
---|
| 177 | get {
|
---|
| 178 | using (MemoryStream stream = new MemoryStream()) {
|
---|
[8609] | 179 | svm.svm_save_model(new StreamWriter(stream), Model);
|
---|
[5624] | 180 | stream.Seek(0, System.IO.SeekOrigin.Begin);
|
---|
| 181 | StreamReader reader = new StreamReader(stream);
|
---|
| 182 | return reader.ReadToEnd();
|
---|
| 183 | }
|
---|
| 184 | }
|
---|
| 185 | set {
|
---|
| 186 | using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(value))) {
|
---|
[8609] | 187 | model = svm.svm_load_model(new StreamReader(stream));
|
---|
[5624] | 188 | }
|
---|
| 189 | }
|
---|
| 190 | }
|
---|
| 191 | [Storable]
|
---|
| 192 | private string RangeTransformAsString {
|
---|
| 193 | get {
|
---|
| 194 | using (MemoryStream stream = new MemoryStream()) {
|
---|
[8609] | 195 | RangeTransform.Write(stream, RangeTransform);
|
---|
[5624] | 196 | stream.Seek(0, System.IO.SeekOrigin.Begin);
|
---|
| 197 | StreamReader reader = new StreamReader(stream);
|
---|
| 198 | return reader.ReadToEnd();
|
---|
| 199 | }
|
---|
| 200 | }
|
---|
| 201 | set {
|
---|
| 202 | using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(value))) {
|
---|
[8609] | 203 | RangeTransform = RangeTransform.Read(stream);
|
---|
[5624] | 204 | }
|
---|
| 205 | }
|
---|
| 206 | }
|
---|
[5861] | 207 | #endregion
|
---|
[5624] | 208 | }
|
---|
| 209 | }
|
---|