[FIXED] For loop iterating with only last value of the list

Issue

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.


Solution

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)


Answered By - perpetualstudent
Answer Checked By - Mildred Charles (sql.easybugfix Admin)

Related Posts

Post a Comment