{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn import svm, datasets\n", "from matplotlib.pylab import rcParams\n", "\n", "%matplotlib inline\n", "rcParams['figure.figsize'] = 10, 5\n", "iris = datasets.load_iris()\n", "X = iris.data\n", "y = iris.target" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Grid Search for SVM Parameters" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.model_selection import GridSearchCV\n", "parameters = {\n", " 'kernel': ['linear', 'rbf'],\n", " 'C': [0.01, 0.1, 1, 10],\n", " 'gamma': [0.01, 0.1, 1, 10]\n", "}\n", "model = svm.SVC()\n", "model.fit(X, y)\n", "best_model = GridSearchCV(model,\n", " parameters,\n", " cv=5,\n", " scoring='accuracy',\n", " return_train_score='cv_results_')\n", "best_model.fit(X, y)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('accuracy before Grid Search CV:%.4f' % model.score(X, y))\n", "print('accuracy after Grid Search CV:%.4f' % best_model.score(X, y))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Best Parameter" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "best_model.best_estimator_" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "best_model.cv_results_" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.10.2" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 4 }