image_output_1.png
from sklearn import metrics

from sklearn.ensemble import RandomForestClassifier

from sklearn.ensemble import RandomForestClassifier

from sklearn.neighbors import KNeighborsClassifier

import numpy as np # linear algebra

Ks = 100
mean_acc = np.zeros(Ks - 1)
std_acc = np.zeros(Ks - 1)
for n in range(1, Ks):
    neigh = KNeighborsClassifier(n_neighbors=n).fit(x_train, y_train)
    yhat = neigh.predict(x_test)
    mean_acc[n - 1] = metrics.accuracy_score(y_test, yhat)
    std_acc[n - 1] = np.std(yhat == y_test) / np.sqrt(yhat.shape[0])

from sklearn.ensemble import RandomForestClassifier
Ns = 200
mean_acc = np.zeros(Ns - 1)
for n in range(1, Ns):
    forest = RandomForestClassifier(n_estimators=n).fit(x_train, y_train)
    yhat = forest.predict(x_test)
    mean_acc[n - 1] = metrics.accuracy_score(y_test, yhat)
print('The best accuracy was ', mean_acc.max(), 'with n = ', mean_acc.argmax() + 1)