Skip to content

Commit

Permalink
calculate feature importance
Browse files Browse the repository at this point in the history
  • Loading branch information
narumiruna committed Dec 6, 2024
1 parent c69e80d commit 1d18a7f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pkg/ml/ensemble/iforest/forest.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,15 @@ func (f *IsolationForest) Predict(samples *mat.Dense) []int {
}
return predictions
}

func (f *IsolationForest) FeatureImportance(sample []float64) []float64 {
o := make([]float64, len(sample))

for _, tree := range f.Forest {
for i, c := range tree.FeatureImportance(sample) {
o[i] += float64(c) / float64(f.NumTrees)
}
}

return o
}
18 changes: 18 additions & 0 deletions pkg/ml/ensemble/iforest/tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,21 @@ type TreeNode struct {
func (node *TreeNode) IsLeaf() bool {
return node.Left == nil && node.Right == nil
}

func (node *TreeNode) trackUsedFeatures(sample []float64, featureUsed []float64) []float64 {
if node.IsLeaf() {
return featureUsed
}

featureUsed[node.SplitIndex]++

if sample[node.SplitIndex] < node.SplitValue {
return node.Left.trackUsedFeatures(sample, featureUsed)
} else {
return node.Right.trackUsedFeatures(sample, featureUsed)
}
}

func (node *TreeNode) FeatureImportance(sample []float64) []float64 {
return node.trackUsedFeatures(sample, make([]float64, len(sample)))
}

0 comments on commit 1d18a7f

Please sign in to comment.