简体   繁体   English

for 循环问题(如何在 for 循环中创建的 obj 名称上使用 i 参数)

[英]for-loop issue (how to use i-parameter on the obj name created within the for-loop)

i'd like to create few Random forest model within a for loop in which i move the number of estimators.我想在我移动估计器数量的 for 循环中创建一些随机森林 model 。 Train each of them on the same data sample and measure the accuracy of each.在相同的数据样本上训练他们每个人并测量每个人的准确性。 This is my beginning code:这是我的开始代码:

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)

what i like to understand is:我想理解的是:

  1. how can i put the i-parameter on the name of each model (in order to recognise them)?如何将i 参数放在每个 model 的名称上(以便识别它们)?
  2. after tained and calculated the accuracy score each of the i-models how can i put the result on a list within the for-loop?在获取并计算每个i 模型的准确度得分后,我如何将结果放在 for 循环内的列表中?

You can do something like this:你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM