%% Credit Scorecards with Constrained Logistic Regression Coefficients
% To compute scores for a creditscorecard object with constraints for equality, inequality, or bounds on the coefficients of the logistic regression model, use fitconstrainedModel. Unlike fitmodel, fitconstrainedModel solves for both the unconstrained and constrained problem. The current solver used to minimize an objective function for fitconstrainedModel is fmincon, from the Optimization Toolbox™.
% This example has three main sections. First, fitconstrainedModel is used to solve for the coefficients in the unconstrained model. Then, fitconstrainedModel demonstrates how to use several types of constraints. Finally, fitconstrainedModel uses bootstrapping for the significance analysis to determine which predictors to reject from the model.
%
%% Create the creditscorecard Object and Bin data

load CreditCardData.mat
sc = creditscorecard(data,'IDVar','CustID');
sc = autobinning(sc);

%
%% Unconstrained Model Using fitConstrainedModel
% Solve for the unconstrained coefficients using fitconstrainedModel with default values for the input parameters. fitconstrainedModel uses the internal optimization solver fmincon from the Optimization Toolbox™. If you do not set any constraints, fmincon treats the model as an unconstrained optimization problem. The default parameters for the LowerBound and UpperBound are -Inf and +Inf, respectively. For the equality and inequality constraints, the default is an empty numeric array.

[sc1,mdl1] = fitConstrainedModel(sc);
coeff1 = mdl1.Coefficients.Estimate;
disp(mdl1.Coefficients);

% Unlike fitmodel which gives p-values, when using fitconstrainedModel, you must use bootstrapping to find out which predictors are rejected from the model, when subject to constraints. This is illustrated in the "Significance Bootstrapping" section.
%% Using fitmodel to Compare the Results and Calibrate the Model
% fitmodel fits a logistic regression model to the Weight-of-Evidence (WOE) data and there are no constraints. You can compare the results from the "Unconstrained Model Using fitConstrainedModel" section with those of fitmodel to verify that the model is well calibrated.
% Now, solve the unconstrained problem by using fitmodel. Note that fitmodel and fitconstrainedModel use different solvers. While fitconstrainedModel uses fmincon, fitmodel uses stepwiseglm by default. To include all predictors from the start, set the 'VariableSelection' name-value pair argument of fitmodel to 'fullmodel'.

[sc2,mdl2] = fitmodel(sc,'VariableSelection','fullmodel','Display','off');
coeff2 = mdl2.Coefficients.Estimate;
disp(mdl2.Coefficients);
figure
plot(coeff1,'*')
hold on
plot(coeff2,'s')
xticklabels(mdl1.Coefficients.Properties.RowNames)
xtickangle(45)
ylabel('Model Coefficients')
title('Unconstrained Model Coefficients')
legend({'Calculated by fitConstrainedModel with defaults','Calculated by fimodel'},'Location','best')
grid on

%
% As both the tables and the plot show, the model coefficients match. You can be confident that this implementation of fitconstrainedModel is well calibrated.
%
%% Constrained Model
% In the constrained model approach, you solve for the values of the coefficients b_i of the logistic model, subject to constraints. The supported constraints are bound, equality, or inequality. The coefficients maximize the likelihood-of-default function defined, for observation i, as:
% L_i ={p\left({\textrm{Default}}_i \right)}^{y_i } \times {\left(1-p\left({\textrm{Default}}_i \right)\right)}^{1-y_i } \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;
% where:
% {p\left({\textrm{Default}}_i \right)=\frac{\;\;\;\;1\;\;\;\;}{1+e^{-b{\mathrm{x}}_i } }\;}^{\;}
% \mathit{\mathbf{b}}=\left\lbrack b_{1\;} b_2 \;\ldotp \ldotp \ldotp b_K \right\rbrack is an unknown model coefficient
% {\mathit{\mathbf{x}}}_{\mathit{\mathbf{i}}} =\left\lbrack x_{\textrm{i1}} \;x_2 \;\ldotp \ldotp \ldotp x_{\textrm{iK}} \right\rbrack is the predictor values at observation i
% y_i is the response value; a value of 1 represents default and a value of 0 represents non-default
% This formula is for non-weighted data. When observation i has weight w_i, it means that there are w_i as many observations i. Therefore, the probability that default occurs at observation i is the product of the probabilities of default:
% p_{i\;} =\;\underset{w_{i\;} \textrm{times}}{{p\left({\textrm{Default}}_i \right)}^{y_i } *{p\left({\textrm{Default}}_i \right)}^{y_i } *\ldotp \ldotp \ldotp *{p\left({\textrm{Default}}_i \right)}^{y_i } } ={p\left({\textrm{Default}}_i \right)}^{{w_i *y}_i }
% Likewise, the probability of non-default for weighted observation i is:
% {\hat{p} }_{i\;} =\;\underset{w_{i\;} \textrm{times}}{{p\left({~\textrm{Default}}_i \right)}^{{1-y}_i } *{p\left(~{\textrm{Default}}_i \right)}^{1-y_i } *\ldotp \ldotp \ldotp *{p\left(~{\textrm{Default}}_i \right)}^{1-y_i } } ={\left(1-p\left({\textrm{Default}}_i \right)\right)}^{w_i *\left(1-y_i \right)}
% For weighted data, if there is default at a given observation i whose weight is w_i, it is as if there was a w_i count of that one observation, and all of them either all default, or all non-default. w_i may or may not be an integer.
% Therefore, for the weighted data, the likelihood-of-default function for observation i in the first equation becomes
% L_i ={p\left({\textrm{Default}}_i \right)}^{{w_i *y}_i } \times {\left(1-p\left({\textrm{Default}}_i \right)\right)}^{w_i *\left(1-y_i \right)}
%
% By assumption, all defaults are independent events, so the objective function is
% L=L_1 \times L_2 \times \ldotp \ldotp \ldotp \times {\;L}_N
% or, in more convenient logarithmic terms:
% \log \left(L\right)=\sum_{i=1}^N w_i *\left\lbrack y_i \log \left(p\left({\textrm{Default}}_i \right)\right)+\left(1-y_i \right)\log \left(1-p\left({\textrm{Default}}_i \right)\right)\right\rbrack \;
%
%% Apply Constraints on the Coefficients
% After calibrating the unconstrained model as described in the "Unconstrained Model Using fitConstrainedModel" section, you can solve for the model coefficients subject to constraints. You can choose lower and upper bounds such that 0\le b_i \le 1,\forall i=1\ldotp \ldotp \ldotp K, except for the intercept. Also, since the customer age and customer income are somewhat correlated, you can also use additional constraints on their coefficients, for example, |b_{CusAge} - b_{CustIncome}| < 0.1. The coefficients corresponding to the predictors 'CustAge' and 'CustIncome' in this example are b_2 and b_6, respectively.

K  = length(sc.PredictorVars);
lb = [-Inf;zeros(K,1)];
ub = [Inf;ones(K,1)];
AIneq = [0 -1 0 0 0 1 0 0 0 0;0 -1 0 0 0 -1 0 0 0 0];
bIneq = [0.05;0.05];
Options = optimoptions('fmincon','SpecifyObjectiveGradient',true,'Display','off');
[sc3,mdl] = fitConstrainedModel(sc,'AInequality',AIneq,'bInequality',bIneq,...
    'LowerBound',lb,'UpperBound',ub,'Options',Options);

figure
plot(coeff1,'*','MarkerSize',8)
hold on
plot(mdl.Coefficients.Estimate,'.','MarkerSize',12)
line(xlim,[0 0],'color','k','linestyle',':')
line(xlim,[1 1],'color','k','linestyle',':')
text(1.1,0.1,'Lower bound')
text(1.1,1.1,'Upper bound')
grid on

xticklabels(mdl.Coefficients.Properties.RowNames)
xtickangle(45)
ylabel('Model Coefficients')
title('Comparison Between Unconstrained and Constrained Solutions')
legend({'Unconstrained','Constrained'},'Location','best')

%
%% Significance Bootstrapping
% For the unconstrained problem, standard formulas are available for computing p-values, which you use to evaluate which coefficients are significant and which are to be rejected. However, for the constrained problem, standard formulas are not available, and the derivation of formulas for significance analysis is complicated. A practical alternative is to perform significance analysis through bootstrapping.
% In the bootstrapping approach, when using fitconstrainedModel, you set the name-value argument 'Bootstrap' to true and chose a value for the name-value argument 'BootstrapIter'. Bootstrapping means that \textrm{NIter} samples (with replacement) from the original observations are selected. In each iteration, fitconstrainedModel solves for the same constrained problem as the "Constrained Model" section. fitconstrainedModel obtains several values (solutions) for each coefficient b_i and you can plot these as a boxplot or histogram. Using the boxplot or histogram, you can examine the median values to evaluate whether the coefficients are away from zero and how much the coefficients deviate from their means.

lb = [-Inf;zeros(K,1)];
ub = [Inf;ones(K,1)];
AIneq = [0 -1 0 0 0 1 0 0 0 0;0 1 0 0 0 -1 0 0 0 0];
bIneq = [0.05;0.05];
c0 = zeros(K,1);
NIter = 100;
Options = optimoptions('fmincon','SpecifyObjectiveGradient',true,'Display','off');
rng('default')

[sc,mdl] = fitConstrainedModel(sc,'AInequality',AIneq,'bInequality',bIneq,...
    'LowerBound',lb,'UpperBound',ub,'Bootstrap',true,'BootstrapIter',NIter,'Options',Options);

figure
boxplot(mdl.Bootstrap.Matrix,mdl.Coefficients.Properties.RowNames)
hold on
line(xlim,[0 0],'color','k','linestyle',':')
line(xlim,[1 1],'color','k','linestyle',':')
title('Bootstrapping with N = 100 Iterations')
ylabel('Model Coefficients')
xtickangle(45)

% The solid red lines in the boxplot indicate that the median values and the bottom and top edges are for the {25}^{\textrm{th}} and {75}^{\textrm{th}} percentiles. The "whiskers" are the minimum and maximum values, not including outliers. The dotted lines represent the lower and upper bound constraints on the coefficients. In this example, the coefficients cannot be negative, by construction.
% To help decide which predictors to keep in the model, assess the proportion of times each coefficient is zero.

Tol = 1e-6;
figure
bar(100*sum(mdl.Bootstrap.Matrix<= Tol)/NIter)
ylabel('% of Zeros')
title('Percentage of Zeros Over Bootstrap Iterations')
xticklabels(mdl.Coefficients.Properties.RowNames)
xtickangle(45)
grid on

% Based on the plot, you can reject 'UtilRate' since it has the highest number of zero values. You can also decide to reject 'TmAtAddress' since it shows a peak, albeit small.
%% Set the Corresponding Coefficients to Zero
% To set the corresponding coefficients to zero, set their upper bound to zero and solve the model again using the original data set.

ub(3) = 0;
ub(end) = 0;
[sc,mdl] = fitConstrainedModel(sc,'AInequality',AIneq,'bInequality',bIneq,'LowerBound',lb,'UpperBound',ub,'Options',Options);
Ind = (abs(mdl.Coefficients.Estimate) <= Tol);
ModelCoeff = mdl.Coefficients.Estimate(~Ind);
ModelPreds = mdl.Coefficients.Properties.RowNames(~Ind)';

figure
hold on
plot(ModelCoeff,'.','MarkerSize',12)
ylim([0.2 1.2])
ylabel('Model Coefficients')
xticklabels(ModelPreds)
xtickangle(45)
title('Selected Model Coefficients After Bootstrapping')
grid on

%
%% Set Constrained Coefficients Back Into the creditscorecard
% Now that you have solved for the constrained coefficients, use setmodel to set the model's coefficients and predictors. Then you can compute the (unscaled) points.

ModelPreds = ModelPreds(2:end);
sc = setmodel(sc,ModelPreds,ModelCoeff);
p = displaypoints(sc);

disp(p)

% Using the unscaled points, you can follow the remainder of the creditscorecard workflow to compute scores and probabilities of default and to validate the model.
% Copyright 2018 The MathWorks, Inc.