{ "metadata": { "name": "", "signature": "sha256:34be6ef2c9bac34e1f81ca80575ecb079576411a4c18110b3fbb4d8622bd5dc1" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "![jpeg](../galleries/validation/1.jpg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With separate training and testing dataset, we would know how are the performance of our learning model against dataset that haven't been seen. In this way we know how our model generalize if there's new examples. It also acts as a background check whether your model is overfitting. It may cause dataset shortage, but it's kind of step that is worth for. Keep in mind that every machine learning algorithm fit in the training set, not in a test set. If you fit in a test set, and score also in the test set, you definitely would have high performance. And that's called tremendous CHEATING in machine learning.\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To do this in scikit-learn, you can look at the documentation. Here's the code snippet from Udacity:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\n", "\"\"\" this example borrows heavily from the example\n", " shown on the sklearn documentation:\n", "\n", " http://scikit-learn.org/stable/modules/cross_validation.html\n", "\n", "\"\"\"\n", "\n", "from sklearn import datasets\n", "from sklearn.svm import SVC\n", "\n", "iris = datasets.load_iris()\n", "features = iris.data\n", "labels = iris.target\n", "\n", "###############################################################\n", "### YOUR CODE HERE\n", "###############################################################\n", "\n", "### import the relevant code and make your train/test split\n", "### name the output datasets features_train, features_test,\n", "### labels_train, and labels_test\n", "\n", "### set the random_state to 0 and the test_size to 0.4 so\n", "### we can exactly check your result\n", "\n", "from sklearn import cross_validation\n", "\n", "features_train,features_test,labels_train,labels_test = cross_validation.train_test_split(features,labels, test_size=0.4, random_state=0)\n", "\n", "###############################################################\n", "\n", "clf = SVC(kernel=\"linear\", C=1.)\n", "clf.fit(features_train, labels_train)\n", "\n", "print clf.score(features_test, labels_test)\n", "\n", "\n", "##############################################################\n", "def submitAcc():\n", " return clf.score(features_test, labels_test)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "0.966666666667\n" ] } ], "prompt_number": 2 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Using K-Fold rather than train/test" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![jpeg](../galleries/validation/2.jpg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another method is using K-Fold, where you split our dataset into K units. You narrow the test set to 1 units, and K-1 units as training set. Then we take iterative K-steps with different test bin each steps, springing K units test results. Then you average the results. This will give you max accuracy, as all bagging method, but gives up to longer training time than usual." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's the code snippet using K-Fold in authors' emai example:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![jpeg](../galleries/validation/3.jpg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Using K-Fold and train/test wouldn't shuffle your data in scikit-learn. Sometimes you have dataset that have labeled in order. This will gives you bad performance in your model, as you perhaps split the training into one label, and test on the other label. That's why perform shuffle first before doing any kinds of machine learning process. Of course, scikit-learn have this additional parameter for shuffling.\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "#without shuffling\n", "cv = KFold( len(authors), 2 )\n", "#with shuffling\n", "cv = KFold( len(authors), 2, shuffle=True )" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ " \n", "There's another rising problem that, you tweak each of the parameter of your algorithm to achieve best performance. This could be boring work. Cross Validation takes away this problems and perform automatic testing and tuning parameters. This called GridCV in scikit-learn, and you can have quantitative learning model that has list of values with respect to parameters." ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Mini Project" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As usual, because this blog post are the note that I have taken from Udacity course, you can see the link of the course for this note at the bottom of the page. Here I attack some of the problem they have at their mini project." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "GridCV is a way of systematically working through multiple combinations of parameter tunes, cross-validating as it goes to determine which tune gives the best performance. The beauty is that it can work through many combinations in only a couple extra lines of code.\n", "\n", "Here's an example from the sklearn documentation, which can be found here:\n", "\n", "parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}\n", "svr = svm.SVC()\n", "clf = grid_search.GridSearchCV(svr, parameters)\n", "clf.fit(iris.data, iris.target)\n", "\n", "Let's break this down line by line.\n", "\n", "parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]} \n", "A dictionary of the parameters, and the possible values you want to try for them. In this case, they're playing around with the kernel (possible choices are 'linear' and 'rbf'), and C (possible choices are 1 and 10).\n", "\n", "Then all the following (kernel, C) combinations are automatically generated: [('rbf', 1), ('rbf', 10), ('linear', 1), ('linear', 10)]. Each is used to train an SVM, and the performance is then assessed using cross-validation.\n", "\n", "svr = svm.SVC() \n", "This looks kind of like creating a classifier, just like we've been doing since the first lesson. But note that the \"clf\" isn't made until the next line--this is just saying what kind of algorithm to use. Another way to think about this is that the \"classifier\" isn't just the algorithm in this case, it's algorithm plus parameter values. Note that there's no monkeying around with the kernel or C; all that is handled in the next line.\n", "\n", "clf = grid_search.GridSearchCV(svr, parameters)\n", "This is where the first bit of magic happens; the classifier is being created. We pass the algorithm (svr) and the dictionary of parameters to try (parameters) and it generates a grid of parameter combinations to try.\n", "\n", "clf.fit(iris.data, iris.target)\n", "And the second bit of magic. The fit function now tries all the parameter combinations, and returns a fitted classifier that's automatically tuned to the optimal parameter combination. You can now access the parameter values via clf.best_estimator_." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Refer to the eigenfaces code, which you can find here. What parameters of the SVM are being tuned with GridSearchCV?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "C and gammas" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this mini-project, you\u2019ll start from scratch in making a training-testing split in the data. This will be the first step toward your final project, of building a POI identifier." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You\u2019ll start by building the simplest imaginable (unvalidated) POI identifier. The starter code (validation/validate_poi.py) for this lesson is pretty bare--all it does is read in the data, and format it into lists of labels and features. Create a decision tree classifier (just use the default parameters), train it on all the data (you will fix this in the next part!), and print out the accuracy. THIS IS AN OVERFIT TREE, DO NOT TRUST THIS NUMBER! Nonetheless, what\u2019s the accuracy?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%load validate_poi.py" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "%%writefile validate_poi.py\n", "\n", "\n", "\"\"\"\n", " starter code for the validation mini-project\n", " the first step toward building your POI identifier!\n", "\n", " start by loading/formatting the data\n", "\n", " after that, it's not our code anymore--it's yours!\n", "\"\"\"\n", "\n", "import pickle\n", "import sys\n", "sys.path.append(\"../tools/\")\n", "from feature_format import featureFormat, targetFeatureSplit\n", "from sklearn.tree import DecisionTreeClassifier\n", "\n", "data_dict = pickle.load(open(\"../final_project/final_project_dataset.pkl\", \"r\") )\n", "\n", "### add more features to features_list!\n", "features_list = [\"poi\", \"salary\"]\n", "\n", "data = featureFormat(data_dict, features_list)\n", "labels, features = targetFeatureSplit(data)\n", "\n", "#Uncomment this for the next lesson, evaluation\n", "# features_train,features_test,labels_train,labels_test = cross_validation.train_test_split(features,labels,test_size=0.3,\n", "# random_state=42)\n", "# clf = DecisionTreeClassifier()\n", "# clf.fit(features_train,labels_train)\n", "# clf.score(features_test,labels_test)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Overwriting validate_poi.py\n" ] } ], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "from sklearn.tree import DecisionTreeClassifier\n", "clf = DecisionTreeClassifier()\n", "clf.fit(features,labels)\n", "clf.score(features,labels)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 17, "text": [ "0.98958333333333337" ] } ], "prompt_number": 17 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Pretty high accuracy, huh? Yet another case where testing on the training data would make you think you were doing amazingly well, but as you already know, that's exactly what holdout test data is for..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now you\u2019ll add in training and testing, so that you get a trustworthy accuracy number. Use the training_test_split validation available in sklearn.cross_validation; hold out 30% of the data for testing and set the random_state parameter to 42 (random_state controls which points go into the training set and which are used for testing; setting it to 42 means we know exactly which events are in which set, and can check the results you get). What\u2019s your updated accuracy?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "features_train,features_test,labels_train,labels_test = cross_validation.train_test_split(features,labels,test_size=0.3,\n", " random_state=42)\n", "clf = DecisionTreeClassifier()\n", "clf.fit(features_train,labels_train)\n", "clf.score(features_test,labels_test)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 16, "text": [ "0.72413793103448276" ] } ], "prompt_number": 16 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Aaaand the testing data brings us back down to earth after that 99% accuracy in the last quiz." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> **REFERENCE**:\n", "\n", "> * https://www.udacity.com/course/viewer#!/c-ud120/l-2960698751/e-3038338563/m-3053458603\n", "> * http://scikit-learn.org/stable/auto_examples/applications/face_recognition.html" ] } ], "metadata": {} } ] }