-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomForest.cs
More file actions
64 lines (56 loc) · 1.69 KB
/
RandomForest.cs
File metadata and controls
64 lines (56 loc) · 1.69 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
using DecisionTree;
using Microsoft.Data.Analysis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTModel
{
internal class RandomForest
{
private List<Tree> forest;
private int numTrees;
public RandomForest(DataFrame trainDf, string targetCol, int numTrees = 100)
{
this.numTrees = numTrees;
this.forest = new List<Tree>();
for (int i = 0; i < numTrees; i++)
{
DataFrame bootstrapSample = GetBootstrapSample(trainDf);
Tree tree = new Tree(bootstrapSample, targetCol, minSampleLeaf: 1, maxDepth: 20);
forest.Add(tree);
Console.WriteLine($"Trained tree {i + 1}/{numTrees}");
}
}
private DataFrame GetBootstrapSample(DataFrame df)
{
Random rand = new Random();
long rowCount = df.Rows.Count;
List<int> rowIndices = new List<int>();
for (int i = 0; i < rowCount; i++)
rowIndices.Add(rand.Next(0, (int)rowCount));
return df.Sample(rowIndices.Count);
}
public DataFrame Pred(DataFrame inputDf)
{
DebugLog($"Forest Prediction started | Rows: {inputDf.Rows.Count}");
var finalPredictions = new List<string>();
foreach (var row in inputDf.Rows)
{
var votes = forest.Select(tree => tree.PredictRow(row)?.ToString()).ToList();
var winner = votes.GroupBy(v => v).OrderByDescending(g => g.Count()).First().Key;
finalPredictions.Add(winner);
}
DataFrame output = inputDf.Clone();
var predCol = new StringDataFrameColumn("Prediction", finalPredictions);
output.Columns.Add(predCol);
DebugLog("Forest Prediction completed");
return output;
}
private void DebugLog(string msg)
{
Console.WriteLine($"[Forest DEBUG] {msg}");
}
}
}