# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/toraaglobal/Case_Studies/blob/master/Perceptron_Iris.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + id="SIHHQjD35syL" colab_type="code" colab={}
# Python 3.5.4 |Continuum Analytics, Inc.|
# Jupyter Notebook 5.0.0

# SAMPLE CODE FROM RASCHKA (2015)
# PERCEPTRON CLASSIFICATION FOR IRIS DATA
import numpy as np
import pandas as pd

# %matplotlib inline
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

import seaborn as sns


# + id="WUTNeBvu5syQ" colab_type="code" colab={}
class Perceptron(object):
    """Perceptron classifier.

    Parameters
    ------------
    eta : float
        Learning rate (between 0.0 and 1.0)
    n_iter : int
        Passes over the training dataset.

    Attributes
    -----------
    w_ : 1d-array
        Weights after fitting.
    errors_ : list
        Number of misclassifications in every epoch.

    """
    def __init__(self, eta=0.01, n_iter=10):
        self.eta = eta
        self.n_iter = n_iter

    def fit(self, X, y):
        """Fit training data.

        Parameters
        ----------
        X : {array-like}, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples and
            n_features is the number of features.
        y : array-like, shape = [n_samples]
            Target values.

        Returns
        -------
        self : object

        """
        self.w_ = np.zeros(1 + X.shape[1])
        self.errors_ = []

        for _ in range(self.n_iter):
            errors = 0
            for xi, target in zip(X, y):
                update = self.eta * (target - self.predict(xi))
                self.w_[1:] += update * xi
                self.w_[0] += update
                errors += int(update != 0.0)
            self.errors_.append(errors)   # NOW COMPARING ERRORS VERSUS COST
        return self

    def net_input(self, X):
        """Calculate net input"""
        return np.dot(X, self.w_[1:]) + self.w_[0]  # SAME AS ADALINE

    def predict(self, X):
        """Return class label after unit step"""
        return np.where(self.net_input(X) >= 0.0, 1, -1)


# + id="2S8y_Fcc5syr" colab_type="code" colab={}
# FUNCTION FOR PLOTTING CLASSIFICATION REGIONS

def plot_decision_regions(X, y, classifier, resolution=0.02):

    # setup marker generator and color map
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                         np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    # plot class samples
    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
                    alpha=0.8, c=cmap(idx),
                    marker=markers[idx], label=cl)


# + id="2ocL7S-S5syw" colab_type="code" outputId="4680c0d8-602c-4966-ed08-d1419284dafb" colab={"base_uri": "https://localhost:8080/", "height": 194}
# OBTAIN

df = pd.read_csv('https://archive.ics.uci.edu/ml/'
        'machine-learning-databases/iris/iris.data', header=None)
df.head()

# + id="2rR7fqEA5sy3" colab_type="code" colab={}
# SCRUB

# ONLY USE SETOSA & VERSICOLOR
y = df.iloc[0:100, 4].values
y = np.where(y == 'Iris-setosa', -1, 1)

# ONLY USE SEPAL & PETAL LENGTH
X = df.iloc[0:100, [0, 2]].values



# + id="QpW2diWy5sy7" colab_type="code" outputId="58283e82-3177-494b-e538-ef84f1b92301" colab={"base_uri": "https://localhost:8080/", "height": 297}
# EXPLORE
plt.scatter(X[:50, 0], X[:50, 1],
            color='red', marker='o', label='setosa')
plt.scatter(X[50:100, 0], X[50:100, 1],
            color='blue', marker='x', label='versicolor')

plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.legend(loc='upper left')

plt.tight_layout()
#plt.savefig('./images/02_06.png', dpi=300)
plt.show()

# + id="BJwYwTki5szB" colab_type="code" colab={}
# SCRUB
# STANDARDIZATION - SUBTRACTING MEAN / DIVIDING BY STD DEV
# IF FEATURES HAVE A LARGE RANGE, THESE FEATURES MIGHT DOMINATE IMPACT ON CLASSIFIER
# GRADIENT DESCENT CONVERGES FASTER WITH FEATURE SCALING

X_std = np.copy(X)
X_std[:,0] = (X[:,0] - X[:,0].mean()) / X[:,0].std()
X_std[:,1] = (X[:,1] - X[:,1].mean()) / X[:,1].std()

# + id="uJObLh9N5szG" colab_type="code" outputId="84587e0a-d63f-4dcb-c1fc-0be939ff9071" colab={"base_uri": "https://localhost:8080/", "height": 632}
# FIRST PASS ON USING Perceptron
# SET ITERATIONS AT 25 & LEARNING RATE AT 0.1

ppn = Perceptron(eta=0.1, n_iter=25)

ppn.fit(X, y)

# PLOT REGIONS
plot_decision_regions(X, y, classifier=ppn)
plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.legend(loc='upper left')

plt.tight_layout()
plt.show()

# PLOT EPOCHS

plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of misclassifications')

plt.tight_layout()
# plt.savefig('./perceptron_1.png', dpi=300)
plt.show()

# + id="xwXnEnwA5szW" colab_type="code" outputId="25690177-c31f-4676-a11d-16f5ccd72040" colab={"base_uri": "https://localhost:8080/", "height": 632}
# SECOND PASS ON USING Perceptron
# SET ITERATIONS AT 100 & LEARNING RATE AT 0.0001

ppn = Perceptron(eta=0.0001, n_iter=100)

ppn.fit(X, y)

# PLOT REGIONS
plot_decision_regions(X, y, classifier=ppn)
plt.xlabel('sepal length [cm]')
plt.ylabel('petal length [cm]')
plt.legend(loc='upper left')

plt.tight_layout()
plt.show()

# PLOT EPOCHS

plt.plot(range(1, len(ppn.errors_) + 1), ppn.errors_, marker='o')
plt.xlabel('Epochs')
plt.ylabel('Number of misclassifications')

plt.tight_layout()
# plt.savefig('./perceptron_1.png', dpi=300)
plt.show()

# + id="xIZoy-az5sze" colab_type="code" outputId="89ad58e9-7692-43d9-ead2-11c7ca25e466" colab={"base_uri": "https://localhost:8080/", "height": 997}
# System Information
import platform

print('Python is ' + platform.python_version())

pd.show_versions(as_json=False)

# + id="8sv5qtJV5szk" colab_type="code" colab={}


StarcoderdataJupyterScriptsDedupFiltered