%% prepare workspace
clear; close all; clc;
format COMPACT;

%% read in data and explore
bc = readtable('bc_data.csv');

head(bc);

summary(bc);  % summary for all columns

s = summary(bc);  % save summary results and access one variable at a time
s.Class

%% plot variables
display(bc.Properties.VariableNames);

% boxplot
boxplot(bc.Epith_c_size);

% count of unique values
[cnt_unique, unique_class] = hist(bc.Class,unique(bc.Class));

% stackplot
stackedplot(bc,{'Epith_c_size','Cell_size','Cl_thickness'})


%% Clean the dataset to prepare it for running the model
% 1. remove Id column
% 2. Convert the outcome variable to categorical
bc_clean = bc(:,2:11);
bc_clean.Class = categorical(bc_clean.Class);

%check summary of the Class column now:
s = summary(bc_clean); 
s.Class

%% Prepare for training

X = bc_clean{:, 1:9};   % Convert table to matrix
y = bc_clean.Class;
ratio = 0.8;       % Ratio of data for training
n_total = height(X);   % Number of observations in the full table
n_train = round(ratio * n_total)   % Number of training data points
X_train = X(1:n_train,:);     % Training data: x
X_test = X(n_train+1:n_total,:);  % Test data: x
y_train = y(1:n_train);     % Training data: y
y_test = y(n_train+1:n_total);  % Test data: y
n_test = length(y_test)       % Number of test data points


%% Training (multinomial logistic regression)
[beta,dev,stats] = mnrfit(X_train, y_train);  % Logistic regression


%% Predict using test data
y_prob = mnrval(beta, X_test);
[~, y_pred] = max(y_prob');  % Return [value, index]


%% Evaluate the model
y_test_num = grp2idx(y_test);   % Convert categories to numbers
n_correct = 0;
for i=1:1:n_test
    if y_pred(i) == y_test_num(i)
       n_correct = n_correct + 1; % Count correct events 
    end
end
acc_logit = n_correct / n_test  % Prediction accuracy


%% Let's take a look at the Matlab Apps
% regressionLearner
% classificationLearner