0

I just started using Python. I would like to plot a dynamic graph that shows me the performance (in terms of accuracy) of a kNN algorithm obtained with n-fold cross-validation. I would like to get a graph where: x = k nearest neighbours y = average accuracy (obtained with cross-validation) with the possibility of varying n, i.e. the number of folds in the cross validation, and dynamically changing the graph as n varies. This is the code i already did but that doesn't dynamically change the graph. Why?

X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=4)


knn_model = KNeighborsClassifier(n_neighbors=3)
knn_model_fitted=knn_model.fit(X_train,y_train)


import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider
from matplotlib.animation import FuncAnimation
%matplotlib notebook

fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(111) 
fig.subplots_adjust(bottom=0.2, top=0.75)
ax_nfold = fig.add_axes([0.3, 0.85, 0.4, 0.05]) 
ax_nfold.spines['top'].set_visible(True) 
ax_nfold.spines['right'].set_visible(True)
s_nfold = Slider(ax=ax_nfold, label='n folds', valmin=2, valmax=10, 
              valfmt='%i', facecolor='#cc7000')

accuracy_values=[]
k_values=[]
for k in range(1,21):
    knn_model = KNeighborsClassifier(n_neighbors=k)
    knn_model_fitted=knn_model.fit(X_train,y_train)
    scores = cross_val_score(knn_model, iris.data, iris.target, cv=5)
    media_accuracy=scores.mean()
    accuracy_values.append(media_accuracy)
    k_values.append(k)

import numpy as np    
accuracy_values=np.asarray(accuracy_values)
k_values=np.asarray(k_values)

dynamic_plot, = ax.plot(k_values, accuracy_values, linewidth=2.5)


def update(): 
    nfold = s_nfold.val 
    print(s_nfold.val)
    accuracy_values=[]
    k_values=[]
    for k in range(1,21):
        knn_model = KNeighborsClassifier(n_neighbors=k)
        knn_model_fitted=knn_model.fit(X_train,y_train)
        scores = cross_val_score(knn_model, iris.data, iris.target, cv=n_fold)
        media_accuracy=scores.mean()
        accuracy_values.append(media_accuracy)
        k_values.append(k)
    import numpy as np    
    accuracy_values=np.asarray(accuracy_values)
    k_values=np.asarray(k_values)
    #dynamic_plot.set_data(k_values, accuracy_values) 
    dynamic_plot, = ax.plot(k_values, accuracy_values, linewidth=2.5)
    #dynamic_plot.canvas.draw_idle()#serve per aggiornare una figura modificata

s_nfold.on_changed(update) 

Thanks everyone in advance!

The code I used just returns me the graph at the initial number of n folds. It allows me to scroll the level of n but changing n doesn't change the graph

  • Does this answer your question? [How to update a plot in matplotlib](https://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib) – alec_djinn Apr 03 '23 at 11:44

0 Answers0