1+ # -*- coding: utf-8 -*-
2+ """
3+ Spyder Editor
4+
5+ This is my submission to Machine Learning Course on Coursera.
6+ This containts heavily sample code provided in the course.
7+ I changed the dataset, test ratio 0.2, and max_depth = 3
8+ I also have to use write_pdf instead of create_png to create output
9+ Input file used:
10+
11+ """
12+
13+ # -*- coding: utf-8 -*-
14+
15+ from pandas import Series , DataFrame
16+ import pandas as pd
17+ import numpy as np
18+ import os
19+ import matplotlib .pylab as plt
20+ from sklearn .cross_validation import train_test_split
21+ from sklearn .tree import DecisionTreeClassifier
22+ from sklearn .metrics import classification_report
23+ import sklearn .metrics
24+
25+ os .chdir ("C:\Machine_learning" )
26+
27+ """
28+ Data Engineering and Analysis
29+ """
30+ #Load the dataset
31+
32+ AH_data = pd .read_csv ("addhealth_pds.csv" )
33+ #read data
34+ data_clean = AH_data .dropna ()
35+ #drop all NA in dataset
36+
37+ #data_clean.dtypes
38+
39+ # data_clean.describe()
40+ #examine and summary data
41+
42+ """
43+ Modeling and Prediction
44+ """
45+ #Split into training and testing sets
46+
47+ #predictors = data_clean[['BIO_SEX','CORE1','CORE2','HIEDBLK',
48+ #'age','H1GI1M','H1GI1Y','H1GI2','H1GI6E','H1GI7F',
49+ #'H1GI14','SMP07','CLUSTER1','CLUSTER2','H2GI1M']]
50+
51+ predictors = data_clean [['CLUSTER2' ,'CLUSTER1' ]]
52+
53+
54+ #predictors.dtypes
55+
56+ #define many data fields as predictors,
57+
58+ targets = data_clean .SCH_YR
59+ # and one for target (dependent variables)
60+
61+ pred_train , pred_test , tar_train , tar_test = train_test_split (predictors ,
62+ targets , test_size = .2 )
63+ # with the order of train-test and pred-target, this train_test_spit()
64+ # function cut predictior set and target set into two: train subset and test subset.
65+ # test_size determine the relative size of test subset
66+
67+ pred_train .shape
68+ pred_test .shape
69+ tar_train .shape
70+ tar_test .shape
71+ #check the shape (what it means??) of four subset created
72+
73+ #Build model on training data
74+ classifier = DecisionTreeClassifier ()
75+ classifier = classifier .fit (pred_train ,tar_train )
76+ #make predictions
77+ predictions = classifier .predict (pred_test )
78+
79+ sklearn .metrics .confusion_matrix (tar_test ,predictions )
80+ sklearn .metrics .accuracy_score (tar_test , predictions )
81+
82+ #Displaying the decision tree
83+ from sklearn import tree
84+ #from StringIO import StringIO
85+ from io import StringIO
86+ #from StringIO import StringIO
87+ from IPython .display import Image
88+ out = StringIO ()
89+ tree .export_graphviz (classifier , out_file = out ,max_depth = 3 )
90+
91+
92+
93+ import pydotplus
94+ graph = pydotplus .graph_from_dot_data (out .getvalue ())
95+ Image (graph .write_pdf ('love2.pdf' ))
0 commit comments