-3

This is the snippet of the code where the error occurs I can't seem to figure out why there is an error. I am learning decision tree algorithm.

def gini(rows):
    """calculate the gini impurity for a list of rows."""
    
    counts = class_counts(rows)
    impurity  = 1
    for lbl in counts:
        prob_of_lbl = counts[lbl] / float(len(rows))
        impurity -= prob_of_lbl**2
    return impurity

def info_gain(left, right, current_uncertainty):
    """Information Gain"""
    
    #The uncertainty of the starting node, minus the weighted
    #impurity of two child nodes.
    
    p = float(len(left)) / (len(left) + len(right))
    return current_uncertainty - p * gini(left) - (1 - p) * gini(right)
A.Brusola
  • 59
  • 5
  • return current_uncertainty - p * gini(left) - (1 - p) * gini(right) this is where the error occurs – A.Brusola May 21 '22 at 07:44
  • 5
    There is no problem in _this_ code - beside you not showing how to call it and missing other things. Check your indentations, check that gini() occures before info_gain(), check that you haven't got giní or gìnì instead. Check out how name scoping works in python – Patrick Artner May 21 '22 at 07:47
  • [https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces) – Patrick Artner May 21 '22 at 08:29
  • Usually class methods got `self` as first param if they belong to the classes instance, else they can be marked `@staticmethod` or `@classmethod` - but then you still need to tell python which class they reside in: `MyClass.Whatever(...)` – Patrick Artner May 21 '22 at 08:30

1 Answers1

0

Do you have an indentation before the def gini ... ? If your gini function is in a class you should use ClassName.gini.

For example:

class ClassName:
    def gini(rows):
        ...
    def info_gain(left, right, current_uncertainty):
        ...
        ClassName.gini(rows)
        ...