我有一个 DecisionTree 对象来创建机器学习模型。决策树中有很多表示设置的字段。每个字段都有一个默认值,大多数情况下只需更改其中一两个字段。
问题是,实际构建决策树的计算成本很高。因此,我没有在制作模型时构建模型,而是让制作者仅解析并保存数据。在调用 DecisionTree.build 之前不会构建模型。这允许在构建之前更改设置。但是,这也意味着如果在构建之前调用 DecisionTree.predict 将失败。
我知道让对象始终处于有效状态是一种很好的做法。但这意味着在构造函数中构建树,这是昂贵的,并且如果任何设置发生更改,则必须重新构建。
示例 1:构建调用是单独的
DecisionTree tree = new DecisionTree(data, classes, attributes);
tree.predict(item); //This would error
tree.maxDepth = 15;
tree.infoGain = 0.5;
tree.build();
tree.predict(item) // Now it would work
示例 2:包含构建调用,但设置不在构造函数中
DecisionTree tree = new DecisionTree(data, classes, attributes); // This would take a long time to complete
tree.predict(item); //This would now work
tree.maxDepth = 15;
tree.infoGain = 0.5;
tree.build(); // This would once again take a long time to complete
tree.predict(item) // Done, but takes twice as long as the previous example
示例 3
DecisionTree tree = new DecisionTree(data, classes, attributes, null, null, 15, null, null, 0.5, null, null, null); // Settings are all included in constructor
tree.predict(item); //This would immediately be callable
我的问题是,这 3 个选项是处理许多设置的唯一方法吗?这方面的标准/最佳实践是什么?
最佳答案
我认为将算法与其他方法相匹配并不是一个坏习惯,例如scikit-learn ,它们提供了额外的方法来拟合对象,构造函数本身只是初始化内部变量,如果你在拟合之前调用预测,它只会抛出 NotFittedError 。除此之外,也许将来您希望扩展您的算法以使用小批量,在这种情况下不可能多次调用构造函数,因此您将需要类似 partial_fit 的东西。方法,使分类器适合额外的数据 block 。所以你不能在构造函数中做所有事情。
如果你在初始化时有大量参数,也许你会发现有用的 Builder pattern
关于object - 在需要构建的对象中设置字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32018746/