├── .gitignore ├── 001 - Naive Bayes Classifier ├── exercise │ ├── bayes.png │ ├── classify_NB.py │ └── main.py └── nb_author_id.py ├── 002 - SVM ├── exercise │ ├── main.py │ └── svm_lin.png └── svm_author_id.py ├── 003 - Decision Tree ├── dt_author_id.py └── exercise │ ├── dec_tree.png │ ├── main.py │ └── overfitted.png ├── 004 - AdaBoost + kNN + Random Forrest ├── ada_boost.png ├── ada_boost.py ├── knn.png ├── knn.py ├── random_forest.png └── random_forest.py ├── 005 - Datasets Questions ├── explore_enron_data.py ├── explore_enron_data.py~ ├── final_project_dataset.pkl └── poi_names.txt ├── 006 - Regression ├── final_project_dataset_modified.pkl ├── finance_regression.py ├── finance_regression.py~ └── regression.png ├── 007 - Outliers ├── enron_outliers.py ├── final_project_dataset.pkl ├── outlier_cleaner.py ├── outlier_fig.png ├── outlier_removal_regression.py ├── practice_outliers_ages.pkl └── practice_outliers_net_worths.pkl ├── 008 - K_Means ├── .DS_Store ├── clusters.png ├── clusters_before_scaling.png ├── k_means.png ├── k_means_cluster.py └── k_means_plot.py ├── 010 - Text Learning ├── from_chris.txt ├── from_sara.txt ├── parse_out_email_text.py ├── test_email.txt ├── vectorize_text.py ├── your_email_authors.pkl └── your_word_data.pkl ├── 011 - Feature Selection ├── email_authors.pkl ├── email_authors_overfit.pkl ├── find_signature.py ├── word_data.pkl └── word_data_overfit.pkl ├── 012 - PCA ├── eigenfaces.png ├── eigenfaces.py └── pred.png ├── 013 - Validation ├── final_project_dataset.pkl └── validate_poi.py ├── 014 - Evaluation └── evaluate_poi_identifier.py ├── LICENSE ├── README.md └── tools ├── class_vis.py ├── email_authors.pkl ├── email_preprocess.py ├── feature_format.py ├── prep_terrain_data.py ├── python2_lesson06_keys.pkl ├── python2_lesson13_keys.pkl ├── python2_lesson14_keys.pkl ├── startup.py └── word_data.pkl /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | maildir/ 12 | env/ 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | maildir 61 | -------------------------------------------------------------------------------- /001 - Naive Bayes Classifier/exercise/bayes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/001 - Naive Bayes Classifier/exercise/bayes.png -------------------------------------------------------------------------------- /001 - Naive Bayes Classifier/exercise/classify_NB.py: -------------------------------------------------------------------------------- 1 | from sklearn.naive_bayes import GaussianNB 2 | from sklearn.metrics import accuracy_score 3 | 4 | def classify(features_train, labels_train): 5 | clf = GaussianNB() 6 | return clf.fit(features_train, labels_train) 7 | 8 | 9 | def NB_accuracy(features_train, labels_train, features_test, labels_test): 10 | """ compute the accuracy of your Naive Bayes classifier as a seperate method """ 11 | 12 | clf = GaussianNB() 13 | clf.fit(features_train, labels_train) 14 | 15 | pred = clf.predict(features_test) 16 | 17 | accuracy = accuracy_score(labels_test, pred) 18 | return accuracy 19 | 20 | 21 | -------------------------------------------------------------------------------- /001 - Naive Bayes Classifier/exercise/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ The objective of this exercise is to recreate the decision 4 | boundary found in the lesson video, and make a plot that 5 | visually shows the decision boundary """ 6 | 7 | import sys 8 | sys.path.append("../../tools") 9 | from prep_terrain_data import makeTerrainData 10 | from sklearn.metrics import accuracy_score 11 | from class_vis import prettyPicture, output_image 12 | from classify_NB import classify, NB_accuracy 13 | import numpy as np 14 | import pylab as pl 15 | from PIL import Image 16 | 17 | features_train, labels_train, features_test, labels_test = makeTerrainData() 18 | 19 | # the training data (features_train, labels_train) have both "fast" and "slow" points mixed 20 | # in together--separate them so we can give them different colors in the scatterplot, 21 | # and visually identify them 22 | grade_fast = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==0] 23 | bumpy_fast = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==0] 24 | grade_slow = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==1] 25 | bumpy_slow = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==1] 26 | 27 | clf = classify(features_train, labels_train) 28 | 29 | # draw the decision boundary with the text points overlaid 30 | prettyPicture(clf, features_test, labels_test, f_name="bayes.png") 31 | Image.open('bayes.png').show() 32 | 33 | # JSON object to read data: 34 | # output_image("test.png", "png", open("test.png", "rb").read()) 35 | 36 | pred = clf.predict(features_test) 37 | 38 | print "Naive Bayes accuracy: %r" % accuracy_score(labels_test, pred) 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /001 - Naive Bayes Classifier/nb_author_id.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | this is the code to accompany the Lesson 1 (Naive Bayes) mini-project 5 | 6 | use a Naive Bayes Classifier to identify emails by their authors 7 | 8 | authors and labels: 9 | Sara has label 0 10 | Chris has label 1 11 | 12 | """ 13 | 14 | import sys 15 | from time import time 16 | sys.path.append("../tools/") 17 | from email_preprocess import preprocess 18 | from sklearn.naive_bayes import GaussianNB 19 | from sklearn.metrics import accuracy_score 20 | 21 | 22 | ### features_train and features_test are the features for the training 23 | ### and testing datasets, respectively 24 | ### labels_train and labels_test are the corresponding item labels 25 | features_train, features_test, labels_train, labels_test = preprocess() 26 | 27 | clf = GaussianNB() 28 | t0 = time() 29 | clf.fit(features_train, labels_train) 30 | print "training time:", round(time()-t0, 3), "s" 31 | t0 = time() 32 | pred = clf.predict(features_test) 33 | print "predict time:", round(time()-t0, 3), "s" 34 | print "accuracy: %r" % accuracy_score(labels_test, pred) 35 | 36 | 37 | -------------------------------------------------------------------------------- /002 - SVM/exercise/main.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import sys 3 | sys.path.append("../../tools") 4 | from class_vis import prettyPicture 5 | from prep_terrain_data import makeTerrainData 6 | from sklearn.metrics import accuracy_score 7 | 8 | import matplotlib.pyplot as plt 9 | import copy 10 | import numpy as np 11 | import pylab as pl 12 | 13 | features_train, labels_train, features_test, labels_test = makeTerrainData() 14 | 15 | ########################## SVM ################################# 16 | # we handle the import statement and SVC creation for you here 17 | from sklearn.svm import SVC 18 | clf = SVC(kernel="linear") 19 | 20 | # now your job is to fit the classifier 21 | # using the training features/labels, and to 22 | # make a set of predictions on the test data 23 | 24 | clf.fit(features_train, labels_train) 25 | 26 | # store your predictions in a list named pred 27 | 28 | pred = clf.predict(features_test) 29 | 30 | prettyPicture(clf, features_test, labels_test, f_name="svm_lin.png") 31 | Image.open('svm_lin.png').show() 32 | 33 | acc = accuracy_score(pred, labels_test) 34 | print "SVM accuracy: %r" % acc 35 | 36 | clf = SVC(kernel="rbf") 37 | clf.fit(features_train, labels_train) 38 | pred = clf.predict(features_test) 39 | prettyPicture(clf, features_test, labels_test, f_name="svm_rbf.png") 40 | 41 | def submitAccuracy(): 42 | return acc -------------------------------------------------------------------------------- /002 - SVM/exercise/svm_lin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/002 - SVM/exercise/svm_lin.png -------------------------------------------------------------------------------- /002 - SVM/svm_author_id.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | this is the code to accompany the Lesson 2 (SVM) mini-project 5 | 6 | use an SVM to identify emails from the Enron corpus by their authors 7 | 8 | Sara has label 0 9 | Chris has label 1 10 | 11 | """ 12 | 13 | import sys 14 | from time import time 15 | sys.path.append("../tools/") 16 | import matplotlib.pyplot as plt 17 | from email_preprocess import preprocess 18 | from sklearn.svm import SVC 19 | from sklearn.metrics import accuracy_score 20 | 21 | # features_train and features_test are the features for the training 22 | # and testing datasets, respectively 23 | # labels_train and labels_test are the corresponding item labels 24 | features_train, features_test, labels_train, labels_test = preprocess() 25 | 26 | # clf = SVC(kernel="linear") 27 | clf = SVC(kernel="rbf", C=10000) 28 | t0 = time() 29 | """ 30 | 31 | One way to speed up an algorithm is to train it on a smaller training 32 | dataset. The tradeoff is that the accuracy almost always goes down when 33 | you do this. Let's explore this more concretely: 34 | 35 | original (linear): 36 | training time: 188.996 s 37 | predict time: 20.275 s 38 | SVM accuracy: 0.98407281001137659 39 | 40 | These lines effectively slice the training dataset down to 1 percent of its 41 | original size, tossing out 99 percent of the training data. 42 | 43 | Sliced (linear): 44 | training time: 0.09 s 45 | predict time: 0.961 s 46 | accuracy: 0.88452787258248011 47 | 48 | If speed is a major consideration (and for many real-time machine learning 49 | applications, it certainly is) then you may want to sacrifice a bit of 50 | accuracy if it means you can train/predict faster. 51 | 52 | Different Kernel: 53 | clf = SVC(kernel="rbf", C=10000) 54 | Also, C is very effective in this assignment, try to change it and see. 55 | 56 | Sliced data set: 57 | training time: 0.098 s 58 | predict time: 0.833 s 59 | accuracy: 0.89249146757679176 60 | 61 | Full sized data set: 62 | training time: 118.729 s 63 | predict time: 13.075 s 64 | accuracy: 0.99089874857792948 #FTW 65 | 66 | """ 67 | # comment out those two lines if you want to see original one 68 | #features_train = features_train[:len(features_train)/100] 69 | #labels_train = labels_train[:len(labels_train)/100] 70 | 71 | clf.fit(features_train, labels_train) 72 | print "training time:", round(time()-t0, 3), "s" 73 | t0 = time() 74 | pred = clf.predict(features_test) 75 | print "predict time:", round(time()-t0, 3), "s" 76 | 77 | # originally: 0.98407281001137659 acc... FTW but it takes time 78 | print "SVM accuracy: %r" % accuracy_score(pred, labels_test) 79 | 80 | """ 81 | What class does your SVM (0 or 1, corresponding to Sara and Chris respectively) 82 | predict for element 10 of the test set? The 26th? The 50th? 83 | (Use the RBF kernel, C=10000, and 1% of the training set. Normally you'd get 84 | the best results using the full training set, but we found that using 1% sped up 85 | the computation considerably and did not change our results--so feel free to use 86 | that shortcut here.) 87 | 88 | """ 89 | print "10th: %r, 26th: %r, 50th: %r" % (pred[10], pred[26], pred[50]) 90 | 91 | # There are over 1700 test events, how many are predicted to be in the "Chris" (1) class? 92 | print "No. of predicted to be in the 'Chris'(1): %r" % sum(pred) 93 | 94 | """ 95 | Hopefully it's becoming clearer what they told us about the Naive Bayes -- is 96 | great for text -- it's faster and generally gives better performance than an SVM 97 | for this particular problem. Of course, there are plenty of other problems where 98 | an SVM might work better. Knowing which one to try when you're tackling a problem 99 | for the first time is part of the art and science of machine learning. In addition 100 | to picking your algorithm, depending on which one you try, there are parameter 101 | tunes to worry about as well, and the possibility of overfitting (especially if 102 | you don't have lots of training data). 103 | 104 | Our general suggestion is to try a few different algorithms for each problem. 105 | Tuning the parameters can be a lot of work, but just sit tight for now--toward 106 | the end of the class we will introduce you to GridCV, a great sklearn tool that 107 | can find an optimal parameter tune almost automatically. 108 | 109 | """ -------------------------------------------------------------------------------- /003 - Decision Tree/dt_author_id.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | this is the code to accompany the Lesson 3 (decision tree) mini-project 5 | 6 | use an DT to identify emails from the Enron corpus by their authors 7 | 8 | Sara has label 0 9 | Chris has label 1 10 | 11 | """ 12 | 13 | import sys 14 | from time import time 15 | sys.path.append("../tools/") 16 | from email_preprocess import preprocess 17 | from sklearn.metrics import accuracy_score 18 | from sklearn.tree import DecisionTreeClassifier 19 | 20 | ### features_train and features_test are the features for the training 21 | ### and testing datasets, respectively 22 | ### labels_train and labels_test are the corresponding item labels 23 | features_train, features_test, labels_train, labels_test = preprocess(percentile=1) 24 | clf = DecisionTreeClassifier(min_samples_split=40) 25 | clf.fit(features_train, labels_train) 26 | pred = clf.predict(features_test) 27 | acc = accuracy_score(pred, labels_test) 28 | print "Decision Tree accuracy: %r" % acc 29 | 30 | """ 31 | 32 | You found in the SVM mini-project that the parameter tune can significantly 33 | speed up the training time of a machine learning algorithm. A general rule is 34 | that the parameters can tune the complexity of the algorithm, with more 35 | complex algorithms generally running more slowly. 36 | 37 | Another way to control the complexity of an algorithm is via the number of 38 | features that you use in training/testing. The more features the algorithm 39 | has available, the more potential there is for a complex fit. We will explore 40 | this in detail in the 'Feature Selection' lesson, but you'll get a sneak preview now. 41 | 42 | What's the number of features in your data? 43 | """ 44 | 45 | print "no. of features in your data: %r" % len(features_train[0]) 46 | # Change percentile from 10 to 1, and rerun dt_author_id.py. 47 | # What's the number of features now? 379, before: 3785 48 | """ 49 | 50 | Would a large value for percentile lead to a more complex or less complex decision tree, 51 | all other things being equal? 52 | 53 | * More complex 54 | 55 | Accuracy percentile = 1 : 0.96587030716723554 56 | Accuracy percentile = 10 : 0.97838452787258245 57 | """ -------------------------------------------------------------------------------- /003 - Decision Tree/exercise/dec_tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/003 - Decision Tree/exercise/dec_tree.png -------------------------------------------------------------------------------- /003 - Decision Tree/exercise/main.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import sys 3 | sys.path.append("../../tools") 4 | from class_vis import prettyPicture 5 | from prep_terrain_data import makeTerrainData 6 | from sklearn.metrics import accuracy_score 7 | from sklearn.tree import DecisionTreeClassifier 8 | 9 | import matplotlib.pyplot as plt 10 | import copy 11 | import numpy as np 12 | import pylab as pl 13 | 14 | features_train, labels_train, features_test, labels_test = makeTerrainData() 15 | 16 | 17 | clf = DecisionTreeClassifier(min_samples_split=50) 18 | 19 | # now your job is to fit the classifier 20 | # using the training features/labels, and to 21 | # make a set of predictions on the test data 22 | 23 | clf.fit(features_train, labels_train) 24 | 25 | # store your predictions in a list named pred 26 | 27 | pred = clf.predict(features_test) 28 | 29 | prettyPicture(clf, features_test, labels_test, f_name="dec_tree.png") 30 | Image.open('dec_tree.png').show() 31 | 32 | acc = accuracy_score(pred, labels_test) 33 | print "Decision Tree accuracy: %r" % acc 34 | 35 | """ 36 | clf = DecisionTreeClassifier(min_samples_split=2) 37 | clf.fit(features_train, labels_train) 38 | pred = clf.predict(features_test) 39 | acc_min_samples_split_2 = accuracy_score(pred, labels_test) 40 | 41 | clf = DecisionTreeClassifier(min_samples_split=50) 42 | clf.fit(features_train, labels_train) 43 | pred = clf.predict(features_test) 44 | acc_min_samples_split_50 = accuracy_score(pred, labels_test) 45 | 46 | 47 | def submit_accuracies(): 48 | return {"acc_min_samples_split_2":round(acc_min_samples_split_2,3), 49 | "acc_min_samples_split_50":round(acc_min_samples_split_50,3)} 50 | 51 | submit_accuracies() 52 | 53 | """ -------------------------------------------------------------------------------- /003 - Decision Tree/exercise/overfitted.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/003 - Decision Tree/exercise/overfitted.png -------------------------------------------------------------------------------- /004 - AdaBoost + kNN + Random Forrest/ada_boost.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/004 - AdaBoost + kNN + Random Forrest/ada_boost.png -------------------------------------------------------------------------------- /004 - AdaBoost + kNN + Random Forrest/ada_boost.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | sys.path.append("../tools/") 5 | from class_vis import prettyPicture 6 | import matplotlib.pyplot as plt 7 | from prep_terrain_data import makeTerrainData 8 | from sklearn.ensemble import AdaBoostClassifier 9 | from sklearn.metrics import accuracy_score 10 | 11 | features_train, labels_train, features_test, labels_test = makeTerrainData() 12 | 13 | ### the training data (features_train, labels_train) have both "fast" and "slow" points mixed 14 | ### in together--separate them so we can give them different colors in the scatterplot, 15 | ### and visually identify them 16 | grade_fast = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==0] 17 | bumpy_fast = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==0] 18 | grade_slow = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==1] 19 | bumpy_slow = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==1] 20 | 21 | #### initial visualization 22 | plt.xlim(0.0, 1.0) 23 | plt.ylim(0.0, 1.0) 24 | plt.scatter(bumpy_fast, grade_fast, color = "b", label="fast") 25 | plt.scatter(grade_slow, bumpy_slow, color = "r", label="slow") 26 | plt.legend() 27 | plt.xlabel("bumpiness") 28 | plt.ylabel("grade") 29 | plt.show() 30 | 31 | clf = AdaBoostClassifier() 32 | clf.fit(features_train, labels_train) 33 | pred = clf.predict(features_test) 34 | acc = accuracy_score(pred, labels_test) 35 | print "Decision Tree accuracy: %r" % acc 36 | 37 | try: 38 | prettyPicture(clf, features_test, labels_test, f_name="ada_boost.png") 39 | except NameError: 40 | pass 41 | -------------------------------------------------------------------------------- /004 - AdaBoost + kNN + Random Forrest/knn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/004 - AdaBoost + kNN + Random Forrest/knn.png -------------------------------------------------------------------------------- /004 - AdaBoost + kNN + Random Forrest/knn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | sys.path.append("../tools/") 5 | from class_vis import prettyPicture 6 | import matplotlib.pyplot as plt 7 | from prep_terrain_data import makeTerrainData 8 | from sklearn.neighbors import KNeighborsClassifier 9 | from sklearn.metrics import accuracy_score 10 | 11 | features_train, labels_train, features_test, labels_test = makeTerrainData() 12 | 13 | ### the training data (features_train, labels_train) have both "fast" and "slow" points mixed 14 | ### in together--separate them so we can give them different colors in the scatterplot, 15 | ### and visually identify them 16 | grade_fast = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==0] 17 | bumpy_fast = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==0] 18 | grade_slow = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==1] 19 | bumpy_slow = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==1] 20 | 21 | #### initial visualization 22 | plt.xlim(0.0, 1.0) 23 | plt.ylim(0.0, 1.0) 24 | plt.scatter(bumpy_fast, grade_fast, color = "b", label="fast") 25 | plt.scatter(grade_slow, bumpy_slow, color = "r", label="slow") 26 | plt.legend() 27 | plt.xlabel("bumpiness") 28 | plt.ylabel("grade") 29 | plt.show() 30 | 31 | clf = KNeighborsClassifier() 32 | clf.fit(features_train, labels_train) 33 | pred = clf.predict(features_test) 34 | acc = accuracy_score(pred, labels_test) 35 | print "Decision Tree accuracy: %r" % acc 36 | 37 | try: 38 | prettyPicture(clf, features_test, labels_test, f_name="knn.png") 39 | except NameError: 40 | pass 41 | -------------------------------------------------------------------------------- /004 - AdaBoost + kNN + Random Forrest/random_forest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/004 - AdaBoost + kNN + Random Forrest/random_forest.png -------------------------------------------------------------------------------- /004 - AdaBoost + kNN + Random Forrest/random_forest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys 3 | sys.path.append("../tools/") 4 | from class_vis import prettyPicture 5 | import matplotlib.pyplot as plt 6 | from prep_terrain_data import makeTerrainData 7 | from sklearn.ensemble import RandomForestClassifier 8 | from sklearn.metrics import accuracy_score 9 | 10 | features_train, labels_train, features_test, labels_test = makeTerrainData() 11 | 12 | ### the training data (features_train, labels_train) have both "fast" and "slow" points mixed 13 | ### in together--separate them so we can give them different colors in the scatterplot, 14 | ### and visually identify them 15 | grade_fast = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==0] 16 | bumpy_fast = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==0] 17 | grade_slow = [features_train[ii][0] for ii in range(0, len(features_train)) if labels_train[ii]==1] 18 | bumpy_slow = [features_train[ii][1] for ii in range(0, len(features_train)) if labels_train[ii]==1] 19 | 20 | #### initial visualization 21 | plt.xlim(0.0, 1.0) 22 | plt.ylim(0.0, 1.0) 23 | plt.scatter(bumpy_fast, grade_fast, color = "b", label="fast") 24 | plt.scatter(grade_slow, bumpy_slow, color = "r", label="slow") 25 | plt.legend() 26 | plt.xlabel("bumpiness") 27 | plt.ylabel("grade") 28 | plt.show() 29 | 30 | clf = RandomForestClassifier() 31 | clf.fit(features_train, labels_train) 32 | pred = clf.predict(features_test) 33 | acc = accuracy_score(pred, labels_test) 34 | print "Decision Tree accuracy: %r" % acc 35 | 36 | try: 37 | prettyPicture(clf, features_test, labels_test, f_name="random_forest.png") 38 | except NameError: 39 | pass 40 | -------------------------------------------------------------------------------- /005 - Datasets Questions/explore_enron_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | starter code for exploring the Enron dataset (emails + finances) 5 | loads up the dataset (pickled dict of dicts) 6 | 7 | the dataset has the form 8 | enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } 9 | 10 | {features_dict} is a dictionary of features associated with that person 11 | you should explore features_dict as part of the mini-project, 12 | but here's an example to get you started: 13 | 14 | enron_data["SKILLING JEFFREY K"]["bonus"] = 5600000 15 | 16 | """ 17 | 18 | import pickle 19 | 20 | enron_data = pickle.load(open("final_project_dataset.pkl", "r")) 21 | money, n_poi, n_sal, n_email, total_payments, n_poi_nan_pay = 0, 0, 0, 0, 0, 0 22 | people = ("SKILLING JEFFREY K", "LAY KENNETH L","FASTOW ANDREW S") 23 | who = "" 24 | 25 | for i in enron_data: 26 | if enron_data[i]["poi"]: 27 | n_poi += 1 28 | if enron_data[i]["total_payments"] == "NaN": 29 | n_poi_nan_pay += 1 30 | if enron_data[i]["email_address"] != "NaN": 31 | n_email += 1 32 | if enron_data[i]["salary"] != "NaN": 33 | n_sal += 1 34 | if enron_data[i]["total_payments"] == "NaN": 35 | total_payments += 1 36 | 37 | for i in people: 38 | if money 0: 56 | ages, net_worths, errors = zip(*cleaned_data) 57 | ages = numpy.reshape( numpy.array(ages), (len(ages), 1)) 58 | net_worths = numpy.reshape( numpy.array(net_worths), (len(net_worths), 1)) 59 | 60 | # refit your cleaned data! 61 | try: 62 | reg.fit(ages, net_worths) 63 | print "Slope: ", reg.coef_[0][0] 64 | print "Intercept: ", reg.intercept_ 65 | print "Score of train set: ", reg.score(ages_train, net_worths_train) 66 | print "Score of test set: ", reg.score(ages_test, net_worths_test) 67 | 68 | plt.subplot(212) 69 | plt.title("after outlier removal") 70 | plt.plot(ages, reg.predict(ages), color="green") 71 | except NameError: 72 | print "you don't seem to have regression imported/created," 73 | print " or else your regression object isn't named reg" 74 | print " either way, only draw the scatter plot of the cleaned data" 75 | plt.scatter(ages, net_worths) 76 | plt.xlabel("ages") 77 | plt.ylabel("net worths") 78 | plt.tight_layout() 79 | plt.savefig("outlier_fig.png") 80 | plt.show() 81 | 82 | else: 83 | print "outlierCleaner() is returning an empty list, no refitting to be done" 84 | 85 | -------------------------------------------------------------------------------- /007 - Outliers/practice_outliers_ages.pkl: -------------------------------------------------------------------------------- 1 | (lp0 2 | I49 3 | aI21 4 | aI32 5 | aI30 6 | aI53 7 | aI51 8 | aI61 9 | aI23 10 | aI39 11 | aI21 12 | aI30 13 | aI43 14 | aI21 15 | aI29 16 | aI49 17 | aI45 18 | aI30 19 | aI47 20 | aI57 21 | aI20 22 | aI57 23 | aI52 24 | aI35 25 | aI27 26 | aI64 27 | aI35 28 | aI24 29 | aI24 30 | aI58 31 | aI47 32 | aI57 33 | aI53 34 | aI44 35 | aI64 36 | aI37 37 | aI45 38 | aI58 39 | aI48 40 | aI59 41 | aI46 42 | aI52 43 | aI22 44 | aI30 45 | aI33 46 | aI23 47 | aI30 48 | aI24 49 | aI32 50 | aI49 51 | aI36 52 | aI37 53 | aI29 54 | aI32 55 | aI63 56 | aI49 57 | aI48 58 | aI27 59 | aI53 60 | aI27 61 | aI37 62 | aI65 63 | aI49 64 | aI45 65 | aI51 66 | aI58 67 | aI55 68 | aI30 69 | aI21 70 | aI34 71 | aI32 72 | aI29 73 | aI63 74 | aI60 75 | aI34 76 | aI50 77 | aI38 78 | aI62 79 | aI41 80 | aI32 81 | aI31 82 | aI45 83 | aI32 84 | aI46 85 | aI61 86 | aI38 87 | aI30 88 | aI65 89 | aI43 90 | aI24 91 | aI22 92 | aI25 93 | aI48 94 | aI56 95 | aI39 96 | aI22 97 | aI37 98 | aI65 99 | aI44 100 | aI64 101 | aI59 102 | a. -------------------------------------------------------------------------------- /007 - Outliers/practice_outliers_net_worths.pkl: -------------------------------------------------------------------------------- 1 | (lp0 2 | F316.18428306022463 3 | aF128.4847139765763 4 | aF212.95377076201385 5 | aF217.96059712816052 6 | aF326.56693250553326 7 | aF314.0672608610164 8 | aF412.83425631014785 9 | aF159.09869458305818 10 | aF234.36051228130097 11 | aF142.1012008717193 12 | aF178.23164614375077 13 | aF259.43540492859483 14 | aF136.08924543132068 15 | aF142.98439510684403 16 | aF271.75164334973937 17 | aF270.00424941518054 18 | aF167.24337759331152 19 | aF300.0349466519055 20 | aF338.08951848957577 21 | aF96.75392597329417 22 | aF385.5629753784311 23 | aF320.4844739902693 24 | aF220.10056409375846 25 | aF140.25503627573087 26 | aF389.1123455094963 27 | aF220.96845179419734 28 | aF126.98012845155395 29 | aF157.51396036691344 30 | aF350.4872262016239 31 | aF287.91612500413447 32 | aF344.21586775541203 33 | aF368.29556369017877 34 | aF274.7300555052413 35 | aF378.84578142088196 36 | aF247.70089824206377 37 | aF256.83312700057957 38 | aF366.6772719000951 39 | aF260.8065975224045 40 | aF342.1862790220314 41 | aF291.4372247173825 42 | aF339.7693315999082 43 | aF140.9273656237994 44 | aF185.1870343522352 45 | aF200.22792608821422 46 | aF114.17956019265145 47 | aF173.10311583210583 48 | aF140.78722458080426 49 | aF221.1424445243783 50 | aF313.12236579136925 51 | aF189.73919689274533 52 | aF237.7316793878959 53 | aF173.54835439167368 54 | aF186.46155999388083 55 | aF405.9835257768174 56 | aF326.86999044991904 57 | aF318.62560238232396 58 | aF151.96564953554724 59 | aF325.0657524829757 60 | aF175.37526862807127 61 | aF250.76090254244718 62 | aF396.6665152430942 63 | aF302.53682046672367 64 | aF259.1233005198794 65 | aF294.8258675183866 66 | aF378.75051644788397 67 | aF370.8748005714165 68 | aF186.05979756839332 69 | aF151.32065795784047 70 | aF219.7327205009527 71 | aF187.0976049078975 72 | aF188.4779121101683 73 | aF424.51073132931936 74 | aF374.28347921780096 75 | aF243.79287311628013 76 | aF260.1050979182051 77 | aF253.93805008750448 78 | aF389.24094136476344 79 | aF250.26985299068266 80 | aF201.83521553071006 81 | aF153.99862170798215 82 | aF276.85656224324975 83 | aF207.14225143023492 84 | aF317.0578808948303 85 | aF370.88459563452705 86 | aF221.33012794213624 87 | aF177.46485912830926 88 | aF424.5580423540415 89 | aF275.3250221931937 90 | aF139.40479592465923 91 | aF147.76534866226712 92 | aF133.88384977349668 93 | aF80.9013362873476 94 | aF121.11602327460938 95 | aF134.41369498852399 96 | aF47.70052124577958 97 | aF16.507788679151513 98 | aF34.19027438129125 99 | aF64.06616829393845 100 | aF122.70221488837397 101 | aF129.10958748845152 102 | a. -------------------------------------------------------------------------------- /008 - K_Means/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/008 - K_Means/.DS_Store -------------------------------------------------------------------------------- /008 - K_Means/clusters.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/008 - K_Means/clusters.png -------------------------------------------------------------------------------- /008 - K_Means/clusters_before_scaling.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/008 - K_Means/clusters_before_scaling.png -------------------------------------------------------------------------------- /008 - K_Means/k_means.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/008 - K_Means/k_means.png -------------------------------------------------------------------------------- /008 - K_Means/k_means_cluster.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | skeleton code for k-means clustering mini-project 5 | 6 | """ 7 | 8 | import pickle 9 | import numpy 10 | import matplotlib.pyplot as plt 11 | import sys 12 | sys.path.append("../tools/") 13 | from feature_format import featureFormat, targetFeatureSplit 14 | 15 | def Draw(pred, features, poi, mark_poi=False, name="image.png", f1_name="feature 1", f2_name="feature 2"): 16 | """ some plotting code designed to help you visualize your clusters """ 17 | 18 | # plot each cluster with a different color--add more colors for 19 | # drawing more than 4 clusters 20 | colors = ["b", "c", "k", "m", "g"] 21 | for ii, pp in enumerate(pred): 22 | plt.scatter(features[ii][0], features[ii][1], color = colors[pred[ii]]) 23 | 24 | # if you like, place red stars over points that are POIs (just for funsies) 25 | if mark_poi: 26 | for ii, pp in enumerate(pred): 27 | if poi[ii]: 28 | plt.scatter(features[ii][0], features[ii][1], color="r", marker="*") 29 | plt.xlabel(f1_name) 30 | plt.ylabel(f2_name) 31 | plt.savefig(name) 32 | plt.show() 33 | 34 | 35 | 36 | # load in the dict of dicts containing all the data on each person in the dataset 37 | data_dict = pickle.load( open("../final_project/final_project_dataset.pkl", "r") ) 38 | # there's an outlier--remove it! 39 | data_dict.pop("TOTAL", 0) 40 | 41 | 42 | # the input features we want to use 43 | # can be any key in the person-level dictionary (salary, director_fees, etc.) 44 | feature_1 = "salary" 45 | feature_2 = "exercised_stock_options" 46 | feature_3 = "total_payments" 47 | poi = "poi" 48 | features_list = [poi, feature_1, feature_2] 49 | data = featureFormat(data_dict, features_list ) 50 | poi, finance_features = targetFeatureSplit( data ) 51 | 52 | 53 | # in the "clustering with 3 features" part of the mini-project, 54 | # you'll want to change this line to 55 | # for f1, f2, _ in finance_features: 56 | # (as it's currently written, line below assumes 2 features) 57 | for f1, f2 in finance_features: 58 | plt.scatter(f1, f2) 59 | plt.show() 60 | 61 | 62 | """ 63 | 64 | Deploy k-means clustering on the financial_features data, with 2 clusters 65 | specified as a parameter. Store your cluster predictions to a list called pred, 66 | so that the Draw() command at the bottom of the script works properly. 67 | In the scatterplot that pops up, are the clusters what you expected? 68 | """ 69 | from sklearn.cluster import KMeans 70 | features_list = ["poi", feature_1, feature_2, feature_3] 71 | data2 = featureFormat(data_dict, features_list ) 72 | poi, finance_features = targetFeatureSplit( data2 ) 73 | clf = KMeans(n_clusters=3) 74 | pred = clf.fit_predict( finance_features ) 75 | Draw(pred, finance_features, poi, name="clusters_before_scaling.png", f1_name=feature_1, f2_name=feature_2) 76 | 77 | # cluster here; create predictions of the cluster labels 78 | # for the data and store them to a list called pred 79 | 80 | try: 81 | Draw(pred, finance_features, poi, mark_poi=False, name="clusters.png", f1_name=feature_1, f2_name=feature_2) 82 | except NameError: 83 | print "no predictions object named pred found, no clusters to plot" 84 | 85 | """ 86 | 87 | In the next lesson, we'll talk about feature scaling. It's a type of feature 88 | preprocessing that you should perform before some classification and regression 89 | tasks. Here's a sneak preview that should call your attention to the general 90 | outline of what feature scaling does. 91 | 92 | What are the maximum and minimum values taken by the "exercised_stock_options" 93 | feature used in this example? 94 | 95 | NB: if you look at finance_features, there are some "NaN" values that have been 96 | cleaned away and replaced with zeroes -- so while those might look like 97 | the minima, it's a bit deceptive because they're more like points for which 98 | we don't have information, and just have to put in a number. So for this question, 99 | go back to data_dict and look for the maximum and minimum numbers that show up there, 100 | ignoring all the "NaN" entries. 101 | 102 | """ 103 | 104 | from sklearn.preprocessing import MinMaxScaler 105 | stock = [] 106 | for i in data_dict: 107 | if (data_dict[i]["exercised_stock_options"]=='NaN'): 108 | #stock.append(0.0) 109 | pass 110 | else: 111 | stock.append(float(data_dict[i]["exercised_stock_options"])) 112 | ma = max(stock) 113 | mi = min(stock) 114 | print "Exercised stock options maximum: ", ma, " minimum: ", mi 115 | # maximum: 34348384.0 minimum: 3285.0 comment out line 108 to get rid of zeroes. 116 | print float(1000000-mi)/(ma-mi) 117 | 118 | salary = [] 119 | for i in data_dict: 120 | if (data_dict[i][feature_1]=='NaN'): 121 | # salary.append(0.0) 122 | pass 123 | else: 124 | salary.append(float(data_dict[i][feature_1])) 125 | ma= max(salary) 126 | mi=min(salary) 127 | print "Exercised stock options maximum: ", ma, " minimum: ", mi 128 | # maximum: 1111258.0 minimum: 477.0 comment out line 121 to get rid of zeroes. 129 | print float(1000000-mi)/(ma-mi) 130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /008 - K_Means/k_means_plot.py: -------------------------------------------------------------------------------- 1 | print(__doc__) 2 | 3 | from time import time 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | 7 | from sklearn import metrics 8 | from sklearn.cluster import KMeans 9 | from sklearn.datasets import load_digits 10 | from sklearn.decomposition import PCA 11 | from sklearn.preprocessing import scale 12 | 13 | np.random.seed(42) 14 | 15 | digits = load_digits() 16 | data = scale(digits.data) 17 | 18 | n_samples, n_features = data.shape 19 | n_digits = len(np.unique(digits.target)) 20 | labels = digits.target 21 | 22 | sample_size = 300 23 | 24 | print("n_digits: %d, \t n_samples %d, \t n_features %d" 25 | % (n_digits, n_samples, n_features)) 26 | 27 | 28 | print(79 * '_') 29 | print('% 9s' % 'init' 30 | ' time inertia homo compl v-meas ARI AMI silhouette') 31 | 32 | 33 | def bench_k_means(estimator, name, data): 34 | t0 = time() 35 | estimator.fit(data) 36 | print('% 9s %.2fs %i %.3f %.3f %.3f %.3f %.3f %.3f' 37 | % (name, (time() - t0), estimator.inertia_, 38 | metrics.homogeneity_score(labels, estimator.labels_), 39 | metrics.completeness_score(labels, estimator.labels_), 40 | metrics.v_measure_score(labels, estimator.labels_), 41 | metrics.adjusted_rand_score(labels, estimator.labels_), 42 | metrics.adjusted_mutual_info_score(labels, estimator.labels_), 43 | metrics.silhouette_score(data, estimator.labels_, 44 | metric='euclidean', 45 | sample_size=sample_size))) 46 | 47 | bench_k_means(KMeans(init='k-means++', n_clusters=n_digits, n_init=10), 48 | name="k-means++", data=data) 49 | 50 | bench_k_means(KMeans(init='random', n_clusters=n_digits, n_init=10), 51 | name="random", data=data) 52 | 53 | # in this case the seeding of the centers is deterministic, hence we run the 54 | # kmeans algorithm only once with n_init=1 55 | pca = PCA(n_components=n_digits).fit(data) 56 | bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1), 57 | name="PCA-based", 58 | data=data) 59 | print(79 * '_') 60 | 61 | ############################################################################### 62 | # Visualize the results on PCA-reduced data 63 | 64 | reduced_data = PCA(n_components=2).fit_transform(data) 65 | kmeans = KMeans(init='k-means++', n_clusters=n_digits, n_init=10) 66 | kmeans.fit(reduced_data) 67 | 68 | # Step size of the mesh. Decrease to increase the quality of the VQ. 69 | h = .02 # point in the mesh [x_min, m_max]x[y_min, y_max]. 70 | 71 | # Plot the decision boundary. For that, we will assign a color to each 72 | x_min, x_max = reduced_data[:, 0].min() + 1, reduced_data[:, 0].max() - 1 73 | y_min, y_max = reduced_data[:, 1].min() + 1, reduced_data[:, 1].max() - 1 74 | xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) 75 | 76 | # Obtain labels for each point in mesh. Use last trained model. 77 | Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()]) 78 | 79 | # Put the result into a color plot 80 | Z = Z.reshape(xx.shape) 81 | plt.figure(1) 82 | plt.clf() 83 | plt.imshow(Z, interpolation='nearest', 84 | extent=(xx.min(), xx.max(), yy.min(), yy.max()), 85 | cmap=plt.cm.Paired, 86 | aspect='auto', origin='lower') 87 | 88 | plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2) 89 | # Plot the centroids as a white X 90 | centroids = kmeans.cluster_centers_ 91 | plt.scatter(centroids[:, 0], centroids[:, 1], 92 | marker='x', s=169, linewidths=3, 93 | color='w', zorder=10) 94 | plt.title('K-means clustering on the digits dataset (PCA-reduced data)\n' 95 | 'Centroids are marked with white cross') 96 | plt.xlim(x_min, x_max) 97 | plt.ylim(y_min, y_max) 98 | plt.xticks(()) 99 | plt.yticks(()) 100 | plt.savefig("k_means.png") 101 | plt.show() -------------------------------------------------------------------------------- /010 - Text Learning/parse_out_email_text.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from nltk.stem.snowball import SnowballStemmer 4 | import string 5 | 6 | def parseOutText(f): 7 | """ given an opened email file f, parse out all text below the 8 | metadata block at the top 9 | (in Part 2, you will also add stemming capabilities) 10 | and return a string that contains all the words 11 | in the email (space-separated) 12 | 13 | example use case: 14 | f = open("email_file_name.txt", "r") 15 | text = parseOutText(f) 16 | 17 | """ 18 | 19 | f.seek(0) # go back to beginning of file (annoying) 20 | all_text = f.read() 21 | # split off metadata 22 | content = all_text.split("X-FileName:") 23 | words = "" 24 | if len(content) > 1: 25 | # remove punctuation 26 | text_string = content[1].translate(string.maketrans("", ""), string.punctuation) 27 | 28 | # project part 2: comment out the line below 29 | #words = text_string 30 | 31 | # split the text string into individual words, stem each word, 32 | stemmer = SnowballStemmer('english') 33 | text_string = text_string.split() #makes a list of words 34 | for i in range(len(text_string)): 35 | text_string[i] = stemmer.stem(text_string[i]) 36 | # and append the stemmed word to words (make sure there's a single 37 | # space between each stemmed word) 38 | 39 | words = " ".join(text_string)# this -> " " ensures space b/w words 40 | 41 | return words 42 | 43 | def main(): 44 | ff = open("test_email.txt", "r") 45 | text = parseOutText(ff) 46 | print text 47 | 48 | if __name__ == '__main__': 49 | main() -------------------------------------------------------------------------------- /010 - Text Learning/test_email.txt: -------------------------------------------------------------------------------- 1 | To: Katie_and_Sebastians_Excellent_Students@udacity.com 2 | From: katie@udacity.com 3 | X-FileName: 4 | 5 | Hi Everyone! If you can read this message, you're properly using parseOutText. Please proceed to the next part of the project! 6 | -------------------------------------------------------------------------------- /010 - Text Learning/vectorize_text.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import os 4 | import pickle 5 | import re 6 | import sys 7 | 8 | from parse_out_email_text import parseOutText 9 | from sklearn.feature_extraction.text import TfidfVectorizer 10 | try: 11 | from progressbar import ProgressBar, Percentage, Bar 12 | except ImportError: 13 | import pip 14 | pip.main(['install', 'progressbar']) 15 | 16 | 17 | """ 18 | starter code to process the emails from Sara and Chris to extract 19 | the features and get the documents ready for classification 20 | 21 | the list of all the emails from Sara are in the from_sara list 22 | likewise for emails from Chris (from_chris) 23 | 24 | the actual documents are in the Enron email dataset, which 25 | you downloaded/unpacked in Part 0 of the first mini-project 26 | 27 | the data is stored in lists and packed away in pickle files at the end 28 | 29 | """ 30 | 31 | from_sara = open("from_sara.txt", "r") 32 | from_chris = open("from_chris.txt", "r") 33 | 34 | from_data = [] 35 | word_data = [] 36 | 37 | # temp_counter is a way to speed up the development--there are 38 | # thousands of emails from Sara and Chris, so running over all of them 39 | # can take a long time 40 | # temp_counter helps you only look at the first 200 emails in the list 41 | # temp_counter = 0 42 | 43 | print '[\033[91m LOADING\033[0m ] \033[94m\033[1mEmails are processing right now...\033[0m' 44 | 45 | 46 | pbar = ProgressBar(widgets=[Percentage(), Bar()], maxval=17578).start() 47 | for name, from_person in [("sara", from_sara), ("chris", from_chris)]: 48 | for path in from_person: 49 | # only look at first 200 emails when developing 50 | # once everything is working, remove this line to run over full dataset 51 | # temp_counter += 1 52 | # if temp_counter < 200: #remove comment if you need 200 53 | path = os.path.join('..', path[:-1]) 54 | # print '[\033[91m OK\033[0m ]' + path 55 | email = open(path, "r") 56 | 57 | # use parseOutText to extract the text from the opened email 58 | raw_txt = parseOutText(email) 59 | # use str.replace() to remove any instances of the words 60 | # ["sara", "shackleton", "chris", "germani"] 61 | unwanted_words = ["sara", "shackleton", "chris", "germani"] 62 | for word in unwanted_words: 63 | raw_txt = raw_txt.replace(word, "") 64 | # append the text to word_data 65 | word_data.append(raw_txt) 66 | # append a 0 to from_data if email is from Sara, and 1 if email is from Chris 67 | from_data.append(0) if (name == "sara") else from_data.append(1) 68 | email.close() 69 | pbar.update(len(word_data)) 70 | pbar.finish() 71 | 72 | print "[\033[92m OK\033[0m ] \033[94m\033[1mEmails Processed\033[0m" 73 | from_sara.close() 74 | from_chris.close() 75 | print "[\033[95m\033[1m Question 1 \033[0m]:", word_data[152] 76 | pickle.dump( word_data, open("your_word_data.pkl", "w") ) 77 | pickle.dump( from_data, open("your_email_authors.pkl", "w") ) 78 | 79 | # in Part 4, do TfIdf vectorization heres 80 | 81 | # !!! IMPORTANT !!! 82 | # If you run nltk first time please uncomment those 2 lines: 83 | 84 | # import nltk 85 | # nltk.download("stopwords") 86 | 87 | vectorizer = TfidfVectorizer(stop_words="english",lowercase=True) 88 | vectorizer.fit_transform(word_data) 89 | vocab_list = vectorizer.get_feature_names() 90 | print "[\033[95m\033[1m Question 2 \033[0m]:", len(vocab_list) 91 | print "[\033[95m\033[1m Question 3 \033[0m]:", vocab_list[34597] 92 | 93 | 94 | """ 95 | BONUS: intro. to coloring in terminal YEY! for more hand implementation: 96 | 97 | HEADER = '\033[95m' 98 | OKBLUE = '\033[94m' 99 | OKGREEN = '\033[92m' 100 | WARNING = '\033[93m' 101 | FAIL = '\033[91m' 102 | ENDC = '\033[0m' 103 | BOLD = '\033[1m' 104 | UNDERLINE = '\033[4m' 105 | 106 | or install colorama library from pip. for more adv. (e.g. fore + back ground coloring) 107 | both of them will work on windows too if it has enabled ansi.sys 108 | [https://support.microsoft.com/en-us/kb/101875] 109 | 110 | """ -------------------------------------------------------------------------------- /011 - Feature Selection/email_authors.pkl: -------------------------------------------------------------------------------- 1 | (lp0 2 | I0 3 | aI0 4 | aI0 5 | aI0 6 | aI0 7 | aI0 8 | aI0 9 | aI0 10 | aI0 11 | aI0 12 | aI0 13 | aI0 14 | aI0 15 | aI0 16 | aI0 17 | aI0 18 | aI0 19 | aI0 20 | aI0 21 | aI0 22 | aI0 23 | aI0 24 | aI0 25 | aI0 26 | aI0 27 | aI0 28 | aI0 29 | aI0 30 | aI0 31 | aI0 32 | aI0 33 | aI0 34 | aI0 35 | aI0 36 | aI0 37 | aI0 38 | aI0 39 | aI0 40 | aI0 41 | aI0 42 | aI0 43 | aI0 44 | aI0 45 | aI0 46 | aI0 47 | aI0 48 | aI0 49 | aI0 50 | aI0 51 | aI0 52 | aI0 53 | aI0 54 | aI0 55 | aI0 56 | aI0 57 | aI0 58 | aI0 59 | aI0 60 | aI0 61 | aI0 62 | aI0 63 | aI0 64 | aI0 65 | aI0 66 | aI0 67 | aI0 68 | aI0 69 | aI0 70 | aI0 71 | aI0 72 | aI0 73 | aI0 74 | aI0 75 | aI0 76 | aI0 77 | aI0 78 | aI0 79 | aI0 80 | aI0 81 | aI0 82 | aI0 83 | aI0 84 | aI0 85 | aI0 86 | aI0 87 | aI0 88 | aI0 89 | aI0 90 | aI0 91 | aI0 92 | aI0 93 | aI0 94 | aI0 95 | aI0 96 | aI0 97 | aI0 98 | aI0 99 | aI0 100 | aI0 101 | aI0 102 | aI0 103 | aI0 104 | aI0 105 | aI0 106 | aI0 107 | aI0 108 | aI0 109 | aI0 110 | aI0 111 | aI0 112 | aI0 113 | aI0 114 | aI0 115 | aI0 116 | aI0 117 | aI0 118 | aI0 119 | aI0 120 | aI0 121 | aI0 122 | aI0 123 | aI0 124 | aI0 125 | aI0 126 | aI0 127 | aI0 128 | aI0 129 | aI0 130 | aI0 131 | aI0 132 | aI0 133 | aI0 134 | aI0 135 | aI0 136 | aI0 137 | aI0 138 | aI0 139 | aI0 140 | aI0 141 | aI0 142 | aI0 143 | aI0 144 | aI0 145 | aI0 146 | aI0 147 | aI0 148 | aI0 149 | aI0 150 | aI0 151 | aI0 152 | aI0 153 | aI0 154 | aI0 155 | aI0 156 | aI0 157 | aI0 158 | aI0 159 | aI0 160 | aI0 161 | aI0 162 | aI0 163 | aI0 164 | aI0 165 | aI0 166 | aI0 167 | aI0 168 | aI0 169 | aI0 170 | aI0 171 | aI0 172 | aI0 173 | aI0 174 | aI0 175 | aI0 176 | aI0 177 | aI0 178 | aI0 179 | aI0 180 | aI0 181 | aI0 182 | aI0 183 | aI0 184 | aI0 185 | aI0 186 | aI0 187 | aI0 188 | aI0 189 | aI0 190 | aI0 191 | aI0 192 | aI0 193 | aI0 194 | aI0 195 | aI0 196 | aI0 197 | aI0 198 | aI0 199 | aI0 200 | aI0 201 | a. -------------------------------------------------------------------------------- /011 - Feature Selection/find_signature.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import pickle 4 | import numpy 5 | numpy.random.seed(42) 6 | 7 | 8 | # the words (features) and authors (labels), already largely processed 9 | # these files should have been created from the previous (Lesson 10) mini-project. 10 | words_file = "../010 - Text Learning/your_word_data.pkl" 11 | authors_file = "../010 - Text Learning/your_email_authors.pkl" 12 | word_data = pickle.load( open(words_file, "r")) 13 | word_data2 = list() 14 | 15 | for i in word_data: 16 | if "sshacklensf" in i: # second one is "cgermannsf" 17 | i = i.replace("sshacklensf", "") 18 | if "cgermannsf" in i: 19 | i = i.replace("cgermannsf", "") 20 | if "houectect" in i: 21 | i = i.replace("houectect", "") 22 | if "houect" in i: 23 | i = i.replace("houect", "") 24 | word_data2.append(i) 25 | 26 | authors = pickle.load( open(authors_file, "r") ) 27 | 28 | 29 | 30 | # test_size is the percentage of events assigned to the test set (remainder go into training) 31 | # feature matrices changed to dense representations for compatibility with classifier 32 | # functions in versions 0.15.2 and earlier 33 | from sklearn import cross_validation 34 | features_train, features_test, labels_train, labels_test = cross_validation.train_test_split(word_data2, authors, test_size=0.1, random_state=42) 35 | 36 | from sklearn.feature_extraction.text import TfidfVectorizer 37 | vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, 38 | stop_words='english') 39 | features_train = vectorizer.fit_transform(features_train) 40 | features_test = vectorizer.transform(features_test).toarray() 41 | 42 | 43 | # a classic way to overfit is to use a small number 44 | # of data points and a large number of features 45 | # train on only 150 events to put ourselves in this regime 46 | features_train = features_train[:150].toarray() 47 | labels_train = labels_train[:150] 48 | 49 | 50 | 51 | # your code goes here 52 | from sklearn.metrics import accuracy_score 53 | from sklearn.tree import DecisionTreeClassifier 54 | 55 | d_tree = DecisionTreeClassifier() 56 | d_tree.fit(features_train, labels_train) 57 | pred = d_tree.predict(features_test) 58 | print "Accuracy: ", accuracy_score(labels_test, pred) 59 | i_features = d_tree.feature_importances_ 60 | count = 0 61 | for f in i_features: 62 | if(f > 0.2): 63 | print "f: ", f, " index: ", count 64 | break 65 | count += 1 66 | print vectorizer.get_feature_names()[count] 67 | 68 | -------------------------------------------------------------------------------- /012 - PCA/eigenfaces.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/012 - PCA/eigenfaces.png -------------------------------------------------------------------------------- /012 - PCA/eigenfaces.py: -------------------------------------------------------------------------------- 1 | """ 2 | =================================================== 3 | Faces recognition example using eigenfaces and SVMs 4 | =================================================== 5 | 6 | The dataset used in this example is a preprocessed excerpt of the 7 | "Labeled Faces in the Wild", aka LFW_: 8 | 9 | http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz (233MB) 10 | 11 | .. _LFW: http://vis-www.cs.umass.edu/lfw/ 12 | 13 | original source: http://scikit-learn.org/stable/auto_examples/applications/face_recognition.html 14 | 15 | """ 16 | 17 | 18 | 19 | print __doc__ 20 | 21 | from time import time 22 | import logging 23 | import pylab as pl 24 | import numpy as np 25 | 26 | from sklearn.cross_validation import train_test_split 27 | from sklearn.datasets import fetch_lfw_people 28 | from sklearn.grid_search import GridSearchCV 29 | from sklearn.metrics import classification_report 30 | from sklearn.metrics import confusion_matrix 31 | from sklearn.decomposition import RandomizedPCA 32 | from sklearn.svm import SVC 33 | 34 | # Display progress logs on stdout 35 | logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') 36 | 37 | 38 | ############################################################################### 39 | # Download the data, if not already on disk and load it as numpy arrays 40 | 41 | lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4) 42 | 43 | # introspect the images arrays to find the shapes (for plotting) 44 | n_samples, h, w = lfw_people.images.shape 45 | np.random.seed(42) 46 | 47 | # fot machine learning we use the 2 data directly (as relative pixel 48 | # positions info is ignored by this model) 49 | X = lfw_people.data 50 | n_features = X.shape[1] 51 | 52 | # the label to predict is the id of the person 53 | y = lfw_people.target 54 | target_names = lfw_people.target_names 55 | n_classes = target_names.shape[0] 56 | 57 | print "Total dataset size:" 58 | print "n_samples: %d" % n_samples 59 | print "n_features: %d" % n_features 60 | print "n_classes: %d" % n_classes 61 | 62 | 63 | ############################################################################### 64 | # Split into a training set and a test set using a stratified k fold 65 | 66 | # split into a training and testing set 67 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) 68 | 69 | 70 | ############################################################################### 71 | # Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled 72 | # dataset): unsupervised feature extraction / dimensionality reduction 73 | n_components = 150 74 | 75 | print "Extracting the top %d eigenfaces from %d faces" % (n_components, X_train.shape[0]) 76 | t0 = time() 77 | pca = RandomizedPCA(n_components=n_components, whiten=True).fit(X_train) 78 | print "done in %0.3fs" % (time() - t0) 79 | # uncomment to see variances 80 | # print "Variance: ", pca.explained_variance_ratio_ 81 | 82 | eigenfaces = pca.components_.reshape((n_components, h, w)) 83 | 84 | print "Projecting the input data on the eigenfaces orthonormal basis" 85 | t0 = time() 86 | X_train_pca = pca.transform(X_train) 87 | X_test_pca = pca.transform(X_test) 88 | print "done in %0.3fs" % (time() - t0) 89 | 90 | 91 | ############################################################################### 92 | # Train a SVM classification model 93 | 94 | print "Fitting the classifier to the training set" 95 | t0 = time() 96 | param_grid = { 97 | 'C': [1e3, 5e3, 1e4, 5e4, 1e5], 98 | 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], 99 | } 100 | clf = GridSearchCV(SVC(kernel='rbf', class_weight='auto'), param_grid) 101 | clf = clf.fit(X_train_pca, y_train) 102 | print "done in %0.3fs" % (time() - t0) 103 | print "Best estimator found by grid search:" 104 | print clf.best_estimator_ 105 | 106 | 107 | ############################################################################### 108 | # Quantitative evaluation of the model quality on the test set 109 | 110 | print "Predicting the people names on the testing set" 111 | t0 = time() 112 | y_pred = clf.predict(X_test_pca) 113 | print "done in %0.3fs" % (time() - t0) 114 | 115 | print classification_report(y_test, y_pred, target_names=target_names) 116 | print confusion_matrix(y_test, y_pred, labels=range(n_classes)) 117 | 118 | 119 | ############################################################################### 120 | # Qualitative evaluation of the predictions using matplotlib 121 | 122 | def plot_gallery(images, titles, h, w, n_row=3, n_col=4): 123 | """Helper function to plot a gallery of portraits""" 124 | pl.figure(figsize=(1.8 * n_col, 2.4 * n_row)) 125 | pl.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35) 126 | for i in range(n_row * n_col): 127 | pl.subplot(n_row, n_col, i + 1) 128 | pl.imshow(images[i].reshape((h, w)), cmap=pl.cm.gray) 129 | pl.title(titles[i], size=12) 130 | pl.xticks(()) 131 | pl.yticks(()) 132 | 133 | 134 | # plot the result of the prediction on a portion of the test set 135 | 136 | def title(y_pred, y_test, target_names, i): 137 | pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1] 138 | true_name = target_names[y_test[i]].rsplit(' ', 1)[-1] 139 | return 'predicted: %s\ntrue: %s' % (pred_name, true_name) 140 | 141 | prediction_titles = [title(y_pred, y_test, target_names, i) 142 | for i in range(y_pred.shape[0])] 143 | 144 | plot_gallery(X_test, prediction_titles, h, w) 145 | 146 | # plot the gallery of the most significative eigenfaces 147 | 148 | eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])] 149 | plot_gallery(eigenfaces, eigenface_titles, h, w) 150 | 151 | pl.show() 152 | -------------------------------------------------------------------------------- /012 - PCA/pred.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdegis/machine-learning/c5e7694bf28487e20194f6724e1cdce92bd0a59a/012 - PCA/pred.png -------------------------------------------------------------------------------- /013 - Validation/validate_poi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import pickle 4 | import sys 5 | sys.path.append("../tools/") 6 | from feature_format import featureFormat, targetFeatureSplit 7 | from sklearn import cross_validation 8 | from sklearn.tree import DecisionTreeClassifier 9 | 10 | data_dict = pickle.load(open("final_project_dataset.pkl", "r")) 11 | 12 | # first element is our labels, any added elements are predictor 13 | # features. Keep this the same for the mini-project, but you'll 14 | # have a different feature list when you do the final project. 15 | features_list = ["poi", "salary"] 16 | 17 | data = featureFormat(data_dict, features_list) 18 | labels, features = targetFeatureSplit(data) 19 | 20 | # without spliting data part: 21 | clf = DecisionTreeClassifier() 22 | # clf.fit(features,labels) 23 | # print clf.score(features, labels) # 0.989473684211 24 | 25 | features_train, features_test, labels_train, labels_test = cross_validation.train_test_split( 26 | features, labels, test_size=0.3, random_state=42) 27 | clf.fit(features_train, labels_train) 28 | print clf.score(features_test, labels_test) # 0.724137931034 -------------------------------------------------------------------------------- /014 - Evaluation/evaluate_poi_identifier.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import pickle 4 | import sys 5 | sys.path.append("../tools/") 6 | from feature_format import featureFormat, targetFeatureSplit 7 | from sklearn import cross_validation 8 | from sklearn.tree import DecisionTreeClassifier 9 | from sklearn.metrics import precision_score 10 | from sklearn.metrics import recall_score 11 | 12 | data_dict = pickle.load(open("../013 - Validation/final_project_dataset.pkl", "r")) 13 | features_list = ["poi", "salary"] 14 | 15 | data = featureFormat(data_dict, features_list) 16 | labels, features = targetFeatureSplit(data) 17 | 18 | clf = DecisionTreeClassifier() 19 | features_train, features_test, labels_train, labels_test = cross_validation.train_test_split( 20 | features, labels, test_size=0.3, random_state=42) 21 | clf.fit(features_train, labels_train) 22 | 23 | pred = clf.predict(features_test) 24 | print "[Q1] How many POIs are predicted for the test set for your POI identifier?" 25 | print "[A1]", sum(pred) 26 | print "[Q2] How many people total are in your test set?" 27 | print "[A2]", len(pred) 28 | print "[Q3] If your identifier predicted 0. (not POI) for everyone in the test set, what would its accuracy be?" 29 | print "[A3]", pred.tolist().count(0) / float(len(pred)) 30 | print "[Q4] Do you get any true positives? (In this case, we define a true positive as a case where both the actual label and the predicted label are 1)" 31 | true_positives = 0 32 | for i in range(len(pred)): 33 | if (pred[i] == labels_test[i]) and labels_test[i] == 1: 34 | true_positives += 1 35 | print "[A3]", true_positives 36 | print "Precision score:", precision_score(pred, labels_test) 37 | print "Recall score:", recall_score(pred, labels_test) 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. {http://fsf.org/} 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see {http://www.gnu.org/licenses/}. 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Machine Learning in Python (C) 2015 Melih Degis 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | {http://www.gnu.org/licenses/}. 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | {http://www.gnu.org/philosophy/why-not-lgpl.html}. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Machine Learning in Python 2 | 3 | This repository contains some assignments and exercises of Machine Learning course of Sebastian Thrun and Katie Malone. 4 | 5 | Please read the license file. I do **NOT** take any responsibility in case of plagiarism. It's **ONLY** educational purpose. 6 | 7 | ## Mini-Projects: 8 | 9 | Before try to run any of the assignments, please run 'startup.py' in 'tools' directory. This will automatically install e-mail data set and extract it (which is about 423 MB in tgz, 1.4 GB when decompressed). 10 | 11 | ### Lesson 1: Naive Bayes 12 | 13 | * Naive Bayes Classifier is used to identify emails by their authors. 14 | * Also time performance and accuracy are calculated. 15 | * Decide whether car should go fast or slow depending on bumpiness level of road. 16 | 17 | ![plot](https://github.com/mdegis/machine-learning/raw/master/001%20-%20Naive%20Bayes%20Classifier/exercise/bayes.png) 18 | 19 | ### Lesson 2: SVM 20 | 21 | In this mini-project, we’ll tackle the exact same email author ID problem as the Naive Bayes mini-project, but now with an SVM. What we find will help clarify some of the practical differences between the two algorithms. This project also gives us a chance to play around with parameters a lot more than Naive Bayes did, so we will do that too. 22 | 23 | Read the comments in the code, for more information. 24 | 25 | ![plot](https://github.com/mdegis/machine-learning/raw/master/002%20-%20SVM/exercise/svm_lin.png) 26 | 27 | ### Lesson 3: Decision Tree 28 | 29 | In this project we'll be tackling the same project that we've done with our last two supervised classification algorithms. We're trying to understand who wrote an email based on the word content of that email. This time we'll be using a decision tree. We'll also dig into the features that we use a little bit more. This'll be a dedicated topic in the latter part of the class. What features give you the most effective, the most accurate supervised classification algorithm? 30 | 31 | Read the comments in the code, for more information. 32 | 33 | Overfitted example: 34 | ![plot](https://github.com/mdegis/machine-learning/raw/master/003%20-%20Decision%20Tree/exercise/overfitted.png) 35 | Fixed: 36 | ![plot](https://github.com/mdegis/machine-learning/raw/master/003%20-%20Decision%20Tree/exercise/dec_tree.png) 37 | 38 | 39 | ### Lesson 4: AdaBoost (Adaptive Boosting), kNN and Random Forrest 40 | 41 | * **AdaBoost**: 42 | 43 | While every learning algorithm will tend to suit some problem types better than others, and will typically have many different parameters and configurations to be adjusted before achieving optimal performance on a dataset, AdaBoost (with decision trees as the weak learners) is often referred to as the best out-of-the-box classifier. When used with decision tree learning, information gathered at each stage of the AdaBoost algorithm about the relative 'hardness' of each training sample is fed into the tree growing algorithm such that later trees tend to focus on harder to classify examples. 44 | 45 | A great article about AdaBoost can be found at https://www.cs.princeton.edu/~schapire/papers/explaining-adaboost.pdf 46 | 47 | ![plot](https://github.com/mdegis/machine-learning/raw/master/004%20-%20AdaBoost%20%2B%20kNN%20%2B%20%20Random%20Forrest/ada_boost.png) 48 | 49 | * **k Nearest Neighbors**: 50 | 51 | Neighbors-based classification is a type of instance-based learning or non-generalizing learning; it does not attempt to construct a general internal model, but simply stores instances of the training data. Classification is computed from a simple majority vote of the nearest neighbors of each point: a query point is assigned the data class which has the most representatives within the nearest neighbors of the point. 52 | 53 | ![plot](https://github.com/mdegis/machine-learning/raw/master/004%20-%20AdaBoost%20%2B%20kNN%20%2B%20%20Random%20Forrest/knn.png) 54 | 55 | 56 | * **Random Forrest**: 57 | 58 | The Random Forrest (ensemble learning method [like AdaBoost] for classification, regression) method combines Breiman's "bagging" idea and the random selection of features, introduced independently by Ho and Amit and Geman in order to construct a collection of decision trees with controlled variance. The selection of a random subset of features is an example of the random subspace method, which, in Ho's formulation, is a way to implement classification proposed by Eugene Kleinberg. 59 | 60 | ![plot](https://github.com/mdegis/machine-learning/raw/master/004%20-%20AdaBoost%20%2B%20kNN%20%2B%20%20Random%20Forrest/random_forest.png) 61 | 62 | 63 | ### Lesson 5: Dataset and Questions 64 | 65 | The Enron fraud is a big, messy and totally fascinating story about corporate malfeasance of nearly every imaginable type. The Enron email and financial datasets are also big, messy treasure troves of information, which become much more useful once you know your way around them a bit. We’ve combined the email and finance data into a single dataset, which you’ll explore in this mini-project. 66 | 67 | The aggregated Enron email + financial dataset is stored in a dictionary, where each key in the dictionary is a person’s name and the value is a dictionary containing all the features of that person. The email + finance (E+F) data dictionary is stored as a pickle file, which is a handy way to store and load python objects directly. 68 | 69 | ### Lesson 6: Regression 70 | 71 | In this project, we will use regression to predict financial data for Enron employees and associates. Once we know some financial data about an employee, like their salary, what would you predict for the size of their bonus? 72 | 73 | Read the comments in the code, for more information. 74 | 75 | ![plot](https://github.com/mdegis/machine-learning/raw/master/006%20-%20Regression/regression.png) 76 | 77 | 78 | ### Lesson 7: Outliers 79 | 80 | Having large outliers can have a big effect on your regression result. So in the first part of this mini project, you're going to implement the algorithm that is you take the 10% or so of data points that have the largest residuals, relative to your regression. You remove them, and then you refit the regression, and you see how the result changes. 81 | 82 | The second thing we'll do is take a closer at the Enron data. This time with a particular eye towards outliers. You'll find very quickly that there are some data points that fall far outside of the general pattern. 83 | 84 | ![plot](https://github.com/mdegis/machine-learning/raw/master/007%20-%20Outliers/outlier_fig.png) 85 | 86 | ### Lesson 8: Unsupervised Learning (K-Means Clustering) 87 | 88 | In this project, we'll apply k-means clustering to our Enron financial data. Our final goal, of course, is to identify persons of interest; since we have labeled data, this is not a question that particularly calls for an unsupervised approach like k-means clustering. 89 | 90 | Nonetheless, you'll get some hands-on practice with k-means in this project, and play around with feature scaling, which will give you a sneak preview of the next lesson's material. 91 | 92 | Great online tool to visualize k-Means Cluster algorithm can be founded at http://www.naftaliharris.com/blog/visualizing-k-means-clustering/ 93 | 94 | ![plot](https://github.com/mdegis/machine-learning/raw/master/008%20-%20K_Means/k_means.png) 95 | 96 | ### Lesson 9: Feature Scaling 97 | 98 | In the mini-project on K-means clustering, you clustered the data points. And then at the end, we sort of gestured towards feature scaling as something that could change the output of that clustering algorithm. In this mini-project, you'll actually deploy the feature scaling yourself. So you'll take the code from the K-means clustering algorithm and add in the feature scaling and then in doing so, you'll be recreating the steps that we took to make those new clusters. 99 | 100 | ```python 101 | salary = [] 102 | for i in data_dict: 103 | if (data_dict[i][feature_1]=='NaN'): 104 | salary.append(0.0) 105 | # pass 106 | else: 107 | salary.append(float(data_dict[i][feature_1])) 108 | ma= max(salary) 109 | mi=min(salary) 110 | print "salary maximum: ", ma, " minimum: ", mi 111 | # maximum: 1111258.0 minimum: 477.0 comment out line 121 to get rid of zeroes. 112 | print float(200000-mi)/(ma-mi) 113 | 114 | salary_ = numpy.array(salary) 115 | salary_ = salary_.astype(float) 116 | scaler = MinMaxScaler() 117 | rescaled_salary = scaler.fit_transform(salary_) 118 | print rescaled_salary 119 | ``` 120 | 121 | ### Lesson 10: Text Learning 122 | 123 | In the beginning of this class, you identified emails by their authors using a number of supervised classification algorithms. In those projects, we handled the preprocessing for you, transforming the input emails into a TfIdf so they could be fed into the algorithms. Now you will construct your own version of that preprocessing step, so that you are going directly from raw data to processed features. 124 | 125 | You will be given two text files: one contains the locations of all the emails from Sara, the other has emails from Chris. You will also have access to the parseOutText() function, which accepts an opened email as an argument and returns a string containing all the (stemmed) words in the email. 126 | 127 | Read the comments in the code, for more information ([This code](/010 - Text Learning/vectorize_text.py) contains some cool examples). 128 | 129 | ### Lesson 11: Feature Selection 130 | 131 | In one of the earlier videos in this lesson we told you about that there was a word that was effectively serving as a signature on the e-mails and we didn't initially realize it. Now, the mark of a good machine learner doesn't mean that they never make any mistakes or that their features are always perfect. It means that they're on the lookout for ways to check this and to figure out if there is a bug in there that they need to go in and fix. 132 | 133 | So in this case it would mean that there's a type of signature word, that we would need to go in and remove in order for us to, to feel like we were being fair in our supervised classification. We will be working on a problem that arose in preparing Chris and Sara’s email for the author identification project; it had to do with a feature that was a little too powerful (effectively acting like a signature, which gives an arguably unfair advantage to an algorithm). You’ll work through that discovery process here. 134 | 135 | Read the comments in the [code](/011 - Feature Selection/find_signature.py), for more information. 136 | 137 | ### Lesson 12: Principal Component Analysis 138 | 139 | PCA example by Eigenfaces (face recognition). 140 | ![plot](https://github.com/mdegis/machine-learning/raw/master/012%20-%20PCA/eigenfaces.png) 141 | 142 | ``` 143 | =================================================== 144 | Faces recognition example using eigenfaces and SVMs 145 | =================================================== 146 | 147 | The dataset used in this example is a preprocessed excerpt of the 148 | "Labeled Faces in the Wild", aka LFW_: 149 | 150 | http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz (233MB) 151 | 152 | .. _LFW: http://vis-www.cs.umass.edu/lfw/ 153 | 154 | original source: http://scikit-learn.org/stable/auto_examples/applications/face_recognition.html 155 | 156 | 157 | 2015-08-05 22:25:02,927 Loading LFW people faces from /home/mdegis/scikit_learn_data/lfw_home 158 | Total dataset size: 159 | n_samples: 1288 160 | n_features: 1850 161 | n_classes: 7 162 | Extracting the top 150 eigenfaces from 966 faces 163 | done in 4.846s 164 | Projecting the input data on the eigenfaces orthonormal basis 165 | done in 0.372s 166 | Fitting the classifier to the training set 167 | done in 18.366s 168 | Best estimator found by grid search: 169 | SVC(C=1000.0, cache_size=200, class_weight='auto', coef0=0.0, degree=3, 170 | gamma=0.005, kernel='rbf', max_iter=-1, probability=False, 171 | random_state=None, shrinking=True, tol=0.001, verbose=False) 172 | Predicting the people names on the testing set 173 | done in 0.061s 174 | precision recall f1-score support 175 | 176 | Ariel Sharon 1.00 0.62 0.76 13 177 | Colin Powell 0.78 0.82 0.80 60 178 | Donald Rumsfeld 0.87 0.74 0.80 27 179 | George W Bush 0.82 0.92 0.87 146 180 | Gerhard Schroeder 0.90 0.76 0.83 25 181 | Hugo Chavez 1.00 0.53 0.70 15 182 | Tony Blair 0.77 0.75 0.76 36 183 | 184 | avg / total 0.83 0.83 0.82 322 185 | 186 | [[ 8 2 0 3 0 0 0] 187 | [ 0 49 2 6 0 0 3] 188 | [ 0 0 20 5 0 0 2] 189 | [ 0 11 0 135 0 0 0] 190 | [ 0 0 0 4 19 0 2] 191 | [ 0 0 0 5 1 8 1] 192 | [ 0 1 1 6 1 0 27]] 193 | ``` 194 | 195 | ![plot](https://github.com/mdegis/machine-learning/raw/master/012%20-%20PCA/pred.png) 196 | 197 | ### 013 - Validation 198 | 199 | ```python 200 | data_dict = pickle.load(open("final_project_dataset.pkl", "r")) 201 | 202 | # first element is our labels, any added elements are predictor 203 | # features. Keep this the same for the mini-project, but you'll 204 | # have a different feature list when you do the final project. 205 | features_list = ["poi", "salary"] 206 | 207 | data = featureFormat(data_dict, features_list) 208 | labels, features = targetFeatureSplit(data) 209 | 210 | # without spliting data part: 211 | clf = DecisionTreeClassifier() 212 | # clf.fit(features,labels) 213 | # print clf.score(features, labels) # 0.989473684211 214 | 215 | features_train, features_test, labels_train, labels_test = cross_validation.train_test_split( 216 | features, labels, test_size=0.3, random_state=42) 217 | clf.fit(features_train, labels_train) 218 | print clf.score(features_test, labels_test) # 0.724137931034 219 | ``` 220 | 221 | ### Lesson 14: Evaluation Metrics 222 | 223 | In the last lesson, you created your first person of interest identifier algorithm, and you set up a training and testing framework so that you could assess the accuracy of that model. 224 | 225 | Now that you know much more about evaluation metrics, we're going to have you deploy those evaluation metrics on the framework that you've set up in the last lesson. And so, by the time you get to the final project, the main thing that you'll have to think about will be the features that you want to use, the algorithm that you want to use, and any parameter tunes. You'll already have the training and testing, and the evaluation matrix all set up. 226 | -------------------------------------------------------------------------------- /tools/class_vis.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | #from udacityplots import * 4 | import matplotlib 5 | matplotlib.use('agg') 6 | 7 | import matplotlib.pyplot as plt 8 | import pylab as pl 9 | import numpy as np 10 | 11 | #import numpy as np 12 | #import matplotlib.pyplot as plt 13 | #plt.ioff() 14 | 15 | def prettyPicture(clf, X_test, y_test, f_name="test.png"): 16 | x_min = 0.0; x_max = 1.0 17 | y_min = 0.0; y_max = 1.0 18 | 19 | # Plot the decision boundary. For that, we will assign a color to each 20 | # point in the mesh [x_min, m_max]x[y_min, y_max]. 21 | h = .01 # step size in the mesh 22 | xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) 23 | Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) 24 | 25 | # Put the result into a color plot 26 | Z = Z.reshape(xx.shape) 27 | plt.xlim(xx.min(), xx.max()) 28 | plt.ylim(yy.min(), yy.max()) 29 | 30 | plt.pcolormesh(xx, yy, Z, cmap=pl.cm.seismic) 31 | 32 | # Plot also the test points 33 | grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==0] 34 | bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==0] 35 | grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==1] 36 | bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==1] 37 | 38 | plt.scatter(grade_sig, bumpy_sig, color = "b", label="fast") 39 | plt.scatter(grade_bkg, bumpy_bkg, color = "r", label="slow") 40 | plt.legend() 41 | plt.xlabel("bumpiness") 42 | plt.ylabel("grade") 43 | 44 | plt.savefig(f_name) 45 | 46 | import base64 47 | import json 48 | import subprocess 49 | 50 | def output_image(name, format, bytes): 51 | # test purpose; you may change it to see the image it self. 52 | image_start = "BEGIN_IMAGE_f9825uweof8jw9fj4r8" 53 | image_end = "END_IMAGE_0238jfw08fjsiufhw8frs" 54 | data = {} 55 | data['name'] = name 56 | data['format'] = format 57 | data['bytes'] = base64.encodestring(bytes) 58 | print image_start+json.dumps(data)+image_end -------------------------------------------------------------------------------- /tools/email_preprocess.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import pickle 4 | import cPickle 5 | import numpy 6 | 7 | from sklearn import cross_validation 8 | from sklearn.feature_extraction.text import TfidfVectorizer 9 | from sklearn.feature_selection import SelectPercentile, f_classif 10 | 11 | 12 | 13 | def preprocess(words_file = "../tools/word_data.pkl", authors_file="../tools/email_authors.pkl", percentile=10): 14 | """ 15 | this function takes a pre-made list of email texts (by default word_data.pkl) 16 | and the corresponding authors (by default email_authors.pkl) and performs 17 | a number of preprocessing steps: 18 | -- splits into training/testing sets (10% testing) 19 | -- vectorizes into tfidf matrix 20 | -- selects/keeps most helpful features 21 | 22 | after this, the feaures and labels are put into numpy arrays, which play nice with sklearn functions 23 | 24 | 4 objects are returned: 25 | -- training/testing features 26 | -- training/testing labels 27 | 28 | """ 29 | 30 | ### the words (features) and authors (labels), already largely preprocessed 31 | ### this preprocessing will be repeated in the text learning mini-project 32 | authors_file_handler = open(authors_file, "r") 33 | authors = pickle.load(authors_file_handler) 34 | authors_file_handler.close() 35 | 36 | words_file_handler = open(words_file, "r") 37 | word_data = cPickle.load(words_file_handler) 38 | words_file_handler.close() 39 | 40 | ### test_size is the percentage of events assigned to the test set (remainder go into training) 41 | features_train, features_test, labels_train, labels_test = cross_validation.train_test_split(word_data, authors, test_size=0.1, random_state=42) 42 | 43 | 44 | 45 | ### text vectorization--go from strings to lists of numbers 46 | vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, 47 | stop_words='english') 48 | features_train_transformed = vectorizer.fit_transform(features_train) 49 | features_test_transformed = vectorizer.transform(features_test) 50 | 51 | 52 | 53 | ### feature selection, because text is super high dimensional and 54 | ### can be really computationally chewy as a result 55 | selector = SelectPercentile(f_classif, percentile=percentile) 56 | selector.fit(features_train_transformed, labels_train) 57 | features_train_transformed = selector.transform(features_train_transformed).toarray() 58 | features_test_transformed = selector.transform(features_test_transformed).toarray() 59 | 60 | ### info on the data 61 | print "no. of Chris training emails:", sum(labels_train) 62 | print "no. of Sara training emails:", len(labels_train)-sum(labels_train) 63 | 64 | return features_train_transformed, features_test_transformed, labels_train, labels_test 65 | -------------------------------------------------------------------------------- /tools/feature_format.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | A general tool for converting data from the 5 | dictionary format to an (n x k) python list that's 6 | ready for training an sklearn algorithm 7 | 8 | n--no. of key-value pairs in dictonary 9 | k--no. of features being extracted 10 | 11 | dictionary keys are names of persons in dataset 12 | dictionary values are dictionaries, where each 13 | key-value pair in the dict is the name 14 | of a feature, and its value for that person 15 | 16 | In addition to converting a dictionary to a numpy 17 | array, you may want to separate the labels from the 18 | features--this is what targetFeatureSplit is for 19 | 20 | so, if you want to have the poi label as the target, 21 | and the features you want to use are the person's 22 | salary and bonus, here's what you would do: 23 | 24 | feature_list = ["poi", "salary", "bonus"] 25 | data_array = featureFormat( data_dictionary, feature_list ) 26 | label, features = targetFeatureSplit(data_array) 27 | 28 | the line above (targetFeatureSplit) assumes that the 29 | label is the _first_ item in feature_list--very important 30 | that poi is listed first! 31 | """ 32 | 33 | 34 | import numpy as np 35 | 36 | def featureFormat( dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys = False): 37 | """ convert dictionary to numpy array of features 38 | remove_NaN = True will convert "NaN" string to 0.0 39 | remove_all_zeroes = True will omit any data points for which 40 | all the features you seek are 0.0 41 | remove_any_zeroes = True will omit any data points for which 42 | any of the features you seek are 0.0 43 | sort_keys = True sorts keys by alphabetical order. Setting the value as 44 | a string opens the corresponding pickle file with a preset key 45 | order (this is used for Python 3 compatibility, and sort_keys 46 | should be left as False for the course mini-projects). 47 | NOTE: first feature is assumed to be 'poi' and is not checked for 48 | removal for zero or missing values. 49 | """ 50 | 51 | 52 | return_list = [] 53 | 54 | # Key order - first branch is for Python 3 compatibility on mini-projects, 55 | # second branch is for compatibility on final project. 56 | if isinstance(sort_keys, str): 57 | import pickle 58 | keys = pickle.load(open(sort_keys, "rb")) 59 | elif sort_keys: 60 | keys = sorted(dictionary.keys()) 61 | else: 62 | keys = dictionary.keys() 63 | 64 | for key in keys: 65 | tmp_list = [] 66 | for feature in features: 67 | try: 68 | dictionary[key][feature] 69 | except KeyError: 70 | print "error: key ", feature, " not present" 71 | return 72 | value = dictionary[key][feature] 73 | if value=="NaN" and remove_NaN: 74 | value = 0 75 | tmp_list.append( float(value) ) 76 | 77 | # Logic for deciding whether or not to add the data point. 78 | append = True 79 | # exclude 'poi' class as criteria. 80 | if features[0] == 'poi': 81 | test_list = tmp_list[1:] 82 | else: 83 | test_list = tmp_list 84 | ### if all features are zero and you want to remove 85 | ### data points that are all zero, do that here 86 | if remove_all_zeroes: 87 | append = False 88 | for item in test_list: 89 | if item != 0 and item != "NaN": 90 | append = True 91 | break 92 | ### if any features for a given data point are zero 93 | ### and you want to remove data points with any zeroes, 94 | ### handle that here 95 | if remove_any_zeroes: 96 | if 0 in test_list or "NaN" in test_list: 97 | append = False 98 | ### Append the data point if flagged for addition. 99 | if append: 100 | return_list.append( np.array(tmp_list) ) 101 | 102 | return np.array(return_list) 103 | 104 | 105 | def targetFeatureSplit( data ): 106 | """ 107 | given a numpy array like the one returned from 108 | featureFormat, separate out the first feature 109 | and put it into its own list (this should be the 110 | quantity you want to predict) 111 | 112 | return targets and features as separate lists 113 | 114 | (sklearn can generally handle both lists and numpy arrays as 115 | input formats when training/predicting) 116 | """ 117 | 118 | target = [] 119 | features = [] 120 | for item in data: 121 | target.append( item[0] ) 122 | features.append( item[1:] ) 123 | 124 | return target, features 125 | 126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /tools/prep_terrain_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import random 3 | 4 | 5 | def makeTerrainData(n_points=1000): 6 | # make the toy dataset 7 | random.seed(42) 8 | grade = [random.random() for ii in range(0,n_points)] 9 | bumpy = [random.random() for ii in range(0,n_points)] 10 | error = [random.random() for ii in range(0,n_points)] 11 | y = [round(grade[ii]*bumpy[ii]+0.3+0.1*error[ii]) for ii in range(0,n_points)] 12 | for ii in range(0, len(y)): 13 | if grade[ii]>0.8 or bumpy[ii]>0.8: 14 | y[ii] = 1.0 15 | 16 | # split into train/test sets 17 | X = [[gg, ss] for gg, ss in zip(grade, bumpy)] 18 | split = int(0.75*n_points) 19 | X_train = X[0:split] 20 | X_test = X[split:] 21 | y_train = y[0:split] 22 | y_test = y[split:] 23 | 24 | grade_sig = [X_train[ii][0] for ii in range(0, len(X_train)) if y_train[ii]==0] 25 | bumpy_sig = [X_train[ii][1] for ii in range(0, len(X_train)) if y_train[ii]==0] 26 | grade_bkg = [X_train[ii][0] for ii in range(0, len(X_train)) if y_train[ii]==1] 27 | bumpy_bkg = [X_train[ii][1] for ii in range(0, len(X_train)) if y_train[ii]==1] 28 | 29 | # training_data = {"fast":{"grade":grade_sig, "bumpiness":bumpy_sig} 30 | # , "slow":{"grade":grade_bkg, "bumpiness":bumpy_bkg}} 31 | 32 | grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==0] 33 | bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==0] 34 | grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==1] 35 | bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==1] 36 | 37 | test_data = {"fast":{"grade":grade_sig, "bumpiness":bumpy_sig} 38 | , "slow":{"grade":grade_bkg, "bumpiness":bumpy_bkg}} 39 | 40 | return X_train, y_train, X_test, y_test 41 | # return training_data, test_data -------------------------------------------------------------------------------- /tools/python2_lesson06_keys.pkl: -------------------------------------------------------------------------------- 1 | (lp0 2 | S'METTS MARK' 3 | p1 4 | aS'BAXTER JOHN C' 5 | p2 6 | aS'ELLIOTT STEVEN' 7 | p3 8 | aS'CORDES WILLIAM R' 9 | p4 10 | aS'HANNON KEVIN P' 11 | p5 12 | aS'MORDAUNT KRISTINA M' 13 | p6 14 | aS'MEYER ROCKFORD G' 15 | p7 16 | aS'MCMAHON JEFFREY' 17 | p8 18 | aS'HORTON STANLEY C' 19 | p9 20 | aS'PIPER GREGORY F' 21 | p10 22 | aS'HUMPHREY GENE E' 23 | p11 24 | aS'UMANOFF ADAM S' 25 | p12 26 | aS'BLACHMAN JEREMY M' 27 | p13 28 | aS'SUNDE MARTIN' 29 | p14 30 | aS'GIBBS DANA R' 31 | p15 32 | aS'LOWRY CHARLES P' 33 | p16 34 | aS'COLWELL WESLEY' 35 | p17 36 | aS'MULLER MARK S' 37 | p18 38 | aS'JACKSON CHARLENE R' 39 | p19 40 | aS'WESTFAHL RICHARD K' 41 | p20 42 | aS'WALTERS GARETH W' 43 | p21 44 | aS'WALLS JR ROBERT H' 45 | p22 46 | aS'KITCHEN LOUISE' 47 | p23 48 | aS'CHAN RONNIE' 49 | p24 50 | aS'BELFER ROBERT' 51 | p25 52 | aS'SHANKMAN JEFFREY A' 53 | p26 54 | aS'WODRASKA JOHN' 55 | p27 56 | aS'BERGSIEKER RICHARD P' 57 | p28 58 | aS'URQUHART JOHN A' 59 | p29 60 | aS'BIBI PHILIPPE A' 61 | p30 62 | aS'RIEKER PAULA H' 63 | p31 64 | aS'WHALEY DAVID A' 65 | p32 66 | aS'BECK SALLY W' 67 | p33 68 | aS'HAUG DAVID L' 69 | p34 70 | aS'ECHOLS JOHN B' 71 | p35 72 | aS'MENDELSOHN JOHN' 73 | p36 74 | aS'HICKERSON GARY J' 75 | p37 76 | aS'CLINE KENNETH W' 77 | p38 78 | aS'LEWIS RICHARD' 79 | p39 80 | aS'HAYES ROBERT E' 81 | p40 82 | aS'MCCARTY DANNY J' 83 | p41 84 | aS'KOPPER MICHAEL J' 85 | p42 86 | aS'LEFF DANIEL P' 87 | p43 88 | aS'LAVORATO JOHN J' 89 | p44 90 | aS'BERBERIAN DAVID' 91 | p45 92 | aS'DETMERING TIMOTHY J' 93 | p46 94 | aS'WAKEHAM JOHN' 95 | p47 96 | aS'POWERS WILLIAM' 97 | p48 98 | aS'GOLD JOSEPH' 99 | p49 100 | aS'BANNANTINE JAMES M' 101 | p50 102 | aS'DUNCAN JOHN H' 103 | p51 104 | aS'SHAPIRO RICHARD S' 105 | p52 106 | aS'SHERRIFF JOHN R' 107 | p53 108 | aS'SHELBY REX' 109 | p54 110 | aS'LEMAISTRE CHARLES' 111 | p55 112 | aS'DEFFNER JOSEPH M' 113 | p56 114 | aS'KISHKILL JOSEPH G' 115 | p57 116 | aS'WHALLEY LAWRENCE G' 117 | p58 118 | aS'MCCONNELL MICHAEL S' 119 | p59 120 | aS'PIRO JIM' 121 | p60 122 | aS'DELAINEY DAVID W' 123 | p61 124 | aS'SULLIVAN-SHAKLOVITZ COLLEEN' 125 | p62 126 | aS'WROBEL BRUCE' 127 | p63 128 | aS'LINDHOLM TOD A' 129 | p64 130 | aS'MEYER JEROME J' 131 | p65 132 | aS'BUTTS ROBERT H' 133 | p66 134 | aS'OLSON CINDY K' 135 | p67 136 | aS'MCDONALD REBECCA' 137 | p68 138 | aS'CUMBERLAND MICHAEL S' 139 | p69 140 | aS'GAHN ROBERT S' 141 | p70 142 | aS'MCCLELLAN GEORGE' 143 | p71 144 | aS'HERMANN ROBERT J' 145 | p72 146 | aS'SCRIMSHAW MATTHEW' 147 | p73 148 | aS'GATHMANN WILLIAM D' 149 | p74 150 | aS'HAEDICKE MARK E' 151 | p75 152 | aS'BOWEN JR RAYMOND M' 153 | p76 154 | aS'GILLIS JOHN' 155 | p77 156 | aS'FASTOW ANDREW S' 157 | p78 158 | aS'FITZGERALD JAY L' 159 | p79 160 | aS'MORAN MICHAEL P' 161 | p80 162 | aS'REDMOND BRIAN L' 163 | p81 164 | aS'BAZELIDES PHILIP J' 165 | p82 166 | aS'BELDEN TIMOTHY N' 167 | p83 168 | aS'DURAN WILLIAM D' 169 | p84 170 | aS'THORN TERENCE H' 171 | p85 172 | aS'FOY JOE' 173 | p86 174 | aS'CALGER CHRISTOPHER F' 175 | p87 176 | aS'RICE KENNETH D' 177 | p88 178 | aS'KAMINSKI WINCENTY J' 179 | p89 180 | aS'LOCKHART EUGENE E' 181 | p90 182 | aS'COX DAVID' 183 | p91 184 | aS'OVERDYKE JR JERE C' 185 | p92 186 | aS'PEREIRA PAULO V. FERRAZ' 187 | p93 188 | aS'STABLER FRANK' 189 | p94 190 | aS'BLAKE JR. NORMAN P' 191 | p95 192 | aS'SHERRICK JEFFREY B' 193 | p96 194 | aS'PRENTICE JAMES' 195 | p97 196 | aS'GRAY RODNEY' 197 | p98 198 | aS'PICKERING MARK R' 199 | p99 200 | aS'THE TRAVEL AGENCY IN THE PARK' 201 | p100 202 | aS'NOLES JAMES L' 203 | p101 204 | aS'KEAN STEVEN J' 205 | p102 206 | aS'FOWLER PEGGY' 207 | p103 208 | aS'WASAFF GEORGE' 209 | p104 210 | aS'WHITE JR THOMAS E' 211 | p105 212 | aS'CHRISTODOULOU DIOMEDES' 213 | p106 214 | aS'ALLEN PHILLIP K' 215 | p107 216 | aS'SHARP VICTORIA T' 217 | p108 218 | aS'JAEDICKE ROBERT' 219 | p109 220 | aS'WINOKUR JR. HERBERT S' 221 | p110 222 | aS'BROWN MICHAEL' 223 | p111 224 | aS'BADUM JAMES P' 225 | p112 226 | aS'HUGHES JAMES A' 227 | p113 228 | aS'REYNOLDS LAWRENCE' 229 | p114 230 | aS'DIMICHELE RICHARD G' 231 | p115 232 | aS'BHATNAGAR SANJAY' 233 | p116 234 | aS'CARTER REBECCA C' 235 | p117 236 | aS'BUCHANAN HAROLD G' 237 | p118 238 | aS'YEAP SOON' 239 | p119 240 | aS'MURRAY JULIA H' 241 | p120 242 | aS'GARLAND C KEVIN' 243 | p121 244 | aS'DODSON KEITH' 245 | p122 246 | aS'YEAGER F SCOTT' 247 | p123 248 | aS'HIRKO JOSEPH' 249 | p124 250 | aS'DIETRICH JANET R' 251 | p125 252 | aS'DERRICK JR. JAMES V' 253 | p126 254 | aS'FREVERT MARK A' 255 | p127 256 | aS'PAI LOU L' 257 | p128 258 | aS'BAY FRANKLIN R' 259 | p129 260 | aS'HAYSLETT RODERICK J' 261 | p130 262 | aS'FUGH JOHN L' 263 | p131 264 | aS'FALLON JAMES B' 265 | p132 266 | aS'KOENIG MARK E' 267 | p133 268 | aS'SAVAGE FRANK' 269 | p134 270 | aS'IZZO LAWRENCE L' 271 | p135 272 | aS'TILNEY ELIZABETH A' 273 | p136 274 | aS'MARTIN AMANDA K' 275 | p137 276 | aS'BUY RICHARD B' 277 | p138 278 | aS'GRAMM WENDY L' 279 | p139 280 | aS'CAUSEY RICHARD A' 281 | p140 282 | aS'TAYLOR MITCHELL S' 283 | p141 284 | aS'DONAHUE JR JEFFREY M' 285 | p142 286 | aS'GLISAN JR BEN F' 287 | p143 288 | a. -------------------------------------------------------------------------------- /tools/python2_lesson13_keys.pkl: -------------------------------------------------------------------------------- 1 | (lp0 2 | S'METTS MARK' 3 | p1 4 | aS'BAXTER JOHN C' 5 | p2 6 | aS'ELLIOTT STEVEN' 7 | p3 8 | aS'CORDES WILLIAM R' 9 | p4 10 | aS'HANNON KEVIN P' 11 | p5 12 | aS'MORDAUNT KRISTINA M' 13 | p6 14 | aS'MEYER ROCKFORD G' 15 | p7 16 | aS'MCMAHON JEFFREY' 17 | p8 18 | aS'HORTON STANLEY C' 19 | p9 20 | aS'PIPER GREGORY F' 21 | p10 22 | aS'HUMPHREY GENE E' 23 | p11 24 | aS'UMANOFF ADAM S' 25 | p12 26 | aS'BLACHMAN JEREMY M' 27 | p13 28 | aS'SUNDE MARTIN' 29 | p14 30 | aS'GIBBS DANA R' 31 | p15 32 | aS'LOWRY CHARLES P' 33 | p16 34 | aS'COLWELL WESLEY' 35 | p17 36 | aS'MULLER MARK S' 37 | p18 38 | aS'JACKSON CHARLENE R' 39 | p19 40 | aS'WESTFAHL RICHARD K' 41 | p20 42 | aS'WALTERS GARETH W' 43 | p21 44 | aS'WALLS JR ROBERT H' 45 | p22 46 | aS'KITCHEN LOUISE' 47 | p23 48 | aS'CHAN RONNIE' 49 | p24 50 | aS'BELFER ROBERT' 51 | p25 52 | aS'SHANKMAN JEFFREY A' 53 | p26 54 | aS'WODRASKA JOHN' 55 | p27 56 | aS'BERGSIEKER RICHARD P' 57 | p28 58 | aS'URQUHART JOHN A' 59 | p29 60 | aS'BIBI PHILIPPE A' 61 | p30 62 | aS'RIEKER PAULA H' 63 | p31 64 | aS'WHALEY DAVID A' 65 | p32 66 | aS'BECK SALLY W' 67 | p33 68 | aS'HAUG DAVID L' 69 | p34 70 | aS'ECHOLS JOHN B' 71 | p35 72 | aS'MENDELSOHN JOHN' 73 | p36 74 | aS'HICKERSON GARY J' 75 | p37 76 | aS'CLINE KENNETH W' 77 | p38 78 | aS'LEWIS RICHARD' 79 | p39 80 | aS'HAYES ROBERT E' 81 | p40 82 | aS'MCCARTY DANNY J' 83 | p41 84 | aS'KOPPER MICHAEL J' 85 | p42 86 | aS'LEFF DANIEL P' 87 | p43 88 | aS'LAVORATO JOHN J' 89 | p44 90 | aS'BERBERIAN DAVID' 91 | p45 92 | aS'DETMERING TIMOTHY J' 93 | p46 94 | aS'WAKEHAM JOHN' 95 | p47 96 | aS'POWERS WILLIAM' 97 | p48 98 | aS'GOLD JOSEPH' 99 | p49 100 | aS'BANNANTINE JAMES M' 101 | p50 102 | aS'DUNCAN JOHN H' 103 | p51 104 | aS'SHAPIRO RICHARD S' 105 | p52 106 | aS'SHERRIFF JOHN R' 107 | p53 108 | aS'SHELBY REX' 109 | p54 110 | aS'LEMAISTRE CHARLES' 111 | p55 112 | aS'DEFFNER JOSEPH M' 113 | p56 114 | aS'KISHKILL JOSEPH G' 115 | p57 116 | aS'WHALLEY LAWRENCE G' 117 | p58 118 | aS'MCCONNELL MICHAEL S' 119 | p59 120 | aS'PIRO JIM' 121 | p60 122 | aS'DELAINEY DAVID W' 123 | p61 124 | aS'SULLIVAN-SHAKLOVITZ COLLEEN' 125 | p62 126 | aS'WROBEL BRUCE' 127 | p63 128 | aS'LINDHOLM TOD A' 129 | p64 130 | aS'MEYER JEROME J' 131 | p65 132 | aS'LAY KENNETH L' 133 | p66 134 | aS'BUTTS ROBERT H' 135 | p67 136 | aS'OLSON CINDY K' 137 | p68 138 | aS'MCDONALD REBECCA' 139 | p69 140 | aS'CUMBERLAND MICHAEL S' 141 | p70 142 | aS'GAHN ROBERT S' 143 | p71 144 | aS'MCCLELLAN GEORGE' 145 | p72 146 | aS'HERMANN ROBERT J' 147 | p73 148 | aS'SCRIMSHAW MATTHEW' 149 | p74 150 | aS'GATHMANN WILLIAM D' 151 | p75 152 | aS'HAEDICKE MARK E' 153 | p76 154 | aS'BOWEN JR RAYMOND M' 155 | p77 156 | aS'GILLIS JOHN' 157 | p78 158 | aS'FITZGERALD JAY L' 159 | p79 160 | aS'MORAN MICHAEL P' 161 | p80 162 | aS'REDMOND BRIAN L' 163 | p81 164 | aS'BAZELIDES PHILIP J' 165 | p82 166 | aS'BELDEN TIMOTHY N' 167 | p83 168 | aS'DURAN WILLIAM D' 169 | p84 170 | aS'THORN TERENCE H' 171 | p85 172 | aS'FASTOW ANDREW S' 173 | p86 174 | aS'FOY JOE' 175 | p87 176 | aS'CALGER CHRISTOPHER F' 177 | p88 178 | aS'RICE KENNETH D' 179 | p89 180 | aS'KAMINSKI WINCENTY J' 181 | p90 182 | aS'LOCKHART EUGENE E' 183 | p91 184 | aS'COX DAVID' 185 | p92 186 | aS'OVERDYKE JR JERE C' 187 | p93 188 | aS'PEREIRA PAULO V. FERRAZ' 189 | p94 190 | aS'STABLER FRANK' 191 | p95 192 | aS'SKILLING JEFFREY K' 193 | p96 194 | aS'BLAKE JR. NORMAN P' 195 | p97 196 | aS'SHERRICK JEFFREY B' 197 | p98 198 | aS'PRENTICE JAMES' 199 | p99 200 | aS'GRAY RODNEY' 201 | p100 202 | aS'PICKERING MARK R' 203 | p101 204 | aS'THE TRAVEL AGENCY IN THE PARK' 205 | p102 206 | aS'NOLES JAMES L' 207 | p103 208 | aS'KEAN STEVEN J' 209 | p104 210 | aS'TOTAL' 211 | p105 212 | aS'FOWLER PEGGY' 213 | p106 214 | aS'WASAFF GEORGE' 215 | p107 216 | aS'WHITE JR THOMAS E' 217 | p108 218 | aS'CHRISTODOULOU DIOMEDES' 219 | p109 220 | aS'ALLEN PHILLIP K' 221 | p110 222 | aS'SHARP VICTORIA T' 223 | p111 224 | aS'JAEDICKE ROBERT' 225 | p112 226 | aS'WINOKUR JR. HERBERT S' 227 | p113 228 | aS'BROWN MICHAEL' 229 | p114 230 | aS'BADUM JAMES P' 231 | p115 232 | aS'HUGHES JAMES A' 233 | p116 234 | aS'REYNOLDS LAWRENCE' 235 | p117 236 | aS'DIMICHELE RICHARD G' 237 | p118 238 | aS'BHATNAGAR SANJAY' 239 | p119 240 | aS'CARTER REBECCA C' 241 | p120 242 | aS'BUCHANAN HAROLD G' 243 | p121 244 | aS'YEAP SOON' 245 | p122 246 | aS'MURRAY JULIA H' 247 | p123 248 | aS'GARLAND C KEVIN' 249 | p124 250 | aS'DODSON KEITH' 251 | p125 252 | aS'YEAGER F SCOTT' 253 | p126 254 | aS'HIRKO JOSEPH' 255 | p127 256 | aS'DIETRICH JANET R' 257 | p128 258 | aS'DERRICK JR. JAMES V' 259 | p129 260 | aS'FREVERT MARK A' 261 | p130 262 | aS'PAI LOU L' 263 | p131 264 | aS'BAY FRANKLIN R' 265 | p132 266 | aS'HAYSLETT RODERICK J' 267 | p133 268 | aS'FUGH JOHN L' 269 | p134 270 | aS'FALLON JAMES B' 271 | p135 272 | aS'KOENIG MARK E' 273 | p136 274 | aS'SAVAGE FRANK' 275 | p137 276 | aS'IZZO LAWRENCE L' 277 | p138 278 | aS'TILNEY ELIZABETH A' 279 | p139 280 | aS'MARTIN AMANDA K' 281 | p140 282 | aS'BUY RICHARD B' 283 | p141 284 | aS'GRAMM WENDY L' 285 | p142 286 | aS'CAUSEY RICHARD A' 287 | p143 288 | aS'TAYLOR MITCHELL S' 289 | p144 290 | aS'DONAHUE JR JEFFREY M' 291 | p145 292 | aS'GLISAN JR BEN F' 293 | p146 294 | a. -------------------------------------------------------------------------------- /tools/python2_lesson14_keys.pkl: -------------------------------------------------------------------------------- 1 | (lp0 2 | S'METTS MARK' 3 | p1 4 | aS'BAXTER JOHN C' 5 | p2 6 | aS'ELLIOTT STEVEN' 7 | p3 8 | aS'CORDES WILLIAM R' 9 | p4 10 | aS'HANNON KEVIN P' 11 | p5 12 | aS'MORDAUNT KRISTINA M' 13 | p6 14 | aS'MEYER ROCKFORD G' 15 | p7 16 | aS'MCMAHON JEFFREY' 17 | p8 18 | aS'HORTON STANLEY C' 19 | p9 20 | aS'PIPER GREGORY F' 21 | p10 22 | aS'HUMPHREY GENE E' 23 | p11 24 | aS'UMANOFF ADAM S' 25 | p12 26 | aS'BLACHMAN JEREMY M' 27 | p13 28 | aS'SUNDE MARTIN' 29 | p14 30 | aS'GIBBS DANA R' 31 | p15 32 | aS'LOWRY CHARLES P' 33 | p16 34 | aS'COLWELL WESLEY' 35 | p17 36 | aS'MULLER MARK S' 37 | p18 38 | aS'JACKSON CHARLENE R' 39 | p19 40 | aS'WESTFAHL RICHARD K' 41 | p20 42 | aS'WALTERS GARETH W' 43 | p21 44 | aS'WALLS JR ROBERT H' 45 | p22 46 | aS'KITCHEN LOUISE' 47 | p23 48 | aS'CHAN RONNIE' 49 | p24 50 | aS'BELFER ROBERT' 51 | p25 52 | aS'SHANKMAN JEFFREY A' 53 | p26 54 | aS'WODRASKA JOHN' 55 | p27 56 | aS'BERGSIEKER RICHARD P' 57 | p28 58 | aS'URQUHART JOHN A' 59 | p29 60 | aS'BIBI PHILIPPE A' 61 | p30 62 | aS'RIEKER PAULA H' 63 | p31 64 | aS'WHALEY DAVID A' 65 | p32 66 | aS'BECK SALLY W' 67 | p33 68 | aS'HAUG DAVID L' 69 | p34 70 | aS'ECHOLS JOHN B' 71 | p35 72 | aS'MENDELSOHN JOHN' 73 | p36 74 | aS'HICKERSON GARY J' 75 | p37 76 | aS'CLINE KENNETH W' 77 | p38 78 | aS'LEWIS RICHARD' 79 | p39 80 | aS'HAYES ROBERT E' 81 | p40 82 | aS'MCCARTY DANNY J' 83 | p41 84 | aS'KOPPER MICHAEL J' 85 | p42 86 | aS'LEFF DANIEL P' 87 | p43 88 | aS'LAVORATO JOHN J' 89 | p44 90 | aS'BERBERIAN DAVID' 91 | p45 92 | aS'DETMERING TIMOTHY J' 93 | p46 94 | aS'WAKEHAM JOHN' 95 | p47 96 | aS'POWERS WILLIAM' 97 | p48 98 | aS'GOLD JOSEPH' 99 | p49 100 | aS'BANNANTINE JAMES M' 101 | p50 102 | aS'DUNCAN JOHN H' 103 | p51 104 | aS'SHAPIRO RICHARD S' 105 | p52 106 | aS'SHERRIFF JOHN R' 107 | p53 108 | aS'SHELBY REX' 109 | p54 110 | aS'LEMAISTRE CHARLES' 111 | p55 112 | aS'DEFFNER JOSEPH M' 113 | p56 114 | aS'KISHKILL JOSEPH G' 115 | p57 116 | aS'WHALLEY LAWRENCE G' 117 | p58 118 | aS'MCCONNELL MICHAEL S' 119 | p59 120 | aS'PIRO JIM' 121 | p60 122 | aS'DELAINEY DAVID W' 123 | p61 124 | aS'SULLIVAN-SHAKLOVITZ COLLEEN' 125 | p62 126 | aS'WROBEL BRUCE' 127 | p63 128 | aS'LINDHOLM TOD A' 129 | p64 130 | aS'MEYER JEROME J' 131 | p65 132 | aS'LAY KENNETH L' 133 | p66 134 | aS'BUTTS ROBERT H' 135 | p67 136 | aS'OLSON CINDY K' 137 | p68 138 | aS'MCDONALD REBECCA' 139 | p69 140 | aS'CUMBERLAND MICHAEL S' 141 | p70 142 | aS'GAHN ROBERT S' 143 | p71 144 | aS'MCCLELLAN GEORGE' 145 | p72 146 | aS'HERMANN ROBERT J' 147 | p73 148 | aS'SCRIMSHAW MATTHEW' 149 | p74 150 | aS'GATHMANN WILLIAM D' 151 | p75 152 | aS'HAEDICKE MARK E' 153 | p76 154 | aS'BOWEN JR RAYMOND M' 155 | p77 156 | aS'GILLIS JOHN' 157 | p78 158 | aS'FITZGERALD JAY L' 159 | p79 160 | aS'MORAN MICHAEL P' 161 | p80 162 | aS'REDMOND BRIAN L' 163 | p81 164 | aS'BAZELIDES PHILIP J' 165 | p82 166 | aS'BELDEN TIMOTHY N' 167 | p83 168 | aS'DURAN WILLIAM D' 169 | p84 170 | aS'THORN TERENCE H' 171 | p85 172 | aS'FASTOW ANDREW S' 173 | p86 174 | aS'FOY JOE' 175 | p87 176 | aS'CALGER CHRISTOPHER F' 177 | p88 178 | aS'RICE KENNETH D' 179 | p89 180 | aS'KAMINSKI WINCENTY J' 181 | p90 182 | aS'LOCKHART EUGENE E' 183 | p91 184 | aS'COX DAVID' 185 | p92 186 | aS'OVERDYKE JR JERE C' 187 | p93 188 | aS'PEREIRA PAULO V. FERRAZ' 189 | p94 190 | aS'STABLER FRANK' 191 | p95 192 | aS'SKILLING JEFFREY K' 193 | p96 194 | aS'BLAKE JR. NORMAN P' 195 | p97 196 | aS'SHERRICK JEFFREY B' 197 | p98 198 | aS'PRENTICE JAMES' 199 | p99 200 | aS'GRAY RODNEY' 201 | p100 202 | aS'PICKERING MARK R' 203 | p101 204 | aS'THE TRAVEL AGENCY IN THE PARK' 205 | p102 206 | aS'NOLES JAMES L' 207 | p103 208 | aS'KEAN STEVEN J' 209 | p104 210 | aS'TOTAL' 211 | p105 212 | aS'FOWLER PEGGY' 213 | p106 214 | aS'WASAFF GEORGE' 215 | p107 216 | aS'WHITE JR THOMAS E' 217 | p108 218 | aS'CHRISTODOULOU DIOMEDES' 219 | p109 220 | aS'ALLEN PHILLIP K' 221 | p110 222 | aS'SHARP VICTORIA T' 223 | p111 224 | aS'JAEDICKE ROBERT' 225 | p112 226 | aS'WINOKUR JR. HERBERT S' 227 | p113 228 | aS'BROWN MICHAEL' 229 | p114 230 | aS'BADUM JAMES P' 231 | p115 232 | aS'HUGHES JAMES A' 233 | p116 234 | aS'REYNOLDS LAWRENCE' 235 | p117 236 | aS'DIMICHELE RICHARD G' 237 | p118 238 | aS'BHATNAGAR SANJAY' 239 | p119 240 | aS'CARTER REBECCA C' 241 | p120 242 | aS'BUCHANAN HAROLD G' 243 | p121 244 | aS'YEAP SOON' 245 | p122 246 | aS'MURRAY JULIA H' 247 | p123 248 | aS'GARLAND C KEVIN' 249 | p124 250 | aS'DODSON KEITH' 251 | p125 252 | aS'YEAGER F SCOTT' 253 | p126 254 | aS'HIRKO JOSEPH' 255 | p127 256 | aS'DIETRICH JANET R' 257 | p128 258 | aS'DERRICK JR. JAMES V' 259 | p129 260 | aS'FREVERT MARK A' 261 | p130 262 | aS'PAI LOU L' 263 | p131 264 | aS'BAY FRANKLIN R' 265 | p132 266 | aS'HAYSLETT RODERICK J' 267 | p133 268 | aS'FUGH JOHN L' 269 | p134 270 | aS'FALLON JAMES B' 271 | p135 272 | aS'KOENIG MARK E' 273 | p136 274 | aS'SAVAGE FRANK' 275 | p137 276 | aS'IZZO LAWRENCE L' 277 | p138 278 | aS'TILNEY ELIZABETH A' 279 | p139 280 | aS'MARTIN AMANDA K' 281 | p140 282 | aS'BUY RICHARD B' 283 | p141 284 | aS'GRAMM WENDY L' 285 | p142 286 | aS'CAUSEY RICHARD A' 287 | p143 288 | aS'TAYLOR MITCHELL S' 289 | p144 290 | aS'DONAHUE JR JEFFREY M' 291 | p145 292 | aS'GLISAN JR BEN F' 293 | p146 294 | a. -------------------------------------------------------------------------------- /tools/startup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | print 4 | print "checking for nltk" 5 | try: 6 | import nltk 7 | except ImportError: 8 | print "you should install nltk before continuing" 9 | 10 | print "checking for numpy" 11 | try: 12 | import numpy 13 | except ImportError: 14 | print "you should install numpy before continuing" 15 | 16 | print "checking for sklearn" 17 | try: 18 | import sklearn 19 | except: 20 | print "you should install sklearn before continuing" 21 | 22 | print 23 | print "downloading the Enron dataset (this may take a while)" 24 | print "to check on progress, you can cd up one level, then execute " 25 | print "Enron dataset should be last item on the list, along with its current size" 26 | print "download will complete at about 423 MB" 27 | import urllib 28 | url = "https://www.cs.cmu.edu/~./enron/enron_mail_20150507.tgz" 29 | urllib.urlretrieve(url, filename="../enron_mail_20150507.tgz") 30 | print "download complete!" 31 | 32 | 33 | print 34 | print "unzipping Enron dataset (this may take a while)" 35 | import tarfile 36 | import os 37 | os.chdir("..") 38 | tfile = tarfile.open("enron_mail_20150507.tgz", "r:gz") 39 | tfile.extractall(".") 40 | 41 | print "you're ready to go!" 42 | --------------------------------------------------------------------------------