Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
From the k-NN algorithm and model evaluation to regression, SVMs, and decision trees
Fundamentals of ML
K-Nearest Neighbours
this lab
Model Evaluation & Selection
Support Vector Machines
Decision Trees
Naive Bayes
Neural Networks
k-NN) Algorithmk-NNX_train/y_train and a new instance x_test, it finds similar neighbors and votes on a label.x_test in X_train (call them X_NN)y_NNx_test's label by combining y_NN, for example a simple majority votek) to look at, an optional weighting function on neighbors, and a method to aggregate neighbor classesk (e.g. k=1) leads to low bias, high variance: overfittingk leads to higher bias, lower variance: underfittingKNN Classification and Regressionfrom sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
X_train, X_test, y_train, y_test = train_test_split(X_C2, y_C2, random_state=0)
# k=1 overfits (very jagged boundary); larger k generalizes better
clf = KNeighborsClassifier(n_neighbors=11).fit(X_train, y_train)
knnreg = KNeighborsRegressor(n_neighbors=5).fit(X_train, y_train)
print('R-squared test score: {:.3f}'.format(knnreg.score(X_test, y_test)))k=1 overfits with a very jagged boundary; a larger k generalizes better.model.score(X, y) for regression returns R^2 (coefficient of determination): 0 predicts the mean, 1 is a perfect predictionk-NN works for both classification and regressionfrom sklearn.linear_model import LinearRegression
linreg = LinearRegression().fit(X_train, y_train)
print('coeff (w): {}'.format(linreg.coef_))
print('intercept (b): {:.3f}'.format(linreg.intercept_))
print('R-squared (train): {:.3f}'.format(linreg.score(X_train, y_train)))
print('R-squared (test): {:.3f}'.format(linreg.score(X_test, y_test)))from sklearn.linear_model import Ridge, Lasso
from sklearn.preprocessing import MinMaxScaler, PolynomialFeatures
scaler = MinMaxScaler()
X_train_scaled = scaler.fit_transform(X_train)
linridge = Ridge(alpha=20.0).fit(X_train_scaled, y_train) # L2 penalty
linlasso = Lasso(alpha=2.0, max_iter=10000).fit(X_train_scaled, y_train) # L1 penalty, drives coefficients to 0
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X_F1) # adds quadratic feature interactionsL2)L1)from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(C=100).fit(X_train, y_train)
print('Accuracy on training set: {:.2f}'.format(clf.score(X_train, y_train)))
print('Accuracy on test set: {:.2f}'.format(clf.score(X_test, y_test)))C controls regularization strength, try multiple values of C to find the best fitfrom sklearn.svm import SVC, LinearSVC
clf = SVC(kernel='linear', C=1.0).fit(X_train, y_train)
clf2 = LinearSVC(C=100).fit(X_train, y_train)SVMsC controls the tolerance for misclassified points: a small C gives a wider margin (more tolerant), a large C fits training data more tightlySVMfrom sklearn.svm import SVC
clf = SVC(kernel='rbf', gamma=1.0, C=15).fit(X_train, y_train) # default kernel is RBF
clf_poly = SVC(kernel='poly', degree=3).fit(X_train, y_train)RBF (radial basis function)gamma controls how complex or tight the decision boundary is; combine with C to tune the fitMinMaxScaler) before fitting significantly improves test accuracy on unnormalized real datasetsfrom sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier().fit(X_train, y_train) # tends to overfit (train acc = 1.00)
clf2 = DecisionTreeClassifier(max_depth=3).fit(X_train, y_train) # limit depth to reduce overfitting
print('Feature importances: {}'.format(clf.feature_importances_))100% train accuracy) but generalizes worsemax_depth trades a little training accuracy for better generalizationfeature_importances_ shows which input features drove the tree's decisions mostk-NN classifies and predicts by combining the labels of the k most similar training instances; small k overfits, large k underfitsL2) and Lasso (L1) add regularization, with Lasso capable of zeroing out features entirelySVM, and kernelized SVM (RBF/polynomial) are the standard classifiers, all tuned via C (and gamma for RBF)MinMaxScaler) meaningfully improves regularized regression and SVM performancefeature_importances_ reveals which features matter most to predictionsMahmoud Abas|ML Week01 Lab (KNN)