如何在自定义函数中为DecisionTreeRegressor构造器指定参数名?
解决方法
你的问题出在没有正确传递动态关键字参数——直接写feature=value时,Python会把feature当作字面量的参数名,而不是你传入的字符串(比如'max_depth')对应的参数名。要实现动态指定参数名,需要用**字典解包的方式传递关键字参数。
修改后的代码如下:
import numpy as np from sklearn.tree import DecisionTreeRegressor # 示例数据,替换成你的真实数据即可 x = np.random.rand(100, 5) y = np.random.rand(100) def tryfeatures(feature, value, x, y): # 将参数名和值打包为字典,通过**解包传递给构造器 tree = DecisionTreeRegressor(**{feature: value}) return tree.fit(x, y) # 调用示例 tryfeatures('max_depth', 5, x, y) tryfeatures('min_samples_split', 3, x, y)
这样调用时,**{feature: value}会把字典的键作为参数名、值作为参数值,完全等价于直接写DecisionTreeRegressor(max_depth=5)或DecisionTreeRegressor(min_samples_split=3)。
如果需要同时传递多个参数,可以扩展函数直接接收关键字参数,用法更灵活:
def tryfeatures(x, y, **kwargs): tree = DecisionTreeRegressor(**kwargs) return tree.fit(x, y) # 同时传递多个参数的调用示例 tryfeatures(x, y, max_depth=5, min_samples_split=3)
内容的提问来源于stack exchange,提问作者ignacM
相关产品推荐
相关产品推荐

