Supervised Learning with scikit-learn
George Boorman
Core Curriculum Manager, DataCamp
In classification, accuracy is a commonly used metric
Accuracy:
How do we measure accuracy?
Could compute accuracy on the data used to fit the classifier
NOT indicative of ability to generalize
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=21, stratify=y)
knn = KNeighborsClassifier(n_neighbors=6)
knn.fit(X_train, y_train)
print(knn.score(X_test, y_test))
0.8800599700149925
Larger k = less complex model = can cause underfitting
Smaller k = more complex model = can lead to overfitting
train_accuracies = {} test_accuracies = {} neighbors = np.arange(1, 26)
for neighbor in neighbors:
knn = KNeighborsClassifier(n_neighbors=neighbor)
knn.fit(X_train, y_train)
train_accuracies[neighbor] = knn.score(X_train, y_train) test_accuracies[neighbor] = knn.score(X_test, y_test)
plt.figure(figsize=(8, 6))
plt.title("KNN: Varying Number of Neighbors")
plt.plot(neighbors, train_accuracies.values(), label="Training Accuracy")
plt.plot(neighbors, test_accuracies.values(), label="Testing Accuracy")
plt.legend()
plt.xlabel("Number of Neighbors")
plt.ylabel("Accuracy")
plt.show()
Supervised Learning with scikit-learn