【问题标题】:Sample mean in RandomForest随机森林中的样本均值
【发布时间】:2022-12-17 14:37:42
【问题描述】:

我确实参加了最高班。如何将Leaf类中的predict方法从取最大类更改为取样本均值?

class Leaf:
    
    def __init__(self, data, labels):
        self.data = data
        self.labels = labels
        self.prediction = self.predict()
        
    def predict(self):
        classes = {} 
        for label in self.labels:
            if label not in classes:
                classes[label] = 0
            classes[label] += 1
              
        prediction = max(classes, key=classes.get)
        return prediction   

测试代码:

%%time
n_trees = 1
my_forest_1 = random_forest(train_data, train_labels, n_trees)

【问题讨论】:

    标签: python pandas machine-learning random-forest


    【解决方案1】:

    这个我觉得: 取类值的总和,然后除以类的数量。 首先检查是否不为零:

    class Leaf:
        def __init__(self, data, labels):
            self.data = data
            self.labels = labels
            self.prediction = self.predict()
        def predict(self):
            classes = {} 
            for label in self.labels:
                if label not in classes:
                    classes[label] = 0
                classes[label] += 1
            if len(classes):
                prediction = sum(classes, key=classes.get) / len(classes)
            else:
                prediction = 0 # Default value for when there are no classes
            return prediction
    

    【讨论】:

    • 你好。我真的很感谢你的努力。但是,出现错误:'key' 是 sum() 的无效关键字参数
    • 啊,那你能给我一个测试代码的方法吗?
    • 我在主题的描述中添加了它。当我运行这段代码时,出现错误。
    猜你喜欢
    • 2017-05-13
    • 2016-01-21
    • 2023-03-27
    • 2021-03-21
    • 2021-08-17
    • 2017-12-04
    • 2013-01-28
    • 2016-07-16
    • 2016-05-25
    相关资源
    最近更新 更多