{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [ "hide-input" ] }, "outputs": [], "source": [ "# Install the necessary dependencies\n", "\n", "import os\n", "import sys \n", "!{sys.executable} -m pip install --quiet pandas scikit-learn numpy matplotlib jupyterlab_myst ipython\n" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "remove-cell" ] }, "source": [ "---\n", "license:\n", " code: MIT\n", " content: CC-BY-4.0\n", "github: https://github.com/ocademy-ai/machine-learning\n", "venue: By Ocademy\n", "open_access: true\n", "bibliography:\n", " - https://raw.githubusercontent.com/ocademy-ai/machine-learning/main/open-machine-learning-jupyter-book/references.bib\n", "---" ] }, { "cell_type": "markdown", "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [] }, "source": [ "# Yet other classifiers\n", "\n", "In this second classification section, you will explore more ways to classify numeric data. You will also learn about the ramifications for choosing one classifier over the other.\n", "\n", "## Preparation\n", "\n", "We have loaded your [build-classification-model.ipynb](https://static-1300131294.cos.ap-shanghai.myqcloud.com/assignments/ml-fundamentals/build-classification-model.ipynb) file with the cleaned dataset and have divided it into x and y dataframes, ready for the model building process.\n", "\n", "## A classification map\n", "\n", "Previously, you learned about the various options you have when classifying data using Microsoft's cheat sheet. Scikit-learn offers a similar, but more granular cheat sheet that can further help narrow down your estimators (another term for classifiers):\n", "\n", ":::{figure} https://static-1300131294.cos.ap-shanghai.myqcloud.com/images/ml-fundamentals/ml-classification/map.png\n", "---\n", "name: 'ML Map from Scikit-learn'\n", "width: 90%\n", "---\n", "ML Map from Scikit-learn. [Ref](https://scikit-learn.org/stable/tutorial/machine_learning_map/)\n", ":::\n", "\n", "### The plan\n", "\n", "This map is very helpful once you have a clear grasp of your data, as you can 'walk' along its paths to a decision:\n", "\n", "- We have >50 samples\n", "- We want to predict a category\n", "- We have labeled data\n", "- We have fewer than 100K samples\n", "- ✨ We can choose a Linear SVC\n", "- If that doesn't work, since we have numeric data\n", " - We can try a ✨ KNeighbors Classifier \n", " - If that doesn't work, try ✨ SVC and ✨ Ensemble Classifiers\n", "\n", "This is a very helpful trail to follow.\n", "\n", "## Exercise - split the data\n", "\n", "Following this path, we should start by importing some libraries to use.\n", "\n", "1\\. Import the needed libraries:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "editable": true, "slideshow": { "slide_type": "" }, "tags": [] }, "outputs": [], "source": [ "from sklearn.neighbors import KNeighborsClassifier\n", "from sklearn.linear_model import LogisticRegression\n", "from sklearn.svm import SVC\n", "from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\n", "from sklearn.model_selection import train_test_split, cross_val_score\n", "from sklearn.metrics import accuracy_score,precision_score,confusion_matrix,classification_report, precision_recall_curve\n", "import numpy as np\n", "import pandas as pd\n", "\n", "cuisines_df = pd.read_csv(\"https://static-1300131294.cos.ap-shanghai.myqcloud.com/data/classification/cleaned_cuisines.csv\")\n", "cuisines_feature_df = cuisines_df.drop(['Unnamed: 0', 'cuisine'], axis=1)\n", "cuisines_label_df = cuisines_df['cuisine']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2\\. Split your training and test data:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "X_train, X_test, y_train, y_test = train_test_split(cuisines_feature_df, cuisines_label_df, test_size=0.3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Linear SVC classifier\n", "\n", "Support-Vector clustering (SVC) is a child of the Support-Vector machines family of ML techniques (learn more about these below). In this method, you can choose a 'kernel' to decide how to cluster the labels. The 'C' parameter refers to 'regularization' which regulates the influence of parameters. The kernel can be one of [several](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC); here we set it to 'linear' to ensure that we leverage linear SVC. Probability defaults to 'false'; here we set it to 'true' to gather probability estimates. We set the random state to '0' to shuffle the data to get probabilities.\n", "\n", "### Exercise - apply a linear SVC\n", "\n", "Start by creating an array of classifiers. You will add progressively to this array as we test. \n", "\n", "1\\. Start with a Linear SVC:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "C = 10\n", "# Create different classifiers.\n", "classifiers = {\n", " 'Linear SVC': SVC(kernel='linear', C=C, probability=True,random_state=0)\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2\\. Train your model using the Linear SVC and print out a report:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy (train) for Linear SVC: 79.4% \n", " precision recall f1-score support\n", "\n", " chinese 0.66 0.72 0.69 223\n", " indian 0.91 0.89 0.90 255\n", " japanese 0.76 0.75 0.76 244\n", " korean 0.90 0.73 0.81 225\n", " thai 0.77 0.85 0.81 252\n", "\n", " accuracy 0.79 1199\n", " macro avg 0.80 0.79 0.79 1199\n", "weighted avg 0.80 0.79 0.80 1199\n", "\n" ] } ], "source": [ "n_classifiers = len(classifiers)\n", "\n", "def classify():\n", " for index, (name, classifier) in enumerate(classifiers.items()):\n", " classifier.fit(X_train, np.ravel(y_train))\n", "\n", " y_pred = classifier.predict(X_test)\n", " accuracy = accuracy_score(y_test, y_pred)\n", " print(\"Accuracy (train) for %s: %0.1f%% \" % (name, accuracy * 100))\n", " print(classification_report(y_test,y_pred))\n", "\n", "classify()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result is pretty good.\n", "\n", "## K-Neighbors classifier\n", "\n", "K-Neighbors is part of the \"neighbors\" family of ML methods, which can be used for both supervised and unsupervised learning. In this method, a predefined number of points is created and data are gathered around these points such that generalized labels can be predicted for the data.\n", "\n", "### Exercise - apply the K-Neighbors classifier\n", "\n", "The previous classifier was good, and worked well with the data, but maybe we can get better accuracy. Try a K-Neighbors classifier.\n", "\n", "1\\. Add a line to your classifier array (add a comma after the Linear SVC item):" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy (train) for Linear SVC: 79.4% \n", " precision recall f1-score support\n", "\n", " chinese 0.66 0.72 0.69 223\n", " indian 0.91 0.89 0.90 255\n", " japanese 0.76 0.75 0.76 244\n", " korean 0.90 0.73 0.81 225\n", " thai 0.77 0.85 0.81 252\n", "\n", " accuracy 0.79 1199\n", " macro avg 0.80 0.79 0.79 1199\n", "weighted avg 0.80 0.79 0.80 1199\n", "\n", "Accuracy (train) for KNN classifier: 73.1% \n", " precision recall f1-score support\n", "\n", " chinese 0.62 0.66 0.64 223\n", " indian 0.89 0.78 0.83 255\n", " japanese 0.65 0.85 0.73 244\n", " korean 0.91 0.55 0.68 225\n", " thai 0.71 0.79 0.75 252\n", "\n", " accuracy 0.73 1199\n", " macro avg 0.76 0.73 0.73 1199\n", "weighted avg 0.76 0.73 0.73 1199\n", "\n" ] } ], "source": [ "classifiers['KNN classifier'] = KNeighborsClassifier(C)\n", "\n", "classify()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result is a little worse.\n", "\n", ":::{seealso}\n", "Learn about [K-Neighbors](https://scikit-learn.org/stable/modules/neighbors.html#neighbors)\n", ":::\n", "\n", "## Support Vector Classifier\n", "\n", "Support-Vector classifiers are part of the [Support-Vector Machine](https://wikipedia.org/wiki/Support-vector_machine) family of ML methods that are used for classification and regression tasks. SVMs \"map training examples to points in space\" to maximize the distance between two categories. Subsequent data is mapped into this space so their category can be predicted.\n", "\n", "### Exercise - apply a Support Vector Classifier\n", "\n", "Let's try for a little better accuracy with a Support Vector Classifier.\n", "\n", "1\\. Add a comma after the K-Neighbors item, and then add this line:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy (train) for Linear SVC: 79.4% \n", " precision recall f1-score support\n", "\n", " chinese 0.66 0.72 0.69 223\n", " indian 0.91 0.89 0.90 255\n", " japanese 0.76 0.75 0.76 244\n", " korean 0.90 0.73 0.81 225\n", " thai 0.77 0.85 0.81 252\n", "\n", " accuracy 0.79 1199\n", " macro avg 0.80 0.79 0.79 1199\n", "weighted avg 0.80 0.79 0.80 1199\n", "\n", "Accuracy (train) for KNN classifier: 73.1% \n", " precision recall f1-score support\n", "\n", " chinese 0.62 0.66 0.64 223\n", " indian 0.89 0.78 0.83 255\n", " japanese 0.65 0.85 0.73 244\n", " korean 0.91 0.55 0.68 225\n", " thai 0.71 0.79 0.75 252\n", "\n", " accuracy 0.73 1199\n", " macro avg 0.76 0.73 0.73 1199\n", "weighted avg 0.76 0.73 0.73 1199\n", "\n", "Accuracy (train) for SVC: 82.0% \n", " precision recall f1-score support\n", "\n", " chinese 0.73 0.73 0.73 223\n", " indian 0.90 0.89 0.90 255\n", " japanese 0.80 0.80 0.80 244\n", " korean 0.92 0.80 0.86 225\n", " thai 0.77 0.87 0.82 252\n", "\n", " accuracy 0.82 1199\n", " macro avg 0.82 0.82 0.82 1199\n", "weighted avg 0.82 0.82 0.82 1199\n", "\n" ] } ], "source": [ "classifiers['SVC'] = SVC()\n", "\n", "classify()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result is quite good!\n", "\n", ":::{seealso}\n", "Learn about [Support-Vectors](https://scikit-learn.org/stable/modules/svm.html#svm)\n", ":::\n", "\n", "## Ensemble Classifiers\n", "\n", "Let's follow the path to the very end, even though the previous test was quite good. Let's try some 'Ensemble Classifiers, specifically Random Forest and AdaBoost:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy (train) for Linear SVC: 79.4% \n", " precision recall f1-score support\n", "\n", " chinese 0.66 0.72 0.69 223\n", " indian 0.91 0.89 0.90 255\n", " japanese 0.76 0.75 0.76 244\n", " korean 0.90 0.73 0.81 225\n", " thai 0.77 0.85 0.81 252\n", "\n", " accuracy 0.79 1199\n", " macro avg 0.80 0.79 0.79 1199\n", "weighted avg 0.80 0.79 0.80 1199\n", "\n", "Accuracy (train) for KNN classifier: 73.1% \n", " precision recall f1-score support\n", "\n", " chinese 0.62 0.66 0.64 223\n", " indian 0.89 0.78 0.83 255\n", " japanese 0.65 0.85 0.73 244\n", " korean 0.91 0.55 0.68 225\n", " thai 0.71 0.79 0.75 252\n", "\n", " accuracy 0.73 1199\n", " macro avg 0.76 0.73 0.73 1199\n", "weighted avg 0.76 0.73 0.73 1199\n", "\n", "Accuracy (train) for SVC: 82.0% \n", " precision recall f1-score support\n", "\n", " chinese 0.73 0.73 0.73 223\n", " indian 0.90 0.89 0.90 255\n", " japanese 0.80 0.80 0.80 244\n", " korean 0.92 0.80 0.86 225\n", " thai 0.77 0.87 0.82 252\n", "\n", " accuracy 0.82 1199\n", " macro avg 0.82 0.82 0.82 1199\n", "weighted avg 0.82 0.82 0.82 1199\n", "\n", "Accuracy (train) for RFST: 84.7% \n", " precision recall f1-score support\n", "\n", " chinese 0.78 0.80 0.79 223\n", " indian 0.94 0.91 0.93 255\n", " japanese 0.85 0.79 0.82 244\n", " korean 0.89 0.81 0.85 225\n", " thai 0.79 0.92 0.85 252\n", "\n", " accuracy 0.85 1199\n", " macro avg 0.85 0.84 0.85 1199\n", "weighted avg 0.85 0.85 0.85 1199\n", "\n", "Accuracy (train) for ADA: 68.6% \n", " precision recall f1-score support\n", "\n", " chinese 0.55 0.49 0.52 223\n", " indian 0.87 0.84 0.86 255\n", " japanese 0.63 0.60 0.62 244\n", " korean 0.66 0.75 0.70 225\n", " thai 0.69 0.73 0.71 252\n", "\n", " accuracy 0.69 1199\n", " macro avg 0.68 0.68 0.68 1199\n", "weighted avg 0.68 0.69 0.68 1199\n", "\n" ] } ], "source": [ "classifiers['RFST'] = RandomForestClassifier(n_estimators=100)\n", "classifiers['ADA'] = AdaBoostClassifier(n_estimators=100)\n", "\n", "classify()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result is very good, especially for Random Forest.\n", "\n", ":::{seealso}\n", "Learn about [Ensemble Classifiers](https://scikit-learn.org/stable/modules/ensemble.html)\n", ":::\n", "\n", "This method of Machine Learning \"combines the predictions of several base estimators\" to improve the model's quality. In our example, we used Random Trees and AdaBoost.\n", "\n", "- [Random Forest](https://scikit-learn.org/stable/modules/ensemble.html#forest), an averaging method, builds a 'forest' of 'decision trees' infused with randomness to avoid overfitting. The n_estimators parameter is set to the number of trees.\n", "\n", "- [AdaBoost](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostClassifier.html) fits a classifier to a dataset and then fits copies of that classifier to the same dataset. It focuses on the weights of incorrectly classified items and adjusts the fit for the next classifier to correct.\n", "\n", "---\n", "\n", "## Self Study\n", "\n", "There's a lot of jargon in these sections, so take a minute to review [this list](https://docs.microsoft.com/dotnet/machine-learning/resources/glossary?WT.mc_id=academic-77952-leestott) of useful terminology!\n", "\n", "## Your turn! 🚀\n", "\n", "Each of these techniques has a large number of parameters that you can tweak. Research each one's default parameters and think about what tweaking these parameters would mean for the model's quality.\n", "\n", "Assignment - [Parameter play](../../assignments/ml-fundamentals/parameter-play.md)\n", "\n", "## Acknowledgments\n", "\n", "Thanks to Microsoft for creating the open-source course [ML-For-Beginners](https://github.com/microsoft/ML-For-Beginners). It inspires the majority of the content in this chapter.\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.18" } }, "nbformat": 4, "nbformat_minor": 4 }