Home > Blockchain >  For loop iterating with only last value of the list
For loop iterating with only last value of the list

Time:08-26

For-loop iterating but store with only last value of the list

Here is the code:

models = [KNN,NB,LR,SVM]
result = pd.DataFrame()
for i in models:
    i.fit(x_train, y_train)
    ypred = i.predict(x_test)
    model_valuation = result.append({'Model': i, 
                                  'Accuracy': accuracy_score(y_test, ypred),
                                    'Recall': recall_score(y_test, ypred),
                                 'Precision': precision_score(y_test, ypred),
                               'Specificity': recall_score(y_test, ypred, pos_label=0),
                                  'F1 score': f1_score(y_test, ypred)}, ignore_index=True)

It appends only the SVM which is the last value in the list models.

CodePudding user response:

You need to assign result.append() to the dataframe result in order to append the new record

Try this:

models = [KNN, NB, LR, SVM]
result = pd.DataFrame()
for i in models:
    i.fit(x_train, y_train)
    ypred = i.predict(x_test)
    result = result.append({'Model': i, 
                         'Accuracy': accuracy_score(y_test, ypred),
                           'Recall': recall_score(y_test, ypred),
                        'Precision': precision_score(y_test, ypred),
                      'Specificity': recall_score(y_test, ypred, pos_label=0),
                         'F1 score': f1_score(y_test, ypred)}, ignore_index=True)
  • Related