clear all;

data = load('Data/pima.txt');

% Calculate numbers of examples and features
[n_examples, data_col] = size(data)
n_features = data_col - 1

% divide class and feautures
class=data(:,end);
features=data(:,1:end-1);

% plot pairs of feature for 2 different classes
class1 = find(class==0);
class2 = find(class);

figure(1)
plot(features(class1,1),features(class1,2),'*',features(class2,1),features(class2,2),'o');
axis('square');
title('First two dimensions of the Pima dataset.')
figure(2)
plot(features(class1,3),features(class1,4),'*',features(class2,3),features(class2,4),'o');axis('square');
title('Third and forth dimensions of the Pima dataset.')
axis('square');

% run 100 times and get the average accuracy
for run=1:100
    % split the data into training  and testing subsets
    % leave 30% of data for testing of our model
    [trainin, testin] = divideset(data, 30);
    % normalize all the features to mean 0 and variance 1;
    [meanv, stdv, trainin(:, 1 : n_features)] = normalize(trainin(:, 1 : n_features), [], []);
    % normalize testing data
    [meanv, stdv, testin(:, 1 : n_features)] = normalize(testin(:, 1 : n_features), [], []);
    
    % set learning rate
    alpha = 0.2;
    % set the limit on number of epochs when the weights do not change
    epochs_limit=10;
    % train perceptron
    W = perceptron(trainin(:, 1 : n_features), trainin(:, n_features+1:end), alpha, epochs_limit);
    
    % test on 30%
    % add bias to the testin
    n_test_examples = size(testin,1);
    testin = [ones(n_test_examples,1) testin];
    testout = ((W * testin(:,1:n_features+1)')>=0);
    testtgt = testin(:,end);
    
    %  Calculate the accuracy
    [acc(run,1), conf_matrix] = accuracy(testout',testtgt);
    error(run,1) = sum((testout'-testtgt).^2)/size(testtgt,1);
    
end

mean(acc) % the accuracy ranges from 57% on average to the maximum of 70%
max(acc)

return