简体   繁体   中英

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. 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)?
  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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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