#!/usr/bin/env python
# coding: utf-8

# # Advanced Binary Image Segmentation for the Geo- and Eco-sciences, using Deep Learning
#
# ## Case Study: Detecting Intertidal Reefs
#
# #### Daniel Buscombe, MARDA Science
#
# ![](https://mardascience.com/wp-content/uploads/2019/06/cropped-MardaScience_logo-5.png)

# Before you do anything, go to `File > Save copy in Drive` so you can keep and work on your own copy
#
# ## Lesson 3: Getting ready to train a oyster reef masker (binary segmentation of intertidal shellfish reefs) with the "OysterNet" data set
#
# This jupyter notebook running on Google Colab is part of the "Advanced Binary Image Segmentation for the Geo- and Eco-sciences, using Deep Learning" course. The main course website can be accessed [here](https://mardascience.gitlab.io/binary_image_segmentation_for_geosciences/#/)
#
# In the previous lesson we made functions to read and pair image and label tiles from this data. In this lesson, we will start by repeating that process without the visualization steps
#
# Then we will construct, train and evaluate the model. In the [oysterNet paper](https://zslpublications.onlinelibrary.wiley.com/doi/full/10.1002/rse2.134), the authors used a bigger, more sophisticated model for `instance segmentation`, that is, semantic segmentation that is aware of all the different `instances` of the class (i.e. each individual piece of reef). The model they use is called `Mask RCNN`, the implementation of which is [here](https://github.com/matterport/Mask_RCNN). That is a large and very complicated model that is hard to experiment with. The research behind the [oysterNet paper](https://zslpublications.onlinelibrary.wiley.com/doi/full/10.1002/rse2.134) is state-of-the-art.
#
# Here, we use a simpler model with fewer parameters (namely, a residual UNet) and acheive acceptable results for a semantic segmentation (predicting the masks of where the reefs are, rather than by individual instances). The UNet is the same we used in a [previous set of tutorials](https://mardascience.gitlab.io/deep_learning_landscape_classification/#/) and is relatively simple to adapt and play with to demonstrate a few principles.
#
# Actually, in this tutorial we'll start with a basic implementation and get really bad results (!). This is designed to introduce you to the complicated workflow, but at the same time demonstrating a principle: use an appropriate loss function to train your model - one that isn't sensitive to class imbalance. We talk about what that means as we go
#
# This is designed to demonstrate a problem-solving strategy, and also a principle that often applies to natural imagery:
#
# > It's not just the model you choose, it's how you train it that counts

# ### Import libraries

# In[ ]:

import os #for accessing operating system utilities
from glob import glob #for finding files that match a certain string pattern
import matplotlib.pyplot as plt #for plotting
import numpy as np #for numerical operations
import random, string #for creating random strings
import tensorflow as tf #tensorflow
import json # for reading lable annotations in json format
import requests #for downloading files
from PIL import Image, ImageFilter #for reading and filtering imagery
import skimage.draw #for making masks (raster label images) from label annotations
from skimage.transform import resize #for resizing imagery
from psutil import virtual_memory #for interrogating our filesystem and RAM specifications
from imageio import imwrite

# ### Prepare the data

# #### Download the JSON annotations and imagery
#
# If you followed the previous lesson, you'll see that we downloaded the dataset consisting of three large (spatially extensive) orthomosaics, split that data into 555 tiles and labels, and visualize those data
#
# Because this lesson assumes you are running this notebook on Google Colab, we'll have to download and split the data again before training a model. This time we'll do it without the commentary. If you need a recap, see the previous lesson

# In[ ]:

# from https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url

def download_file_from_google_drive(id, destination):
    URL = "https://docs.google.com/uc?export=download"

    session = requests.Session()

    response = session.get(URL, params = { 'id' : id }, stream = True)
    token = get_confirm_token(response)

    if token:
        params = { 'id' : id, 'confirm' : token }
        response = session.get(URL, params = params, stream = True)

    save_response_content(response, destination)

def get_confirm_token(response):
    for key, value in response.cookies.items():
        if key.startswith('download_warning'):
            return value

    return None

def save_response_content(response, destination):
    """
    response = filename for input
    destination = filename for output
    """
    CHUNK_SIZE = 32768

    with open(destination, "wb") as f:
        for chunk in response.iter_content(CHUNK_SIZE):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)

# In[ ]:

## if you are doing this for the second time, you'll want to delete the files first
# !rm -rf 1kx1k_dataset
# !rm 1kx1k_dataset.zip

# In[ ]:

file_id = '1gJq3J8CpXZqLGgUeOU7rXRGEq9glOMmI'
destination = '1kx1k_dataset.zip'
download_file_from_google_drive(file_id, destination)

# In[ ]:

get_ipython().system('unzip 1kx1k_dataset.zip > tmp.txt')

# In[ ]:

data_dir = "1kx1k_dataset/test"
test_annotations = json.load(open(os.path.join(data_dir, "via_region_data.json")))
test_annotations = list(test_annotations.values())

# In[ ]:

data_dir = "1kx1k_dataset/train"
train_annotations = json.load(open(os.path.join(data_dir, "via_region_data.json")))
train_annotations = list(train_annotations.values())

# In[ ]:

data_dir = "1kx1k_dataset/val"
val_annotations = json.load(open(os.path.join(data_dir, "via_region_data.json")))
val_annotations = list(val_annotations.values())

# In[ ]:

print("# test files: %i" % (len(test_annotations)))
print("# train files: %i" % (len(train_annotations)))
print("# validation files: %i" % (len(val_annotations)))

# #### Visualize

# In[ ]:

a = test_annotations[50]

im = Image.open(os.path.join(data_dir, a['filename']))

# In[ ]:

plt.figure(figsize=(16,16))
plt.subplot(121)
plt.imshow(np.array(im))
plt.axis('off')
plt.title('Original')

plt.subplot(122)
im = im.filter(ImageFilter.UnsharpMask(radius=5, percent=200, threshold=3))
plt.imshow(np.array(im))
plt.axis('off')
plt.title('Filtered')

# #### Augment

# Augmentation isn't just about increasing the size of the dataset. In fact its main function is to give the model greater variability so it can generalize better (i.e. it is a regularization strategy). We will create zoomed in and zoomed out copies of the imagery, with random rotations and flips. This will give the model more opportunity to develop a scale and rotation invariant image feature extraction solution
#
# This is going to be a lot easier if both images and labels exist in image formats. That way, we can use keras' built-in augmentation functions. Currently, the labels are still in json format
#
# So, the first thing we do is write out all the labels in jpg format, for both training and validation sets
#
# Then, we make a new directory to store those labels and move them in there
#
# Finally, we make an assoiated image directory and copy the images associated with each of the labels in its own directory
#
# We'll need a function to get every image and label like we did in the previous tutorial
#

# In[ ]:

def get_image_mask_pair(a, sz):

  if type(a['regions']) is dict:
      polygons = [r['shape_attributes'] for r in a['regions'].values()]
  else:
      print('in the dict type')
      polygons = [r['shape_attributes'] for r in a['regions']]

  image_path = os.path.join(data_dir, a['filename'])
  #image = skimage.io.imread(image_path)
  image = Image.open(image_path)

  image = image.filter(ImageFilter.UnsharpMask(radius=5, percent=200, threshold=3))

  height, width = np.array(image).shape[:2]

  # Convert polygons to a bitmap mask of shape
  # [height, width, number of polygons]
  info = a['filename']
  mask = np.zeros([height, width, len(polygons)],dtype=np.uint8)

  for i, p in enumerate(polygons):
      # Get indexes of pixels inside the polygon and set them to 1
      rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])
      mask[rr, cc, i] = 1

  mask = mask.astype(np.int) #, np.ones([mask.shape[-1]], dtype=np.int)
  mask = np.sum(mask, axis=2)

  if np.sum(np.isnan(mask))==(sz[0]*sz[1]):
      print(info)

  image = np.array(image.resize(sz))/255.
  mask = resize(mask, sz)

  mask = (mask-mask.min())/(mask.max()-mask.min()) #*255.

  return image, mask

# Get the training set and write them to file

# In[ ]:

root = './'

# In[ ]:

# train set
for t in train_annotations:
   _, mask = get_image_mask_pair(t, ((1000,1000)))
   imwrite(root+"1kx1k_dataset"+t['filename'].replace('.png', '.jpg').replace('../','/'), mask)

# make a new directory called `train_labels` and move all the jpgs we just made there

# In[ ]:

try:
    os.mkdir(root+"1kx1k_dataset/train_labels")
except:
    pass
os.system("mv "+root+"1kx1k_dataset/*.jpg "+root+"1kx1k_dataset/train_labels")

# Get a list of those files

# In[ ]:

train_label_names = sorted(glob(root+"1kx1k_dataset/train_labels/*.jpg"))

train_image_names = [l.replace('.jpg','.png').replace('train_labels/', '') for l in train_label_names]

# Do the same thing as the above but for the RGB imagery

# In[ ]:

try:
    os.mkdir(root+"1kx1k_dataset/train_images")
except:
    pass
for k in train_image_names:
   os.system("cp "+k+" "+root+"1kx1k_dataset/train_images")

# Do the same for the validation subset

# In[ ]:

# validation
for t in val_annotations:
   _, mask = get_image_mask_pair(t, ((1000,1000)))
   imwrite(root+"1kx1k_dataset"+t['filename'].replace('.png', '.jpg').replace('../','/'), mask)

try:
    os.mkdir(root+"1kx1k_dataset/val_labels")
except:
    pass
os.system("mv "+root+"1kx1k_dataset/*.jpg "+root+"1kx1k_dataset/val_labels")

val_label_names = sorted(glob(root+"1kx1k_dataset/val_labels/*.jpg"))

val_image_names = [l.replace('.jpg','.png').replace('val_labels/', '') for l in val_label_names]

try:
    os.mkdir(root+"1kx1k_dataset/val_images")
except:
    pass
for k in val_image_names:
   os.system("cp "+k+" "+root+"1kx1k_dataset/val_images")

# Finally, do the same for the test subset

# In[ ]:

# test
for t in test_annotations:
   _, mask = get_image_mask_pair(t, ((1000,1000)))
   imwrite(root+"1kx1k_dataset"+t['filename'].replace('.png', '.jpg').replace('../','/'), mask)

try:
    os.mkdir(root+"1kx1k_dataset/test_labels")
except:
    pass
os.system("mv "+root+"1kx1k_dataset/*.jpg "+root+"1kx1k_dataset/test_labels")

val_label_names = sorted(glob(root+"1kx1k_dataset/test_labels/*.jpg"))

val_image_names = [l.replace('.jpg','.png').replace('test_labels/', '') for l in val_label_names]

try:
    os.mkdir(root+"1kx1k_dataset/test_images")
except:
    pass
for k in val_image_names:
   os.system("cp "+k+" "+root+"1kx1k_dataset/test_images")

# Next to augmentation. We'll be using the `flow_from_directory` option of the `tf.keras.preprocessing.image.ImageDataGenerator`
# function, which will allow us to feed our existing training files into a generator to  augment each image using a random combination of transformations
#
# Now, a quirk of `flow_from_directory` is that it expects imagery from each class to be in its own subdirectory of the directory you point it to. So, we create one subdirectory in each of the 4 folders we created just now called 'data', and move the files into it

# In[ ]:

os.mkdir(root+"1kx1k_dataset/val_images/data")
os.mkdir(root+"1kx1k_dataset/train_images/data")
os.mkdir(root+"1kx1k_dataset/val_labels/data")
os.mkdir(root+"1kx1k_dataset/train_labels/data")

os.system("mv "+root+"1kx1k_dataset/val_images/*.png "+root+"1kx1k_dataset/val_images/data")
os.system("mv "+root+"1kx1k_dataset/train_images/*.png "+root+"1kx1k_dataset/train_images/data")
os.system("mv "+root+"1kx1k_dataset/val_labels/*.jpg "+root+"1kx1k_dataset/val_labels/data")
os.system("mv "+root+"1kx1k_dataset/train_labels/*.jpg "+root+"1kx1k_dataset/train_labels/data")

# We'll use random combinations of vertical and horizontal flips, zoom in/out up to 30% and up to +/- 10 deg. rotations. Boundaries are mirrored for a more natural look

# In[ ]:

datagen = tf.keras.preprocessing.image.ImageDataGenerator(
        featurewise_center=False,
        featurewise_std_normalization=False,
        zoom_range=0.3,
        vertical_flip = True,
        rotation_range=10,
        horizontal_flip=True,
        fill_mode='reflect')

img_generator = datagen.flow_from_directory(
        root+"1kx1k_dataset/train_images",
        target_size=(1000, 1000),
        batch_size=1,
        class_mode=None, seed=2020, shuffle=False)

mask_generator = datagen.flow_from_directory(
        root+"1kx1k_dataset/train_labels",
        target_size=(1000, 1000),
        batch_size=1,
        class_mode=None, seed=2020, shuffle=False)

train_generator = (pair for pair in zip(img_generator, mask_generator))

# Write them to file

# In[ ]:

import matplotlib

# In[ ]:

n_aug_files = len(train_annotations)

train_generator2 = (tuple(np.array(pair, dtype='float64')/255) for pair in zip(img_generator, mask_generator))

counter = 0
while counter<n_aug_files:
    x, y = next(train_generator2)
    matplotlib.image.imsave(root+"1kx1k_dataset/train_labels/data/aug00"+str(counter)+".jpg", np.squeeze(y[0]))
    matplotlib.image.imsave(root+"1kx1k_dataset/train_images/data/aug00"+str(counter)+".png", np.squeeze(x[0]))
    counter += 1

# Check to see how many images we now have to work with

# In[ ]:

train_files = glob(root+"1kx1k_dataset/train_images/data/*.png")
val_files = glob(root+"1kx1k_dataset/val_images/data/*.png")

print("# train files: %i" % (len(train_files)))
print("# validation files: %i" % (len(val_files)))

# Previously we have 527 train files. Now we have 1054

# ## Custom batch generator

# In[ ]:

def image_batch_generator(files, sz, batch_size = 4):

  while True: # this is here because it will be called repeatedly by the training function

    #extract a random subset of files of length "batch_size"
    batch = np.random.choice(files, size = batch_size)

    #variables for collecting batches of inputs (x) and outputs (y)
    batch_x = []
    batch_y = []

    #cycle through each image in the batch
    for f in batch:

        #preprocess the raw images
        raw = Image.open(f)
        raw = raw.resize(sz)
        raw = raw.filter(ImageFilter.UnsharpMask(radius=20, percent=100)) #apply the unsharp filter
        raw = np.array(raw)

        #check the number of channels because some of the images are RGBA or GRAY
        if len(raw.shape) == 2:
            raw = np.stack((raw,)*3, axis=-1)

        else:
            raw = raw[:,:,0:3]

        #get the image dimensions, find the min dimension, then square the image off
        nx, ny, nz = np.shape(raw)
        n = np.minimum(nx,ny)
        raw = raw[:n,:n,:]

        raw[np.isnan(raw)] = 1e-5 #turn bad values (nans and infs) into tiny numbers
        raw[np.isinf(raw)] = 1e-5

        batch_x.append(raw)

        #get the masks.
        maskfile = f.replace('_images','_labels').replace('.png','.jpg')
        mask = Image.open(maskfile)
        # the mask is 3-dimensional so get the max in each channel to flatten to 2D
        try:
           mask = np.max(np.array(mask.resize(sz)),axis=2)
        except:
           mask = np.array(mask.resize(sz))

        # class pixels are greater than 170
        mask = (mask>170).astype('int') ##170 = (2/3)*255

        mask = mask[:n,:n]

        mask[np.isnan(mask)] = 1e-5
        mask[np.isinf(mask)] = 1e-5
        batch_y.append(mask)

    #preprocess a batch of images and masks
    batch_x = np.array(batch_x) #/255. #divide image by 255 to normalize
    batch_y = np.array(batch_y)
    batch_y = np.expand_dims(batch_y,1) #add singleton dimension to batch_y

    yield (batch_x, batch_y) #yield both the image and the label together

# In[ ]:

sz = (1024, 1024)

gen = image_batch_generator(train_files, sz, batch_size = 4)

images, masks = next(gen)

plt.figure(figsize=(10,10))
plt.imshow(images[0])
plt.imshow(masks[0].squeeze(), alpha=0.25, cmap=plt.cm.Reds)

#

# In[ ]:

get_ipython().system('tar -czf train_images.tar.gz /content/1kx1k_dataset/train_images')

# Do the same for the train labels, validation images and validation labels

# In[ ]:

get_ipython().system('tar -czf train_labels.tar.gz /content/1kx1k_dataset/train_labels')

# In[ ]:

get_ipython().system('tar -czf val_images.tar.gz /content/1kx1k_dataset/val_images')

# In[ ]:

get_ipython().system('tar -czf val_labels.tar.gz /content/1kx1k_dataset/val_labels')

# finally the test set

# In[ ]:

get_ipython().system('tar -czf test_images.tar.gz /content/1kx1k_dataset/test_images')
get_ipython().system('tar -czf test_labels.tar.gz /content/1kx1k_dataset/test_labels')

# For the remainder of the tutorials, we'll be using this version of the data, consisting of imagery and image labels, with an augmented training set consisting of double the original number of imagery, half of which have been augmented with random flips, zoms and rotations

# This jupyter notebook running on Google Colab is part of the "Advanced Binary Image Segmentation for the Geo- and Eco-sciences, using Deep Learning" course. The main course website can be accessed [here](https://mardascience.gitlab.io/binary_image_segmentation_for_geosciences/#/)
#

# In[ ]:


# -*- coding: utf-8 -*-
# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: percent
#       format_version: '1.3'
#       jupytext_version: 1.11.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# %% [raw] raw_mimetype="text/restructuredtext"
#
# .. _polar: https://matplotlib.org/3.1.0/gallery/pie_and_polar_charts/polar_demo.html
#
# .. _cartopy: https://scitools.org.uk/cartopy/docs/latest/
#
# .. _basemap: https://matplotlib.org/basemap/index.html
#
# .. _ug_proj:
#
# Geographic and polar axes
# =========================
#
# This section documents several useful features for working with `polar`_ plots
# and :ref:`geographic projections <ug_geo>`. The geographic features are powered by
# `cartopy`_ (or, optionally, `basemap`_). Note that these features are *optional* --
# installation of cartopy or basemap are not required to use proplot.
#
# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_polar:
#
# Polar axes
# ----------
#
# To create `polar axes <polar_>`_, pass ``proj='polar'`` to an axes-creation
# command like `proplot.figure.Figure.add_subplot`. Polar axes are represented with the
# `~proplot.axes.PolarAxes` subclass, which has its own `~proplot.axes.PolarAxes.format`
# command. `proplot.axes.PolarAxes.format` facilitates polar-specific modifications
# like changing the central radius `r0`, the zero azimuth location `theta0`,
# and the positive azimuthal direction `thetadir`. It also supports toggling and
# configuring the "major" and "minor" gridline locations with `grid`, `rlocator`,
# `thetalocator`, `gridminor`, `rminorlocator`, and `thetaminorlocator` and formatting
# the gridline labels with `rformatter` and `thetaformatter` (analogous to `xlocator`,
# `xformatter`, and `xminorlocator` used by `proplot.axes.CartesianAxes.format`),
# and creating "annular" or "sector" plots by changing the radial or azimuthal
# bounds `rlim` and `thetalim`. Finally, since `proplot.axes.PolarAxes.format`
# calls `proplot.axes.Axes.format`, it can be used to add axes titles, a-b-c
# labels, and figure titles.
#
# For details, see `proplot.axes.PolarAxes.format`.

# %%
import proplot as pplt
import numpy as np
N = 200
state = np.random.RandomState(51423)
x = np.linspace(0, 2 * np.pi, N)[:, None] + np.arange(5) * 2 * np.pi / 5
y = 100 * (state.rand(N, 5) - 0.3).cumsum(axis=0) / N
fig, axs = pplt.subplots([[1, 1, 2, 2], [0, 3, 3, 0]], proj='polar')
axs.format(
    suptitle='Polar axes demo', linewidth=1, titlepad='1em',
    ticklabelsize=9, rlines=0.5, rlim=(0, 19),
)
for ax in axs:
    ax.plot(x, y, cycle='default', zorder=0, lw=3)

# Standard polar plot
axs[0].format(
    title='Normal plot', thetaformatter='tau',
    rlabelpos=225, rlines=pplt.arange(5, 30, 5),
    edgecolor='red8', tickpad='1em',
)

# Sector plot
axs[1].format(
    title='Sector plot', thetadir=-1, thetalines=90, thetalim=(0, 270), theta0='N',
    rlim=(0, 22), rlines=pplt.arange(5, 30, 5),
)

# Annular plot
axs[2].format(
    title='Annular plot', thetadir=-1, thetalines=20, gridcolor='red',
    r0=-20, rlim=(0, 22), rformatter='null', rlocator=2
)

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_geo:
#
# Geographic axes
# ---------------
#
# To create geographic axes, pass ``proj='name'`` to an axes-creation command like
# `proplot.figure.Figure.add_subplot`, where ``name`` is any valid :ref:`PROJ projection
# name <proj_table>`. Alternatively, you can pass a `cartopy.crs.Projection` or
# `~mpl_toolkits.basemap.Basemap` instance returned by the `~proplot.constructor.Proj`
# :ref:`constructor function <why_constructor>` to `proj` (see below for details). If
# you need different projections for different subplots, but you want to
# create your subplots :ref:`all-at-once <ug_subplot>` using
# `~proplot.figure.Figure.subplots`, you can pass a list or dictionary
# to the `proj` keyword (e.g., ``proj=('cartesian', 'pcarree')`` or
# ``proj={2: 'pcarree'}`` -- see `~proplot.figure.Figure.subplots` for details).
# Geographic axes are represented with the `~proplot.axes.GeoAxes` subclass, which
# has its own `~proplot.axes.GeoAxes.format` command. `proplot.axes.GeoAxes.format`
# facilitates :ref:`geographic-specific modifications <ug_geoformat>` like meridional
# and parallel gridlines and land mass outlines. The syntax is very similar to
# `proplot.axes.CartesianAxes.format`. Note that the `proj` keyword and several of
# the `~proplot.axes.GeoAxes.format` keywords are inspired by the basemap API.
# In the below example, we create and format a very simple geographic plot.

# %%
# Use an on-the-fly projection
import proplot as pplt
fig = pplt.figure(refwidth=3)
axs = fig.subplots(nrows=2, proj='robin', proj_kw={'lon0': 150})
# proj = pplt.Proj('robin', lon0=180)
# axs = pplt.subplots(nrows=2, proj=proj)  # equivalent to above
axs.format(
    suptitle='Figure with single projection',
    land=True, latlines=30, lonlines=60,
)

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_backends:
#
# Geographic backends
# -------------------
#
# The `proplot.axes.GeoAxes` class uses either `cartopy`_ or `basemap`_ as "backends"
# to :ref:`format the axes <ug_geoformat>` and :ref:`plot stuff <ug_geoplot>` in
# the axes. A few details:
#
# * Cartopy is the default backend. When you request projection names with cartopy
#   as the backend (or pass a `cartopy.crs.Projection` to the `proj` keyword), the
#   returned axes is a subclass of `cartopy.mpl.geoaxes.GeoAxes`. Under the hood,
#   invoking `~proplot.axes.GeoAxes.format` with cartopy as the backend changes map
#   bounds using `~cartopy.mpl.geoaxes.GeoAxes.set_extent`, adds major and minor
#   gridlines using `~cartopy.mpl.geoaxes.GeoAxes.gridlines`, and adds geographic
#   features using `~cartopy.mpl.geoaxes.GeoAxes.add_feature`. If you prefer, you can
#   use the standard `cartopy.mpl.geoaxes.GeoAxes` methods just like you would in
#   cartopy. If you need to use the underlying `~cartopy.crs.Projection` instance, it
#   is available via the `~proplot.axes.GeoAxes.projection` attribute. If you want
#   to work with the projection classes directly, they are available in the
#   top-level namespace (e.g., ``proj=pplt.PlateCarre()`` is allowed).
#
# * Basemap is an alternative backend. To use basemap, set :rcraw:`geo.backend` to
#   ``'basemap'`` or pass ``backend='basemap'`` to the axes-creation command. When
#   you request a projection name with basemap as the backend (or pass a
#   `~mpl_toolkits.basemap.Basemap` to the `proj` keyword), the returned axes
#   redirects the plotting methods plot, scatter, contour, contourf, pcolor,
#   pcolormesh, quiver, streamplot, and barb to the identically named methods on
#   the `~mpl_toolkits.basemap.Basemap` instance. This means you can work
#   with the standard axes plotting methods rather than the basemap methods --
#   just like cartopy. Under the hood, invoking `~proplot.axes.GeoAxes.format`
#   with basemap as the backend adds major and minor gridlines using
#   `~mpl_toolkits.basemap.Basemap.drawmeridians` and
#   `~mpl_toolkits.basemap.Basemap.drawparallels` and adds geographic features
#   using methods like `~mpl_toolkits.basemap.Basemap.fillcontinents`
#   and `~mpl_toolkits.basemap.Basemap.drawcoastlines`. If you need to
#   use the underlying `~mpl_toolkits.basemap.Basemap` instance, it is
#   available as the `~proplot.axes.GeoAxes.projection` attribute.
#
# Together, these features let you work with geophysical data without invoking
# verbose cartopy classes like `~cartopy.crs.LambertAzimuthalEqualArea` or
# keeping track of separate `~mpl_toolkits.basemap.Basemap` instances. This
# considerably reduces the amount of code needed to make complex geographic
# plots. In the below examples, we create a variety of plots using both
# cartopy and basemap as backends.
#
# .. important::
#
#    * By default, proplot bounds polar cartopy projections like
#      `~cartopy.crs.NorthPolarStereo` at the equator and gives non-polar cartopy
#      projections global extent by calling `~cartopy.mpl.geoaxes.GeoAxes.set_global`.
#      This is a deviation from cartopy, which determines map boundaries automatically
#      based on the coordinates of the plotted content. To revert to cartopy's
#      default behavior, set :rcraw:`geo.extent` to ``'auto`` or pass ``extent='auto'``
#      to `~proplot.axes.GeoAxes.format`.
#    * By default, proplot gives circular boundaries to polar cartopy and basemap
#      projections like `~cartopy.crs.NorthPolarStereo` (see `this example
#      <https://scitools.org.uk/cartopy/docs/latest/gallery/lines_and_polygons/always_circular_stereo.html>`__
#      from the cartopy website). To disable this feature, set :rcraw:`geo.round` to
#      ``False`` or pass ``round=False` to `~proplot.axes.GeoAxes.format`. Please note
#      that older versions of cartopy cannot add gridlines to maps bounded by circles.
#    * To make things more consistent, the `~proplot.constructor.Proj` constructor
#      function lets you supply native `PROJ <https://proj.org>`__ keyword names
#      for the cartopy `~cartopy.crs.Projection` classes (e.g., `lon0` instead
#      of `central_longitude`) and instantiates `~mpl_toolkits.basemap.Basemap`
#      projections with sensible default PROJ parameters rather than raising an error
#      when they are omitted (e.g., ``lon0=0`` as the default for most projections).
#
# .. warning::
#
#    The `basemap`_ package is `no longer actively maintained \
#    <https://matplotlib.org/basemap/users/intro.html#cartopy-new-management-and-eol-announcement>`__
#    and will not work with matplotlib versions more recent than 3.2.2. We originally
#    included basemap support because its gridline labeling was more powerful
#    than cartopy gridline labeling. However, as cartopy gridline labeling has
#    significantly improved since version 0.18, proplot may deprecate basemap support
#    in a future release and fully remove basemap support by version 1.0.0.

# %%
import proplot as pplt
fig = pplt.figure()

# Add projections
gs = pplt.GridSpec(ncols=2, nrows=3, hratios=(1, 1, 1.4))
for i, proj in enumerate(('cyl', 'hammer', 'npstere')):
    ax1 = fig.subplot(gs[i, 0], proj=proj)  # default cartopy backend
    ax2 = fig.subplot(gs[i, 1], proj=proj, backend='basemap')  # basemap backend

# Format projections
axs = fig.subplotgrid
axs.format(
    land=True,
    suptitle='Figure with several projections',
    toplabels=('Cartopy examples', 'Basemap examples'),
    toplabelweight='normal',
    latlines=30, lonlines=60,
)
axs[:2].format(lonlabels='b', latlabels='r')  # or lonlabels=True, lonlabels='bottom',
axs[2:4].format(lonlabels=False, latlabels='both')
axs[4:].format(lonlabels='all', lonlines=30)
pplt.rc.reset()

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_geoplot:
#
# Plotting in projections
# -----------------------
#
# In proplot, plotting with `~proplot.axes.GeoAxes` is just like plotting
# with `~proplot.axes.CartesianAxes`. Proplot makes longitude-latitude
# (i.e., Plate Carrée) coordinates the *default* coordinate system for all plotting
# commands by internally passing ``transform=ccrs.PlateCarree()`` to cartopy commands
# and ``latlon=True`` to basemap commands. And again, when `basemap`_ is the backend,
# plotting is done "cartopy-style" by calling methods from the `proplot.axes.GeoAxes`
# instance rather than the `~mpl_toolkits.basemap.Basemap` instance.
#
# To ensure that a 2D `~proplot.axes.PlotAxes` command like
# `~proplot.axes.PlotAxes.contour` or `~proplot.axes.PlotAxes.pcolor`
# fills the entire globe, simply pass ``globe=True`` to the command.
# This interpolates the data to the North and South poles and across the longitude
# seam before plotting. This is a convenient and succinct alternative to cartopy's
# `~cartopy.util.add_cyclic_point` and basemap's `~mpl_toolkits.basemap.addcyclic`.
#
# To draw content above or underneath a given geographic feature, simply change
# the `zorder <https://matplotlib.org/3.1.1/gallery/misc/zorder_demo.html>`__
# property for that feature. For example, to draw land patches on top of all plotted
# content as a "land mask" you can use ``ax.format(land=True, landzorder=4)`` or set
# ``pplt.rc['land.zorder'] = 4`` (see the :ref:`next section <ug_geoformat>`
# for details).

# %%
import proplot as pplt
import numpy as np

# Fake data with unusual longitude seam location and without coverage over poles
offset = -40
lon = pplt.arange(offset, 360 + offset - 1, 60)
lat = pplt.arange(-60, 60 + 1, 30)
state = np.random.RandomState(51423)
data = state.rand(len(lat), len(lon))

# Plot data both without and with globe=True
for globe in (False, True):
    string = 'with' if globe else 'without'
    gs = pplt.GridSpec(nrows=2, ncols=2)
    fig = pplt.figure(refwidth=2.5)
    for i, ss in enumerate(gs):
        cmap = ('sunset', 'sunrise')[i % 2]
        backend = ('cartopy', 'basemap')[i % 2]
        ax = fig.subplot(ss, proj='kav7', backend=backend)
        if i > 1:
            ax.pcolor(lon, lat, data, cmap=cmap, globe=globe, extend='both')
        else:
            m = ax.contourf(lon, lat, data, cmap=cmap, globe=globe, extend='both')
            fig.colorbar(m, loc='b', span=i + 1, label='values', extendsize='1.7em')
    fig.format(
        suptitle=f'Geophysical data {string} global coverage',
        toplabels=('Cartopy example', 'Basemap example'),
        leftlabels=('Filled contours', 'Grid boxes'),
        toplabelweight='normal', leftlabelweight='normal',
        coast=True, lonlines=90,
        abc='A.', abcloc='ul', abcborder=False,
    )

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_geoformat:
#
# Formatting projections
# ----------------------
#
# The `proplot.axes.GeoAxes.format` command facilitates geographic-specific axes
# modifications. It can toggle and configure the "major" and "minor" longitude and
# latitude gridline locations using the `grid`, `lonlocator`, `latlocator`, `gridminor`,
# `lonminorlocator`, and `latminorlocator` keys, and configure gridline label formatting
# with `lonformatter` and `latformatter` (analogous to `xlocator`, `xminorlocator`,
# and `xformatter` used by `proplot.axes.CartesianAxes.format`). By default, inline
# cartopy labels and cartopy label rotation are turned off, but inline labels can
# be turned on using ``loninline=True``, ``latinline=True``, or ``inlinelabels=True``
# or by setting :rcraw:`grid.inlinelabels` to ``True``, and label rotation can be
# turned on using ``rotatelabels=True`` or by setting :rcraw:`grid.rotatelabels`
# to ``True``. The padding between the map edge and the labels can be changed
# using `labelpad` or by changing :rcraw:`grid.labelpad`.
#
# `proplot.axes.GeoAxes.format` can also set the cartopy projection bounding longitudes
# and latitudes with `lonlim` and `latlim` (analogous to `xlim` and `ylim`), set the
# latitude bound for circular polar projections using `boundinglat`, and toggle and
# configure geographic features like land masses, coastlines, and administrative
# borders using :ref:`settings <rc_proplot>` like `land`, `landcolor`, `coast`,
# `coastcolor`, and `coastlinewidth`. Finally, since `proplot.axes.GeoAxes.format`
# calls `proplot.axes.Axes.format`, it can be used to add axes titles, a-b-c labels,
# and figure titles, just like `proplot.axes.CartesianAxes.format`.
#
# For details, see the `proplot.axes.GeoAxes.format` documentation.

# %%
import proplot as pplt
gs = pplt.GridSpec(ncols=3, nrows=2, wratios=(1, 1, 1.2), hratios=(1, 1.2))
fig = pplt.figure(refwidth=4)

# Styling projections in different ways
ax = fig.subplot(gs[0, :2], proj='eqearth')
ax.format(
    title='Equal earth', land=True, landcolor='navy', facecolor='pale blue',
    coastcolor='gray5', borderscolor='gray5', innerborderscolor='gray5',
    gridlinewidth=1.5, gridcolor='gray5', gridalpha=0.5,
    gridminor=True, gridminorlinewidth=0.5,
    coast=True, borders=True, borderslinewidth=0.8,
)
ax = fig.subplot(gs[0, 2], proj='ortho')
ax.format(
    title='Orthographic', reso='med', land=True, coast=True, latlines=10, lonlines=15,
    landcolor='mushroom', suptitle='Projection axes formatting demo',
    facecolor='petrol', coastcolor='charcoal', coastlinewidth=0.8, gridlinewidth=1
)
ax = fig.subplot(gs[1, :], proj='wintri')
ax.format(
    land=True, facecolor='ocean blue', landcolor='bisque', title='Winkel tripel',
    lonlines=60, latlines=15,
    gridlinewidth=0.8, gridminor=True, gridminorlinestyle=':',
    lonlabels=True, latlabels='r', loninline=True,
    gridlabelcolor='gray8', gridlabelsize='med-large',
)
fig.format(
    suptitle='Projection axes formatting demo',
    toplabels=('Column 1', 'Column 2'),
    abc='A.', abcloc='ul', abcborder=False, linewidth=1.5
)

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _ug_zoom:
#
# Zooming into projections
# ------------------------
#
# To zoom into cartopy projections, use
# `~cartopy.mpl.geoaxes.GeoAxes.set_extent` or pass `lonlim`,
# `latlim`, or `boundinglat` to `~proplot.axes.GeoAxes.format`. The `boundinglat`
# keyword controls the circular latitude boundary for North Polar and
# South Polar Stereographic, Azimuthal Equidistant, Lambert Azimuthal
# Equal-Area, and Gnomonic projections. By default, proplot tries to use the
# degree-minute-second cartopy locators and formatters made available in cartopy
# 0.18. You can switch from minute-second subintervals to traditional decimal
# subintervals by passing ``dms=False`` to `~proplot.axes.GeoAxes.format`
# or by setting :rcraw:`grid.dmslabels` to ``False``.
#
# To zoom into basemap projections, pass any of the `boundinglat`,
# `llcrnrlon`, `llcrnrlat`, `urcrnrlon`, `urcrnrlat`, `llcrnrx`, `llcrnry`,
# `urcrnrx`, `urcrnry`, `width`, or `height` keyword arguments to
# the `~proplot.constructor.Proj` constructor function either directly or via
# the `proj_kw` `~proplot.ui.subplots` keyword argument. You can also pass
# `lonlim` and `latlim` to `~proplot.constructor.Proj` and these arguments
# will be used for `llcrnrlon`, `llcrnrlat`, etc. You cannot zoom into basemap
# projections with `format` after they have already been created.

# %%
import proplot as pplt

# Plate Carrée map projection
pplt.rc.reso = 'med'  # use higher res for zoomed in geographic features
basemap = pplt.Proj('cyl', lonlim=(-20, 180), latlim=(-10, 50), backend='basemap')
fig, axs = pplt.subplots(nrows=2, refwidth=5, proj=('cyl', basemap))
axs.format(
    land=True, labels=True, lonlines=20, latlines=20,
    gridminor=True, suptitle='Zooming into projections'
)
axs[0].format(lonlim=(-140, 60), latlim=(-10, 50), labels=True)
axs[0].format(title='Cartopy example')
axs[1].format(title='Basemap example')

# %%
import proplot as pplt

# Pole-centered map projections
basemap = pplt.Proj('npaeqd', boundinglat=60, backend='basemap')
fig, axs = pplt.subplots(ncols=2, refwidth=2.7, proj=('splaea', basemap))
fig.format(suptitle='Zooming into polar projections')
axs.format(land=True, latmax=80)  # no gridlines poleward of 80 degrees
axs[0].format(boundinglat=-60, title='Cartopy example')
axs[1].format(title='Basemap example')

# %%
import proplot as pplt

# Zooming in on continents
fig = pplt.figure(refwidth=3)
ax = fig.subplot(121, proj='lcc', proj_kw={'lon0': 0})
ax.format(lonlim=(-20, 50), latlim=(30, 70), title='Cartopy example')
proj = pplt.Proj('lcc', lon0=-100, lat0=45, width=8e6, height=8e6, backend='basemap')
ax = fig.subplot(122, proj=proj)
ax.format(lonlines=20, title='Basemap example')
fig.format(suptitle='Zooming into specific regions', land=True)

# %%
import proplot as pplt

# Zooming in with cartopy degree-minute-second labels
pplt.rc.reso = 'hi'
fig = pplt.figure(refwidth=2.5)
ax = fig.subplot(121, proj='cyl')
ax.format(lonlim=(-7.5, 2), latlim=(49.5, 59))
ax = fig.subplot(122, proj='cyl')
ax.format(lonlim=(-6, -2), latlim=(54.5, 58.5))
fig.format(
    land=True, labels=True,
    borders=True, borderscolor='white',
    suptitle='Cartopy degree-minute-second labels',
)
pplt.rc.reset()

# %% [raw] raw_mimetype="text/restructuredtext"
# .. _proj_included:
#
# Included projections
# --------------------
#
# The available `cartopy <https://scitools.org.uk/cartopy/docs/latest/>`__
# and `basemap <https://matplotlib.org/basemap/index.html>`__ projections are
# plotted below. The full table of projection names with links to the relevant
# `PROJ <https://proj.org>`__ documentation is found :ref:`here <proj_table>`.
#
# Proplot uses the cartopy API to add the Aitoff, Hammer, Winkel Tripel, and
# Kavrayskiy VII projections (i.e., ``'aitoff'``, ``'hammer'``, ``'wintri'``,
# and ``'kav7'``), as well as North and South polar versions of the Azimuthal
# Equidistant, Lambert Azimuthal Equal-Area, and Gnomonic projections (i.e.,
# ``'npaeqd'``, ``'spaeqd'``, ``'nplaea'``, ``'splaea'``, ``'npgnom'``, and
# ``'spgnom'``), modeled after cartopy's existing `~cartopy.crs.NorthPolarStereo`
# and `~cartopy.crs.SouthPolarStereo` projections.

# %%
import proplot as pplt

# Table of cartopy projections
projs = [
    'cyl', 'merc', 'mill', 'lcyl', 'tmerc',
    'robin', 'hammer', 'moll', 'kav7', 'aitoff', 'wintri', 'sinu',
    'geos', 'ortho', 'nsper', 'aea', 'eqdc', 'lcc', 'gnom',
    'npstere', 'nplaea', 'npaeqd', 'npgnom', 'igh',
    'eck1', 'eck2', 'eck3', 'eck4', 'eck5', 'eck6'
]
fig, axs = pplt.subplots(ncols=3, nrows=10, figwidth=7, proj=projs)
axs.format(
    land=True, reso='lo', labels=False,
    suptitle='Table of cartopy projections'
)
for proj, ax in zip(projs, axs):
    ax.format(title=proj, titleweight='bold', labels=False)

# %%
import proplot as pplt

# Table of basemap projections
projs = [
    'cyl', 'merc', 'mill', 'cea', 'gall', 'sinu',
    'eck4', 'robin', 'moll', 'kav7', 'hammer', 'mbtfpq',
    'geos', 'ortho', 'nsper',
    'vandg', 'aea', 'eqdc', 'gnom', 'cass', 'lcc',
    'npstere', 'npaeqd', 'nplaea'
]
fig, axs = pplt.subplots(ncols=3, nrows=8, figwidth=7, proj=projs, backend='basemap')
axs.format(
    land=True, labels=False,
    suptitle='Table of basemap projections'
)
for proj, ax in zip(projs, axs):
    ax.format(title=proj, titleweight='bold', labels=False)


#!/usr/bin/env python
# coding: utf-8

# ## Supervised Learning
# ## Project: Finding Donors for *CharityML*

# In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to successfully complete this project. Sections that begin with **'Implementation'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a `'TODO'` statement. Please be sure to read the instructions carefully!
#
# In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
#
# >**Note:** Please specify WHICH VERSION OF PYTHON you are using when submitting this notebook. Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.

# ## Getting Started
#
# In this project, you will employ several supervised algorithms of your choice to accurately model individuals' income using data collected from the 1994 U.S. Census. You will then choose the best candidate algorithm from preliminary results and further optimize this algorithm to best model the data. Your goal with this implementation is to construct a model that accurately predicts whether an individual makes more than $50,000. This sort of task can arise in a non-profit setting, where organizations survive on donations.  Understanding an individual's income can help a non-profit better understand how large of a donation to request, or whether or not they should reach out to begin with.  While it can be difficult to determine an individual's general income bracket directly from public sources, we can (as we will see) infer this value from other publically available features.
#
# The dataset for this project originates from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/Census+Income). The datset was donated by Ron Kohavi and Barry Becker, after being published in the article _"Scaling Up the Accuracy of Naive-Bayes Classifiers: A Decision-Tree Hybrid"_. You can find the article by Ron Kohavi [online](https://www.aaai.org/Papers/KDD/1996/KDD96-033.pdf). The data we investigate here consists of small changes to the original dataset, such as removing the `'fnlwgt'` feature and records with missing or ill-formatted entries.

# ----
# ## Exploring the Data
# Run the code cell below to load necessary Python libraries and load the census data. Note that the last column from this dataset, `'income'`, will be our target label (whether an individual makes more than, or at most, $50,000 annually). All other columns are features about each individual in the census database.

# In[1]:

# Import libraries necessary for this project
import numpy as np
import pandas as pd
from time import time
from IPython.display import display # Allows the use of display() for DataFrames

# Import supplementary visualization code visuals.py
import visuals as vs

# Pretty display for notebooks
get_ipython().run_line_magic('matplotlib', 'inline')

# Load the Census dataset
data = pd.read_csv("census.csv")

# Success - Display the first record
display(data.head(n=1))

# ### Implementation: Data Exploration
# A cursory investigation of the dataset will determine how many individuals fit into either group, and will tell us about the percentage of these individuals making more than \$50,000. In the code cell below, you will need to compute the following:
# - The total number of records, `'n_records'`
# - The number of individuals making more than \$50,000 annually, `'n_greater_50k'`.
# - The number of individuals making at most \$50,000 annually, `'n_at_most_50k'`.
# - The percentage of individuals making more than \$50,000 annually, `'greater_percent'`.
#
# ** HINT: ** You may need to look at the table above to understand how the `'income'` entries are formatted.

# In[2]:

# TODO: Total number of records
n_records = data.shape[0]
# TODO: Number of records where individual's income is more than $50,000
#n_greater_50k=data[data['income']=='>50K'].shape[0]
# TODO: Number of records where individual's income is at most $50,000
#n_at_most_50k=data[data['income']=='<=50K'].shape[0]
n_at_most_50k, n_greater_50k = data.income.value_counts()
# TODO: Percentage of individuals whose income is more than $50,000
greater_percent=(n_greater_50k*100)/n_records

# Print the results
print("Total number of records: {}".format(n_records))
print("Individuals making more than $50,000: {}".format(n_greater_50k))
print("Individuals making at most $50,000: {}".format(n_at_most_50k))
print("Percentage of individuals making more than $50,000: {:.2f}%".format(greater_percent))

# ** Featureset Exploration **
#
# * **age**: continuous.
# * **workclass**: Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked.
# * **education**: Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-6th, Preschool.
# * **education-num**: continuous.
# * **marital-status**: Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse.
# * **occupation**: Tech-support, Craft-repair, Other-service, Sales, Exec-managerial, Prof-specialty, Handlers-cleaners, Machine-op-inspct, Adm-clerical, Farming-fishing, Transport-moving, Priv-house-serv, Protective-serv, Armed-Forces.
# * **relationship**: Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried.
# * **race**: Black, White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other.
# * **sex**: Female, Male.
# * **capital-gain**: continuous.
# * **capital-loss**: continuous.
# * **hours-per-week**: continuous.
# * **native-country**: United-States, Cambodia, England, Puerto-Rico, Canada, Germany, Outlying-US(Guam-USVI-etc), India, Japan, Greece, South, China, Cuba, Iran, Honduras, Philippines, Italy, Poland, Jamaica, Vietnam, Mexico, Portugal, Ireland, France, Dominican-Republic, Laos, Ecuador, Taiwan, Haiti, Columbia, Hungary, Guatemala, Nicaragua, Scotland, Thailand, Yugoslavia, El-Salvador, Trinadad&Tobago, Peru, Hong, Holand-Netherlands.

# ----
# ## Preparing the Data
# Before data can be used as input for machine learning algorithms, it often must be cleaned, formatted, and restructured — this is typically known as **preprocessing**. Fortunately, for this dataset, there are no invalid or missing entries we must deal with, however, there are some qualities about certain features that must be adjusted. This preprocessing can help tremendously with the outcome and predictive power of nearly all learning algorithms.

# ### Transforming Skewed Continuous Features
# A dataset may sometimes contain at least one feature whose values tend to lie near a single number, but will also have a non-trivial number of vastly larger or smaller values than that single number.  Algorithms can be sensitive to such distributions of values and can underperform if the range is not properly normalized. With the census dataset two features fit this description: '`capital-gain'` and `'capital-loss'`.
#
# Run the code cell below to plot a histogram of these two features. Note the range of the values present and how they are distributed.

# In[3]:

# Split the data into features and target label
income_raw = data['income']
features_raw = data.drop('income', axis = 1)

# Visualize skewed continuous features of original data
vs.distribution(data)

# For highly-skewed feature distributions such as `'capital-gain'` and `'capital-loss'`, it is common practice to apply a logarithmic transformation on the data so that the very large and very small values do not negatively affect the performance of a learning algorithm. Using a logarithmic transformation significantly reduces the range of values caused by outliers. Care must be taken when applying this transformation however: The logarithm of `0` is undefined, so we must translate the values by a small amount above `0` to apply the the logarithm successfully.
#
# Run the code cell below to perform a transformation on the data and visualize the results. Again, note the range of values and how they are distributed.

# In[5]:

# Log-transform the skewed features
skewed = ['capital-gain', 'capital-loss']
features_log_transformed = pd.DataFrame(data = features_raw)
features_log_transformed[skewed] = features_raw[skewed].apply(lambda x: np.log(x + 1))

# Visualize the new log distributions
vs.distribution(features_log_transformed, transformed = True)

# ### Normalizing Numerical Features
# In addition to performing transformations on features that are highly skewed, it is often good practice to perform some type of scaling on numerical features. Applying a scaling to the data does not change the shape of each feature's distribution (such as `'capital-gain'` or `'capital-loss'` above); however, normalization ensures that each feature is treated equally when applying supervised learners. Note that once scaling is applied, observing the data in its raw form will no longer have the same original meaning, as exampled below.
#
# Run the code cell below to normalize each numerical feature. We will use [`sklearn.preprocessing.MinMaxScaler`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html) for this.

# In[6]:

# Import sklearn.preprocessing.StandardScaler
from sklearn.preprocessing import MinMaxScaler

# Initialize a scaler, then apply it to the features
scaler = MinMaxScaler() # default=(0, 1)
numerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']

features_log_minmax_transform = pd.DataFrame(data = features_log_transformed)
features_log_minmax_transform[numerical] = scaler.fit_transform(features_log_transformed[numerical])

# Show an example of a record with scaling applied
display(features_log_minmax_transform.head(n = 1))

# ### Implementation: Data Preprocessing
#
# From the table in **Exploring the Data** above, we can see there are several features for each record that are non-numeric. Typically, learning algorithms expect input to be numeric, which requires that non-numeric features (called *categorical variables*) be converted. One popular way to convert categorical variables is by using the **one-hot encoding** scheme. One-hot encoding creates a _"dummy"_ variable for each possible category of each non-numeric feature. For example, assume `someFeature` has three possible entries: `A`, `B`, or `C`. We then encode this feature into `someFeature_A`, `someFeature_B` and `someFeature_C`.
#
# |   | someFeature |                    | someFeature_A | someFeature_B | someFeature_C |
# | :-: | :-: |                            | :-: | :-: | :-: |
# | 0 |  B  |  | 0 | 1 | 0 |
# | 1 |  C  | ----> one-hot encode ----> | 0 | 0 | 1 |
# | 2 |  A  |  | 1 | 0 | 0 |
#
# Additionally, as with the non-numeric features, we need to convert the non-numeric target label, `'income'` to numerical values for the learning algorithm to work. Since there are only two possible categories for this label ("<=50K" and ">50K"), we can avoid using one-hot encoding and simply encode these two categories as `0` and `1`, respectively. In code cell below, you will need to implement the following:
#  - Use [`pandas.get_dummies()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html?highlight=get_dummies#pandas.get_dummies) to perform one-hot encoding on the `'features_log_minmax_transform'` data.
#  - Convert the target label `'income_raw'` to numerical entries.
#    - Set records with "<=50K" to `0` and records with ">50K" to `1`.

# In[7]:

#import pandas as pd
from sklearn import preprocessing
# TODO: One-hot encode the 'features_log_minmax_transform' data using pandas.get_dummies()
features_final = pd.get_dummies(features_log_minmax_transform)
#display(features_final)

# TODO: Encode the 'income_raw' data to numerical values
#display(income_raw)
encoder = preprocessing.LabelEncoder()
income = encoder.fit_transform(income_raw)
#income = income_raw.apply(lambda x: 1 if x == '>50K' else 0)
#display(income)

# Print the number of features after one-hot encoding
encoded = list(features_final.columns)

print("{} total features after one-hot encoding.".format(len(encoded)))

# Uncomment the following line to see the encoded feature names
# print encoded

# ### Shuffle and Split Data
# Now all _categorical variables_ have been converted into numerical features, and all numerical features have been normalized. As always, we will now split the data (both features and their labels) into training and test sets. 80% of the data will be used for training and 20% for testing.
#
# Run the code cell below to perform this split.

# In[8]:

# Import train_test_split
from sklearn.cross_validation import train_test_split

# Split the 'features' and 'income' data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(features_final,
                                                    income,
                                                    test_size = 0.2,
                                                    random_state = 0)

# Show the results of the split
print("Training set has {} samples.".format(X_train.shape[0]))
print("Testing set has {} samples.".format(X_test.shape[0]))

# ----
# ## Evaluating Model Performance
# In this section, we will investigate four different algorithms, and determine which is best at modeling the data. Three of these algorithms will be supervised learners of your choice, and the fourth algorithm is known as a *naive predictor*.

# ### Metrics and the Naive Predictor
# *CharityML*, equipped with their research, knows individuals that make more than \$50,000 are most likely to donate to their charity. Because of this, *CharityML* is particularly interested in predicting who makes more than \$50,000 accurately. It would seem that using **accuracy** as a metric for evaluating a particular model's performace would be appropriate. Additionally, identifying someone that *does not* make more than \$50,000 as someone who does would be detrimental to *CharityML*, since they are looking to find individuals willing to donate. Therefore, a model's ability to precisely predict those that make more than \$50,000 is *more important* than the model's ability to **recall** those individuals. We can use **F-beta score** as a metric that considers both precision and recall:
#
# $$ F_{\beta} = (1 + \beta^2) \cdot \frac{precision \cdot recall}{\left( \beta^2 \cdot precision \right) + recall} $$
#
# In particular, when $\beta = 0.5$, more emphasis is placed on precision. This is called the **F$_{0.5}$ score** (or F-score for simplicity).
#
# Looking at the distribution of classes (those who make at most \$50,000, and those who make more), it's clear most individuals do not make more than \$50,000. This can greatly affect **accuracy**, since we could simply say *"this person does not make more than \$50,000"* and generally be right, without ever looking at the data! Making such a statement would be called **naive**, since we have not considered any information to substantiate the claim. It is always important to consider the *naive prediction* for your data, to help establish a benchmark for whether a model is performing well. That been said, using that prediction would be pointless: If we predicted all people made less than \$50,000, *CharityML* would identify no one as donors.
#
#
# #### Note: Recap of accuracy, precision, recall
#
# ** Accuracy ** measures how often the classifier makes the correct prediction. It’s the ratio of the number of correct predictions to the total number of predictions (the number of test data points).
#
# ** Precision ** tells us what proportion of messages we classified as spam, actually were spam.
# It is a ratio of true positives(words classified as spam, and which are actually spam) to all positives(all words classified as spam, irrespective of whether that was the correct classificatio), in other words it is the ratio of
#
# `[True Positives/(True Positives + False Positives)]`
#
# ** Recall(sensitivity)** tells us what proportion of messages that actually were spam were classified by us as spam.
# It is a ratio of true positives(words classified as spam, and which are actually spam) to all the words that were actually spam, in other words it is the ratio of
#
# `[True Positives/(True Positives + False Negatives)]`
#
# For classification problems that are skewed in their classification distributions like in our case, for example if we had a 100 text messages and only 2 were spam and the rest 98 weren't, accuracy by itself is not a very good metric. We could classify 90 messages as not spam(including the 2 that were spam but we classify them as not spam, hence they would be false negatives) and 10 as spam(all 10 false positives) and still get a reasonably good accuracy score. For such cases, precision and recall come in very handy. These two metrics can be combined to get the F1 score, which is weighted average(harmonic mean) of the precision and recall scores. This score can range from 0 to 1, with 1 being the best possible F1 score(we take the harmonic mean as we are dealing with ratios).

# ### Question 1 - Naive Predictor Performace
# * If we chose a model that always predicted an individual made more than $50,000, what would  that model's accuracy and F-score be on this dataset? You must use the code cell below and assign your results to `'accuracy'` and `'fscore'` to be used later.
#
# ** Please note ** that the the purpose of generating a naive predictor is simply to show what a base model without any intelligence would look like. In the real world, ideally your base model would be either the results of a previous model or could be based on a research paper upon which you are looking to improve. When there is no benchmark model set, getting a result better than random choice is a place you could start from.
#
# ** HINT: **
#
# * When we have a model that always predicts '1' (i.e. the individual makes more than 50k) then our model will have no True Negatives(TN) or False Negatives(FN) as we are not making any negative('0' value) predictions. Therefore our Accuracy in this case becomes the same as our Precision(True Positives/(True Positives + False Positives)) as every prediction that we have made with value '1' that should have '0' becomes a False Positive; therefore our denominator in this case is the total number of records we have in total.
# * Our Recall score(True Positives/(True Positives + False Negatives)) in this setting becomes 1 as we have no False Negatives.

# In[10]:

'''
TP = np.sum(income) # Counting the ones as this is the naive case. Note that 'income' is the 'income_raw' data
encoded to numerical values done in the data preprocessing step.
FP = income.count() - TP # Specific to the naive case

TN = 0 # No predicted negatives in the naive case
FN = 0 # No predicted negatives in the naive case
'''
TP = np.count_nonzero(income)
#FP = len(income) - TP
FP = np.count_nonzero(income==0)
# TODO: Calculate accuracy, precision and recall
accuracy = TP/(TP+FP)
recall = 1 # TP/TP
precision = TP/(TP+FP)

# TODO: Calculate F-score using the formula above for beta = 0.5 and correct values for precision and recall.
fscore = (1+(0.5*0.5))*((precision*recall)/((0.5*0.5*precision)+recall))

# Print the results
print("Naive Predictor: [Accuracy score: {:.4f}, F-score: {:.4f}]".format(accuracy, fscore))

# ###  Supervised Learning Models
# **The following are some of the supervised learning models that are currently available in** [`scikit-learn`](http://scikit-learn.org/stable/supervised_learning.html) **that you may choose from:**
# - Gaussian Naive Bayes (GaussianNB)
# - Decision Trees
# - Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting)
# - K-Nearest Neighbors (KNeighbors)
# - Stochastic Gradient Descent Classifier (SGDC)
# - Support Vector Machines (SVM)
# - Logistic Regression

# ### Question 2 - Model Application
# List three of the supervised learning models above that are appropriate for this problem that you will test on the census data. For each model chosen
#
# - Describe one real-world application in industry where the model can be applied.
# - What are the strengths of the model; when does it perform well?
# - What are the weaknesses of the model; when does it perform poorly?
# - What makes this model a good candidate for the problem, given what you know about the data?
#
# ** HINT: **
#
# Structure your answer in the same format as above^, with 4 parts for each of the three models you pick. Please include references with your answer.

# **Answer:**
#
# Ensemble Methods:
#
# - Describe one real-world application in industry where the model can be applied.
#
#     This is machine learning techniques that combines several base model to produce one optimal predictive model.Type of  Ensemble Methods are Bagging, AdaBoost, Random Forest, Gradient Boosting. The Ensemble Method can fit in many real-world application. One of the important application is Face Recognition
#
# - What are the strengths of the model; when does it perform well?
#
#     1. Difficult to over-fit
#     2. Requires little additional parameter tuning
#     3. Accommodates high non-linear interactions
#     4. This method work with robust performance on outliers.
#
# - What are the weaknesses of the model; when does it perform poorly?
#
#     1. Need more storage
#     2. More computation power
#     3. All of the classifiers need to be processed, rather than just one, so run time of the algorithm very high
#
# - What makes this model a good candidate for the problem, given what you know about the data?
#
#     Above task is to construct a model to perform binary classification of whether an individual income over 50K or not. So, Ensemble Methods should generate good classification results.
#
#     Reference:
#     - https://www.datasciencecentral.com/m/blogpost?id=6448529%3ABlogPost%3A428995
#     - http://phirilytics.blogspot.com/2017/07/ensemble-model-strengthsand-some.html
#     - https://blog.statsbot.co/ensemble-learning-d1dcd548e936
#
# - Discussion about AdaBoost:
#     - AdaBoost is an ensemble classifier model to create high accurate prediction rule by combining many relatively weak and inaccurate rules. Most widely used and well studied algorithm with the applications in numerous fields. More preciesly, Adaboost is a meta-algorithm for machine learning which is an actual machine learning model rather than a way to combine machine learning model. Adaboost is a combination of other Ensemble machine learning classifier e.g. Regression, B-trees, Random forests, Neural Networks). It is taking several weak predictive models and combining them in weighted fashion to form a new classifier.
#
#     - Concept: AdaBoost is for improving weak learners. Each iteration of boosting creates three weak classifiers as mentioned below-
#         1. Classifier is trained normally on a subset of the data
#         2. Classifier is trained on data in which the first classifier achieved only 50% correct identification
#         3. Classifier is trained on data for which the first and second classifier disagree
#
#     - Strengths:
#         - Often the best possible model
#         - Directly optimizes the cost function
#         - Recomended for high bias
#     - Weaknesses:
#         - Not robust against outliers and noise
#         - Can overfit
#         - Need to find proper stopping point
#         - Several hyper-parameters
#         - Lack of transparancy due to the complexity of multiple trees
#         - Not recomended for high variance
#
#     Reference:
#     - https://users.lal.in2p3.fr/kegl/teaching/stages/notes/tutorial
#     - https://towardsdatascience.com/adaboost-for-dummies-breaking-down-the-math-and-its-equations-into-simple-terms-87f439757dcf
#
# Decision Trees:
#
# - Describe one real-world application in industry where the model can be applied.
#
#     One of the  most important applications is 'Automated Identification of Cosmic-Ray' . This algorithm is fit for any kind of prediction.
#
# - What are the strengths of the model; when does it perform well?
#
#     1. Less computing power
#     2. Handle both numerical and geographical data easily
#     3. Reduce ambiguity
#
# - What are the weaknesses of the model; when does it perform poorly?
#
#     1. Highly prone to overfit
#     2. Optimal decision tree is NP-complete problem
#     3. Prone to sampling
#     4. Tree splitting is locally greedy
#
# - What makes this model a good candidate for the problem, given what you know about the data?
#
#     For This problem, Decision Tree models are particularly proficient at binary classification, This algorithm may run with problems due to the number of features, extra attention necessary to sellect feature.
#
#     Reference:
#     - https://en.wikipedia.org/wiki/Decision_tree_learning
#     - https://www.brighthubpm.com/project-planning/106000-advantages-of-decision-tree-analysis/
#     - http://www.simafore.com/blog/bid/62333/4-key-advantages-of-using-decision-trees-for-predictive-analytics
#
# Support Vector Machines (SVM):
#
# - Describe one real-world application in industry where the model can be applied.
#
#     This algorith can be used in many real-worl application. One of the importatnt application Image Clasification.
#
# - What are the strengths of the model; when does it perform well?
#
#     1. This algorithm will in complicated domains
#     2. Can easily identify complex relationship as this is non-linear
#     3. This algorithm perfom both classification and regression
#
# - What are the weaknesses of the model; when does it perform poorly?
#
#     1. The complex data transformations and resulting boundary plane are very difficult to interpret.
#     2. In large datasets it does not work well.
#     3. Don't work well when there's lots of noise, as this algoright can overfit to noise in the data
#
# - What makes this model a good candidate for the problem, given what you know about the data?
#
#     This non-linear classification algorithm which may prove useful for this dataset. In large dataset with too many features, SVM will perform better.
#
#     Reference:
#     - https://en.wikipedia.org/wiki/Support_vector_machine
#     - https://www.kdnuggets.com/2016/07/support-vector-machines-simple-explanation.html

# ### Implementation - Creating a Training and Predicting Pipeline
# To properly evaluate the performance of each model you've chosen, it's important that you create a training and predicting pipeline that allows you to quickly and effectively train models using various sizes of training data and perform predictions on the testing data. Your implementation here will be used in the following section.
# In the code block below, you will need to implement the following:
#  - Import `fbeta_score` and `accuracy_score` from [`sklearn.metrics`](http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics).
#  - Fit the learner to the sampled training data and record the training time.
#  - Perform predictions on the test data `X_test`, and also on the first 300 training points `X_train[:300]`.
#    - Record the total prediction time.
#  - Calculate the accuracy score for both the training subset and testing set.
#  - Calculate the F-score for both the training subset and testing set.
#    - Make sure that you set the `beta` parameter!

# In[11]:

# TODO: Import two metrics from sklearn - fbeta_score and accuracy_score
from sklearn.metrics import fbeta_score
from sklearn.metrics import accuracy_score

def train_predict(learner, sample_size, X_train, y_train, X_test, y_test):
    '''
    inputs:
       - learner: the learning algorithm to be trained and predicted on
       - sample_size: the size of samples (number) to be drawn from training set
       - X_train: features training set
       - y_train: income training set
       - X_test: features testing set
       - y_test: income testing set
    '''

    results = {}

    # TODO: Fit the learner to the training data using slicing with 'sample_size' using .fit(training_features[:], training_labels[:])
    start = time() # Get start time
    learner = learner.fit(X_train[:sample_size], y_train[:sample_size])
    end = time() # Get end time

    # TODO: Calculate the training time
    results['train_time'] = (end - start)

    # TODO: Get the predictions on the test set(X_test),
    #       then get predictions on the first 300 training samples(X_train) using .predict()
    start = time() # Get start time
    predictions_test = learner.predict(X_test)
    predictions_train = learner.predict(X_train[:300])
    end = time() # Get end time

    # TODO: Calculate the total prediction time
    results['pred_time'] = (end - start)

    # TODO: Compute accuracy on the first 300 training samples which is y_train[:300]
    results['acc_train'] = accuracy_score(y_train[:300], predictions_train)

    # TODO: Compute accuracy on test set using accuracy_score()
    results['acc_test'] = accuracy_score(y_test, predictions_test)

    # TODO: Compute F-score on the the first 300 training samples using fbeta_score()
    results['f_train'] = fbeta_score(y_train[:300], predictions_train, average='binary', beta=0.5)

    # TODO: Compute F-score on the test set which is y_test
    results['f_test'] = fbeta_score(y_test, predictions_test, average='binary', beta=0.5)

    # Success
    print("{} trained on {} samples.".format(learner.__class__.__name__, sample_size))

    # Return the results
    return results

# ### Implementation: Initial Model Evaluation
# In the code cell, you will need to implement the following:
# - Import the three supervised learning models you've discussed in the previous section.
# - Initialize the three models and store them in `'clf_A'`, `'clf_B'`, and `'clf_C'`.
#   - Use a `'random_state'` for each model you use, if provided.
#   - **Note:** Use the default settings for each model — you will tune one specific model in a later section.
# - Calculate the number of records equal to 1%, 10%, and 100% of the training data.
#   - Store those values in `'samples_1'`, `'samples_10'`, and `'samples_100'` respectively.
#
# **Note:** Depending on which algorithms you chose, the following implementation may take some time to run!

# In[12]:

# TODO: Import the three supervised learning models from sklearn
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC

# TODO: Initialize the three models
clf_A = AdaBoostClassifier(random_state = 1)
clf_B = DecisionTreeClassifier(random_state = 1)
clf_C = SVC(random_state = 1)

# TODO: Calculate the number of samples for 1%, 10%, and 100% of the training data
# HINT: samples_100 is the entire training set i.e. len(y_train)
# HINT: samples_10 is 10% of samples_100 (ensure to set the count of the values to be `int` and not `float`)
# HINT: samples_1 is 1% of samples_100 (ensure to set the count of the values to be `int` and not `float`)
samples_100 = len(X_train)
samples_10 = int(samples_100/10)
samples_1 = int(samples_100/100)
#print(X_train)
# Collect results on the learners
results = {}
for clf in [clf_A, clf_B, clf_C]:
    clf_name = clf.__class__.__name__
    results[clf_name] = {}
    for i, samples in enumerate([samples_1, samples_10, samples_100]):
        results[clf_name][i] =         train_predict(clf, samples, X_train, y_train, X_test, y_test)

# Run metrics visualization for the three supervised learning models chosen
vs.evaluate(results, accuracy, fscore)

# ----
# ## Improving Results
# In this final section, you will choose from the three supervised learning models the *best* model to use on the student data. You will then perform a grid search optimization for the model over the entire training set (`X_train` and `y_train`) by tuning at least one parameter to improve upon the untuned model's F-score.

# ### Question 3 - Choosing the Best Model
#
# * Based on the evaluation you performed earlier, in one to two paragraphs, explain to *CharityML* which of the three models you believe to be most appropriate for the task of identifying individuals that make more than \$50,000.
#
# ** HINT: **
# Look at the graph at the bottom left from the cell above(the visualization created by `vs.evaluate(results, accuracy, fscore)`) and check the F score for the testing set when 100% of the training set is used. Which model has the highest score? Your answer should include discussion of the:
# * metrics - F score on the testing when 100% of the training data is used,
# * prediction/training time
# * the algorithm's suitability for the data.

# **Answer:**
# AdaBoost Classifier is most appropriate for the task of identifying individuals income more than $50,000. This model provides higher accurac score and F-score with the data set compare to
# Decesion Tree Classifier or the SVM Classifier. Drawback in Decision Tree Classifier is overfit on the training data as this algorithm perform well with 300 samples of training data than on test data.
# Drawback of the SVM is used to train the classifier and then to make predictions is making moe challenging. This model unable to calculate F-score with training data subset as well as testing data subset,
# because of this classifier can't predict a possitive class. For above resesons, Decision Tree and SVM Classifier not choosen. The AdaBoost classifier perform well on binary classification and it
# would appear best model for CharityML.

# ### Question 4 - Describing the Model in Layman's Terms
#
# * In one to two paragraphs, explain to *CharityML*, in layman's terms, how the final model chosen is supposed to work. Be sure that you are describing the major qualities of the model, such as how the model is trained and how the model makes a prediction. Avoid using advanced mathematical jargon, such as describing equations.
#
# ** HINT: **
#
# When explaining your model, if using external resources please include all citations.

# **Answer:**
# - AdaBoost is an ensemble classifier model to create high accurate prediction rule by combining many relatively weak and inaccurate rules. Most widely used and well studied algorithm with the applications in numerous fields. More preciesly, Adaboost is a meta-algorithm for machine learning which is an actual machine learning model rather than a way to combine machine learning model. Adaboost is a combination of other Ensemble machine learning classifier e.g. Regression, B-trees, Random forests, Neural Networks). It is taking several weak predictive models and combining them in weighted fashion to form a new classifier.
#
#     - How the model is trained?
#         - AdaBoost is for improving weak learners. Each iteration of boosting creates three weak classifiers as mentioned below-
#             1. Classifier is trained normally on a subset of the data
#             2. Classifier is trained on data in which the first classifier achieved only 50% correct identification
#             3. Classifier is trained on data for which the first and second classifier disagree
#     - Explaination:
#         - Weak classifier "decision stump" is pepared on the training data using the weighted samples. Only binary classification problems are supported, so each decision stump makes one decision on one input variable and outputs either +1.0 or -1.0 value for the first or second class value. The misclassification rate is calculated for the trained model as error = (correct – N) / N Where "error" is the misclassification rate, "correct" are the number of training instance predicted correctly by the model and "N" is total number of training instances.
#         - Example: if the model predicted 78 of 100 training instances correctly the misclassification rate would be (78-100)/100 = 0.22. This is modified to use the weighting of the training instances: The weighted sum of the misclassification rate: error = sum(w(i) * terror(i)) / sum(w) where "w" is weight for training instance, "i" and "terror" is the prediction error for training instance i which is 1 if misclassified and 0 if correctly classified
#
#         - A stage value is calculated for the trained model which provides a weighting for any predictions that the model makes. The stage value for a trained model is calculated as follows: weight predictions from the model (stage) = ln((1-error) / error) Where ln() is the natural logarithm and "error" is the misclassification error for the model. The effect of the stage weight is that more accurate models have more weight or contribution to the final prediction.
#         - The training weights are updated giving more weight to incorrectly predicted instances, and less weight to correctly predicted instances. The weight of one training instance (w) is updated using: w = w * exp(stage * terror) Where w is the weight for a specific training instance, exp() is numerical constant "Euler’s number raised to a power, stage is the misclassification rate for the weak classifier and terror is weak classifier made predicting the output variable for the training instance, evaluated as:If output variable for the training instance (y) equal to prediction from the weak learner(p)terror = 0 , otherewise terror = 1
#         - This has the effect of not changing the weight if the training instance was classified correctly and making the weight slightly larger if the weak learner misclassified the instance.
#
#     - Weak learners: A 'weak' learner is nothing but, which performs relatively poor (rules of thumb which classify the data correctly at better than 50%). Its accuracy is above chance, but just barely. There is often, but not always, the added implication that it is computationally simple. Weak learner also suggests that many instances of the algorithm are being pooled (via boosting, bagging, etc) together into to create a "strong" classifier.
#
#     - Predictions are made by calculating the weighted average of the weak classifiers. For instance, each weak learner calculates a predicted value as either +1.0 or -1.0. The predicted values are weighted by each weak learners stage value. The prediction for the AdaBoost model is taken as a the sum of the weighted predictions. If the sum is positive, then the first class is predicted, if negative the second class is predicted.
#
#  - Conclution: Mixing different models together with differing weights can help to improve classification and prediction. Interestingly, if more models included, get better the classification. This is unique and somewhat counterintuitive property of boosting methods because one would assume adding more models would lead to overfitting, but it does not occur.
# - Reference:
#     - https://towardsdatascience.com/adaboost-for-dummies-breaking-down-the-math-and-its-equations-into-simple-terms-87f439757dcf
#     - https://users.lal.in2p3.fr/kegl/teaching/stages/notes/tutorial
#     - http://www-math.mit.edu/~rothvoss/18.304.3PM/Presentations/1-Eric-Boosting304FinalRpdf.pdf
#     - https://prateekvjoshi.com/2014/05/05/what-is-adaboost/
#     - https://machinelearningmastery.com/boosting-and-adaboost-for-machine-learning/

# ### Implementation: Model Tuning
# Fine tune the chosen model. Use grid search (`GridSearchCV`) with at least one important parameter tuned with at least 3 different values. You will need to use the entire training set for this. In the code cell below, you will need to implement the following:
# - Import [`sklearn.grid_search.GridSearchCV`](http://scikit-learn.org/0.17/modules/generated/sklearn.grid_search.GridSearchCV.html) and [`sklearn.metrics.make_scorer`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html).
# - Initialize the classifier you've chosen and store it in `clf`.
#  - Set a `random_state` if one is available to the same state you set before.
# - Create a dictionary of parameters you wish to tune for the chosen model.
#  - Example: `parameters = {'parameter' : [list of values]}`.
#  - **Note:** Avoid tuning the `max_features` parameter of your learner if that parameter is available!
# - Use `make_scorer` to create an `fbeta_score` scoring object (with $\beta = 0.5$).
# - Perform grid search on the classifier `clf` using the `'scorer'`, and store it in `grid_obj`.
# - Fit the grid search object to the training data (`X_train`, `y_train`), and store it in `grid_fit`.
#
# **Note:** Depending on the algorithm chosen and the parameter list, the following implementation may take some time to run!

# In[18]:

# TODO: Import 'GridSearchCV', 'make_scorer', and any other necessary libraries
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import make_scorer
from sklearn.ensemble import AdaBoostClassifier

# TODO: Initialize the classifier
clf = AdaBoostClassifier(random_state = 1)

# TODO: Create the parameters list you wish to tune, using a dictionary if needed.
# HINT: parameters = {'parameter_1': [value1, value2], 'parameter_2': [value1, value2]}
parameters = {'n_estimators' : [50,75,100,200], 'learning_rate' : [0.5,0.8,1,1.2]}

# TODO: Make an fbeta_score scoring object using make_scorer()
scorer = make_scorer(fbeta_score, beta=0.5)

# TODO: Perform grid search on the classifier using 'scorer' as the scoring method using GridSearchCV()
grid_obj =  GridSearchCV(clf, parameters, scoring=scorer)

# TODO: Fit the grid search object to the training data and find the optimal parameters using fit()
grid_fit = grid_obj.fit(X_train, y_train)

# Get the estimator
best_clf = grid_fit.best_estimator_

# Make predictions using the unoptimized and model
predictions = (clf.fit(X_train, y_train)).predict(X_test)
best_predictions = best_clf.predict(X_test)

# Report the before-and-afterscores
print("Unoptimized model\n------")
print("Accuracy score on testing data: {:.4f}".format(accuracy_score(y_test, predictions)))
print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, predictions, beta = 0.5)))
print("\nOptimized Model\n------")
print("Final accuracy score on the testing data: {:.4f}".format(accuracy_score(y_test, best_predictions)))
print("Final F-score on the testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta = 0.5)))

# ### Question 5 - Final Model Evaluation
#
# * What is your optimized model's accuracy and F-score on the testing data?
# * Are these scores better or worse than the unoptimized model?
# * How do the results from your optimized model compare to the naive predictor benchmarks you found earlier in **Question 1**?_
#
# **Note:** Fill in the table below with your results, and then provide discussion in the **Answer** box.

# #### Results:
#
# |     Metric     | Unoptimized Model | Optimized Model |
# | :------------: | :---------------: | :-------------: |
# | Accuracy Score |     0.8576        |     0.8646      |
# | F-score        |     0.7246        |     0.3765      |
#

# **Answer:**
# Both of the unoptimized and optimized models work better with this data set compare to naive predictor result found in Question 1. Optimized model also slightly better than
# the unoptimized model. Table above shown the comparison result for both Optimized and Unoptimized model.

# ----
# ## Feature Importance
#
# An important task when performing supervised learning on a dataset like the census data we study here is determining which features provide the most predictive power. By focusing on the relationship between only a few crucial features and the target label we simplify our understanding of the phenomenon, which is most always a useful thing to do. In the case of this project, that means we wish to identify a small number of features that most strongly predict whether an individual makes at most or more than \$50,000.
#
# Choose a scikit-learn classifier (e.g., adaboost, random forests) that has a `feature_importance_` attribute, which is a function that ranks the importance of features according to the chosen classifier.  In the next python cell fit this classifier to training set and use this attribute to determine the top 5 most important features for the census dataset.

# ### Question 6 - Feature Relevance Observation
# When **Exploring the Data**, it was shown there are thirteen available features for each individual on record in the census data. Of these thirteen records, which five features do you believe to be most important for prediction, and in what order would you rank them and why?

# **Answer:**
# 1. Education-num: Econometrics model would be used as an example during my Economics degree was one that showed that having higher levels of education is correlated with higher income.
# 2. Hours worked Around 40 hours mark would have less of an explanatory impact, but those working say 15-20 hours in a week would be more likely to be earning incomes lower than $50k on the other hand, incomes would be above $50k, those who all are working 80 hours or above in a week.
# 3. Capital gain: Would make sense; those who are earning more would also receive capital gains throughout the year, as they are more likely to have disposable income to allocate to their investment portfolios.
# 4. Age: those who all are elder, earn higher incomes than those who all are younger, because they have more years of experience.
# 5. Occupation: There are few occupations that earn workers more than others; In this dataset the categories 'Exec-managerial' and 'Prof-speciality' indicated have higher incomes. Reason for this is a well paying jobs typically require some sort of degree qualification.

# ### Implementation - Extracting Feature Importance
# Choose a `scikit-learn` supervised learning algorithm that has a `feature_importance_` attribute availble for it. This attribute is a function that ranks the importance of each feature when making predictions based on the chosen algorithm.
#
# In the code cell below, you will need to implement the following:
#  - Import a supervised learning model from sklearn if it is different from the three used earlier.
#  - Train the supervised model on the entire training set.
#  - Extract the feature importances using `'.feature_importances_'`.

# In[15]:

# TODO: Import a supervised learning model that has 'feature_importances_'
from sklearn.ensemble import AdaBoostClassifier

# TODO: Train the supervised model on the training set using .fit(X_train, y_train)
classifier = AdaBoostClassifier(random_state = 1)
model = classifier.fit(X_train, y_train)

# TODO: Extract the feature importances using .feature_importances_
importances = model.feature_importances_

# Plot
vs.feature_plot(importances, X_train, y_train)

# ### Question 7 - Extracting Feature Importance
#
# Observe the visualization created above which displays the five most relevant features for predicting if an individual makes at most or above \$50,000.
# * How do these five features compare to the five features you discussed in **Question 6**?
# * If you were close to the same answer, how does this visualization confirm your thoughts?
# * If you were not close, why do you think these features are more relevant?

# **Answer:**
# - How do these five features compare to the five features you discussed in Question 6?
# As discribed in question 6 above 5 features would be better predction for Adaboost and it may vary depending on the model used. And my #5 choice of Occupation is substitute of capital-loss for this data set.
#
# - If you were close to the same answer, how does this visualization confirm your thoughts?
# I was close to the answer. I agree capital loss, age, capital gain, hours per week and education are main feautures to predict an individual makes more than 50,000 USD.
#
# - If you were not close, why do you think these features are more relevant?
# As per me also Occupation features stands in top 5 in deciding the same beacause person working having good occupation earns more compared to person having some low occupation.

# ### Feature Selection
# How does a model perform if we only use a subset of all the available features in the data? With less features required to train, the expectation is that training and prediction time is much lower — at the cost of performance metrics. From the visualization above, we see that the top five most important features contribute more than half of the importance of **all** features present in the data. This hints that we can attempt to *reduce the feature space* and simplify the information required for the model to learn. The code cell below will use the same optimized model you found earlier, and train it on the same training set *with only the top five important features*.

# In[16]:

# Import functionality for cloning a model
from sklearn.base import clone

# Reduce the feature space
X_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]
X_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]

# Train on the "best" model found from grid search earlier
clf = (clone(best_clf)).fit(X_train_reduced, y_train)

# Make new predictions
reduced_predictions = clf.predict(X_test_reduced)

# Report scores from the final model using both versions of data
print("Final Model trained on full data\n------")
print("Accuracy on testing data: {:.4f}".format(accuracy_score(y_test, best_predictions)))
print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta = 0.5)))
print("\nFinal Model trained on reduced data\n------")
print("Accuracy on testing data: {:.4f}".format(accuracy_score(y_test, reduced_predictions)))
print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, reduced_predictions, beta = 0.5)))

# ### Question 8 - Effects of Feature Selection
#
# * How does the final model's F-score and accuracy score on the reduced data using only five features compare to those same scores when all features are used?
# * If training time was a factor, would you consider using the reduced data as your training set?

# **Answer:**
# Accuracy score: 0.8646 is higher with Final Model trained on Full Data Set than accuracy score: 0.8357 with Final Model trained on Reduced Data Set.
# Similarly F-score: 0.7365 is also higher than reduced data set F-score: 0.6850.
# With Laege data set, if the choosen model take long time to train, then training time is important factor to consider. As per the result comparison the
# final model trained with reduced data set would be best approach but it may not be ideal.

# > **Note**: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to
# **File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.

# ##Before You Submit
# You will also need run the following in order to convert the Jupyter notebook into HTML, so that your submission will include both files.

# In[19]:

get_ipython().getoutput('jupyter nbconvert *.ipynb')

# In[ ]:


#!/usr/bin/env python
# coding: utf-8

# (file-types:notebooks)=
# # Jupyter Notebook files
#
# You can create content with Jupyter notebooks.
# For example, the content for the current page is contained in {download}`this notebook file <./notebooks.ipynb>`.
#
# ```{margin}
# If you'd like to write in plain-text files, but still keep a notebook structure, you can write
# Jupyter notebooks with MyST Markdown, which are then automatically converted to notebooks.
# See [](./myst-notebooks.md) for more details.
# ```
#
# Jupyter Book supports all Markdown that is supported by Jupyter Notebook.
# This is mostly a flavour of Markdown called [CommonMark Markdown](https://commonmark.org/) with minor modifications.
# For more information about writing Jupyter-flavoured Markdown in Jupyter Book, see [](./markdown.md).
#
# ## Code blocks and image outputs
#
# Jupyter Book will also embed your code blocks and output in your book.
# For example, here's some sample Matplotlib code:

# In[1]:

from matplotlib import rcParams, cycler
import matplotlib.pyplot as plt
import numpy as np
plt.ion()

# In[2]:

# Fixing random state for reproducibility
np.random.seed(19680801)

N = 10
data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
data = np.array(data).T
cmap = plt.cm.coolwarm
rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))

from matplotlib.lines import Line2D
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
                Line2D([0], [0], color=cmap(.5), lw=4),
                Line2D([0], [0], color=cmap(1.), lw=4)]

fig, ax = plt.subplots(figsize=(10, 5))
lines = ax.plot(data)
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot']);

# Note that the image above is captured and displayed in your site.

# In[3]:

# Fixing random state for reproducibility
np.random.seed(19680801)

N = 10
data = [np.logspace(0, 1, 100) + .1*np.random.randn(100) + ii for ii in range(N)]
data = np.array(data).T
cmap = plt.cm.coolwarm
rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))

from matplotlib.lines import Line2D
custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
                Line2D([0], [0], color=cmap(.5), lw=4),
                Line2D([0], [0], color=cmap(1.), lw=4)]

fig, ax = plt.subplots(figsize=(10, 5))
lines = ax.plot(data)
ax.legend(custom_lines, ['Cold', 'Medium', 'Hot'])
ax.set(title="Smoother linez")

# ```{margin} **You can also pop out content to the side!**
# For more information on how to do this,
# check out the {ref}`layout/sidebar` section.
# ```

# ## Removing content before publishing
#
# You can also remove some content before publishing your book to the web.
# For reference, {download}`you can download the notebook content for this page <notebooks.ipynb>`.

# In[4]:

thisvariable = "none of this should show up in the textbook"

fig, ax = plt.subplots()
x = np.random.randn(100)
y = np.random.randn(100)
ax.scatter(x, y, s=np.abs(x*100), c=x, cmap=plt.cm.coolwarm)
ax.text(0, .5, thisvariable, fontsize=20, transform=ax.transAxes)
ax.set_axis_off()

# You can **remove only the code** so that images and other output still show up.

# In[5]:

thisvariable = "this plot *will* show up in the textbook."

fig, ax = plt.subplots()
x = np.random.randn(100)
y = np.random.randn(100)
ax.scatter(x, y, s=np.abs(x*100), c=x, cmap=plt.cm.coolwarm)
ax.text(0, .5, thisvariable, fontsize=20, transform=ax.transAxes)
ax.set_axis_off()

# Which works well if you'd like to quickly display cell output without cluttering your content with code.
# This works for any cell output, like a Pandas DataFrame.

# In[6]:

import pandas as pd
pd.DataFrame([['hi', 'there'], ['this', 'is'], ['a', 'DataFrame']], columns=['Word A', 'Word B'])

# See {ref}`hiding/remove-content` for more information about hiding and removing content.

# ## Interactive outputs
#
# We can do the same for *interactive* material. Below we'll display a map
# using [folium](https://python-visualization.github.io/folium/). When your book is built,
# the code for creating the interactive map is retained.
#
# ```{margin}
# **This will only work for some packages.** They need to be able to output standalone
# HTML/Javascript, and not
# depend on an underlying Python kernel to work.
# ```

# In[7]:

import folium
m = folium.Map(
    location=[45.372, -121.6972],
    zoom_start=12,
    tiles='Stamen Terrain'
)

folium.Marker(
    location=[45.3288, -121.6625],
    popup='Mt. Hood Meadows',
    icon=folium.Icon(icon='cloud')
).add_to(m)

folium.Marker(
    location=[45.3311, -121.7113],
    popup='Timberline Lodge',
    icon=folium.Icon(color='green')
).add_to(m)

folium.Marker(
    location=[45.3300, -121.6823],
    popup='Some Other Location',
    icon=folium.Icon(color='red', icon='info-sign')
).add_to(m)

m

# ## Rich outputs from notebook cells

# Because notebooks have rich text outputs, you can store these in
# your Jupyter Book as well! For example, here is the command line help
# menu, see how it is nicely formatted.

# In[8]:

get_ipython().system('jupyter-book build --help')

# And here is an error. You can mark notebook cells as "expected to error" by adding a
# `raises-exception` tag to them.

# In[9]:

this_will_error

# ## More features with Jupyter notebooks
#
# There are many other features of Jupyter notebooks to take advantage of,
# such as automatically generating Binder links for notebooks or connecting your content with a kernel in the cloud.
# For more information browse the pages in this site, and [](content:code-outputs) in particular.