import csv
import random
import math
def loadcsv(filename):
    lines = csv.reader(open(filename, "r"))
    dataset = list(lines)
    for i in range(len(dataset)):
        # converting the attributes from string to floating point numbers
        dataset[i] = [float(x) for x in dataset[i]] 
    return dataset
def splitDataset(dataset, splitRatio):
	#67% training size
    trainSize = int(len(dataset) * splitRatio)
    trainSet = []
    copy = list(dataset)
    while len(trainSet) < trainSize:
        #generate indices for the dataset list randomly to pick ele for training data
        index = random.randrange(len(copy)) # random index
        trainSet.append(copy.pop(index))
    return [trainSet, copy]
def separateByClass(dataset):
    separated = {}
	#creates a dictionary of classes 1 and 0 where the values are #the instances belonging to each class
    for i in range(len(dataset)):
        vector = dataset[i]
        if (vector[-1] not in separated):
            separated[vector[-1]] = []
        separated[vector[-1]].append(vector)
    return separated
def mean(numbers):
    return sum(numbers)/float(len(numbers))
def stdev(numbers):
    avg = mean(numbers)
    variance = sum([pow(x-avg,2) for x in numbers])/float(len(numbers)-1)
    return math.sqrt(variance)
def summarize(dataset):  #creates a dictionary of classes
    summaries = [(mean(attribute), stdev(attribute)) for attribute in zip(*dataset)]
    del summaries[-1]
    return summaries
def summarizeByClass(dataset):
    separated = separateByClass(dataset)
#print(separated)
    summaries = {}
    for classValue, instances in separated.items():
        #for key,value in dic.items() 
#summaries is a dic of tuples(mean,std) for each class value
        summaries[classValue] = summarize(instances)
#summarize is used to cal to mean and std    
    return summaries
def calculateProbability(x, mean, stdev):
    exponent = math.exp(-(math.pow(x-mean,2)/(2*math.pow(stdev,2))))
    return (1 / (math.sqrt(2*math.pi) * stdev)) * exponent
def calculateClassProbabilities(summaries, inputVector):
# probabilities contains the all prob of all class of test data   
    probabilities = {}
    for classValue, classSummaries in summaries.items():
#class and attribute information as mean and sd        
        probabilities[classValue] = 1
        for i in range(len(classSummaries)):
            mean, stdev = classSummaries[i]
#take mean and sd of every attribute for class 0 and 1 seperaely
            x = inputVector[i]
            probabilities[classValue] *= calculateProbability(x, mean, stdev) #use normal dist
    return probabilities
def predict(summaries, inputVector): #training and test data is passed
    probabilities = calculateClassProbabilities(summaries, inputVector)
    bestLabel, bestProb = None, -1
    for classValue, probability in probabilities.items():
        #assigns that class which has the highest prob
        if bestLabel is None or probability > bestProb:
            bestProb = probability
            bestLabel = classValue
    return bestLabel
def getPredictions(summaries, testSet):
    predictions = []
    for i in range(len(testSet)):
        result = predict(summaries, testSet[i])
        predictions.append(result)
    return predictions
def getAccuracy(testSet, predictions):
    correct = 0
    for i in range(len(testSet)):
        if testSet[i][-1] == predictions[i]:
            correct = correct+1
    return (correct/float(len(testSet))) * 100.0
def main():
    filename = 'D:\pima_indian.csv'
    splitRatio = 0.67
    dataset = loadcsv(filename)
    
    #print("\n The Data Set :\n",dataset)
    print("\n The length of the Data Set : ",len(dataset))
    
    print("\n The Data Set Splitting into Training and Testing \n")
    trainingSet, testSet = splitDataset(dataset, splitRatio)
    
    print('\n Number of Rows in Training Set:{0} rows'.format(len(trainingSet)))
    print('\n Number of Rows in Testing Set:{0} rows'.format(len(testSet)))
    
    print("\n First Five Rows of Training Set:\n")
    for i in range(0,5):
        print(trainingSet[i],"\n")
    
    print("\n First Five Rows of Testing Set:\n")
    for i in range(0,5):
        print(testSet[i],"\n")
   
    # prepare model
    summaries = summarizeByClass(trainingSet)
    
    print("\n Model Summaries:\n",summaries)
   
    # test model
    predictions = getPredictions(summaries, testSet)
#find the predictions of test data with the training data
    print("\nPredictions:\n",predictions)
    
    accuracy = getAccuracy(testSet, predictions)
    print('\n Accuracy: {0}%'.format(accuracy))
main()
