<jupyter_start><jupyter_text>Q1  Summarize for us the goal of this project and how machine learning is useful in trying to accomplish it. As part of your answer, give some background on the dataset and how it can be used to answer the project question. Were there any outliers in the data when you got it, and how did you handle those? >  Introduction to Enron Dataset>Enron was one of the largest companies in the United States resulting into bankruptcy due to corporate fraud  which is one of the largest bankruptcies in U.S. History.In the resulting Federal investigation, there was a significant amount of typically confidential information entered into public record, including tens of thousands of emails and detailed financial data for top executives.>The main goal is identifying person of interests (POI's) using supervised machine learning algorithms for prediction.This model will classify weather the individual is a POI or notPOI by  using rest of the features available and various machine learning algorithms.<jupyter_code>#!/usr/bin/python

import sys
import pickle
sys.path.append("../tools/")

from feature_format import featureFormat, targetFeatureSplit
from tester import dump_classifier_and_data

### Task 1: Select what features you'll use.
### features_list is a list of strings, each of which is a feature name.
### The first feature must be "poi".
financial_features = ['salary', 'deferral_payments', 'total_payments',
'loan_advances', 'bonus', 'restricted_stock_deferred', 'deferred_income',
'total_stock_value', 'expenses', 'exercised_stock_options', 'other',
'long_term_incentive', 'restricted_stock', 'director_fees']#(all units are in US dollars)

email_features = ['to_messages', 'from_poi_to_this_person', 'email_address',
'from_messages', 'from_this_person_to_poi', 'shared_receipt_with_poi']
#(units are generally number of emails messages;
#notable exception is ‘email_address’, which is a text string)

poi_label = ['poi']# (boolean, represented as integer)


features_list = poi_label + financial_features + email_features

### Load the dictionary containing the dataset
with open("final_project_dataset.pkl", "r") as data_file:
    data_dict = pickle.load(data_file)







import pandas as pd
import numpy as np
enron= pd.DataFrame.from_dict(data_dict, orient = 'index')
print"total poi in dataset:", sum(enron['poi']==1)

#enron.describe()
#We can see all the null values for each index

enron = enron.replace('NaN', np.nan)
print(enron.info())
enron.describe()<jupyter_output><class 'pandas.core.frame.DataFrame'>
Index: 146 entries, <NAME> to YEAP SOON
Data columns (total 21 columns):
salary                       95 non-null float64
to_messages                  86 non-null float64
deferral_payments            39 non-null float64
total_payments               125 non-null float64
exercised_stock_options      102 non-null float64
bonus                        82 non-null float64
restricted_stock             110 non-null float64
shared_receipt_with_poi      86 non-null float64
restricted_stock_deferred    18 non-null float64
total_stock_value            126 non-null float64
expenses                     95 non-null float64
loan_advances                4 non-null float64
from_messages                86 non-null float64
other                        93 non-null float64
from_this_person_to_poi      86 non-null float64
poi                          146 non-null bool
director_fees                17 non-null float64
deferred_income              49 non-null float[...]<jupyter_text>From th above information about dataset we can conlcude that any point with less than 73 non-null  will be having more than 50%of missing data.And the features seem to be in more than 50% null group|Feature|No.of non-null out of 146||---|---||deferral_payments        |    39 non-null| |restricted_stock_deferred   | 18 non-null||loan_advances          |      4 non-null||director_fees            |    17 non-null ||deferred_income          |    49 non-null ||long_term_incentive      |    66 non-null |<jupyter_code>#now checking these features for poi to conclude how much of data is missing for a poi .
missing = ['loan_advances', 'director_fees', 'restricted_stock_deferred',\
           'deferral_payments', 'deferred_income', 'long_term_incentive']
enron_poi=enron[enron['poi']==1][missing]
enron_poi.info()
# its better to remove these with less non null values
removing = ['loan_advances', 'director_fees', 'restricted_stock_deferred']
for x in removing:
    if x in features_list:
        features_list.remove(x)
features_list
### Task 2: Remove outliers
#visualising the outlier

import matplotlib.pyplot

e = enron[(enron.total_payments != np.nan) & (enron.total_stock_value != np.nan)]

matplotlib.pyplot.scatter(x="total_payments", y="total_stock_value", data=e)

matplotlib.pyplot.xlabel("total_payments")
matplotlib.pyplot.ylabel("total_stock_value")
matplotlib.pyplot.show()
# removing outlier 
enron.total_payments.idxmax()

#droping total it must be a spreadsheet mistake
enron=enron.drop("TOTAL")
#data_dict.pop( 'TOTAL', 0 )

e = enron[(enron.total_payments != np.nan) & (enron.total_stock_value != np.nan)]

matplotlib.pyplot.scatter(x="total_payments", y="total_stock_value", data=e)
matplotlib.pyplot.xlabel("total_payments")
matplotlib.pyplot.ylabel("total_stock_value")
matplotlib.pyplot.show()
enron.total_payments.idxmax()<jupyter_output><empty_output><jupyter_text>LAY KENNETH L  is the next outlier but it is a valid point<jupyter_code>#After observing insiderpay.pdf file, I got to know it is not a person so we have to remove THE TRAVEL AGENCY IN THE PARK.
enron=enron.drop("THE TRAVEL AGENCY IN THE PARK")

enron[enron[financial_features].isnull().all(axis=1)].index
#There is 1 person without any financial data that will also need to be removed.
enron=enron.drop( 'LOCKHART EUGENE E')
enron = enron.replace(np.nan, 'NaN') # since to use tester code, i needed to convert back to "NaN"
data_dict = enron[features_list].to_dict(orient = 'index')
from tester import test_classifier
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
if "email_address" in features_list:
    features_list.remove("email_address")
    feat=features_list
else :
    feat=features_list
test_classifier(clf, data_dict, feat)<jupyter_output>DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
            max_features=None, max_leaf_nodes=None, min_samples_leaf=1,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            presort=False, random_state=None, splitter='best')
	Accuracy: 0.79727	Precision: 0.22763	Recall: 0.21750	F1: 0.22245	F2: 0.21945
	Total predictions: 15000	True positives:  435	False positives: 1476	False negatives: 1565	True negatives: 11524<jupyter_text>Q2 What features did you end up using in your POI identifier, and what selection process did you use to pick them? Did you have to do any scaling? Why or why not? As part of the assignment, you should attempt to engineer your own feature that does not come ready-made in the dataset -- explain what feature you tried to make, and the rationale behind it. (You do not necessarily have to use it in the final analysis, only engineer and test it.) In your feature selection step, if you used an algorithm like a decision tree, please also give the feature importances of the features that you use, and if you used an automated feature selection function like SelectKBest, please report the feature scores and reasons for your choice of parameter values.<jupyter_code>### Task 3: Create new feature(s)
### Store to my_dataset for easy export below.
my_dataset = data_dict


#Adding three new features
for key, value in my_dataset.items():
    if value['from_messages'] == 'NaN' or value['from_this_person_to_poi'] == 'NaN':
        value['person_to_poi/total_msgs'] = 0.0
    else:
        value['person_to_poi/total_msgs'] = value['from_this_person_to_poi'] / (1.0*value['from_messages'])

    if value['to_messages'] == 'NaN' or value['from_poi_to_this_person'] == 'NaN':
        value['poi_to_person/to_msgs'] = 0.0
    else:
        value['poi_to_person/to_msgs'] = value['from_poi_to_this_person'] / (1.0*value['to_messages'])
    if value['shared_receipt_with_poi'] == 'NaN' or value['from_poi_to_this_person'] == 'NaN' \
        or value['from_this_person_to_poi'] == 'NaN':
        value['total_poi_interaction'] = 0.0
    else:
        value['total_poi_interaction'] = value['shared_receipt_with_poi'] + \
                                      value['from_this_person_to_poi'] + \
                                      value['from_poi_to_this_person'] 
features_new_list=features_list+['person_to_poi/total_msgs','poi_to_person/to_msgs','total_poi_interaction']<jupyter_output><empty_output><jupyter_text>I tried to make features of ratios : $$\frac{from-this-person-to-poi}{from-messages}$$$$\frac{from-poi-to-this-person}{from-messages}$$ and$$total-poi-interaction = (shared-receipt-with-poi) + (from-this-person-to-poi) + (from-poi-to-this-person) $$  These features were selected since , a poi is often tend to be in contact of another poi.Which may lead to higher importance of features.And the total  interaction with poi gives a higher chance of finding a poi<jupyter_code>#Selectkbest used to rank the features
data = featureFormat(my_dataset, features_new_list, sort_keys = True)
labels, features = targetFeatureSplit(data)
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif, chi2
selector = SelectKBest(k='all').fit(features, labels)
results = pd.DataFrame(selector.scores_,
                          index=features_new_list[1:])
results.columns = ['Importances']
results = results.sort(['Importances'], ascending=False)
results

from tester import test_classifier
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
if "email_address" in features_new_list:
    features_new_list.remove("email_address")
    feat=features_new_list
else :
    feat=features_list
test_classifier(clf, my_dataset, features_new_list)<jupyter_output>DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
            max_features=None, max_leaf_nodes=None, min_samples_leaf=1,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            presort=False, random_state=None, splitter='best')
	Accuracy: 0.81740	Precision: 0.31291	Recall: 0.30900	F1: 0.31094	F2: 0.30977
	Total predictions: 15000	True positives:  618	False positives: 1357	False negatives: 1382	True negatives: 11643<jupyter_text>- We can clearly see that the performance values are increasing which indicates these would be a good predictor  -  From the above we can observe the ranking of various features, on adding these features their is a certain increase in accuracy, precision and recall - SelectKBest was used to rank and select the features . - GridSearchCV was used to select the appropriate value of k in SelectKBest to give the maximum F1 score for the classifier.  Q3**What algorithm did you end up using? What other one(s) did you try? How did model performance differ between algorithms?**<jupyter_code>### Task 4: Try a varity of classifiers
### Please name your classifier clf for easy export below.
### Note that if you want to do PCA or other multi-stage operations,
### you'll need to use Pipelines.
# Provided to give you a starting point. Try a variety of classifiers.
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif, chi2
from sklearn.feature_selection import RFE 
from sklearn import tree
from sklearn.svm import SVC, SVR
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.cross_validation import train_test_split, StratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.grid_search import GridSearchCV
from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler
#from sklearn.model_selection import RandomizedSearchCV

parameters={}
parameters["DecisionTreeClassifier"] = [{'min_samples_split': [2,3], 'criterion': [ 'entropy']}]
parameters["GaussianNB"] = [{ 'selection__k':[9,10,11], 'pca__n_components': [2,3,4,5] }]

parameters["SVC"]  = [{'selection__k':[11], 'svc__kernel': ['rbf',"sigmoid"], 'svc__C': [x/1.0 for x in range(1, 100,10)]
                        ,'svc__gamma':[0.1**(x) for x in range(1,9)]}]
parameters["AdaBoostClassifier"] = [{ "base_estimator":[DecisionTreeClassifier(min_samples_split= 2, criterion= 'entropy')],'learning_rate' : [x/30.0 for x in range(1, 30)],'n_estimators' : range(1,100,20),\
                    'algorithm': ['SAMME','SAMME.R'] }]
parameters["KNeighborsClassifier"] = [{'selection__k': [10,11], "knn__p":range(3,4),'pca__n_components': [2,3,4,5],"knn__n_neighbors": range(1,10), 'knn__weights': ['uniform','distance'] ,'knn__algorithm': ['ball_tree','kd_tree','brute']}]

pipe={}
pipe["DecisionTreeClassifier"] = DecisionTreeClassifier()
pipe["GaussianNB"] = Pipeline([('scaler', MinMaxScaler()),('selection', SelectKBest()),('pca', PCA()),('naive_bayes', GaussianNB())])
pipe["SVC"] =Pipeline([('selection', SelectKBest()),('scaler', StandardScaler())
                       ,('svc', SVC())])
pipe["AdaBoostClassifier"] =  AdaBoostClassifier()
pipe["KNeighborsClassifier"] = Pipeline([('selection',SelectKBest()),
                                         ('pca', PCA()),('knn', KNeighborsClassifier())])



### Task 5: Tune your classifier to achieve better than .3 precision and recall 
### using our testing script. Check the tester.py script in the final project
### folder for details on the evaluation method, especially the test_classifier
### function. Because of the small size of the dataset, the script uses
### stratified shuffle split cross validation. For more info: 
### http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html
data = featureFormat(my_dataset, features_new_list, sort_keys = True)
labels, features = targetFeatureSplit(data)
# Example starting point. Try investigating other evaluation techniques!
from sklearn.cross_validation import train_test_split
features_train, features_test, labels_train, labels_test = \
    train_test_split(features, labels, test_size=0.3, random_state=42)
clf=DecisionTreeClassifier()
clf_name = clf.__class__.__name__
grid = GridSearchCV(estimator =pipe[clf_name],param_grid = parameters[clf_name],\
                                cv = StratifiedKFold(labels_train, n_folds = 6) \
                            ,n_jobs = -1,scoring = 'f1')
grid.fit(features_train, labels_train)
print clf_name 
test_classifier(grid.best_estimator_, my_dataset, features_new_list)
clf=SVC()
clf_name = clf.__class__.__name__
grid = GridSearchCV(estimator =pipe[clf_name],param_grid = parameters[clf_name],\
                                cv = StratifiedKFold(labels_train, n_folds = 6) \
                            ,n_jobs = -1,scoring = 'f1')
grid.fit(features_train, labels_train)
print clf_name 
test_classifier(grid.best_estimator_, my_dataset, features_new_list)
clf=AdaBoostClassifier()
clf_name = clf.__class__.__name__
grid = GridSearchCV(estimator =pipe[clf_name],param_grid = parameters[clf_name],\
                                cv = StratifiedKFold(labels_train, n_folds = 6) \
                            ,n_jobs = -1,scoring = 'f1')
grid.fit(features_train, labels_train)
print clf_name 
test_classifier(grid.best_estimator_, my_dataset, features_new_list)
clf=GaussianNB()
clf_name = clf.__class__.__name__
grid = GridSearchCV(estimator =pipe[clf_name],param_grid = parameters[clf_name],\
                                cv = StratifiedKFold(labels_train, n_folds = 6) \
                            ,n_jobs = -1,scoring = 'f1')
grid.fit(features_train, labels_train)
print clf_name 
test_classifier(grid.best_estimator_, my_dataset, features_new_list)
clf=KNeighborsClassifier()
clf_name = clf.__class__.__name__
grid = GridSearchCV(estimator =pipe[clf_name],param_grid = parameters[clf_name],\
                                cv = StratifiedKFold(labels_train, n_folds = 6) \
                            ,n_jobs = -1,scoring = 'f1')
grid.fit(features_train, labels_train)
print clf_name 
test_classifier(grid.best_estimator_, my_dataset, features_new_list)<jupyter_output>KNeighborsClassifier
Pipeline(steps=[('selection', SelectKBest(k=10, score_func=<function f_classif at 0x000000000C220B38>)), ('pca', PCA(copy=True, n_components=5, whiten=False)), ('knn', KNeighborsClassifier(algorithm='ball_tree', leaf_size=30, metric='minkowski',
           metric_params=None, n_jobs=1, n_neighbors=3, p=3,
           weights='uniform'))])
	Accuracy: 0.87487	Precision: 0.55606	Recall: 0.30500	F1: 0.39393	F2: 0.33528
	Total predictions: 15000	True positives:  610	False positives:  487	False negatives: 1390	True negatives: 12513<jupyter_text>Several different classifiers are deployed:- gaussian naive bayes- k-nearest neighbors- support vector machine- gaussianNB- adaboost  There was not much change in accuracy.   Highest accuracy was for Knearest,Highest precision is for Knearest,Highest recall is for decision tree ,I ended up with really high precision scores for k-nearest neighbors. Unfortunately the recall scores for these weren't as high andalmost all were equal.  The F1 score was highest for the KNN classifier.<jupyter_code>### Task 6: Dump your classifier, dataset, and features_list so anyone can
### check your results. You do not need to change anything below, but make sure
### that the version of poi_id.py that you submit can be run on its own and
### generates the necessary .pkl files for validating your results.

dump_classifier_and_data(clf, my_dataset, features_list)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0971099546008194, 'fraction_numerical': 0.02137083379470712, 'mean_word_length': 4.60093023255814, 'pattern_counts': {'":': 3, '<': 28, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 9, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '266912', 'license': 'MIT', 'n_tokens_mistral': 5897, 'n_tokens_neox': 5460, 'n_words': 1642, 'path': 'P5 machine_learning/report_p5.ipynb', 'repo_name': 'gangadhara691/test', 'size': '18071'}