【问题标题】:for-loop issue (how to use i-parameter on the obj name created within the for-loop)for 循环问题(如何在 for 循环中创建的 obj 名称上使用 i 参数)
【发布时间】:2019-10-26 11:48:47
【问题描述】:

我想在 for 中创建一些随机森林模型 我在其中移动估计器数量的循环。在相同的数据样本上训练他们每个人并测量每个人的准确性。 这是我的开始代码:

r = range(0, 100)
for i in r:
    RF_model_%i = RandomForestClassifier(criterion="entropy", n_estimators=i, oob_score=True)
    RF_model_%i.fit(X_train, y_train)
    y_predict =   RF_model_%i.predict(X_test)
    accuracy_%i = accuracy_score(y_test, y_predict)

我想理解的是:

  1. 如何将 i 参数 放在每个模型的名称上(在 为了识别它们)?
  2. 经过染色和计算 每个 i-models 的准确度得分我如何将结果放在 for 循环中的列表?

【问题讨论】:

    标签: python-3.x for-loop


    【解决方案1】:

    你可以这样做:

    results = [] # init 
    r = range(0, 100)
    for i in r:
        RF_model_%i = RandomForestClassifier(criterion="entropy", n_estimators=i, oob_score=True)
        RF_model_%i.id = i # dynamically add fields to objects
        RF_model_%i.fit(X_train, y_train)
        y_predict =   RF_model_%i.predict(X_test)
        accuracy_%i = accuracy_score(y_test, y_predict)
        results.append(accuracy_%i) # put the result on a list within the for-loop
    

    【讨论】:

    • 文件“”,第 3 行语法错误:无法分配给操作员
    • 在哪里?请分享完整的代码,这样就可以理解你在说什么。我分享的代码只是你的伪代码和相关的补充
    • 我运行了你的代码(在你上面的答案中)并粘贴了整个错误
    • 错误参考这一行:RF_model_%i = RandomForestClassifier(criterion="entropy", n_estimators=i, oob_score=True)
    • 好的,我运行了这段代码:r = range(30, 50) results = [] # init for i in r: RF_model_%i = RandomForestClassifier(criterion="entropy", n_estimators=i, oob_score=True) RF_model_%i.id = i # dynamically add fields to objects RF_model_%i.fit(X_train, y_train),我返回了这个错误:`文件“”,第 4 行语法错误:无法分配给操作员`
    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多