如何比较两个sklearn估计量是否相等?

时间:2016-07-16 15:18:20

标签: python scikit-learn

我有两个sklearn估算器,想要比较它们:

import numpy as np
from sklearn.tree import DecisionTreeClassifier

X, y = np.random.random((100,2)), np.random.choice(2,100)    
dt1 = DecisionTreeClassifier()
dt1.fit(X, y)
dt2 = DecisionTreeClassifier()
dt3 = sklearn.base.copy.deepcopy(dt1)

如何比较分类器,使dt1!= dt2,dt1 == dt3?

1 个答案:

答案 0 :(得分:3)

您需要比较分配给分类器实例的参数和训练分类器的.tree_.value

# the trees have the same params
def compare_trees(tree1, tree2):
    if hash(tree1.__dict__.values())==hash(tree2.__dict__.values()):
        # the trees have both been trained
        if tree1.tree_ != None and tree2.tree_ != None: 
            try: # the tree values are matching arrays
                return (tree1.tree_.value==tree2.tree_.value).all()
            except: # they do not match
                return False
        elif tree1.tree_ != None or tree2.tree_ != None: 
            # XOR of the trees is not trained
            return False
        else: # Neither has been trained
            return True
    else: # the params are different
        return False


dt1 = DecisionTreeClassifier()
X, y = np.random.random((100,2)), np.random.choice(2,100)
dt1.fit(X, y)

dt2 = DecisionTreeClassifier() # untrained

dt3 = sklearn.base.copy.deepcopy(dt1) # copy of 1st

dt4 = DecisionTreeClassifier() # trained on different data
X_, y_ = np.random.random((100,2)), np.random.choice(2,100)   
dt4.fit(X_, y_)

print(compare_trees(dt1, dt1)) # True
print(compare_trees(dt1, dt2)) # False
print(compare_trees(dt1, dt3)) # True
print(compare_trees(dt1, dt4)) # False