-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.cs
More file actions
416 lines (369 loc) · 12.2 KB
/
Tree.cs
File metadata and controls
416 lines (369 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
using Microsoft.Data.Analysis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
using Unit4.CollectionsLib;
namespace DecisionTree
{
internal class Tree
{
private DataFrame trainDf;
private string targetCol;
private BinNode<Dictionary<string, object>> tr;
private int minSampleLeaf = 15;
private int maxDepth = 10;
private static bool DEBUG = true;
private static void DebugLog(string msg)
{
if (DEBUG)
Console.WriteLine($"[Tree DEBUG] {msg}");
}
public BinNode<Dictionary<string, object>> GetTree(){return this.tr;}
public void ExportToDot(string path)
{
using (var writer = new StreamWriter(path))
{
writer.WriteLine("digraph Tree {");
writer.WriteLine("node [shape=box, style=rounded];");
int nodeId = 0;
ExportNode(this.tr, writer, ref nodeId);
writer.WriteLine("}");
}
}
private int ExportNode(BinNode<Dictionary<string, object>> node, StreamWriter writer, ref int id)
{
int myId = id++;
var data = node.GetValue();
string label;
if ((string)data["Type"] == "Leaf")
label = $"Leaf\\nClass: {data["Label"]}";
else if ((bool)data["IsNumeric"])
label = $"{data["Column"]} ≤ {data["Threshold"]}";
else
label = $"{data["Column"]} = {data["Value"]}";
writer.WriteLine($"{myId} [label=\"{label}\"];");
if ((string)data["Type"] != "Leaf")
{
int leftId = ExportNode(node.GetLeft(), writer, ref id);
int rightId = ExportNode(node.GetRight(), writer, ref id);
writer.WriteLine($"{myId} -> {leftId} [label=\"no\"];");
writer.WriteLine($"{myId} -> {rightId} [label=\"yes\"];");
}
return myId;
}
public Tree(DataFrame trainDf, string targetCol, int minSampleLeaf, int maxDepth)
{
DebugLog("Initializing Tree");
DebugLog($"Rows: {trainDf.Rows.Count}, Target column: {targetCol}");
this.trainDf = trainDf;
this.targetCol = targetCol;
this.minSampleLeaf = minSampleLeaf;
this.maxDepth = maxDepth;
this.tr = TrainTree(this.trainDf, this.trainDf.Columns[targetCol], 0);
DebugLog("Training completed");
}
public Tree(DataFrame trainDf, string targetCol)
{
DebugLog("Initializing Tree");
DebugLog($"Rows: {trainDf.Rows.Count}, Target column: {targetCol}");
this.trainDf = trainDf;
this.targetCol = targetCol;
this.minSampleLeaf = 15;
this.maxDepth = 10;
this.tr = TrainTree(this.trainDf, this.trainDf.Columns[targetCol], 0);
DebugLog("Training completed");
}
public DataFrame Pred(DataFrame inputDf)
{
DebugLog($"Prediction started | Rows: {inputDf.Rows.Count}");
var predictions = new List<object>();
foreach (var row in inputDf.Rows)
{
predictions.Add(Traverse(this.tr, row));
}
DataFrame output = inputDf.Clone();
var predCol = new StringDataFrameColumn("Prediction", predictions.Select(p => p.ToString()));
output.Columns.Add(predCol);
DebugLog("Prediction completed");
return output;
}
public object PredictRow(DataFrameRow row)
{
return Traverse(this.tr, row);
}
public object Traverse(BinNode<Dictionary<string, object>> node, DataFrameRow row)
{
var data = node.GetValue();
if ((string)data["Type"] == "Leaf")
return data["Label"];
string col = data["Column"].ToString();
bool isNumeric = (bool)data["IsNumeric"];
if (isNumeric)
{
double threshold = (double)data["Threshold"];
double value = Convert.ToDouble(row[col]);
DebugLog($"Testing {col} <= {threshold} | Row value: {value}");
return value <= threshold
? Traverse(node.GetLeft(), row)
: Traverse(node.GetRight(), row);
}
else
{
object splitVal = data["Value"];
object rowVal = row[col];
DebugLog($"Testing {col} == {splitVal} | Row value: {rowVal}");
return rowVal.Equals(splitVal)
? Traverse(node.GetRight(), row)
: Traverse(node.GetLeft(), row);
}
}
private BinNode<Dictionary<string, object>> TrainTree(DataFrame df, DataFrameColumn y, int currentDepth)
{
int rowCount = (int)df.Rows.Count;
double gini = CalcGini(y.Cast<object>());
if (gini == 0 || currentDepth >= this.maxDepth || rowCount < this.minSampleLeaf)
return CreateLeaf(y);
var potentialSplits = GetRankedPotentialSplits(df, y);
foreach (var split in potentialSplits)
{
DataFrame rightDf, leftDf;
if (split.IsNumeric)
{
var col = df.Columns[split.Column];
var rightMask = col.ElementwiseGreaterThan(split.Threshold.Value);
var leftMask = col.ElementwiseLessThanOrEqual(split.Threshold.Value);
rightDf = df[rightMask];
leftDf = df[leftMask];
}
else
{
var rightMask = df.Columns[split.Column].ElementwiseEquals(split.Value);
var leftMask = df.Columns[split.Column].ElementwiseNotEquals(split.Value);
rightDf = df[rightMask];
leftDf = df[leftMask];
}
if (rightDf.Rows.Count >= this.minSampleLeaf && leftDf.Rows.Count >= this.minSampleLeaf)
{
DebugLog($"Depth {currentDepth}: Split on {split.Column} == {split.Value} (Gini: {split.Score:F4})");
var nodeData = new Dictionary<string, object>
{
{ "Type", "Internal" },
{ "Column", split.Column },
{ "IsNumeric", split.IsNumeric }
};
if (split.IsNumeric)
nodeData["Threshold"] = split.Threshold.Value;
else
nodeData["Value"] = split.Value;
var node = new BinNode<Dictionary<string, object>>(nodeData);
node.SetRight(TrainTree(rightDf, rightDf[y.Name], currentDepth + 1));
node.SetLeft(TrainTree(leftDf, leftDf[y.Name], currentDepth + 1));
return node;
}
DebugLog(split.IsNumeric ? $"Depth {currentDepth}: Split on {split.Column} <= {split.Threshold:F3} (Gini: {split.Score:F4})" : $"Depth {currentDepth}: Split on {split.Column} == {split.Value} (Gini: {split.Score:F4})");
}
DebugLog($"Depth {currentDepth}: No valid splits found among any features. Creating leaf.");
return CreateLeaf(y);
}
private struct SplitInfo
{
public string Column;
public object Value;
public double? Threshold;
public double Score;
public bool IsNumeric;
}
private List<SplitInfo> GetRankedPotentialSplits(DataFrame df, DataFrameColumn y)
{
var splits = new List<SplitInfo>();
foreach (var col in df.Columns)
{
if (col.Name == this.targetCol)
continue;
// NUMERIC
if (col.DataType == typeof(int) ||
col.DataType == typeof(float) ||
col.DataType == typeof(double))
{
var (threshold, gini) = GetBestNumericSplit(df, y, col.Name);
splits.Add(new SplitInfo
{
Column = col.Name,
Threshold = threshold,
Score = gini,
IsNumeric = true
});
DebugLog($"Numeric split {col.Name} <= {threshold:F3} (Gini: {gini:F4})");
}
else
{
var bestValDict = GetBestSplitVal(df, y, col.Name);
var best = bestValDict.First();
splits.Add(new SplitInfo{Column = col.Name, Value = best.Key, Score = best.Value, IsNumeric = false});
DebugLog($"Nominal split {col.Name} == {best.Key} (Gini: {best.Value:F4})");
}
}
return splits.OrderBy(s => s.Score).ToList();
}
private BinNode<Dictionary<string, object>> CreateLeaf(DataFrameColumn y)
{
var leafData = new Dictionary<string, object> {{ "Type", "Leaf" }, { "Label", GetMajorityClass(y) }};
return new BinNode<Dictionary<string, object>>(leafData);
}
public static object GetMajorityClass(DataFrameColumn y)
{
var counts = new Dictionary<object, int>();
foreach (var value in y)
{
if (value == null)
continue;
if (counts.ContainsKey(value))
counts[value]++;
else
counts[value] = 1;
}
return counts.OrderByDescending(kv => kv.Value).First().Key;
}
public static Dictionary<object, double> GetBestSplitVal(DataFrame df, DataFrameColumn y, string col)
{
var scoreDict = new Dictionary<object, double>();
foreach (var row in df.Rows)
{
object val = row[col];
if (!scoreDict.ContainsKey(val))
scoreDict[val] = CalcGiniForNominal(df, y, col, val);
}
var best = scoreDict.OrderBy(kv => kv.Value).First();
return new Dictionary<object, double>{{ best.Key, best.Value }};
}
public static string GetBestSplitCol(DataFrame df, DataFrameColumn y)
{
if (GetBestSplitNominal(df, y).Values.Max() >= GetBestSplitNumeric(df, y).Values.Max())
return GetBestSplitNominal(df, y).First().Key;
return GetBestSplitNumeric(df, y).First().Key;
}
public static Dictionary<string, double> GetBestSplitNumeric(DataFrame df, DataFrameColumn y)
{
var scoreDict = new Dictionary<string, double>();
scoreDict[""] = 0.0;
var res = new Dictionary<string, double>();
res[scoreDict.OrderBy(kv => kv.Value).First().Key] = scoreDict.Values.Max();
return res;
}
public static double CalcGiniForNumeric(DataFrame df, DataFrameColumn y, string col)
{
return 0.0;
}
public static Dictionary<string, double> GetBestSplitNominal(DataFrame df, DataFrameColumn y)
{
var scoreDict = new Dictionary<string, double>();
foreach (var col in df.Columns)
{
if (col.Name == y.Name)
continue;
if (col.DataType != typeof(string) && !col.DataType.IsEnum)
continue;
double best = double.MaxValue;
foreach (var row in df.Rows)
{
object val = row[col.Name];
double gini = CalcGiniForNominal(df, y, col.Name, val);
best = Math.Min(best, gini);
}
scoreDict[col.Name] = best;
}
if (scoreDict.Count == 0)
return new Dictionary<string, double> { { "", 1.0 } };
var bestCol = scoreDict.OrderBy(kv => kv.Value).First();
return new Dictionary<string, double>{{ bestCol.Key, bestCol.Value }};
}
public static double CalcGiniForNominal(DataFrame df, DataFrameColumn y, string col, object value)
{
var left = new List<object>();
var right = new List<object>();
for (int i = 0; i < df.Rows.Count; i++)
if (df[col][i].Equals(value))
right.Add(y[i]);
else
left.Add(y[i]);
int n = left.Count + right.Count;
if (left.Count == 0 || right.Count == 0)
return double.MaxValue;
return (left.Count / (double)n) * CalcGini(left) + (right.Count / (double)n) * CalcGini(right);
}
public static double CalcValProp(DataFrame df, string col, object value)
{
double totalC = (double)df.Rows.Count;
int valC = 0;
foreach (DataFrameRow row in df.Rows)
if (row[col] == value)
valC++;
return valC / totalC;
}
public static double CalcGiniForVal(DataFrame df, DataFrameColumn y, string col, object value)
{
int n = (int)df.Rows.Count;
var ySub = Enumerable.Range(0, (int)n).Where(i => df.Columns[col][i].Equals(value)).Select(i => y[i]).ToList();
return CalcGini(ySub);
}
public static double CalcGini(IEnumerable<object> values)
{
var counts = new Dictionary<object, long>();
int total = 0;
foreach (var val in values)
{
total++;
if (counts.ContainsKey(val))
counts[val]++;
else
counts[val] = 1;
}
if (total == 0) return 0.0;
double sumSquares = counts.Values.Select(c => (double)c / total).Sum(p => p * p);
return 1.0 - sumSquares;
}
// Numeric
public static double CalcGiniForNumeric(DataFrame df, DataFrameColumn y, string col, double threshold)
{
var left = new List<object>();
var right = new List<object>();
for (int i = 0; i < df.Rows.Count; i++)
if (Convert.ToDouble(df[col][i]) <= threshold)
left.Add(y[i]);
else
right.Add(y[i]);
int n = (int)df.Rows.Count;
int nL = left.Count;
int nR = right.Count;
if (nL == 0 || nR == 0)
return double.MaxValue;
return (nL / (double)n) * CalcGini(left) + (nR / (double)n) * CalcGini(right);
}
public static (double threshold, double gini) GetBestNumericSplit(DataFrame df, DataFrameColumn y, string col)
{
var values = new List<double>();
for (int i = 0; i < df.Rows.Count; i++)
if (df[col][i] != null)
values.Add(Convert.ToDouble(df[col][i]));
values = values.Distinct().OrderBy(v => v).ToList();
double bestGini = double.MaxValue;
double bestThreshold = values[0];
for (int i = 0; i < values.Count - 1; i++)
{
double threshold = (values[i] + values[i + 1]) / 2.0;
double gini = CalcGiniForNumeric(df, y, col, threshold);
if (gini < bestGini)
{
bestGini = gini;
bestThreshold = threshold;
}
}
return (bestThreshold, bestGini);
}
}
}