text_plain_output_1.png
from _csv import reader

from numpy import mean

from numpy import std

from scipy.stats import norm

import pandas as pd

import random

def load_csv(filename):
    dataset = list()
    with open(filename, 'r') as file:
        csv_reader = reader(file)
        for row in csv_reader:
            if not row:
                continue
            dataset.append(row)
    return dataset

def str_column_to_float(dataset, column):
    for row in dataset:
        row[column] = float(row[column].strip())

def separate_by_class(dataset):
    separated = dict()
    for i in range(len(dataset)):
        vector = dataset[i]
        class_value = vector[-1]
        if class_value not in separated:
            separated[class_value] = list()
        separated[class_value].append(vector)
    return separated

def splitDataset(dataset, ratio):
    trainSize = int(len(dataset) * ratio)
    trainSet = []
    tempSet = list(dataset)
    while len(trainSet) < trainSize:
        index = random.randrange(len(tempSet))
        trainSet.append(tempSet.pop(index))
    return [trainSet, tempSet]

def fit_distribution(data):
    mu = mean(data)
    sigma = std(data)
    dist = norm(mu, sigma)
    return dist

def probability(X, prior, dist1, dist2, dist3, dist4):
    return prior * dist1.pdf(X[0]) * dist2.pdf(X[1]) * dist3.pdf(X[2]) * dist4.pdf(X[3])

def predictedClass(data, prob_setosa, prob_versicolor, prob_virginica):
    max_prob = [0] * len(data)
    predicted = [''] * len(data)
    for i in range(len(data)):
        max_prob[i] = max(prob_setosa[i], prob_versicolor[i], prob_virginica[i])
        if max_prob[i] == prob_setosa[i]:
            predicted[i] = 'Iris-setosa'
        elif max_prob[i] == prob_versicolor[i]:
            predicted[i] = 'Iris-versicolor'
        else:
            predicted[i] = 'Iris-virginica'
    return predicted

def accuracy(actual, predicted):
    correct = 0
    predicted['is_equal'] = actual['0'] == predicted['0']
    correct = predicted['is_equal'].values.sum()
    return correct / float(len(actual)) * 100.0

def implementedClassifier(data):
    trainSet, testSet = splitDataset(data, 0.6)
    testSet = pd.DataFrame(testSet)
    testX = testSet.loc[:, [0, 1, 2, 3]]
    actualTestClass = testSet.loc[:, [4]]
    actualTestClass.columns = ['0']
    separated = separate_by_class(trainSet)
    X_seto = separated['Iris-setosa']
    X_versi = separated['Iris-versicolor']
    X_virgi = separated['Iris-virginica']
    X_seto = pd.DataFrame(X_seto)
    X_versi = pd.DataFrame(X_versi)
    X_virgi = pd.DataFrame(X_virgi)
    prior_seto = len(X_seto) / len(trainSet)
    prior_versi = len(X_versi) / len(trainSet)
    prior_virgi = len(X_virgi) / len(trainSet)
    X1_seto = fit_distribution(X_seto[0])
    X2_seto = fit_distribution(X_seto[1])
    X3_seto = fit_distribution(X_seto[2])
    X4_seto = fit_distribution(X_seto[3])
    X1_versi = fit_distribution(X_versi[0])
    X2_versi = fit_distribution(X_versi[1])
    X3_versi = fit_distribution(X_versi[2])
    X4_versi = fit_distribution(X_versi[3])
    X1_virgi = fit_distribution(X_virgi[0])
    X2_virgi = fit_distribution(X_virgi[1])
    X3_virgi = fit_distribution(X_virgi[2])
    X4_virgi = fit_distribution(X_virgi[3])
    X_sample1, y_sample1 = (testX.loc[[16]], actualTestClass.loc[[16]])
    X_sample2, y_sample2 = (testX.loc[[30]], actualTestClass.loc[[30]])
    prob_seto = probability(X_sample1, prior_seto, X1_seto, X2_seto, X3_seto, X4_seto)
    prob_versi = probability(X_sample1, prior_versi, X1_versi, X2_versi, X3_versi, X4_versi)
    prob_virgi = probability(X_sample1, prior_virgi, X1_virgi, X2_virgi, X3_virgi, X4_virgi)
    predicted = predictedClass(X_sample1, prob_seto, prob_versi, prob_virgi)
    prob_seto = probability(X_sample2, prior_seto, X1_seto, X2_seto, X3_seto, X4_seto)
    prob_versi = probability(X_sample2, prior_versi, X1_versi, X2_versi, X3_versi, X4_versi)
    prob_virgi = probability(X_sample2, prior_virgi, X1_virgi, X2_virgi, X3_virgi, X4_virgi)
    predicted = predictedClass(X_sample2, prob_seto, prob_versi, prob_virgi)
    prob_seto = probability(testSet, prior_seto, X1_seto, X2_seto, X3_seto, X4_seto)
    prob_versi = probability(testSet, prior_versi, X1_versi, X2_versi, X3_versi, X4_versi)
    prob_virgi = probability(testSet, prior_virgi, X1_virgi, X2_virgi, X3_virgi, X4_virgi)
    predicted = predictedClass(testSet, prob_seto, prob_versi, prob_virgi)
    predicted = pd.DataFrame(predicted)
    predicted.columns = ['0']
    accuracyPercentage = accuracy(actualTestClass, predicted)

if __name__ == '__main__':
    filepath = '../input/iris-dataset/iris.data.csv'
    data = load_csv(filepath)
    for i in range(len(data[0]) - 1):
        str_column_to_float(data, i)
    implementedClassifier(data)