【问题标题】:Accessing object attributes using dictionary keys使用字典键访问对象属性
【发布时间】:2019-05-24 09:36:00
【问题描述】:

我正在尝试将模型的超参数存储在数据框中,其中要存储的确切参数存储为字典的键。

键的值用于网格搜索循环的每次迭代中的最佳值。

例如,超参数字典可能看起来像这样:

hyperParams = {'C':[.0, 0.1, 1.], 'epsilon':[0., 0.1, 0.2]}

存储值的数据框的元素是这样生成的:

for h in hyperParams.keys() :
    df[str(h)] = np.nan

如果参数是固定的,存储特定值的代码将如下所示:

df.loc[row_index, 'C'] = regressor.C

但是参数(回归器的属性)存储为键。

我试过了:

for h in hyperParams.keys() :
    df.loc[row_index, str(h)] = regressor.h

还有这个:

for h in hyperParams.keys() :
    df.loc[row_index, str(h)] = regressor.str(h)

但是两者都不是回归对象的属性。

有没有办法从字典的键中调用这个对象的属性?

【问题讨论】:

    标签: python dictionary attributes key call


    【解决方案1】:

    您可以使用 Python 的内置 getattr 函数。 getattr 函数的参数应该是对象和要从对象中获取的属性的字符串值。所以在你的情况下你可以做getattr(regressor, h)。

    【讨论】:

    • 完美!谢谢德莱娜。
    猜你喜欢
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2014-03-04
    • 1970-01-01
    相关资源
    最近更新 更多