Practical Machine Learning

Airwatch Bangalore
May 7-9, 2018

Notes of this workshop are available online at:
https://bit.ly/airwatch-ml

Home | Day 1 | Day 2 - iris| Day 2 - Boston Housing | Day 3 - Movies

In [1]:
import pandas as pd
import numpy as np

%matplotlib inline

The Iris Flower

There are three different species of the iris flower. Each specieis looks slightly differently. Can we use machine learning to predict the species of the flower by looking at it?

Pictures are from the wikipedia page, CC BY-SA.

The iris prediction problem is the hello world of machine learning.

The scikit-learn dataset comes with this dataset.

In [2]:
from sklearn.datasets import load_iris
In [3]:
iris = load_iris()
In [4]:
iris.keys()
Out[4]:
dict_keys(['feature_names', 'target', 'target_names', 'data', 'DESCR'])
In [5]:
print(iris['DESCR'])
Iris Plants Database
====================

Notes
-----
Data Set Characteristics:
    :Number of Instances: 150 (50 in each of three classes)
    :Number of Attributes: 4 numeric, predictive attributes and the class
    :Attribute Information:
        - sepal length in cm
        - sepal width in cm
        - petal length in cm
        - petal width in cm
        - class:
                - Iris-Setosa
                - Iris-Versicolour
                - Iris-Virginica
    :Summary Statistics:

    ============== ==== ==== ======= ===== ====================
                    Min  Max   Mean    SD   Class Correlation
    ============== ==== ==== ======= ===== ====================
    sepal length:   4.3  7.9   5.84   0.83    0.7826
    sepal width:    2.0  4.4   3.05   0.43   -0.4194
    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
    petal width:    0.1  2.5   1.20  0.76     0.9565  (high!)
    ============== ==== ==== ======= ===== ====================

    :Missing Attribute Values: None
    :Class Distribution: 33.3% for each of 3 classes.
    :Creator: R.A. Fisher
    :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
    :Date: July, 1988

This is a copy of UCI ML iris datasets.
http://archive.ics.uci.edu/ml/datasets/Iris

The famous Iris database, first used by Sir R.A Fisher

This is perhaps the best known database to be found in the
pattern recognition literature.  Fisher's paper is a classic in the field and
is referenced frequently to this day.  (See Duda & Hart, for example.)  The
data set contains 3 classes of 50 instances each, where each class refers to a
type of iris plant.  One class is linearly separable from the other 2; the
latter are NOT linearly separable from each other.

References
----------
   - Fisher,R.A. "The use of multiple measurements in taxonomic problems"
     Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to
     Mathematical Statistics" (John Wiley, NY, 1950).
   - Duda,R.O., & Hart,P.E. (1973) Pattern Classification and Scene Analysis.
     (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.
   - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
     Structure and Classification Rule for Recognition in Partially Exposed
     Environments".  IEEE Transactions on Pattern Analysis and Machine
     Intelligence, Vol. PAMI-2, No. 1, 67-71.
   - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactions
     on Information Theory, May 1972, 431-433.
   - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS II
     conceptual clustering system finds 3 classes in the data.
   - Many, many more ...

The iris data from scikit-learn is available as numpy arrays. To make our job easier, I've exported them as csv so that we can load them as pandas dataframe. I've also divided the dataset into two parts. One to train our model and another to see how well our model is preforming.

In [6]:
url_iris_train = "https://notes.pipal.in/2018/airwatch-ml/iris-train.csv"
url_iris_test = "https://notes.pipal.in/2018/airwatch-ml/iris-test.csv"
In [7]:
df_train = pd.read_csv(url_iris_train, index_col=0)
df_test = pd.read_csv(url_iris_test, index_col=0)
In [8]:
df_train.head()
Out[8]:
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
5 5.4 3.9 1.7 0.4 setosa
6 4.6 3.4 1.4 0.3 setosa
7 5.0 3.4 1.5 0.2 setosa
In [9]:
df_train.describe()
Out[9]:
sepal_length sepal_width petal_length petal_width
count 105.000000 105.000000 105.000000 105.000000
mean 5.808571 3.041905 3.747619 1.204762
std 0.844452 0.380986 1.769240 0.771410
min 4.300000 2.200000 1.000000 0.100000
25% 5.100000 2.800000 1.600000 0.300000
50% 5.800000 3.000000 4.400000 1.300000
75% 6.300000 3.300000 5.100000 1.800000
max 7.700000 4.000000 6.700000 2.500000
In [10]:
def predict(petal_length, petal_width):
    # Improve this function
    return "setosa"
In [11]:
def test(dataset):
    predicted = np.array([predict(x1, x2) for x1, x2 in 
                         zip(dataset.petal_length, dataset.petal_width)])
    actual = dataset.species
    matched = sum(predicted==actual)
    return matched / len(dataset)
In [12]:
test(df_train)
Out[12]:
0.3333333333333333
In [13]:
df_train.boxplot()
Out[13]:
<matplotlib.axes._subplots.AxesSubplot at 0x11518e0f0>
In [14]:
df_train.boxplot("petal_length", by="species")
Out[14]:
<matplotlib.axes._subplots.AxesSubplot at 0x115a6bb38>
In [15]:
df_train.plot(kind="scatter", x="petal_length", y="petal_width")
Out[15]:
<matplotlib.axes._subplots.AxesSubplot at 0x115b36a20>
In [16]:
df_train.head()
Out[16]:
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
5 5.4 3.9 1.7 0.4 setosa
6 4.6 3.4 1.4 0.3 setosa
7 5.0 3.4 1.5 0.2 setosa
In [17]:
df_train.species.unique()
Out[17]:
array(['setosa', 'versicolor', 'virginica'], dtype=object)
In [18]:
species = {"setosa": 0, "versicolor": 1, "virginica": 2}
In [19]:
species.get("setosa")
Out[19]:
0
In [20]:
df_train['ispecies'] = df_train.species.map(species.get)
In [21]:
df_train.head()
Out[21]:
sepal_length sepal_width petal_length petal_width species ispecies
0 5.1 3.5 1.4 0.2 setosa 0
1 4.9 3.0 1.4 0.2 setosa 0
5 5.4 3.9 1.7 0.4 setosa 0
6 4.6 3.4 1.4 0.3 setosa 0
7 5.0 3.4 1.5 0.2 setosa 0
In [22]:
df_train.plot(kind="scatter",
              x="petal_length", y="petal_width", 
              c="ispecies", cmap="viridis")
Out[22]:
<matplotlib.axes._subplots.AxesSubplot at 0x115bd9da0>

Building a Machine Learning Model

In [23]:
from sklearn.tree import DecisionTreeClassifier
In [24]:
model = DecisionTreeClassifier(max_depth=2)
In [25]:
model.fit(df_train[["petal_length", "petal_width"]], df_train.ispecies)
Out[25]:
DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=2,
            max_features=None, max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter='best')
In [26]:
df_train.head()
Out[26]:
sepal_length sepal_width petal_length petal_width species ispecies
0 5.1 3.5 1.4 0.2 setosa 0
1 4.9 3.0 1.4 0.2 setosa 0
5 5.4 3.9 1.7 0.4 setosa 0
6 4.6 3.4 1.4 0.3 setosa 0
7 5.0 3.4 1.5 0.2 setosa 0
In [27]:
model.predict([[1.4, 0.2]])[0]
Out[27]:
0
In [28]:
def predict(petal_length, petal_width):
    data = [[petal_length, petal_width]]
    y = model.predict(data)[0]
    return ["setosa", "versicolor", "virginica"][y]
In [29]:
predict(1.4, 0.2)
Out[29]:
'setosa'
In [30]:
test(df_train)
Out[30]:
0.9619047619047619
In [31]:
test(df_test)
Out[31]:
0.9555555555555556

Visualizing the model

Install the modelvis library.

In [82]:
!pip install -q -U modelvis
In [32]:
import modelvis
In [33]:
modelvis.__version__
Out[33]:
'0.1.5'
In [34]:
modelvis.render_tree(model, 
                     feature_names=["petal_length", "petal_width"],
                     class_names=["setosa", "versicolor", "virginica"])
Out[34]:
Tree 0 petal_length ≤ 2.45 gini = 0.667 samples = 105 value = [35, 35, 35] class = setosa 1 gini = 0.0 samples = 35 value = [35, 0, 0] class = setosa 0->1 True 2 petal_width ≤ 1.75 gini = 0.5 samples = 70 value = [0, 35, 35] class = versicolor 0->2 False 3 gini = 0.149 samples = 37 value = [0, 34, 3] class = versicolor 2->3 4 gini = 0.059 samples = 33 value = [0, 1, 32] class = virginica 2->4
In [35]:
modelvis.print_tree_as_code(model)
def predict(row):
    """Your decision-tree model wrote this code."""
    # 105 samples; value=[35, 35, 35]; class=0
    if row[0] < 2.450000047683716:
        # 35 samples; value=[35, 0, 0]; class=0
        return 0
    else:
        # 70 samples; value=[0, 35, 35]; class=1
        if row[1] < 1.75:
            # 37 samples; value=[0, 34, 3]; class=1
            return 1
        else:
            # 33 samples; value=[0, 1, 32]; class=2
            return 2

In [36]:
modelvis.plot_decision_boundaries(
    model, 
    X=df_train[["petal_length", "petal_width"]],
    y=df_train.ispecies, 
    class_names=["setosa", "versicolor", "virginica"], 
    show_input=True
)
In [37]:
DecisionTreeClassifier??
In [38]:
model = DecisionTreeClassifier(max_depth=20, min_samples_split=2, min_impurity_split=1e-25)
model.fit(df_train[["petal_length", "petal_width"]], df_train.ispecies)
/Users/anand/anaconda/envs/rx/lib/python3.5/site-packages/sklearn/tree/tree.py:282: DeprecationWarning: The min_impurity_split parameter is deprecated and will be removed in version 0.21. Use the min_impurity_decrease parameter instead.
  DeprecationWarning)
Out[38]:
DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=20,
            max_features=None, max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=1e-25,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter='best')
In [39]:
modelvis.plot_decision_boundaries(
    model, 
    X=df_train[["petal_length", "petal_width"]],
    y=df_train.ispecies, 
    class_names=["setosa", "versicolor", "virginica"], 
    show_input=True
)
In [54]:
modelvis.plot_decision_boundaries(
    model, 
    X=df_train[["petal_length", "petal_width"]],
    y=df_train.ispecies, 
    class_names=["setosa", "versicolor", "virginica"], 
    show_input=True, probability=True
)
In [40]:
modelvis.render_tree(model, 
                     feature_names=["petal_length", "petal_width"],
                     class_names=["setosa", "versicolor", "virginica"])
Out[40]:
Tree 0 petal_width ≤ 0.8 gini = 0.667 samples = 105 value = [35, 35, 35] class = setosa 1 gini = 0.0 samples = 35 value = [35, 0, 0] class = setosa 0->1 True 2 petal_width ≤ 1.75 gini = 0.5 samples = 70 value = [0, 35, 35] class = versicolor 0->2 False 3 petal_length ≤ 5.3 gini = 0.149 samples = 37 value = [0, 34, 3] class = versicolor 2->3 10 petal_length ≤ 4.85 gini = 0.059 samples = 33 value = [0, 1, 32] class = virginica 2->10 4 petal_width ≤ 1.65 gini = 0.056 samples = 35 value = [0, 34, 1] class = versicolor 3->4 9 gini = 0.0 samples = 2 value = [0, 0, 2] class = virginica 3->9 5 gini = 0.0 samples = 33 value = [0, 33, 0] class = versicolor 4->5 6 petal_length ≤ 4.75 gini = 0.5 samples = 2 value = [0, 1, 1] class = versicolor 4->6 7 gini = 0.0 samples = 1 value = [0, 0, 1] class = virginica 6->7 8 gini = 0.0 samples = 1 value = [0, 1, 0] class = versicolor 6->8 11 gini = 0.444 samples = 3 value = [0, 1, 2] class = virginica 10->11 12 gini = 0.0 samples = 30 value = [0, 0, 30] class = virginica 10->12
In [41]:
df_train[(df_train.petal_width > 1.75) & (df_train.petal_length <= 4.85)]
Out[41]:
sepal_length sepal_width petal_length petal_width species ispecies
70 5.9 3.2 4.8 1.8 versicolor 1
126 6.2 2.8 4.8 1.8 virginica 2
138 6.0 3.0 4.8 1.8 virginica 2

Linear Model

In [42]:
from sklearn.linear_model import LogisticRegression
In [43]:
model2 = LogisticRegression()
In [45]:
X = df_train[["petal_length", "petal_width"]]
y = df_train.ispecies
In [46]:
model2.fit(X, y)
Out[46]:
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
          intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
          penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
          verbose=0, warm_start=False)
In [50]:
model2.coef_
Out[50]:
array([[-1.02659838, -1.54062581],
       [ 0.56700538, -0.98998603],
       [ 0.02075169,  2.20552223]])
In [51]:
model2.intercept_
Out[51]:
array([ 3.48078934, -1.57478834, -3.65898006])
In [52]:
modelvis.plot_decision_boundaries(
    model2, 
    X=X,
    y=y, 
    class_names=["setosa", "versicolor", "virginica"], 
    show_input=True
)
In [53]:
modelvis.plot_decision_boundaries(
    model2, 
    X=X,
    y=y, 
    class_names=["setosa", "versicolor", "virginica"], 
    probability=True,
    show_input=True
)
In [91]:
def predict(petal_length, petal_width):
    data = [[petal_length, petal_width]]
    y = model.predict(data)[0]
    return ["setosa", "versicolor", "virginica"][y]
In [56]:
test(df_train)
Out[56]:
0.8666666666666667
In [57]:
test(df_test)
Out[57]:
0.8444444444444444

Exercise: Build a decision-tree model and a linear model using all the 4 features of iris and find the accuracy on the test dataset.

In [107]:
df_test['ispecies']=df_test.species.map(species.get)
In [108]:
X = df_train.iloc[:,0:4]
y = df_train.ispecies
X_test = df_test.iloc[:,0:4]
y_test = df_test.ispecies
In [117]:
model = DecisionTreeClassifier()
In [118]:
model.fit(X,y);
In [119]:
scoring = []
for i in range(1, 10):
    model.set_params(max_depth = i)
    model.fit(X,y)
    train_accuracy = model.score(X,y)
    test_accuracy = model.score(X_test, y_test)
    scoring.append([i, train_accuracy, test_accuracy])
In [120]:
scoring
Out[120]:
[[1, 0.6666666666666666, 0.6666666666666666],
 [2, 0.9619047619047619, 0.9555555555555556],
 [3, 0.9809523809523809, 0.9555555555555556],
 [4, 0.9904761904761905, 0.9555555555555556],
 [5, 1.0, 0.9555555555555556],
 [6, 1.0, 0.9555555555555556],
 [7, 1.0, 0.9555555555555556],
 [8, 1.0, 0.9555555555555556],
 [9, 1.0, 0.9555555555555556]]
In [ ]: