import pandas as pd

# 
# Load up the wheat dataset into dataframe 'df'
#
df = pd.read_csv("../datasets/wheat.data", index_col='id')

df.head()

"""
Explanation: Decision trees are a supervised, probabilistic, machine learning classifier that are often used as decision support tools. Like any other classifier, they are capable of predicting the label of a sample, and the way they do this is by examining the probabilistic outcomes of your samples' features.   
Decision trees are one of the oldest and most used machine learning algorithms, perhaps even pre-dating machine learning. They're very popular and have been around for decades. Following through with sequential cause-and-effect decisions comes very naturally.
Decision trees are a good tool to use when you want backing evidence to support a decision.
We train the UCI's wheat-seeds dataset with decision trees and see the decision boundary plots produced by it.
You can find the dataset in the above link or in this Github dataset folder.  
You can refer to the related "Decision Trees" article for more details about the method.
Wheat Seed prediction
Read the data
End of explanation
"""


# we keep groove and perimeter, plus of course the target: wheat type
wheatSimpler = df.drop(columns = ['compactness', 'width', 'length', 'area', 'asymmetry'])

wheatSimpler.info()

# An easy way to show which rows have nans in them

print (wheatSimpler[pd.isnull(wheatSimpler).any(axis=1)])

# 
# Only a few rows. Go ahead and drop any row with a nan
#
wheatSimpler.dropna(axis=0, inplace=True)

# 
# INFO: In the future, you might try setting the nan values to the
# mean value of that column, groove; the mean should only be calculated for
# the specific class rather than across all classes, in this case for canadian type

#
# Copy the labels out of the dataframe into variable 'labels' , then remove
# them from the dataframe. Encode the labels:
# canadian:0, kama:1, and rosa:2
#
labels = wheatSimpler.wheat_type.copy() # copy “y” values out
wheatSimpler.drop(['wheat_type'], axis=1, inplace=True) # drop output column 

labels = labels.map({'canadian':0, 'kama':1, 'rosa':2}) # encoding


"""
Explanation: Pre-processing the data
What we want to do is to predict the wheat type based on the wheat seed characteristics.
To simplify the boundary plot, we consider only two of the characteristics.
End of explanation
"""


from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(wheatSimpler, labels, test_size=0.3, 
                                                    random_state=7)


"""
Explanation: Split dataset into training and test
End of explanation
"""


#
# We use the SkLearn module tree
#
from sklearn import tree

#
# note that I force the tree depth to a maximum of two (for simplification)
#

model = tree.DecisionTreeClassifier(max_depth=2, random_state=2)
model.fit(X_train, y_train)

"""
Explanation: Train the tree model
End of explanation
"""


tree.plot_tree(model, feature_names=X_train.columns, filled=True)

"""
Explanation: Let's plot the tree using the sklearn.tree internal feature, which gives an idea of how the features are considered in the model
End of explanation
"""


import matplotlib as mpl
import matplotlib.pyplot as plt

import numpy as np 

x,y = np.meshgrid(wheatSimpler.perimeter, wheatSimpler.groove)

Z = model.predict(np.c_[x.ravel(), y.ravel()])
Z = Z.reshape(x.shape)

fig, ax = plt.subplots()
ax.scatter(wheatSimpler.perimeter, wheatSimpler.groove, c = labels)

ax.hlines(y=5.6, xmin=12, xmax=17.5, linestyle='-', label="1st question")
ax.vlines(x=13.5, ymin=3.5, ymax=5.6, linestyle='--', label="2nd question")
ax.vlines(x=14, ymin=5.6, ymax=6.9, linestyle=':', label="3rd question")

ax.legend(loc='best')
fig.suptitle("Predictor space")
ax.set_xlabel("Seed Perimeter")
ax.set_ylabel("Seed Groove");

"""
Explanation: As you can see the tree consists of a series of splitting rules, starting at the top of the tree with a question (answer is Yes on the left and No on the right) and goes on with "branches"to finally ends in "leaves" or "terminal nodes" after several splits (in this case two, since I have limited it above using max_depth).  
Decision trees are simple and very easy to interpret, you just need to look at the questions.
The first question is: "has this seed a groove less or equal than 5.576?"
This question in fact splits the predictor space in two. 
Let's plot the decision boundaries to see how they work.
End of explanation
"""


# 
# Load up the mushroom dataset into dataframe 'X'
# Header information is on the dataset's website at the UCI ML Repo
#
colNames=['label', 'cap-shape','cap-surface','cap-color','bruises','odor',
          'gill-attachment','gill-spacing','gill-size','gill-color','stalk-shape',
          'stalk-root','stalk-surface-above-ring','stalk-surface-below-ring',
          'stalk-color-above-ring','stalk-color-below-ring','veil-type',
          'veil-color','ring-number','ring-type','spore-print-color','population',
          'habitat']
X = pd.read_csv("../datasets/agaricus-lepiota.data", header=None, na_values='?',
                names=colNames) 

X.head()

X.describe()

"""
Explanation: You can see that the predictor space has been segmented in a number of simple regions, four to be precise and a wheat type is predicted according to its position in one of the regions.
Another example: poisonous mushrooms
Use decision trees to peruse The Mushroom Data Set, drawn from the Audubon Society Field Guide to North American Mushrooms (1981). The data set details mushrooms described in terms of many physical characteristics, such as cap size  and stalk length, along with a classification of poisonous or edible.
You can find the dataset in the above UCI link or in the Dataset folder here in github.  
As a standard disclaimer, if you eat a random mushroom you find, you are doing so at your own risk.
Read the data
End of explanation
"""


# 
# drop any row with a nan
#
X.dropna(axis=0, inplace=True) 
print (X.shape)

"""
Explanation: Pre-process the data
remove missing data
End of explanation
"""


#
# : Copy the labels out of the dset into variable 'y' then Remove
# them from X. 

y = X[X.columns[0]].copy()
X.drop(X.columns[0], axis=1,inplace=True)

"""
Explanation: separate label
End of explanation
"""


#
# Encode labels poisonous / edible
y = y.map({'p':0, 'e':1})

# Encode the rest 
#
X = pd.get_dummies(X)

"""
Explanation: Encode the dataset using dummies
End of explanation
"""


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, 
                                                    random_state=7)

"""
Explanation: Split the data inot test and training sets
End of explanation
"""


#
# Create a DT classifier. No need to set any parameters, let;s get the ful depth
#

model = tree.DecisionTreeClassifier()

#
# train the classifier on the training data / labels:
#
model.fit(X_train, y_train)

tree.plot_tree(model, feature_names=X_train.columns, filled=True)

"""
Explanation: Train the model
End of explanation
"""


# score the classifier on the testing data / labels:
# Returns the mean accuracy on the given test data and labels.

score = model.score(X_test, y_test)

print ("High-Dimensionality Score: ", round((score*100), 3))

"""
Explanation: RESULT:
top two features you should consider when deciding if a mushroom is eadible or not:
Odor and Gill Size.
End of explanation
"""


