Changeset 9363 for branches/OaaS/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification
- Timestamp:
- 04/16/13 13:13:41 (12 years ago)
- Location:
- branches/OaaS
- Files:
-
- 12 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/OaaS
- Property svn:ignore
-
old new 21 21 protoc.exe 22 22 _ReSharper.HeuristicLab 3.3 Tests 23 Google.ProtocolBuffers-2.4.1.473.dll 23 24 packages
-
- Property svn:mergeinfo changed
- Property svn:ignore
-
branches/OaaS/HeuristicLab.Problems.DataAnalysis
- Property svn:mergeinfo changed
-
branches/OaaS/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationEnsembleModel.cs
r7259 r9363 95 95 96 96 IClassificationSolution IClassificationModel.CreateClassificationSolution(IClassificationProblemData problemData) { 97 return new ClassificationEnsembleSolution(models, problemData);97 return new ClassificationEnsembleSolution(models, new ClassificationEnsembleProblemData(problemData)); 98 98 } 99 99 #endregion -
branches/OaaS/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationEnsembleSolution.cs
r8174 r9363 36 36 [Item("Classification Ensemble Solution", "A classification solution that contains an ensemble of multiple classification models")] 37 37 [Creatable("Data Analysis - Ensembles")] 38 public sealed class ClassificationEnsembleSolution : ClassificationSolution , IClassificationEnsembleSolution {38 public sealed class ClassificationEnsembleSolution : ClassificationSolutionBase, IClassificationEnsembleSolution { 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 IClassificationEnsembleModel Model { … … 104 105 } 105 106 107 public ClassificationEnsembleSolution(IClassificationProblemData problemData) : 108 this(Enumerable.Empty<IClassificationModel>(), problemData) { } 109 106 110 public ClassificationEnsembleSolution(IEnumerable<IClassificationModel> models, IClassificationProblemData problemData) 107 111 : this(models, problemData, … … 150 154 } 151 155 152 protected override void RecalculateResults() {153 CalculateResults();154 }155 156 156 157 #region Evaluation 158 public override IEnumerable<double> EstimatedClassValues { 159 get { return GetEstimatedClassValues(Enumerable.Range(0, ProblemData.Dataset.Rows)); } 160 } 161 157 162 public override IEnumerable<double> EstimatedTrainingClassValues { 158 163 get { -
branches/OaaS/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationProblemData.cs
r8121 r9363 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 … … 277 273 278 274 public ClassificationProblemData() : this(defaultDataset, defaultAllowedInputVariables, defaultTargetVariable) { } 275 276 public ClassificationProblemData(IClassificationProblemData classificationProblemData) 277 : this(classificationProblemData.Dataset, classificationProblemData.AllowedInputVariables, classificationProblemData.TargetVariable) { 278 TrainingPartition.Start = classificationProblemData.TrainingPartition.Start; 279 TrainingPartition.End = classificationProblemData.TrainingPartition.End; 280 TestPartition.Start = classificationProblemData.TestPartition.Start; 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 } 291 } 292 279 293 public ClassificationProblemData(Dataset dataset, IEnumerable<string> allowedInputVariables, string targetVariable) 280 294 : base(dataset, allowedInputVariables) { … … 286 300 Parameters.Add(new FixedValueParameter<DoubleMatrix>(ClassificationPenaltiesParameterName, "")); 287 301 302 RegisterParameterEvents(); 288 303 ResetTargetVariableDependentMembers(); 289 RegisterParameterEvents(); 290 } 291 292 private static IEnumerable<string> CheckVariablesForPossibleTargetVariables(Dataset dataset) { 304 } 305 306 public static IEnumerable<string> CheckVariablesForPossibleTargetVariables(Dataset dataset) { 293 307 int maxSamples = Math.Min(InspectedRowsToDetermineTargets, dataset.Rows); 294 308 var validTargetVariables = (from v in dataset.DoubleVariables … … 310 324 DeregisterParameterEvents(); 311 325 312 classNames = null;313 326 ((IStringConvertibleMatrix)ClassNamesParameter.Value).Columns = 1; 314 ((IStringConvertibleMatrix)ClassNamesParameter.Value).Rows = ClassValues .Count;327 ((IStringConvertibleMatrix)ClassNamesParameter.Value).Rows = ClassValuesCache.Count; 315 328 for (int i = 0; i < Classes; i++) 316 ClassNamesParameter.Value[i, 0] = "Class " + ClassValues [i];329 ClassNamesParameter.Value[i, 0] = "Class " + ClassValuesCache[i]; 317 330 ClassNamesParameter.Value.ColumnNames = new List<string>() { "ClassNames" }; 318 331 ClassNamesParameter.Value.RowNames = ClassValues.Select(s => "ClassValue: " + s); 319 332 320 classificationPenaltiesCache.Clear();321 ((ValueParameter<DoubleMatrix>)ClassificationPenaltiesParameter).ReactOnValueToStringChangedAndValueItemImageChanged = false;322 333 ((IStringConvertibleMatrix)ClassificationPenaltiesParameter.Value).Rows = Classes; 323 334 ((IStringConvertibleMatrix)ClassificationPenaltiesParameter.Value).Columns = Classes; … … 330 341 } 331 342 } 332 ((ValueParameter<DoubleMatrix>)ClassificationPenaltiesParameter).ReactOnValueToStringChangedAndValueItemImageChanged = true;333 343 RegisterParameterEvents(); 334 344 } 335 345 336 346 public string GetClassName(double classValue) { 337 if (!ClassValues .Contains(classValue)) throw new ArgumentException();338 int index = ClassValues .IndexOf(classValue);339 return ClassNames [index];347 if (!ClassValuesCache.Contains(classValue)) throw new ArgumentException(); 348 int index = ClassValuesCache.IndexOf(classValue); 349 return ClassNamesCache[index]; 340 350 } 341 351 public double GetClassValue(string className) { 342 if (!ClassNames .Contains(className)) throw new ArgumentException();343 int index = ClassNames .IndexOf(className);344 return ClassValues [index];352 if (!ClassNamesCache.Contains(className)) throw new ArgumentException(); 353 int index = ClassNamesCache.IndexOf(className); 354 return ClassValuesCache[index]; 345 355 } 346 356 public void SetClassName(double classValue, string className) { 347 if (!classValues.Contains(classValue)) throw new ArgumentException(); 348 int index = ClassValues.IndexOf(classValue); 349 ClassNames[index] = className; 357 if (!ClassValuesCache.Contains(classValue)) throw new ArgumentException(); 358 int index = ClassValuesCache.IndexOf(classValue); 350 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 351 361 } 352 362 … … 355 365 } 356 366 public double GetClassificationPenalty(double correctClassValue, double estimatedClassValue) { 357 var key = Tuple.Create(correctClassValue, estimatedClassValue); 358 if (!classificationPenaltiesCache.ContainsKey(key)) { 359 int correctClassIndex = ClassValues.IndexOf(correctClassValue); 360 int estimatedClassIndex = ClassValues.IndexOf(estimatedClassValue); 361 classificationPenaltiesCache[key] = ClassificationPenaltiesParameter.Value[correctClassIndex, estimatedClassIndex]; 362 } 363 return classificationPenaltiesCache[key]; 367 int correctClassIndex = ClassValuesCache.IndexOf(correctClassValue); 368 int estimatedClassIndex = ClassValuesCache.IndexOf(estimatedClassValue); 369 return ClassificationPenaltiesParameter.Value[correctClassIndex, estimatedClassIndex]; 364 370 } 365 371 public void SetClassificationPenalty(string correctClassName, string estimatedClassName, double penalty) { … … 367 373 } 368 374 public void SetClassificationPenalty(double correctClassValue, double estimatedClassValue, double penalty) { 369 var key = Tuple.Create(correctClassValue, estimatedClassValue); 370 int correctClassIndex = ClassValues.IndexOf(correctClassValue); 371 int estimatedClassIndex = ClassValues.IndexOf(estimatedClassValue); 375 int correctClassIndex = ClassValuesCache.IndexOf(correctClassValue); 376 int estimatedClassIndex = ClassValuesCache.IndexOf(estimatedClassValue); 372 377 373 378 ClassificationPenaltiesParameter.Value[correctClassIndex, estimatedClassIndex] = penalty; … … 378 383 TargetVariableParameter.ValueChanged += new EventHandler(TargetVariableParameter_ValueChanged); 379 384 ClassNamesParameter.Value.Reset += new EventHandler(Parameter_ValueChanged); 380 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); 381 387 ClassificationPenaltiesParameter.Value.Reset += new EventHandler(Parameter_ValueChanged); 382 ClassificationPenaltiesParameter.Value.ItemChanged += new EventHandler<EventArgs<int, int>>(MatrixParameter_ItemChanged);383 388 } 384 389 private void DeregisterParameterEvents() { 385 390 TargetVariableParameter.ValueChanged -= new EventHandler(TargetVariableParameter_ValueChanged); 386 391 ClassNamesParameter.Value.Reset -= new EventHandler(Parameter_ValueChanged); 387 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); 388 394 ClassificationPenaltiesParameter.Value.Reset -= new EventHandler(Parameter_ValueChanged); 389 ClassificationPenaltiesParameter.Value.ItemChanged -= new EventHandler<EventArgs<int, int>>(MatrixParameter_ItemChanged);390 395 } 391 396 392 397 private void TargetVariableParameter_ValueChanged(object sender, EventArgs e) { 393 classValues = null; 398 classValuesCache = null; 399 classNamesCache = null; 394 400 ResetTargetVariableDependentMembers(); 395 401 OnChanged(); 396 402 } 397 403 private void Parameter_ValueChanged(object sender, EventArgs e) { 398 OnChanged();399 }400 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); 401 407 OnChanged(); 402 408 } -
branches/OaaS/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationSolution.cs
r8174 r9363 45 45 : base(model, problemData) { 46 46 evaluationCache = new Dictionary<int, double>(problemData.Dataset.Rows); 47 CalculateClassificationResults(); 47 48 } 48 49 -
branches/OaaS/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ClassificationSolutionBase.cs
r8139 r9363 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/OaaS/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/DiscriminantFunctionClassificationModel.cs
r7259 r9363 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, new ClassificationProblemData(problemData)); 139 } 140 141 public virtual IClassificationSolution CreateClassificationSolution(IClassificationProblemData problemData) { 142 return CreateDiscriminantFunctionClassificationSolution(problemData); 143 } 107 144 } 108 145 } -
branches/OaaS/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/DiscriminantFunctionClassificationSolution.cs
r8139 r9363 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 } 53 56 54 SetAccuracyMaximizingThresholds(); 57 public override IDeepCloneable Clone(Cloner cloner) { 58 return new DiscriminantFunctionClassificationSolution(this, cloner); 55 59 } 56 60 -
branches/OaaS/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/DiscriminantFunctionClassificationSolutionBase.cs
r8139 r9363 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 SetAccuracyMaximizingThresholds();99 RegisterEventHandler();100 base.OnModelChanged();101 93 } 102 94 … … 137 129 } 138 130 139 public void SetAccuracyMaximizingThresholds() {140 double[] classValues;141 double[] thresholds;142 var targetClassValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndices);143 AccuracyMaximizationThresholdCalculator.CalculateThresholds(ProblemData, EstimatedTrainingValues, targetClassValues, out classValues, out thresholds);144 145 Model.SetThresholdsAndClassValues(thresholds, classValues);146 }147 148 public void SetClassDistibutionCutPointThresholds() {149 double[] classValues;150 double[] thresholds;151 var targetClassValues = ProblemData.Dataset.GetDoubleValues(ProblemData.TargetVariable, ProblemData.TrainingIndices);152 NormalDistributionCutPointsThresholdCalculator.CalculateThresholds(ProblemData, EstimatedTrainingValues, targetClassValues, out classValues, out thresholds);153 154 Model.SetThresholdsAndClassValues(thresholds, classValues);155 }156 157 131 protected virtual void OnModelThresholdsChanged(EventArgs e) { 158 CalculateResults(); 159 CalculateRegressionResults(); 132 OnModelChanged(); 160 133 } 161 134 … … 165 138 166 139 public abstract IEnumerable<double> GetEstimatedValues(IEnumerable<int> rows); 140 141 protected override void RecalculateResults() { 142 base.RecalculateResults(); 143 CalculateRegressionResults(); 144 } 167 145 } 168 146 } -
branches/OaaS/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ThresholdCalculators/AccuracyMaximizationThresholdCalculator.cs
r8126 r9363 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/OaaS/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/Classification/ThresholdCalculators/NormalDistributionCutPointsThresholdCalculator.cs
r7259 r9363 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>(); … … 72 71 } 73 72 } 73 74 74 double[] originalClasses = classMean.Keys.OrderBy(x => x).ToArray(); 75 75 int nClasses = originalClasses.Length; … … 82 82 // calculate all thresholds 83 83 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); 84 85 // if the two cut points are too close (for instance because the stdDev=0) 86 // then move them by 0.1% of the range of estimated values 87 if (x1.IsAlmost(x2)) { 88 x1 -= 0.001 * estimatedValuesRange; 89 x2 += 0.001 * estimatedValuesRange; 90 } 91 if (!double.IsInfinity(x1) && !thresholdList.Any(x => x.IsAlmost(x1))) thresholdList.Add(x1); 92 if (!double.IsInfinity(x2) && !thresholdList.Any(x => x.IsAlmost(x2))) thresholdList.Add(x2); 86 93 } 87 94 } 88 95 thresholdList.Sort(); 96 97 // add small value and large value for the calculation of most influential class in each thresholded section 89 98 thresholdList.Insert(0, double.NegativeInfinity); 90 91 // determine class values for each partition separated by a threshold by calculating the density of all class distributions 92 // all points in the partition are classified as the class with the maximal density in the parition 93 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 } 104 105 // determine class with maximal probability density in m 106 double maxDensity = double.MinValue; 107 double maxDensityClassValue = -1; 108 foreach (var classValue in originalClasses) { 109 double density = NormalDensity(m, classMean[classValue], classStdDev[classValue]); 99 thresholdList.Add(double.PositiveInfinity); 100 101 102 // find the most likely class for the points between thresholds m 103 List<double> filteredThresholds = new List<double>(); 104 List<double> filteredClassValues = new List<double>(); 105 for (int i = 0; i < thresholdList.Count - 1; i++) { 106 // determine class with maximal density mass between the thresholds 107 double maxDensity = DensityMass(thresholdList[i], thresholdList[i + 1], classMean[originalClasses[0]], classStdDev[originalClasses[0]]); 108 double maxDensityClassValue = originalClasses[0]; 109 foreach (var classValue in originalClasses.Skip(1)) { 110 double density = DensityMass(thresholdList[i], thresholdList[i + 1], classMean[classValue], classStdDev[classValue]); 110 111 if (density > maxDensity) { 111 112 maxDensity = density; … … 113 114 } 114 115 } 115 classValuesList.Add(maxDensityClassValue); 116 } 117 118 // only keep thresholds at which the class changes 119 // class B overrides threshold s. So only thresholds r and t are relevant and have to be kept 120 // 121 // A B C 122 // /\ /\/\ 123 // / r\/ /\t\ 124 // / /\/ \ \ 125 // / / /\s \ \ 126 // -/---/-/ -\---\-\---- 127 List<double> filteredThresholds = new List<double>(); 128 List<double> filteredClassValues = new List<double>(); 129 filteredThresholds.Add(thresholdList[0]); 130 filteredClassValues.Add(classValuesList[0]); 131 for (int i = 0; i < classValuesList.Count - 1; i++) { 132 if (classValuesList[i] != classValuesList[i + 1]) { 133 filteredThresholds.Add(thresholdList[i + 1]); 134 filteredClassValues.Add(classValuesList[i + 1]); 135 } 136 } 116 if (maxDensity > double.NegativeInfinity && 117 (filteredClassValues.Count == 0 || !maxDensityClassValue.IsAlmost(filteredClassValues.Last()))) { 118 filteredThresholds.Add(thresholdList[i]); 119 filteredClassValues.Add(maxDensityClassValue); 120 } 121 } 122 123 if (filteredThresholds.Count == 0 || !double.IsNegativeInfinity(filteredThresholds.First())) { 124 // this happens if there are no thresholds (distributions for all classes are exactly the same) 125 // or when the CDF up to the first threshold is zero 126 // -> all samples should be classified as the class with the most observations 127 // group observations by target class and select the class with largest count 128 double mostFrequentClass = targetClassValues.GroupBy(c => c) 129 .OrderBy(g => g.Count()) 130 .Last().Key; 131 filteredThresholds.Insert(0, double.NegativeInfinity); 132 filteredClassValues.Insert(0, mostFrequentClass); 133 } 134 137 135 thresholds = filteredThresholds.ToArray(); 138 136 classValues = filteredClassValues.ToArray(); 139 137 } 140 138 141 private static double NormalDensity(double x, double mu, double sigma) { 139 private static double sqr2 = Math.Sqrt(2.0); 140 // returns the density function of the standard normal distribution at x 141 private static double NormalCDF(double x) { 142 return 0.5 * (1 + alglib.errorfunction(x / sqr2)); 143 } 144 145 // approximation of the log of the normal cummulative distribution from the lightspeed toolbox by Tom Minka 146 // http://research.microsoft.com/en-us/um/people/minka/software/lightspeed/ 147 private static double[] c = new double[] { -1, 5 / 2.0, -37 / 3.0, 353 / 4.0, -4081 / 5.0, 55205 / 6.0, -854197 / 7.0 }; 148 private static double LogNormalCDF(double x) { 149 if (x >= -6.5) 150 // calculate the log directly if x is large enough 151 return Math.Log(NormalCDF(x)); 152 else { 153 double z = Math.Pow(x, -2); 154 // asymptotic series for logcdf 155 double y = z * (c[0] + z * (c[1] + z * (c[2] + z * (c[3] + z * (c[4] + z * (c[5] + z * c[6])))))); 156 return y - 0.5 * Math.Log(2 * Math.PI) - 0.5 * x * x - Math.Log(-x); 157 } 158 } 159 160 // determines the value NormalCDF(mu,sigma, upper) - NormalCDF(mu, sigma, lower) 161 // = the integral of the PDF of N(mu, sigma) in the range [lower, upper] 162 private static double DensityMass(double lower, double upper, double mu, double sigma) { 142 163 if (sigma.IsAlmost(0.0)) { 143 if (x.IsAlmost(mu)) return 1.0; else return 0.0; 164 if (lower < mu && mu < upper) return 0.0; // all mass is between lower and upper 165 else return double.NegativeInfinity; // no mass is between lower and upper 166 } 167 168 if (lower > mu) { 169 return DensityMass(-upper, -lower, -mu, sigma); 170 } 171 172 upper = (upper - mu) / sigma; 173 lower = (lower - mu) / sigma; 174 if (double.IsNegativeInfinity(lower)) return LogNormalCDF(upper); 175 176 return LogNormalCDF(upper) + Math.Log(1 - Math.Exp(LogNormalCDF(lower) - LogNormalCDF(upper))); 177 } 178 179 // Calculates the points x1 and x2 where the distributions N(m1, s1) == N(m2,s2). 180 // In the general case there should be two cut points. If either s1 or s2 is 0 then x1==x2. 181 // If both s1 and s2 are zero than there are no cut points but we should return something reasonable (e.g. (m1 + m2) / 2) then. 182 private static void CalculateCutPoints(double m1, double s1, double m2, double s2, out double x1, out double x2) { 183 if (s1.IsAlmost(s2)) { 184 if (m1.IsAlmost(m2)) { 185 x1 = double.NegativeInfinity; 186 x2 = double.NegativeInfinity; 187 } else { 188 // s1==s2 and m1 != m2 189 // return something reasonable. cut point should be half way between m1 and m2 190 x1 = (m1 + m2) / 2; 191 x2 = double.NegativeInfinity; 192 } 193 } else if (s1.IsAlmost(0.0)) { 194 // when s1 is 0.0 the cut points are exactly at m1 ... 195 x1 = m1; 196 x2 = m1; 197 } else if (s2.IsAlmost(0.0)) { 198 // ... same for s2 199 x1 = m2; 200 x2 = m2; 144 201 } else { 145 return (1.0 / Math.Sqrt(2.0 * Math.PI * sigma * sigma)) * Math.Exp(-((x - mu) * (x - mu)) / (2.0 * sigma * sigma)); 146 } 147 } 148 149 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; 202 if (s2 < s1) { 203 // make sure s2 is the larger std.dev. 204 CalculateCutPoints(m2, s2, m1, s1, out x1, out x2); 205 } else { 206 // general case 207 // calculate the solutions x1, x2 where N(m1,s1) == N(m2,s2) 208 double g = Math.Sqrt(2 * s2 * s2 * Math.Log(s2 / s1) - 2 * s1 * s1 * Math.Log(s2 / s1) - 2 * m1 * m2 + m1 * m1 + m2 * m2); 209 double s = (s1 * s1 - s2 * s2); 210 x1 = (m2 * s1 * s1 - m1 * s2 * s2 + s1 * s2 * g) / s; 211 x2 = -(m1 * s2 * s2 - m2 * s1 * s1 + s1 * s2 * g) / s; 212 } 213 } 153 214 } 154 215 }
Note: See TracChangeset
for help on using the changeset viewer.