In [1]:
from sklearn.feature_selection import VarianceThreshold
from sklearn.feature_selection import SelectPercentile

In [4]:
%matplotlib inline
#http://stackoverflow.com/questions/22409855/randomforestclassifier-vs-extratreesclassifier-in-scikit-learn

In [5]:
print(__doc__)

import numpy as np
import matplotlib.pyplot as plt

from sklearn.datasets import make_classification
from sklearn.ensemble import ExtraTreesClassifier

# Build a classification task using 3 informative features
X, y = make_classification(n_samples=1000,
                           n_features=10,
                           n_informative=3,
                           n_redundant=0,
                           n_repeated=0,
                           n_classes=2,
                           random_state=0,
                           shuffle=False)

# Build a forest and compute the feature importances
forest = ExtraTreesClassifier(n_estimators=250,
                              random_state=0)

forest.fit(X, y)
importances = forest.feature_importances_
# Standard deviations for plotting error bars
# Pull out the feature importances of each tree that was created into list of arrays
# Get the standard deviation of each column with 
# Axis 0: by columns
std = np.std([tree.feature_importances_ for tree in forest.estimators_],
             axis=0)
# np.argsort() : Sort the resulting importances, ascending order
# [::-1]: Reverse the order, best to worst
indices = np.argsort(importances)[::-1]

# Print the feature ranking
print("Feature ranking:")

for f in range(10):
    print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))

# Plot the feature importances of the forest
plt.figure()
plt.title("Feature importances")
plt.bar(range(10), importances[indices],
       color="r", yerr=std[indices], align="center")
plt.xticks(range(10), indices)
plt.xlim([-1, 10])
plt.show()


Automatically created module for IPython interactive environment
Feature ranking:
1. feature 0 (0.250398)
2. feature 1 (0.232397)
3. feature 2 (0.148898)
4. feature 3 (0.055363)
5. feature 8 (0.054010)
6. feature 5 (0.053878)
7. feature 6 (0.052583)
8. feature 9 (0.051020)
9. feature 7 (0.050963)
10. feature 4 (0.050489)

In [6]:
indices


Out[6]:
array([0, 1, 2, 3, 8, 5, 6, 9, 7, 4], dtype=int64)

In [7]:
importances


Out[7]:
array([ 0.25039843,  0.23239744,  0.14889819,  0.05536337,  0.05048869,
        0.05387803,  0.05258284,  0.05096332,  0.05401004,  0.05101965])

In [8]:
np.argsort(importances)


Out[8]:
array([4, 7, 9, 6, 5, 8, 3, 2, 1, 0], dtype=int64)

In [10]:
np.argsort(importances)[::-1]


Out[10]:
array([0, 1, 2, 3, 8, 5, 6, 9, 7, 4], dtype=int64)

In [20]:


In [29]:
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
print X.shape
(150, 4)
clf = ExtraTreesClassifier()
# Fit(): fit the model.
# Transform(): Reduce X to its most important features.
X_new = clf.fit(X, y).transform(X, threshold='mean')
print clf.feature_importances_  

print X_new.shape


(150L, 4L)
[ 0.13887153  0.06444076  0.3705303   0.42615741]
(150L, 2L)

In [142]:
import pickle
data_dict = pickle.load(open("../ud120-projects/final_project/final_project_dataset.pkl", "r") )

In [143]:
import pandas as pd
df = pd.DataFrame.from_dict(data_dict, orient='index')

In [155]:
df = df.drop(['email_address'], axis=1)

In [156]:
[suspect for suspect in df.index if " " not in suspect]


Out[156]:
['TOTAL']

In [157]:
df = df.drop('TOTAL', axis=0)

In [157]:


In [158]:
labels = df.poi
features = df.drop(['poi'], axis=1)

In [159]:
print labels.shape
print features.shape


(145,)
(145, 19)

In [206]:
from sklearn.cross_validation import train_test_split
features_train, features_test, labels_train, labels_test = train_test_split(features,
                                                                           labels,
                                                                           test_size=0.2)

In [207]:
pd.DataFrame(features_train, columns=features.columns)
sum(labels_train)


Out[207]:
16

In [208]:
from sklearn.cross_validation import StratifiedKFold

In [298]:
# Create a temporary stratified 5-fold list of indices for train/test splitting
k_temp = StratifiedKFold(labels, n_folds=5, shuffle=True)

In [299]:
for train, test in k_temp:
    # iterate through and overwrite.
    # Only one stratified 80% train, 20% split is needed to 
    # create an out-of-sample test set.
    train_ind = train
    test_ind = test

In [338]:
print test_ind
print train_ind


[  9  21  26  27  28  29  32  39  44  45  52  77  80  81  84  97 107 108
 109 111 115 116 123 129 130 134 138 143]
[  0   1   2   3   4   5   6   7   8  10  11  12  13  14  15  16  17  18
  19  20  22  23  24  25  30  31  33  34  35  36  37  38  40  41  42  43
  46  47  48  49  50  51  53  54  55  56  57  58  59  60  61  62  63  64
  65  66  67  68  69  70  71  72  73  74  75  76  78  79  82  83  85  86
  87  88  89  90  91  92  93  94  95  96  98  99 100 101 102 103 104 105
 106 110 112 113 114 117 118 119 120 121 122 124 125 126 127 128 131 132
 133 135 136 137 139 140 141 142 144]

In [395]:
# Use the indices to filter a training and a testing set.
train_df = df.iloc[train_ind]
holdout_df = df.iloc[test_ind]

In [396]:
# Verify the shape and stratified distribution of boolean y-labels.
print train_df.shape
print holdout_df.shape
print sum(train_df.poi)
print sum(holdout_df.poi)


(117, 20)
(28, 20)
15
3

In [ ]:


In [399]:
train_df = train_df.replace('NaN', np.nan)

In [ ]:
#train_df = train_df.apply(lambda x: x.fillna(x.median()), axis=0)

In [ ]:


In [401]:
train_df[train_df.poi==True].salary


Out[401]:
BELDEN TIMOTHY N         213999
BOWEN JR RAYMOND M       278601
CALGER CHRISTOPHER F     240189
CAUSEY RICHARD A         415189
DELAINEY DAVID W         365163
FASTOW ANDREW S          440698
GLISAN JR BEN F          274975
HANNON KEVIN P           243293
HIRKO JOSEPH                NaN
KOENIG MARK E            309946
LAY KENNETH L           1072321
RICE KENNETH D           420636
RIEKER PAULA H           249201
SHELBY REX               211844
SKILLING JEFFREY K      1111258
Name: salary, dtype: float64

In [410]:
ax = train_df.plot(kind='scatter', x='shared_receipt_with_poi', y='from_this_person_to_poi', 
              color='DarkGreen', label='not poi')
train_df[train_df.poi==True].plot(kind='scatter', x='shared_receipt_with_poi', y='from_this_person_to_poi', 
                                  color='DarkBlue', label='poi', ax=ax)


Out[410]:
<matplotlib.axes._subplots.AxesSubplot at 0x1b4e5160>

In [416]:



<class 'pandas.core.frame.DataFrame'>
Index: 117 entries, ALLEN PHILLIP K to YEAP SOON
Data columns (total 20 columns):
salary                       76 non-null float64
to_messages                  70 non-null float64
deferral_payments            33 non-null float64
total_payments               102 non-null float64
exercised_stock_options      84 non-null float64
bonus                        65 non-null float64
restricted_stock             88 non-null float64
shared_receipt_with_poi      70 non-null float64
restricted_stock_deferred    14 non-null float64
total_stock_value            101 non-null float64
expenses                     78 non-null float64
loan_advances                3 non-null float64
from_messages                70 non-null float64
other                        76 non-null float64
from_this_person_to_poi      70 non-null float64
poi                          117 non-null bool
director_fees                14 non-null float64
deferred_income              40 non-null float64
long_term_incentive          53 non-null float64
from_poi_to_this_person      70 non-null float64
dtypes: bool(1), float64(19)

In [405]:
train_df.columns


Out[405]:
Index([u'salary', u'to_messages', u'deferral_payments', u'total_payments', u'exercised_stock_options', u'bonus', u'restricted_stock', u'shared_receipt_with_poi', u'restricted_stock_deferred', u'total_stock_value', u'expenses', u'loan_advances', u'from_messages', u'other', u'from_this_person_to_poi', u'poi', u'director_fees', u'deferred_income', u'long_term_incentive', u'from_poi_to_this_person'], dtype='object')

In [357]:



Out[357]:
salary to_messages deferral_payments total_payments exercised_stock_options bonus restricted_stock shared_receipt_with_poi restricted_stock_deferred total_stock_value expenses loan_advances from_messages other from_this_person_to_poi poi director_fees deferred_income long_term_incentive from_poi_to_this_person
ALLEN PHILLIP K 201955 2902 2869717 4484442 1729541 4175000 126027 1407 -126027 1729541 13868 NaN 2195 152 65 False NaN -3081055 304805 47
BADUM JAMES P NaN NaN 178980 182466 257817 NaN NaN NaN NaN 257817 3486 NaN NaN NaN NaN False NaN NaN NaN NaN
BANNANTINE JAMES M 477 566 NaN 916197 4046157 NaN 1757552 465 -560222 5243487 56301 NaN 29 864523 0 False NaN -5104 NaN 39
BAXTER JOHN C 267102 NaN 1295738 5634343 6680544 1200000 3942714 NaN NaN 10623258 11200 NaN NaN 2660303 NaN False NaN -1386055 1586055 NaN
BAY FRANKLIN R 239671 NaN 260455 827696 NaN 400000 145796 NaN -82782 63014 129142 NaN NaN 69 NaN False NaN -201641 NaN NaN
BAZELIDES PHILIP J 80818 NaN 684694 860136 1599641 NaN NaN NaN NaN 1599641 NaN NaN NaN 874 NaN False NaN NaN 93750 NaN
BECK SALLY W 231330 7315 NaN 969068 NaN 700000 126027 2639 NaN 126027 37172 NaN 4343 566 386 False NaN NaN NaN 144
BELDEN TIMOTHY N 213999 7991 2144013 5501630 953136 5249999 157569 5521 NaN 1110705 17355 NaN 484 210698 108 True NaN -2334434 NaN 228
BELFER ROBERT NaN NaN -102500 102500 3285 NaN NaN NaN 44093 -44093 NaN NaN NaN NaN NaN False 3285 NaN NaN NaN
BERBERIAN DAVID 216582 NaN NaN 228474 1624396 NaN 869220 NaN NaN 2493616 11892 NaN NaN NaN NaN False NaN NaN NaN NaN
BERGSIEKER RICHARD P 187922 383 NaN 618850 NaN 250000 659249 233 NaN 659249 59175 NaN 59 427316 0 False NaN -485813 180250 4
BHATNAGAR SANJAY NaN 523 NaN 15456290 2604490 NaN -2604490 463 15456290 NaN NaN NaN 29 137864 1 False 137864 NaN NaN 0
BIBI PHILIPPE A 213625 1607 NaN 2047593 1465734 1000000 378082 1336 NaN 1843816 38559 NaN 40 425688 8 False NaN NaN 369721 23
BLACHMAN JEREMY M 248546 2475 NaN 2014835 765313 850000 189041 2326 NaN 954354 84208 NaN 14 272 2 False NaN NaN 831809 25
BLAKE JR. NORMAN P NaN NaN NaN 1279 NaN NaN NaN NaN NaN NaN 1279 NaN NaN NaN NaN False 113784 -113784 NaN NaN
BOWEN JR RAYMOND M 278601 1858 NaN 2669589 NaN 1350000 252055 1593 NaN 252055 65907 NaN 27 1621 15 True NaN -833 974293 140
BROWN MICHAEL NaN 1486 NaN 49288 NaN NaN NaN 761 NaN NaN 49288 NaN 41 NaN 1 False NaN NaN NaN 13
BUCHANAN HAROLD G 248017 1088 NaN 1054637 825464 500000 189041 23 NaN 1014505 600 NaN 125 1215 0 False NaN NaN 304805 0
BUTTS ROBERT H 261516 NaN NaN 1271582 NaN 750000 417619 NaN NaN 417619 9410 NaN NaN 150656 NaN False NaN -75000 175000 NaN
BUY RICHARD B 330546 3523 649584 2355702 2542813 900000 901657 2333 NaN 3444470 NaN NaN 1053 400572 71 False NaN -694862 769862 156
CALGER CHRISTOPHER F 240189 2598 NaN 1639297 NaN 1250000 126027 2188 NaN 126027 35818 NaN 144 486 25 True NaN -262500 375304 199
CARTER REBECCA C 261809 312 NaN 477557 NaN 300000 307301 196 -307301 NaN NaN NaN 15 540 7 False NaN -159792 75000 29
CAUSEY RICHARD A 415189 1892 NaN 1868758 NaN 1000000 2502063 1585 NaN 2502063 30674 NaN 49 307895 12 True NaN -235000 350000 58
CHAN RONNIE NaN NaN NaN NaN NaN NaN 32460 NaN -32460 NaN NaN NaN NaN NaN NaN False 98784 -98784 NaN NaN
CHRISTODOULOU DIOMEDES NaN NaN NaN NaN 5127155 NaN 950730 NaN NaN 6077885 NaN NaN NaN NaN NaN False NaN NaN NaN NaN
CLINE KENNETH W NaN NaN NaN NaN NaN NaN 662086 NaN -472568 189518 NaN NaN NaN NaN NaN False NaN NaN NaN NaN
COLWELL WESLEY 288542 1758 27610 1490344 NaN 1200000 698242 1132 NaN 698242 16514 NaN 40 101740 11 True NaN -144062 NaN 240
CORDES WILLIAM R NaN 764 NaN NaN 651850 NaN 386335 58 NaN 1038185 NaN NaN 12 NaN 0 False NaN NaN NaN 10
COX DAVID 314288 102 NaN 1101393 117551 800000 378082 71 NaN 495633 27861 NaN 33 494 4 False NaN -41250 NaN 0
CUMBERLAND MICHAEL S 184899 NaN NaN 807956 NaN 325000 207940 NaN NaN 207940 22344 NaN NaN 713 NaN False NaN NaN 275000 NaN
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
SCRIMSHAW MATTHEW NaN NaN NaN NaN 759557 NaN NaN NaN NaN 759557 NaN NaN NaN NaN NaN False NaN NaN NaN NaN
SHANKMAN JEFFREY A 304110 3221 NaN 3038702 1441898 2000000 630137 1730 NaN 2072035 178979 NaN 2681 1191 83 False NaN NaN 554422 94
SHAPIRO RICHARD S 269076 15149 NaN 1057548 607837 650000 379164 4527 NaN 987001 137767 NaN 1215 705 65 False NaN NaN NaN 74
SHARP VICTORIA T 248146 3136 187469 1576511 281073 600000 213063 2477 NaN 494136 116337 NaN 136 2401 6 False NaN NaN 422158 24
SHELBY REX 211844 225 NaN 2003885 1624396 200000 869220 91 NaN 2493616 22884 NaN 39 1573324 14 True NaN -4167 NaN 13
SHERRICK JEFFREY B NaN 613 NaN NaN 1426469 NaN 405999 583 NaN 1832468 NaN NaN 25 NaN 18 False NaN NaN NaN 39
SHERRIFF JOHN R 428780 3187 NaN 4335388 1835558 1500000 1293424 2103 NaN 3128982 NaN NaN 92 1852186 23 False NaN NaN 554422 28
SKILLING JEFFREY K 1111258 3627 NaN 8682716 19250000 5600000 6843672 2042 NaN 26093672 29336 NaN 108 22122 30 True NaN NaN 1920000 88
STABLER FRANK 239502 NaN NaN 1112087 NaN 500000 511734 NaN NaN 511734 16514 NaN NaN 356071 NaN False NaN NaN NaN NaN
SULLIVAN-SHAKLOVITZ COLLEEN 162779 NaN 181993 999356 1362375 100000 NaN NaN NaN 1362375 NaN NaN NaN 162 NaN False NaN NaN 554422 NaN
SUNDE MARTIN 257486 2647 NaN 1545059 NaN 700000 698920 2565 NaN 698920 NaN NaN 38 111122 13 False NaN NaN 476451 37
TAYLOR MITCHELL S 265214 533 227449 1092663 3181250 600000 563798 300 NaN 3745048 NaN NaN 29 NaN 0 False NaN NaN NaN 0
THE TRAVEL AGENCY IN THE PARK NaN NaN NaN 362096 NaN NaN NaN NaN NaN NaN NaN NaN NaN 362096 NaN False NaN NaN NaN NaN
THORN TERENCE H 222093 266 16586 911453 4452476 NaN 365320 73 NaN 4817796 46145 NaN 41 426629 0 False NaN NaN 200000 0
TILNEY ELIZABETH A 247338 460 NaN 399393 591250 300000 576792 379 NaN 1168042 NaN NaN 19 152055 11 False NaN -575000 275000 10
UMANOFF ADAM S 288589 111 NaN 1130461 NaN 788750 NaN 41 NaN NaN 53122 NaN 18 NaN 0 False NaN NaN NaN 12
URQUHART JOHN A NaN NaN NaN 228656 NaN NaN NaN NaN NaN NaN 228656 NaN NaN NaN NaN False 36666 -36666 NaN NaN
WAKEHAM JOHN NaN NaN NaN 213071 NaN NaN NaN NaN NaN NaN 103773 NaN NaN NaN NaN False 109298 NaN NaN NaN
WALLS JR ROBERT H 357091 671 NaN 1798780 4346544 850000 1552453 215 NaN 5898997 50936 NaN 146 2 0 False NaN NaN 540751 17
WALTERS GARETH W NaN NaN 53625 87410 1030329 NaN NaN NaN NaN 1030329 33785 NaN NaN NaN NaN False NaN NaN NaN NaN
WASAFF GEORGE 259996 400 831299 1034395 1668260 325000 388167 337 NaN 2056427 NaN NaN 30 1425 7 False NaN -583325 200000 22
WESTFAHL RICHARD K 63744 NaN NaN 762135 NaN NaN 384930 NaN NaN 384930 51870 NaN NaN 401130 NaN False NaN -10800 256191 NaN
WHALEY DAVID A NaN NaN NaN NaN 98718 NaN NaN NaN NaN 98718 NaN NaN NaN NaN NaN False NaN NaN NaN NaN
WHALLEY LAWRENCE G 510364 6019 NaN 4677574 3282960 3000000 2796177 3920 NaN 6079137 57838 NaN 556 301026 24 False NaN NaN 808346 186
WHITE JR THOMAS E 317543 NaN NaN 1934359 1297049 450000 13847074 NaN NaN 15144123 81353 NaN NaN 1085463 NaN False NaN NaN NaN NaN
WINOKUR JR. HERBERT S NaN NaN NaN 84992 NaN NaN NaN NaN NaN NaN 1413 NaN NaN NaN NaN False 108579 -25000 NaN NaN
WODRASKA JOHN NaN NaN NaN 189583 NaN NaN NaN NaN NaN NaN NaN NaN NaN 189583 NaN False NaN NaN NaN NaN
WROBEL BRUCE NaN NaN NaN NaN 139130 NaN NaN NaN NaN 139130 NaN NaN NaN NaN NaN False NaN NaN NaN NaN
YEAGER F SCOTT 158403 NaN NaN 360300 8308552 NaN 3576206 NaN NaN 11884758 53947 NaN NaN 147950 NaN True NaN NaN NaN NaN
YEAP SOON NaN NaN NaN 55097 192758 NaN NaN NaN NaN 192758 55097 NaN NaN NaN NaN False NaN NaN NaN NaN

145 rows × 20 columns


In [ ]:


In [28]:
clf = Pipeline([
  ('feature_selection', LinearSVC(penalty="l1")),
  ('classification', RandomForestClassifier())
])
clf.fit(X, y)

In [ ]:


In [ ]:
from sklearn.preprocessing import Imputer
# Impute values of an np.array by column (axis=0)
# Create Imputer() to train on training set, and use for test set.
imputer = Imputer(missing_values='NaN', strategy='median', axis=0)

imputer.fit(train_data)

imputer.transform(train_data)
imputer.transform(test_data)

In [128]:
from sklearn.grid_search import GridSearchCV
from sklearn.pipeline import Pipeline
pipeline = Pipeline([
('imp', Imputer(missing_values='NaN', axis=0)),
('rf', ExtraTreesClassifier())
])

In [129]:
parameters = {'imp__strategy': ('median', 'mean')}

grid_search = GridSearchCV(pipeline, parameters)

In [132]:
grid_search.fit(train_data)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-132-093ca7920d35> in <module>()
----> 1 grid_search.fit(train_data)

c:\Anaconda\lib\site-packages\sklearn\grid_search.pyc in fit(self, X, y)
    594 
    595         """
--> 596         return self._fit(X, y, ParameterGrid(self.param_grid))
    597 
    598 

c:\Anaconda\lib\site-packages\sklearn\grid_search.pyc in _fit(self, X, y, parameter_iterable)
    376                                     train, test, self.verbose, parameters,
    377                                     self.fit_params, return_parameters=True)
--> 378             for parameters in parameter_iterable
    379             for train, test in cv)
    380 

c:\Anaconda\lib\site-packages\sklearn\externals\joblib\parallel.pyc in __call__(self, iterable)
    651             self._iterating = True
    652             for function, args, kwargs in iterable:
--> 653                 self.dispatch(function, args, kwargs)
    654 
    655             if pre_dispatch == "all" or n_jobs == 1:

c:\Anaconda\lib\site-packages\sklearn\externals\joblib\parallel.pyc in dispatch(self, func, args, kwargs)
    398         """
    399         if self._pool is None:
--> 400             job = ImmediateApply(func, args, kwargs)
    401             index = len(self._jobs)
    402             if not _verbosity_filter(index, self.verbose):

c:\Anaconda\lib\site-packages\sklearn\externals\joblib\parallel.pyc in __init__(self, func, args, kwargs)
    136         # Don't delay the application, to avoid keeping the input
    137         # arguments in memory
--> 138         self.results = func(*args, **kwargs)
    139 
    140     def get(self):

c:\Anaconda\lib\site-packages\sklearn\cross_validation.pyc in _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score, return_parameters)
   1238     else:
   1239         estimator.fit(X_train, y_train, **fit_params)
-> 1240     test_score = _score(estimator, X_test, y_test, scorer)
   1241     if return_train_score:
   1242         train_score = _score(estimator, X_train, y_train, scorer)

c:\Anaconda\lib\site-packages\sklearn\cross_validation.pyc in _score(estimator, X_test, y_test, scorer)
   1292     """Compute the score of an estimator on a given test set."""
   1293     if y_test is None:
-> 1294         score = scorer(estimator, X_test)
   1295     else:
   1296         score = scorer(estimator, X_test, y_test)

c:\Anaconda\lib\site-packages\sklearn\metrics\scorer.pyc in _passthrough_scorer(estimator, *args, **kwargs)
    174 def _passthrough_scorer(estimator, *args, **kwargs):
    175     """Function that wraps estimator.score"""
--> 176     return estimator.score(*args, **kwargs)
    177 
    178 

c:\Anaconda\lib\site-packages\sklearn\pipeline.py in score(self, X, y)
    198         for name, transform in self.steps[:-1]:
    199             Xt = transform.transform(Xt)
--> 200         return self.steps[-1][-1].score(Xt, y)
    201 
    202     @property

AttributeError: 'Imputer' object has no attribute 'score'

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [39]:
# Get median of the columns
# WARNING: np.median treats NaN as a value
a = [[1,2], [10,1], [np.nan, 2]]
np.median(a, axis=0)


Out[39]:
array([ 10.,   2.])

In [40]:
# scipy.stats ignores the NaN so an unbiased median can be estimated 
# for imputation
from scipy import stats
stats.nanmedian(a, axis=0)


Out[40]:
array([ 5.5,  2. ])

In [109]:


In [130]:
train_data = [['1', 'NaN', 'NaN', '0.0127034', '0.0435092'],
 ['1', 'NaN', 'NaN', '0.0113187', '0.228205'],
 ['1', '0.648', '0.248', '0.0142176', '0.202707'],
 ['1', '0.357', '0.470', '0.0328121', '0.255039'],
 ['1', 'NaN', 'NaN', '0.00311825', '0.0381745'],
 ['1', 'NaN', 'NaN', '0.0332604', '0.2857']]
train_data


Out[130]:
[['1', 'NaN', 'NaN', '0.0127034', '0.0435092'],
 ['1', 'NaN', 'NaN', '0.0113187', '0.228205'],
 ['1', '0.648', '0.248', '0.0142176', '0.202707'],
 ['1', '0.357', '0.470', '0.0328121', '0.255039'],
 ['1', 'NaN', 'NaN', '0.00311825', '0.0381745'],
 ['1', 'NaN', 'NaN', '0.0332604', '0.2857']]

In [111]:
A = np.array(train_data)
A[A=='NaN'] = np.nan

In [112]:
# Impute np.array with median values
# 
imputer.fit(train_data)
imputer.transform(train_data).round(2)


Out[112]:
array([[ 1.  ,  0.5 ,  0.36,  0.01,  0.04],
       [ 1.  ,  0.5 ,  0.36,  0.01,  0.23],
       [ 1.  ,  0.65,  0.25,  0.01,  0.2 ],
       [ 1.  ,  0.36,  0.47,  0.03,  0.26],
       [ 1.  ,  0.5 ,  0.36,  0.  ,  0.04],
       [ 1.  ,  0.5 ,  0.36,  0.03,  0.29]])

In [131]:
test_data = [['1', 'NaN', 'NaN', '0.0127034', '0.0435092'],
 ['1', 'NaN', 'NaN', '0.0113187', '0.228205'],
 ['1', '0.648', '0.248', '0.0142176', '0.202707'],
 ['1', '0.357', '0.470', '0.0328121', '0.255039'],
 ['1', '10', 'NaN', '0.00311825', '0.0381745'],
 ['1', 'NaN', 'NaN', '0.0332604', '0.2857']]

In [ ]:
B = np.array(test_data)
B[B=='NaN'] = np.nan
B

In [114]:
B = imputer.transform(B)
B.round(2)


Out[114]:
array([[  1.  ,   0.5 ,   0.36,   0.01,   0.04],
       [  1.  ,   0.5 ,   0.36,   0.01,   0.23],
       [  1.  ,   0.65,   0.25,   0.01,   0.2 ],
       [  1.  ,   0.36,   0.47,   0.03,   0.26],
       [  1.  ,  10.  ,   0.36,   0.  ,   0.04],
       [  1.  ,   0.5 ,   0.36,   0.03,   0.29]])

In [114]:


In [ ]: