Changeset 8811 for branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation
- Timestamp:
- 10/16/12 09:44:07 (12 years ago)
- Location:
- branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis
- Files:
-
- 19 edited
- 1 copied
Legend:
- Unmodified
- Added
- Removed
-
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis
- Property svn:mergeinfo changed
-
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationEnsembleSolution.cs
r8534 r8811 28 28 using HeuristicLab.Data; 29 29 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 30 using HeuristicLab.Problems.DataAnalysis.Interfaces;31 30 32 31 namespace HeuristicLab.Problems.DataAnalysis { … … 37 36 [Item("Classification Ensemble Solution", "A classification solution that contains an ensemble of multiple classification models")] 38 37 [Creatable("Data Analysis - Ensembles")] 39 public sealed class ClassificationEnsembleSolution : ClassificationSolution, IClassificationEnsembleSolution { 38 public sealed class ClassificationEnsembleSolution : ClassificationSolutionBase, IClassificationEnsembleSolution { 39 private readonly Dictionary<int, double> trainingEvaluationCache = new Dictionary<int, double>(); 40 private readonly Dictionary<int, double> testEvaluationCache = new Dictionary<int, double>(); 41 private readonly Dictionary<int, double> evaluationCache = new Dictionary<int, double>(); 42 40 43 public new IClassificationEnsembleModel Model { 41 44 get { return (IClassificationEnsembleModel)base.Model; } … … 162 165 } 163 166 164 protected override void RecalculateResults() {165 weightCalculator.CalculateNormalizedWeights(classificationSolutions.CheckedItems);166 CalculateResults();167 }168 167 169 168 #region Evaluation 169 public override IEnumerable<double> EstimatedClassValues { 170 get { return GetEstimatedClassValues(Enumerable.Range(0, ProblemData.Dataset.Rows)); } 171 } 172 170 173 public override IEnumerable<double> EstimatedTrainingClassValues { 171 174 get { … … 258 261 } 259 262 263 protected override void RecalculateResults() { 264 weightCalculator.CalculateNormalizedWeights(classificationSolutions.CheckedItems); 265 base.RecalculateResults(); 266 } 267 260 268 private void AddClassificationSolution(IClassificationSolution solution) { 261 269 if (Model.Models.Contains(solution.Model)) throw new ArgumentException(); -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationProblemData.cs
r8534 r8811 223 223 } 224 224 225 private List<double> classValues ;226 p ublic List<double> ClassValues{225 private List<double> classValuesCache; 226 private List<double> ClassValuesCache { 227 227 get { 228 if (classValues == null) { 229 classValues = Dataset.GetDoubleValues(TargetVariableParameter.Value.Value).Distinct().ToList(); 230 classValues.Sort(); 228 if (classValuesCache == null) { 229 classValuesCache = Dataset.GetDoubleValues(TargetVariableParameter.Value.Value).Distinct().OrderBy(x => x).ToList(); 231 230 } 232 return classValues ;231 return classValuesCache; 233 232 } 234 233 } 235 IEnumerable<double> IClassificationProblemData.ClassValues { 236 get { return ClassValues; } 237 } 238 234 public IEnumerable<double> ClassValues { 235 get { return ClassValuesCache; } 236 } 239 237 public int Classes { 240 get { return ClassValues .Count; }241 } 242 243 private List<string> classNames ;244 p ublic List<string> ClassNames{238 get { return ClassValuesCache.Count; } 239 } 240 241 private List<string> classNamesCache; 242 private List<string> ClassNamesCache { 245 243 get { 246 if (classNames == null) {247 classNames = new List<string>();244 if (classNamesCache == null) { 245 classNamesCache = new List<string>(); 248 246 for (int i = 0; i < ClassNamesParameter.Value.Rows; i++) 249 classNames .Add(ClassNamesParameter.Value[i, 0]);247 classNamesCache.Add(ClassNamesParameter.Value[i, 0]); 250 248 } 251 return classNames ;249 return classNamesCache; 252 250 } 253 251 } 254 IEnumerable<string> IClassificationProblemData.ClassNames { 255 get { return ClassNames; } 256 } 257 258 private Dictionary<Tuple<double, double>, double> classificationPenaltiesCache = new Dictionary<Tuple<double, double>, double>(); 252 public IEnumerable<string> ClassNames { 253 get { return ClassNamesCache; } 254 } 259 255 #endregion 260 256 … … 284 280 TestPartition.Start = classificationProblemData.TestPartition.Start; 285 281 TestPartition.End = classificationProblemData.TestPartition.End; 282 283 for (int i = 0; i < classificationProblemData.ClassNames.Count(); i++) 284 ClassNamesParameter.Value[i, 0] = classificationProblemData.ClassNames.ElementAt(i); 285 286 for (int i = 0; i < Classes; i++) { 287 for (int j = 0; j < Classes; j++) { 288 ClassificationPenaltiesParameter.Value[i, j] = classificationProblemData.GetClassificationPenalty(ClassValuesCache[i], ClassValuesCache[j]); 289 } 290 } 286 291 } 287 292 … … 295 300 Parameters.Add(new FixedValueParameter<DoubleMatrix>(ClassificationPenaltiesParameterName, "")); 296 301 302 RegisterParameterEvents(); 297 303 ResetTargetVariableDependentMembers(); 298 RegisterParameterEvents();299 304 } 300 305 … … 319 324 DeregisterParameterEvents(); 320 325 321 classNames = null;322 326 ((IStringConvertibleMatrix)ClassNamesParameter.Value).Columns = 1; 323 ((IStringConvertibleMatrix)ClassNamesParameter.Value).Rows = ClassValues .Count;327 ((IStringConvertibleMatrix)ClassNamesParameter.Value).Rows = ClassValuesCache.Count; 324 328 for (int i = 0; i < Classes; i++) 325 ClassNamesParameter.Value[i, 0] = "Class " + ClassValues [i];329 ClassNamesParameter.Value[i, 0] = "Class " + ClassValuesCache[i]; 326 330 ClassNamesParameter.Value.ColumnNames = new List<string>() { "ClassNames" }; 327 331 ClassNamesParameter.Value.RowNames = ClassValues.Select(s => "ClassValue: " + s); 328 332 329 classificationPenaltiesCache.Clear();330 ((ValueParameter<DoubleMatrix>)ClassificationPenaltiesParameter).ReactOnValueToStringChangedAndValueItemImageChanged = false;331 333 ((IStringConvertibleMatrix)ClassificationPenaltiesParameter.Value).Rows = Classes; 332 334 ((IStringConvertibleMatrix)ClassificationPenaltiesParameter.Value).Columns = Classes; … … 339 341 } 340 342 } 341 ((ValueParameter<DoubleMatrix>)ClassificationPenaltiesParameter).ReactOnValueToStringChangedAndValueItemImageChanged = true;342 343 RegisterParameterEvents(); 343 344 } 344 345 345 346 public string GetClassName(double classValue) { 346 if (!ClassValues .Contains(classValue)) throw new ArgumentException();347 int index = ClassValues .IndexOf(classValue);348 return ClassNames [index];347 if (!ClassValuesCache.Contains(classValue)) throw new ArgumentException(); 348 int index = ClassValuesCache.IndexOf(classValue); 349 return ClassNamesCache[index]; 349 350 } 350 351 public double GetClassValue(string className) { 351 if (!ClassNames .Contains(className)) throw new ArgumentException();352 int index = ClassNames .IndexOf(className);353 return ClassValues [index];352 if (!ClassNamesCache.Contains(className)) throw new ArgumentException(); 353 int index = ClassNamesCache.IndexOf(className); 354 return ClassValuesCache[index]; 354 355 } 355 356 public void SetClassName(double classValue, string className) { 356 if (!classValues.Contains(classValue)) throw new ArgumentException(); 357 int index = ClassValues.IndexOf(classValue); 358 ClassNames[index] = className; 357 if (!ClassValuesCache.Contains(classValue)) throw new ArgumentException(); 358 int index = ClassValuesCache.IndexOf(classValue); 359 359 ClassNamesParameter.Value[index, 0] = className; 360 // updating of class names cache is not necessary here as the parameter value fires a changed event which updates the cache 360 361 } 361 362 … … 364 365 } 365 366 public double GetClassificationPenalty(double correctClassValue, double estimatedClassValue) { 366 var key = Tuple.Create(correctClassValue, estimatedClassValue); 367 if (!classificationPenaltiesCache.ContainsKey(key)) { 368 int correctClassIndex = ClassValues.IndexOf(correctClassValue); 369 int estimatedClassIndex = ClassValues.IndexOf(estimatedClassValue); 370 classificationPenaltiesCache[key] = ClassificationPenaltiesParameter.Value[correctClassIndex, estimatedClassIndex]; 371 } 372 return classificationPenaltiesCache[key]; 367 int correctClassIndex = ClassValuesCache.IndexOf(correctClassValue); 368 int estimatedClassIndex = ClassValuesCache.IndexOf(estimatedClassValue); 369 return ClassificationPenaltiesParameter.Value[correctClassIndex, estimatedClassIndex]; 373 370 } 374 371 public void SetClassificationPenalty(string correctClassName, string estimatedClassName, double penalty) { … … 376 373 } 377 374 public void SetClassificationPenalty(double correctClassValue, double estimatedClassValue, double penalty) { 378 var key = Tuple.Create(correctClassValue, estimatedClassValue); 379 int correctClassIndex = ClassValues.IndexOf(correctClassValue); 380 int estimatedClassIndex = ClassValues.IndexOf(estimatedClassValue); 375 int correctClassIndex = ClassValuesCache.IndexOf(correctClassValue); 376 int estimatedClassIndex = ClassValuesCache.IndexOf(estimatedClassValue); 381 377 382 378 ClassificationPenaltiesParameter.Value[correctClassIndex, estimatedClassIndex] = penalty; … … 387 383 TargetVariableParameter.ValueChanged += new EventHandler(TargetVariableParameter_ValueChanged); 388 384 ClassNamesParameter.Value.Reset += new EventHandler(Parameter_ValueChanged); 389 ClassNamesParameter.Value.ItemChanged += new EventHandler<EventArgs<int, int>>(MatrixParameter_ItemChanged); 385 ClassNamesParameter.Value.ItemChanged += new EventHandler<EventArgs<int, int>>(Parameter_ValueChanged); 386 ClassificationPenaltiesParameter.Value.ItemChanged += new EventHandler<EventArgs<int, int>>(Parameter_ValueChanged); 390 387 ClassificationPenaltiesParameter.Value.Reset += new EventHandler(Parameter_ValueChanged); 391 ClassificationPenaltiesParameter.Value.ItemChanged += new EventHandler<EventArgs<int, int>>(MatrixParameter_ItemChanged);392 388 } 393 389 private void DeregisterParameterEvents() { 394 390 TargetVariableParameter.ValueChanged -= new EventHandler(TargetVariableParameter_ValueChanged); 395 391 ClassNamesParameter.Value.Reset -= new EventHandler(Parameter_ValueChanged); 396 ClassNamesParameter.Value.ItemChanged -= new EventHandler<EventArgs<int, int>>(MatrixParameter_ItemChanged); 392 ClassNamesParameter.Value.ItemChanged -= new EventHandler<EventArgs<int, int>>(Parameter_ValueChanged); 393 ClassificationPenaltiesParameter.Value.ItemChanged -= new EventHandler<EventArgs<int, int>>(Parameter_ValueChanged); 397 394 ClassificationPenaltiesParameter.Value.Reset -= new EventHandler(Parameter_ValueChanged); 398 ClassificationPenaltiesParameter.Value.ItemChanged -= new EventHandler<EventArgs<int, int>>(MatrixParameter_ItemChanged);399 395 } 400 396 401 397 private void TargetVariableParameter_ValueChanged(object sender, EventArgs e) { 402 classValues = null; 398 classValuesCache = null; 399 classNamesCache = null; 403 400 ResetTargetVariableDependentMembers(); 404 401 OnChanged(); 405 402 } 406 403 private void Parameter_ValueChanged(object sender, EventArgs e) { 407 OnChanged();408 }409 private void MatrixParameter_ItemChanged(object sender, EventArgs<int, int> e) {404 classNamesCache = null; 405 ClassificationPenaltiesParameter.Value.RowNames = ClassNames.Select(name => "Actual " + name); 406 ClassificationPenaltiesParameter.Value.ColumnNames = ClassNames.Select(name => "Estimated " + name); 410 407 OnChanged(); 411 408 } -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationSolution.cs
r8508 r8811 45 45 : base(model, problemData) { 46 46 evaluationCache = new Dictionary<int, double>(problemData.Dataset.Rows); 47 CalculateClassificationResults(); 47 48 } 48 49 -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationSolutionBase.cs
r8508 r8811 85 85 } 86 86 87 protected void Calculate Results() {87 protected void CalculateClassificationResults() { 88 88 double[] estimatedTrainingClassValues = EstimatedTrainingClassValues.ToArray(); // cache values 89 89 double[] originalTrainingClassValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndices).ToArray(); … … 114 114 115 115 public abstract IEnumerable<double> GetEstimatedClassValues(IEnumerable<int> rows); 116 117 protected override void RecalculateResults() { 118 CalculateClassificationResults(); 119 } 116 120 } 117 121 } -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/DiscriminantFunctionClassificationModel.cs
r7259 r8811 33 33 [StorableClass] 34 34 [Item("DiscriminantFunctionClassificationModel", "Represents a classification model that uses a discriminant function and classification thresholds.")] 35 public abstractclass DiscriminantFunctionClassificationModel : NamedItem, IDiscriminantFunctionClassificationModel {35 public class DiscriminantFunctionClassificationModel : NamedItem, IDiscriminantFunctionClassificationModel { 36 36 [Storable] 37 37 private IRegressionModel model; 38 public IRegressionModel Model { 39 get { return model; } 40 private set { model = value; } 41 } 38 42 39 43 [Storable] … … 51 55 } 52 56 57 private IDiscriminantFunctionThresholdCalculator thresholdCalculator; 58 [Storable] 59 public IDiscriminantFunctionThresholdCalculator ThresholdCalculator { 60 get { return thresholdCalculator; } 61 private set { thresholdCalculator = value; } 62 } 63 53 64 54 65 [StorableConstructor] … … 61 72 } 62 73 63 public DiscriminantFunctionClassificationModel(IRegressionModel model )74 public DiscriminantFunctionClassificationModel(IRegressionModel model, IDiscriminantFunctionThresholdCalculator thresholdCalculator) 64 75 : base() { 65 76 this.name = ItemName; 66 77 this.description = ItemDescription; 67 78 this.model = model; 68 this.classValues = new double[] { 0.0 }; 69 this.thresholds = new double[] { double.NegativeInfinity }; 79 this.classValues = new double[0]; 80 this.thresholds = new double[0]; 81 this.thresholdCalculator = thresholdCalculator; 82 } 83 84 [StorableHook(HookType.AfterDeserialization)] 85 private void AfterDeserialization() { 86 if (ThresholdCalculator == null) ThresholdCalculator = new AccuracyMaximizationThresholdCalculator(); 87 } 88 89 public override IDeepCloneable Clone(Cloner cloner) { 90 return new DiscriminantFunctionClassificationModel(this, cloner); 70 91 } 71 92 … … 80 101 } 81 102 103 public virtual void RecalculateModelParameters(IClassificationProblemData problemData, IEnumerable<int> rows) { 104 double[] classValues; 105 double[] thresholds; 106 var targetClassValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows); 107 var estimatedTrainingValues = GetEstimatedValues(problemData.Dataset, rows); 108 thresholdCalculator.Calculate(problemData, estimatedTrainingValues, targetClassValues, out classValues, out thresholds); 109 SetThresholdsAndClassValues(thresholds, classValues); 110 } 111 112 82 113 public IEnumerable<double> GetEstimatedValues(Dataset dataset, IEnumerable<int> rows) { 83 114 return model.GetEstimatedValues(dataset, rows); … … 85 116 86 117 public IEnumerable<double> GetEstimatedClassValues(Dataset dataset, IEnumerable<int> rows) { 118 if (!Thresholds.Any() && !ClassValues.Any()) throw new ArgumentException("No thresholds and class values were set for the current classification model."); 87 119 foreach (var x in GetEstimatedValues(dataset, rows)) { 88 120 int classIndex = 0; … … 103 135 #endregion 104 136 105 public abstract IDiscriminantFunctionClassificationSolution CreateDiscriminantFunctionClassificationSolution(IClassificationProblemData problemData); 106 public abstract IClassificationSolution CreateClassificationSolution(IClassificationProblemData problemData); 137 public virtual IDiscriminantFunctionClassificationSolution CreateDiscriminantFunctionClassificationSolution(IClassificationProblemData problemData) { 138 return new DiscriminantFunctionClassificationSolution(this, problemData); 139 } 140 141 public virtual IClassificationSolution CreateClassificationSolution(IClassificationProblemData problemData) { 142 return CreateDiscriminantFunctionClassificationSolution(problemData); 143 } 107 144 } 108 145 } -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/DiscriminantFunctionClassificationSolution.cs
r8534 r8811 32 32 [StorableClass] 33 33 [Item("DiscriminantFunctionClassificationSolution", "Represents a classification solution that uses a discriminant function and classification thresholds.")] 34 public abstractclass DiscriminantFunctionClassificationSolution : DiscriminantFunctionClassificationSolutionBase {34 public class DiscriminantFunctionClassificationSolution : DiscriminantFunctionClassificationSolutionBase { 35 35 protected readonly Dictionary<int, double> valueEvaluationCache; 36 36 protected readonly Dictionary<int, double> classValueEvaluationCache; … … 47 47 classValueEvaluationCache = new Dictionary<int, double>(original.classValueEvaluationCache); 48 48 } 49 p rotectedDiscriminantFunctionClassificationSolution(IDiscriminantFunctionClassificationModel model, IClassificationProblemData problemData)49 public DiscriminantFunctionClassificationSolution(IDiscriminantFunctionClassificationModel model, IClassificationProblemData problemData) 50 50 : base(model, problemData) { 51 51 valueEvaluationCache = new Dictionary<int, double>(); 52 52 classValueEvaluationCache = new Dictionary<int, double>(); 53 CalculateRegressionResults(); 54 CalculateClassificationResults(); 55 } 56 57 public override IDeepCloneable Clone(Cloner cloner) { 58 return new DiscriminantFunctionClassificationSolution(this, cloner); 53 59 } 54 60 -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/DiscriminantFunctionClassificationSolutionBase.cs
r8534 r8811 85 85 Add(new Result(TrainingRSquaredResultName, "Squared Pearson's correlation coefficient of the model output and the actual values on the training partition", new DoubleValue())); 86 86 Add(new Result(TestRSquaredResultName, "Squared Pearson's correlation coefficient of the model output and the actual values on the test partition", new DoubleValue())); 87 88 87 RegisterEventHandler(); 89 88 } … … 92 91 private void AfterDeserialization() { 93 92 RegisterEventHandler(); 94 }95 96 protected override void OnModelChanged() {97 DeregisterEventHandler();98 RegisterEventHandler();99 base.OnModelChanged();100 93 } 101 94 … … 137 130 138 131 protected virtual void OnModelThresholdsChanged(EventArgs e) { 139 CalculateResults(); 140 CalculateRegressionResults(); 132 OnModelChanged(); 141 133 } 142 134 … … 146 138 147 139 public abstract IEnumerable<double> GetEstimatedValues(IEnumerable<int> rows); 140 141 protected override void RecalculateResults() { 142 base.RecalculateResults(); 143 CalculateRegressionResults(); 144 } 148 145 } 149 146 } -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ThresholdCalculators/AccuracyMaximizationThresholdCalculator.cs
r8508 r8811 53 53 54 54 public static void CalculateThresholds(IClassificationProblemData problemData, IEnumerable<double> estimatedValues, IEnumerable<double> targetClassValues, out double[] classValues, out double[] thresholds) { 55 int slices = 100;56 double minThresholdInc = 10e-5; // necessary to prevent infinite loop when maxEstimated - minEstimated is effectively zero (constant model)55 const int slices = 100; 56 const double minThresholdInc = 10e-5; // necessary to prevent infinite loop when maxEstimated - minEstimated is effectively zero (constant model) 57 57 List<double> estimatedValuesList = estimatedValues.ToList(); 58 58 double maxEstimatedValue = estimatedValuesList.Max(); … … 61 61 var estimatedAndTargetValuePairs = 62 62 estimatedValuesList.Zip(targetClassValues, (x, y) => new { EstimatedValue = x, TargetClassValue = y }) 63 .OrderBy(x => x.EstimatedValue) 64 .ToList(); 63 .OrderBy(x => x.EstimatedValue).ToList(); 65 64 66 classValues = problemData.ClassValues.OrderBy(x => x).ToArray(); 65 classValues = estimatedAndTargetValuePairs.GroupBy(x => x.TargetClassValue) 66 .Select(x => new { Median = x.Select(y => y.EstimatedValue).Median(), Class = x.Key }) 67 .OrderBy(x => x.Median).Select(x => x.Class).ToArray(); 68 67 69 int nClasses = classValues.Length; 68 70 thresholds = new double[nClasses]; 69 71 thresholds[0] = double.NegativeInfinity; 70 // thresholds[thresholds.Length - 1] = double.PositiveInfinity;71 72 72 73 // incrementally calculate accuracy of all possible thresholds … … 85 86 //all positives 86 87 if (pair.TargetClassValue.IsAlmost(classValues[i - 1])) { 87 if (pair.EstimatedValue > lowerThreshold && pair.EstimatedValue < actualThreshold)88 if (pair.EstimatedValue > lowerThreshold && pair.EstimatedValue <= actualThreshold) 88 89 //true positive 89 classificationScore += problemData.GetClassificationPenalty( classValues[i - 1], classValues[i - 1]);90 classificationScore += problemData.GetClassificationPenalty(pair.TargetClassValue, pair.TargetClassValue); 90 91 else 91 92 //false negative 92 classificationScore += problemData.GetClassificationPenalty( classValues[i], classValues[i - 1]);93 classificationScore += problemData.GetClassificationPenalty(pair.TargetClassValue, classValues[i]); 93 94 } 94 95 //all negatives 95 96 else { 96 if (pair.EstimatedValue > lowerThreshold && pair.EstimatedValue < actualThreshold) 97 //false positive 98 classificationScore += problemData.GetClassificationPenalty(classValues[i - 1], classValues[i]); 99 else 100 //true negative, consider only upper class 101 classificationScore += problemData.GetClassificationPenalty(classValues[i], classValues[i]); 97 //false positive 98 if (pair.EstimatedValue > lowerThreshold && pair.EstimatedValue <= actualThreshold) 99 classificationScore += problemData.GetClassificationPenalty(pair.TargetClassValue, classValues[i - 1]); 100 else if (pair.EstimatedValue <= lowerThreshold) 101 classificationScore += problemData.GetClassificationPenalty(pair.TargetClassValue, classValues[i - 2]); 102 else if (pair.EstimatedValue > actualThreshold) { 103 if (pair.TargetClassValue < classValues[i - 1]) //negative in wrong class, consider upper class 104 classificationScore += problemData.GetClassificationPenalty(pair.TargetClassValue, classValues[i]); 105 else //true negative, must be optimized by the other thresholds 106 classificationScore += problemData.GetClassificationPenalty(pair.TargetClassValue, pair.TargetClassValue); 107 } 102 108 } 103 109 } -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ThresholdCalculators/NormalDistributionCutPointsThresholdCalculator.cs
r7259 r8811 53 53 54 54 public static void CalculateThresholds(IClassificationProblemData problemData, IEnumerable<double> estimatedValues, IEnumerable<double> targetClassValues, out double[] classValues, out double[] thresholds) { 55 double maxEstimatedValue = estimatedValues.Max();56 double minEstimatedValue = estimatedValues.Min();57 55 var estimatedTargetValues = Enumerable.Zip(estimatedValues, targetClassValues, (e, t) => new { EstimatedValue = e, TargetValue = t }).ToList(); 56 double estimatedValuesRange = estimatedValues.Range(); 58 57 59 58 Dictionary<double, double> classMean = new Dictionary<double, double>(); … … 82 81 // calculate all thresholds 83 82 CalculateCutPoints(classMean[class0], classStdDev[class0], classMean[class1], classStdDev[class1], out x1, out x2); 84 if (!thresholdList.Any(x => x.IsAlmost(x1))) thresholdList.Add(x1); 85 if (!thresholdList.Any(x => x.IsAlmost(x2))) thresholdList.Add(x2); 83 84 // if the two cut points are too close (for instance because the stdDev=0) 85 // then move them by 0.1% of the range of estimated values 86 if (x1.IsAlmost(x2)) { 87 x1 -= 0.001 * estimatedValuesRange; 88 x2 += 0.001 * estimatedValuesRange; 89 } 90 if (!double.IsInfinity(x1) && !thresholdList.Any(x => x.IsAlmost(x1))) thresholdList.Add(x1); 91 if (!double.IsInfinity(x2) && !thresholdList.Any(x => x.IsAlmost(x2))) thresholdList.Add(x2); 86 92 } 87 93 } 88 94 thresholdList.Sort(); 89 thresholdList.Insert(0, double.NegativeInfinity); 95 96 // add small value and large value for the calculation of most influential class in each thresholded section 97 thresholdList.Insert(0, estimatedValues.Min() - 1); 98 thresholdList.Add(estimatedValues.Max() + 1); 90 99 91 100 // determine class values for each partition separated by a threshold by calculating the density of all class distributions 92 101 // all points in the partition are classified as the class with the maximal density in the parition 93 102 List<double> classValuesList = new List<double>(); 94 for (int i = 0; i < thresholdList.Count; i++) { 95 double m; 96 if (double.IsNegativeInfinity(thresholdList[i])) { 97 m = thresholdList[i + 1] - 1.0; // smaller than the smalles non-infinity threshold 98 } else if (i == thresholdList.Count - 1) { 99 // last threshold 100 m = thresholdList[i] + 1.0; // larger than the last threshold 101 } else { 102 m = thresholdList[i] + (thresholdList[i + 1] - thresholdList[i]) / 2.0; // middle of partition 103 if (thresholdList.Count == 2) { 104 // this happens if there are no thresholds (distributions for all classes are exactly the same) 105 // -> all samples should be classified as the first class 106 classValuesList.Add(originalClasses[0]); 107 } else { 108 // at least one reasonable threshold ... 109 // find the most likely class for the points between thresholds m 110 for (int i = 0; i < thresholdList.Count - 1; i++) { 111 112 // determine class with maximal density mass between the thresholds 113 double maxDensity = LogNormalDensityMass(thresholdList[i], thresholdList[i + 1], classMean[originalClasses[0]], classStdDev[originalClasses[0]]); 114 double maxDensityClassValue = originalClasses[0]; 115 foreach (var classValue in originalClasses.Skip(1)) { 116 double density = LogNormalDensityMass(thresholdList[i], thresholdList[i + 1], classMean[classValue], classStdDev[classValue]); 117 if (density > maxDensity) { 118 maxDensity = density; 119 maxDensityClassValue = classValue; 120 } 121 } 122 classValuesList.Add(maxDensityClassValue); 103 123 } 104 105 // determine class with maximal probability density in m106 double maxDensity = double.MinValue;107 double maxDensityClassValue = -1;108 foreach (var classValue in originalClasses) {109 double density = NormalDensity(m, classMean[classValue], classStdDev[classValue]);110 if (density > maxDensity) {111 maxDensity = density;112 maxDensityClassValue = classValue;113 }114 }115 classValuesList.Add(maxDensityClassValue);116 124 } 117 125 … … 125 133 // / / /\s \ \ 126 134 // -/---/-/ -\---\-\---- 135 127 136 List<double> filteredThresholds = new List<double>(); 128 137 List<double> filteredClassValues = new List<double>(); 129 filteredThresholds.Add( thresholdList[0]);138 filteredThresholds.Add(double.NegativeInfinity); // the smallest possible threshold for the first class 130 139 filteredClassValues.Add(classValuesList[0]); 140 // do not include the last threshold which was just needed for the previous step 131 141 for (int i = 0; i < classValuesList.Count - 1; i++) { 132 if ( classValuesList[i] != classValuesList[i + 1]) {142 if (!classValuesList[i].IsAlmost(classValuesList[i + 1])) { 133 143 filteredThresholds.Add(thresholdList[i + 1]); 134 144 filteredClassValues.Add(classValuesList[i + 1]); … … 139 149 } 140 150 141 private static double NormalDensity(double x, double mu, double sigma) {151 private static double LogNormalDensityMass(double lower, double upper, double mu, double sigma) { 142 152 if (sigma.IsAlmost(0.0)) { 143 if (x.IsAlmost(mu)) return 1.0; else return 0.0; 144 } else { 145 return (1.0 / Math.Sqrt(2.0 * Math.PI * sigma * sigma)) * Math.Exp(-((x - mu) * (x - mu)) / (2.0 * sigma * sigma)); 153 if (lower < mu && mu < upper) return double.PositiveInfinity; // log(1) 154 else return double.NegativeInfinity; // log(0) 146 155 } 156 157 Func<double, double> f = (x) => 158 x * -0.5 * Math.Log(2.0 * Math.PI * sigma * sigma) - Math.Pow(x - mu, 3) / (3 * 2.0 * sigma * sigma); 159 160 if (double.IsNegativeInfinity(lower)) return f(upper); 161 else return f(upper) - f(lower); 147 162 } 148 163 149 164 private static void CalculateCutPoints(double m1, double s1, double m2, double s2, out double x1, out double x2) { 150 double a = (s1 * s1 - s2 * s2); 151 x1 = -(-m2 * s1 * s1 + m1 * s2 * s2 + Math.Sqrt(s1 * s1 * s2 * s2 * ((m1 - m2) * (m1 - m2) + 2.0 * (-s1 * s1 + s2 * s2) * Math.Log(s2 / s1)))) / a; 152 x2 = (m2 * s1 * s1 - m1 * s2 * s2 + Math.Sqrt(s1 * s1 * s2 * s2 * ((m1 - m2) * (m1 - m2) + 2.0 * (-s1 * s1 + s2 * s2) * Math.Log(s2 / s1)))) / a; 165 if (s1.IsAlmost(s2)) { 166 if (m1.IsAlmost(m2)) { 167 x1 = double.NegativeInfinity; 168 x2 = double.NegativeInfinity; 169 } else { 170 x1 = (m1 + m2) / 2; 171 x2 = double.NegativeInfinity; 172 } 173 } else if (s1.IsAlmost(0.0)) { 174 x1 = m1; 175 x2 = m1; 176 } else if (s2.IsAlmost(0.0)) { 177 x1 = m2; 178 x2 = m2; 179 } else { 180 if (s2 < s1) { 181 // make sure s2 is the larger std.dev. 182 CalculateCutPoints(m2, s2, m1, s1, out x1, out x2); 183 } else { 184 double a = (s1 + s2) * (s1 - s2); 185 double g = Math.Sqrt(s1 * s1 * s2 * s2 * ((m1 - m2) * (m1 - m2) + 2.0 * (s1 * s1 + s2 * s2) * Math.Log(s2 / s1))); 186 double m1s2 = m1 * s2 * s2; 187 double m2s1 = m2 * s1 * s1; 188 x1 = -(-m2s1 + m1s2 + g) / a; 189 x2 = (m2s1 - m1s2 + g) / a; 190 } 191 } 153 192 } 154 193 } -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/WeightCalculators/ClassificationWeightCalculator.cs
r8297 r8811 26 26 using HeuristicLab.Data; 27 27 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 28 using HeuristicLab.Problems.DataAnalysis.Interfaces;29 28 30 29 namespace HeuristicLab.Problems.DataAnalysis { -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/WeightCalculators/DiscriminantClassificationWeightCalculator.cs
r8297 r8811 24 24 using HeuristicLab.Common; 25 25 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 26 using HeuristicLab.Problems.DataAnalysis.Interfaces;27 26 28 27 namespace HeuristicLab.Problems.DataAnalysis { -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/DataAnalysisProblem.cs
r7866 r8811 66 66 } 67 67 68 protected DataAnalysisProblem(T problemData) 69 : this() { 70 ProblemData = problemData; 71 } 72 68 73 [StorableHook(HookType.AfterDeserialization)] 69 74 private void AfterDeserialization() { -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/DataAnalysisProblemData.cs
r8508 r8811 107 107 [StorableConstructor] 108 108 protected DataAnalysisProblemData(bool deserializing) : base(deserializing) { } 109 109 110 [StorableHook(HookType.AfterDeserialization)] 110 111 private void AfterDeserialization() { -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/ConstantRegressionModel.cs
r8534 r8811 30 30 public class ConstantRegressionModel : NamedItem, IRegressionModel { 31 31 [Storable] 32 pr ivatedouble constant;32 protected double constant; 33 33 public double Constant { 34 34 get { return constant; } -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionEnsembleSolution.cs
r8508 r8811 36 36 [Item("Regression Ensemble Solution", "A regression solution that contains an ensemble of multiple regression models")] 37 37 [Creatable("Data Analysis - Ensembles")] 38 public sealed class RegressionEnsembleSolution : RegressionSolution , IRegressionEnsembleSolution {38 public sealed class RegressionEnsembleSolution : RegressionSolutionBase, IRegressionEnsembleSolution { 39 39 private readonly Dictionary<int, double> trainingEvaluationCache = new Dictionary<int, double>(); 40 40 private readonly Dictionary<int, double> testEvaluationCache = new Dictionary<int, double>(); 41 private readonly Dictionary<int, double> evaluationCache = new Dictionary<int, double>(); 41 42 42 43 public new IRegressionEnsembleModel Model { … … 155 156 } 156 157 157 protected override void RecalculateResults() {158 CalculateResults();159 }160 161 158 #region Evaluation 159 public override IEnumerable<double> EstimatedValues { 160 get { return GetEstimatedValues(Enumerable.Range(0, ProblemData.Dataset.Rows)); } 161 } 162 162 163 public override IEnumerable<double> EstimatedTrainingValues { 163 164 get { -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionProblem.cs
r7866 r8811 36 36 public override IDeepCloneable Clone(Cloner cloner) { return new RegressionProblem(this, cloner); } 37 37 38 public RegressionProblem() 39 : base() { 40 ProblemData = new RegressionProblemData(); 41 } 38 public RegressionProblem() : base(new RegressionProblemData()) { } 39 42 40 } 43 41 } -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionSolution.cs
r8508 r8811 45 45 : base(model, problemData) { 46 46 evaluationCache = new Dictionary<int, double>(problemData.Dataset.Rows); 47 CalculateRegressionResults(); 47 48 } 48 49 49 protected override void RecalculateResults() {50 CalculateResults();51 }52 50 53 51 public override IEnumerable<double> EstimatedValues { -
branches/ClassificationEnsembleVoting/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Regression/RegressionSolutionBase.cs
r8508 r8811 29 29 [StorableClass] 30 30 public abstract class RegressionSolutionBase : DataAnalysisSolution, IRegressionSolution { 31 private const string TrainingMeanSquaredErrorResultName = "Mean squared error (training)"; 32 private const string TestMeanSquaredErrorResultName = "Mean squared error (test)"; 33 private const string TrainingMeanAbsoluteErrorResultName = "Mean absolute error (training)"; 34 private const string TestMeanAbsoluteErrorResultName = "Mean absolute error (test)"; 35 private const string TrainingSquaredCorrelationResultName = "Pearson's R² (training)"; 36 private const string TestSquaredCorrelationResultName = "Pearson's R² (test)"; 37 private const string TrainingRelativeErrorResultName = "Average relative error (training)"; 38 private const string TestRelativeErrorResultName = "Average relative error (test)"; 39 private const string TrainingNormalizedMeanSquaredErrorResultName = "Normalized mean squared error (training)"; 40 private const string TestNormalizedMeanSquaredErrorResultName = "Normalized mean squared error (test)"; 41 private const string TrainingMeanErrorResultName = "Mean error (training)"; 42 private const string TestMeanErrorResultName = "Mean error (test)"; 31 protected const string TrainingMeanSquaredErrorResultName = "Mean squared error (training)"; 32 protected const string TestMeanSquaredErrorResultName = "Mean squared error (test)"; 33 protected const string TrainingMeanAbsoluteErrorResultName = "Mean absolute error (training)"; 34 protected const string TestMeanAbsoluteErrorResultName = "Mean absolute error (test)"; 35 protected const string TrainingSquaredCorrelationResultName = "Pearson's R² (training)"; 36 protected const string TestSquaredCorrelationResultName = "Pearson's R² (test)"; 37 protected const string TrainingRelativeErrorResultName = "Average relative error (training)"; 38 protected const string TestRelativeErrorResultName = "Average relative error (test)"; 39 protected const string TrainingNormalizedMeanSquaredErrorResultName = "Normalized mean squared error (training)"; 40 protected const string TestNormalizedMeanSquaredErrorResultName = "Normalized mean squared error (test)"; 41 protected const string TrainingMeanErrorResultName = "Mean error (training)"; 42 protected const string TestMeanErrorResultName = "Mean error (test)"; 43 44 protected const string TrainingMeanSquaredErrorResultDescription = "Mean of squared errors of the model on the training partition"; 45 protected const string TestMeanSquaredErrorResultDescription = "Mean of squared errors of the model on the test partition"; 46 protected const string TrainingMeanAbsoluteErrorResultDescription = "Mean of absolute errors of the model on the training partition"; 47 protected const string TestMeanAbsoluteErrorResultDescription = "Mean of absolute errors of the model on the test partition"; 48 protected const string TrainingSquaredCorrelationResultDescription = "Squared Pearson's correlation coefficient of the model output and the actual values on the training partition"; 49 protected const string TestSquaredCorrelationResultDescription = "Squared Pearson's correlation coefficient of the model output and the actual values on the test partition"; 50 protected const string TrainingRelativeErrorResultDescription = "Average of the relative errors of the model output and the actual values on the training partition"; 51 protected const string TestRelativeErrorResultDescription = "Average of the relative errors of the model output and the actual values on the test partition"; 52 protected const string TrainingNormalizedMeanSquaredErrorResultDescription = "Normalized mean of squared errors of the model on the training partition"; 53 protected const string TestNormalizedMeanSquaredErrorResultDescription = "Normalized mean of squared errors of the model on the test partition"; 54 protected const string TrainingMeanErrorResultDescription = "Mean of errors of the model on the training partition"; 55 protected const string TestMeanErrorResultDescription = "Mean of errors of the model on the test partition"; 43 56 44 57 public new IRegressionModel Model { … … 115 128 protected RegressionSolutionBase(IRegressionModel model, IRegressionProblemData problemData) 116 129 : base(model, problemData) { 117 Add(new Result(TrainingMeanSquaredErrorResultName, "Mean of squared errors of the model on the training partition", new DoubleValue()));118 Add(new Result(TestMeanSquaredErrorResultName, "Mean of squared errors of the model on the test partition", new DoubleValue()));119 Add(new Result(TrainingMeanAbsoluteErrorResultName, "Mean of absolute errors of the model on the training partition", new DoubleValue()));120 Add(new Result(TestMeanAbsoluteErrorResultName, "Mean of absolute errors of the model on the test partition", new DoubleValue()));121 Add(new Result(TrainingSquaredCorrelationResultName, "Squared Pearson's correlation coefficient of the model output and the actual values on the training partition", new DoubleValue()));122 Add(new Result(TestSquaredCorrelationResultName, "Squared Pearson's correlation coefficient of the model output and the actual values on the test partition", new DoubleValue()));123 Add(new Result(TrainingRelativeErrorResultName, "Average of the relative errors of the model output and the actual values on the training partition", new PercentValue()));124 Add(new Result(TestRelativeErrorResultName, "Average of the relative errors of the model output and the actual values on the test partition", new PercentValue()));125 Add(new Result(TrainingNormalizedMeanSquaredErrorResultName, "Normalized mean of squared errors of the model on the training partition", new DoubleValue()));126 Add(new Result(TestNormalizedMeanSquaredErrorResultName, "Normalized mean of squared errors of the model on the test partition", new DoubleValue()));127 Add(new Result(TrainingMeanErrorResultName, "Mean of errors of the model on the training partition", new DoubleValue()));128 Add(new Result(TestMeanErrorResultName, "Mean of errors of the model on the test partition", new DoubleValue()));130 Add(new Result(TrainingMeanSquaredErrorResultName, TrainingMeanSquaredErrorResultDescription, new DoubleValue())); 131 Add(new Result(TestMeanSquaredErrorResultName, TestMeanSquaredErrorResultDescription, new DoubleValue())); 132 Add(new Result(TrainingMeanAbsoluteErrorResultName, TrainingMeanAbsoluteErrorResultDescription, new DoubleValue())); 133 Add(new Result(TestMeanAbsoluteErrorResultName, TestMeanAbsoluteErrorResultDescription, new DoubleValue())); 134 Add(new Result(TrainingSquaredCorrelationResultName, TrainingSquaredCorrelationResultDescription, new DoubleValue())); 135 Add(new Result(TestSquaredCorrelationResultName, TestSquaredCorrelationResultDescription, new DoubleValue())); 136 Add(new Result(TrainingRelativeErrorResultName, TrainingRelativeErrorResultDescription, new PercentValue())); 137 Add(new Result(TestRelativeErrorResultName, TestRelativeErrorResultDescription, new PercentValue())); 138 Add(new Result(TrainingNormalizedMeanSquaredErrorResultName, TrainingNormalizedMeanSquaredErrorResultDescription, new DoubleValue())); 139 Add(new Result(TestNormalizedMeanSquaredErrorResultName, TestNormalizedMeanSquaredErrorResultDescription, new DoubleValue())); 140 Add(new Result(TrainingMeanErrorResultName, TrainingMeanErrorResultDescription, new DoubleValue())); 141 Add(new Result(TestMeanErrorResultName, TestMeanErrorResultDescription, new DoubleValue())); 129 142 } 130 143 … … 164 177 } 165 178 166 protected void CalculateResults() { 179 protected override void RecalculateResults() { 180 CalculateRegressionResults(); 181 } 182 183 protected void CalculateRegressionResults() { 167 184 IEnumerable<double> estimatedTrainingValues = EstimatedTrainingValues; // cache values 168 185 IEnumerable<double> originalTrainingValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndices);
Note: See TracChangeset
for help on using the changeset viewer.