In [1]:
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
%pylab inline
import matplotlib.pyplot as plt
plt.xkcd()
Out[1]:
In [2]:
!curl -O https://raw.githubusercontent.com/DJCordhose/deep-learning-crash-course-notebooks/master/data/insurance-customers-1500.csv
In [0]:
import pandas as pd
df = pd.read_csv('./insurance-customers-1500.csv', sep=';')
In [4]:
df.head()
Out[4]:
In [5]:
df.describe()
Out[5]:
In [0]:
# we deliberately decide this is going to be our label, it is often called lower case y
y=df['group']
In [7]:
y.head()
Out[7]:
In [0]:
# since 'group' is now the label we want to predict, we need to remove it from the training data
df.drop('group', axis='columns', inplace=True)
In [9]:
df.head()
Out[9]:
In [0]:
# input data often is named upper case X, the upper case indicates, that each row is a vector
X = df.as_matrix()
In [0]:
# ignore this, it is just technical code to plot decision boundaries
# Adapted from:
# http://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html
# http://jponttuset.cat/xkcd-deep-learning/
from matplotlib.colors import ListedColormap
cmap_print = ListedColormap(['#AA8888', '#004000', '#FFFFDD'])
cmap_bold = ListedColormap(['#AA4444', '#006000', '#EEEE44'])
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#FFFFDD'])
font_size=25
title_font_size=40
def meshGrid(x_data, y_data):
h = 1 # step size in the mesh
x_min, x_max = x_data.min() - 1, x_data.max() + 1
y_min, y_max = y_data.min() - 1, y_data.max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
return (xx,yy)
def plotPrediction(clf, x_data, y_data, x_label, y_label, ground_truth, title="",
size=(15, 8)):
xx,yy = meshGrid(x_data, y_data)
fig, ax = plt.subplots(figsize=size)
if clf:
Z = clf.predict(np.c_[yy.ravel(), xx.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
ax.pcolormesh(xx, yy, Z, cmap=cmap_light)
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.scatter(x_data, y_data, c=ground_truth, cmap=cmap_bold, s=100, marker='o', edgecolors='k')
ax.set_xlabel(x_label, fontsize=font_size)
ax.set_ylabel(y_label, fontsize=font_size)
ax.set_title(title, fontsize=title_font_size)
In [12]:
plotPrediction(None, X[:, 1], X[:, 0],
'Age', 'Max Speed', y,
title="All Data")
In [13]:
X[:, :2]
Out[13]:
In [14]:
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
%time clf.fit(X[:, :2], y)
Out[14]:
In [15]:
input = [[100.0, 48.0]]
clf.predict(input)
Out[15]:
In [16]:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
X_train.shape, y_train.shape, X_test.shape, y_test.shape
Out[16]:
In [0]:
X_train_2_dim = X_train[:, :2]
X_test_2_dim = X_test[:, :2]
In [18]:
plotPrediction(None, X_train_2_dim[:, 1], X_train_2_dim[:, 0],
'Age', 'Max Speed', y_train, title="Train Data")
In [19]:
plotPrediction(None, X_test_2_dim[:, 1], X_test_2_dim[:, 0],
'Age', 'Max Speed', y_test, title="Test Data")
https://machinelearningmastery.com/classification-and-regression-trees-for-machine-learning/
In [20]:
clf = DecisionTreeClassifier()
%time clf.fit(X_train_2_dim, y_train)
Out[20]:
In [21]:
# we perform at most 20 splits of our data until we make a decision where the data point belongs
clf.tree_.max_depth
Out[21]:
In [22]:
plotPrediction(clf, X_train_2_dim[:, 1], X_train_2_dim[:, 0],
'Age', 'Max Speed', y_train,
title="Train Data, Decision Tree")
In [23]:
clf.score(X_train_2_dim, y_train)
Out[23]:
In [24]:
plotPrediction(clf, X_test_2_dim[:, 1], X_test_2_dim[:, 0],
'Age', 'Max Speed', y_test,
title="Test Data, Decision Tree")
In [25]:
clf.score(X_test_2_dim, y_test)
Out[25]:
In [26]:
clf = DecisionTreeClassifier(max_depth=10,
min_samples_leaf=3,
min_samples_split=2)
%time clf.fit(X_train_2_dim, y_train)
Out[26]:
In [27]:
clf.tree_.max_depth
Out[27]:
In [28]:
plotPrediction(clf, X_train_2_dim[:, 1], X_train_2_dim[:, 0],
'Age', 'Max Speed', y_train,
title="Train Data, Regularized Decision Tree")
In [29]:
clf.score(X_train_2_dim, y_train)
Out[29]:
In [30]:
plotPrediction(clf, X_test_2_dim[:, 1], X_test_2_dim[:, 0],
'Age', 'Max Speed', y_test,
title="Test Data, Regularized Decision Tree")
In [31]:
clf.score(X_test_2_dim, y_test)
Out[31]:
In [32]:
# http://scikit-learn.org/stable/modules/cross_validation.html
from sklearn.model_selection import cross_val_score
scores = cross_val_score(clf, X[:, :2], y, n_jobs=-1)
scores
Out[32]:
In [0]:
# cross_val_score?
In [34]:
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
In [35]:
from sklearn.model_selection import GridSearchCV
param_grid = {
'max_depth': list(range(2, 25)),
'min_samples_split': list(range(2, 11)),
'min_samples_leaf': list(range(1, 11))
}
clf = GridSearchCV(DecisionTreeClassifier(), param_grid, n_jobs=-1)
%time clf.fit(X[:, :2], y)
clf.best_params_
Out[35]:
In [36]:
clf = DecisionTreeClassifier(max_depth=6,
min_samples_leaf=6,
min_samples_split=2)
%time clf.fit(X_train_2_dim, y_train)
Out[36]:
In [37]:
clf.score(X_train_2_dim, y_train)
Out[37]:
In [38]:
clf.score(X_test_2_dim, y_test)
Out[38]:
In [39]:
# http://scikit-learn.org/stable/modules/cross_validation.html
from sklearn.model_selection import cross_val_score
scores = cross_val_score(clf, X[:, :2], y, n_jobs=-1)
scores
Out[39]:
In [40]:
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
In [0]: