# Basic example of using ROC with Linear regression

**URL:** <https://community.wolfram.com/t/basic-example-of-using-roc-with-linear-regression/9417>\
**Category:** Staff Picks\
**Tags:** data-science, operations-research, curated-data, graphics-and-visualization, machine-learning, staff-pick\
**Created:** [October 12, 2016, 1:21pm UTC](https://community.wolfram.com/t/basic-example-of-using-roc-with-linear-regression/9417 "2016-10-12T13:21:04Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![antononcube](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/antononcube/32/7348_2.png) [@antononcube](https://community.wolfram.com/u/antononcube)\
**Post date:** [October 12, 2016, 1:21pm UTC](https://community.wolfram.com/t/basic-example-of-using-roc-with-linear-regression/9417/1 "2016-10-12T13:21:04Z")

</div>

## Introduction

This post is for the package [[2](https://github.com/antononcube/MathematicaForPrediction/blob/master/ROCFunctions.m)] that provides _Mathematica_ implementations of [Receiver Operating Characteristic](https://en.wikipedia.org/wiki/Receiver_operating_characteristic) (ROC) functions calculation and plotting. The ROC framework is used for analysis and tuning of binary classifiers, [[3](https://en.wikipedia.org/wiki/Receiver_operating_characteristic)]. (The classifiers are assumed to classify into a positive/true label or a negative/false label. )

The function `ROCFuntions` gives access to the individual ROC functions through string arguments. Those ROC functions are applied to special objects, called ROC Association objects.

Each ROC Association object is an `Association` that has the following four keys: “TruePositive”, “FalsePositive”, “TrueNegative”, and “FalseNegative” .

Given two lists of actual and predicted labels a ROC Association object can be made with the function `ToROCAssociation` .

For more definitions and example of ROC terminology and functions see [[3](https://en.wikipedia.org/wiki/Receiver_operating_characteristic),[4](https://ccrma.stanford.edu/workshops/mir2009/references/ROCintro.pdf)].

## Minimal example

Note that here although we use both of the provided Titanic training and test data, the code is doing only training. The test data is used to find the best tuning parameter (threshold) through ROC analysis.

### Get packages

These commands load the packages [[1](https://github.com/antononcube/MathematicaForPrediction/blob/master/MathematicaForPredictionUtilities.m),[2](https://github.com/antononcube/MathematicaForPrediction/blob/master/ROCFunctions.m)]:

```
Import["https://raw.githubusercontent.com/antononcube/MathematicaForPrediction/master/MathematicaForPredictionUtilities.m"]
Import["https://raw.githubusercontent.com/antononcube/MathematicaForPrediction/master/ROCFunctions.m"]

```

### Using Titanic data

Here is the summary of the Titanic data used below:

```
titanicData = (Flatten@*List) @@@ExampleData[{"MachineLearning", "Titanic"}, "Data"];
columnNames = (Flatten@*List) @@ExampleData[{"MachineLearning", "Titanic"}, "VariableDescriptions"];
RecordsSummary[titanicData, columnNames]

```

[![Titanic1](https://global.discourse-cdn.com/wolfram/original/3X/e/4/e4be9a94b354eb9d7f0e6f6dd8c209c83bde6e59.png)](http://i.imgur.com/VTVyV9P.png)

This variable dependence grid shows the relationships between the variables.

```
Magnify[#, 0.7] &@VariableDependenceGrid[titanicData, columnNames]

```

[![VariableDependencies](https://global.discourse-cdn.com/wolfram/original/3X/d/2/d200690a68dfa67fe3559b597f7a236ae90cd09f.png)](http://i.imgur.com/DSkPQOH.png)

### Get training and testing data

```
data = ExampleData[{"MachineLearning", "Titanic"}, "TrainingData"];
data = ((Flatten@*List) @@@ data)[[All, {1, 2, 3, -1}]];
trainingData = DeleteCases[data, { ___, _Missing,___ }];
Dimensions[trainingData]

```

(\* {732, 4} \*)

```
data = ExampleData[{"MachineLearning", "Titanic"}, "TestData"];
data = ((Flatten@*List) @@@ data)[[All, {1, 2, 3, -1}]];
testData = DeleteCases[data, { ___, _Missing,___ }];
Dimensions[testData]

```

(\* {314, 4} \*)

### Replace categorical with numerical values

```
trainingData = trainingData /. {"survived" -> 1, "died" -> 0, "1st" -> 0, "2nd" -> 1, "3rd" -> 2, "male" -> 0, "female" -> 1};

testData = testData /. {"survived" -> 1, "died" -> 0, "1st" -> 1, "2nd" -> 2, "3rd" -> 3, "male" -> 0, "female" -> 1};

```

### Do linear regression

```
lfm = LinearModelFit[{trainingData[[All, 1 ;; -2]], trainingData[[All, -1]]}]

```

[![Regression1](https://global.discourse-cdn.com/wolfram/original/3X/f/f/ff26197f65e82eac7e81f9cf5b4eefeaac3a9f2a.png)](http://i.imgur.com/d663I98.png)

### Get the predicted values

```
modelValues = lfm @@@ testData[[All, 1 ;; -2]];

Histogram[modelValues, 20]

```

[![Prediction1](https://global.discourse-cdn.com/wolfram/original/3X/0/4/044db918efe248dfe09fbcf342dbaf49cddf11eb.png)](http://i.imgur.com/bBXsDp2.png)

RecordsSummary[modelValues]

[![Prediction2](https://global.discourse-cdn.com/wolfram/original/3X/2/8/283479da0420d9e207efd655ba2a60328ba92278.png)](http://i.imgur.com/mzWjhZc.png)

### Obtain ROC associations over a set of parameter values

```
testLabels = testData[[All, -1]];

thRange = Range[0.1, 0.9, 0.025];
aROCs = Table[ToROCAssociation[{1, 0}, testLabels, Map[If[# > \[Theta], 1, 0] &, modelValues]], {\[Theta], thRange}];

```

### Evaluate ROC functions for given ROC association

```
N @ Through[ROCFunctions[{"PPV", "NPV", "TPR", "ACC", "SPC", "MCC"}][aROCs[[3]]]]

(* {0.513514, 0.790698, 0.778689, 0.627389, 0.53125, 0.319886} *)

```

### Standard ROC plot

```
ROCPlot[thRange, aROCs, "PlotJoined" -> Automatic, "ROCPointCallouts" -> True, "ROCPointTooltips" -> True, GridLines -> Automatic]

```

[![ROCPlot1](https://global.discourse-cdn.com/wolfram/original/3X/1/d/1d3b6c825413204c16cd30a8fed1349fb5bec95e.png)](https://i.imgur.com/Sam8wX5.png)

### Plot ROC functions wrt to parameter values

```
rocFuncs = {"PPV", "NPV", "TPR", "ACC", "SPC", "MCC"};
rocFuncTips = Map[# <> ", " <> (ROCFunctions["FunctionInterpretations"][#]) &, rocFuncs];
ListLinePlot[
 MapThread[Tooltip[Transpose[{thRange, #1}], #2] &, {Transpose[Map[Through[ROCFunctions[rocFuncs][#]] &, aROCs]], rocFuncTips}],
 Frame -> True, 
 FrameLabel -> Map[Style[#, Larger] &, {"threshold, \[Theta]", "rate"}], 
 PlotLegends -> rocFuncTips, GridLines -> Automatic]

```

[![ROCPlot2](https://global.discourse-cdn.com/wolfram/original/3X/e/1/e15326d1efff55964a4a2e01c80ef171ef802e24.png)](https://i.imgur.com/lrGRgJp.png)

### Finding the intersection point of PPV and TPR

We want to find a point that provides balanced positive and negative labels success rates. One way to do this is to find the intersection point of the ROC functions PPV (positive predictive value) and TPR (true positive rate).

Examining the plot above we can come up with the initial condition for x.

```
ppvFunc = Interpolation[Transpose@{thRange, ROCFunctions["PPV"] /@ aROCs}];
tprFunc = Interpolation[Transpose@{thRange, ROCFunctions["TPR"] /@ aROCs}];
FindRoot[ppvFunc[x] - tprFunc[x] == 0, {x, 0.2}]

```

(\* {x → 0.3} \*)

### Area under the ROC curve

The Area Under the ROC curve (AUROC) tells for a given range of the controlling parameter “what is the probability of the classifier to rank a randomly chosen positive instance higher than a randomly chosen negative instance, (assuming ‘positive’ ranks higher than ‘negative’)”, [3,4]

Calculating AUROC is easy using the Trapezoidal quadrature formula:

```
 N@Total[Partition[Sort@Transpose[{ROCFunctions["FPR"] /@ aROCs, ROCFunctions["TPR"] /@ aROCs}], 2, 1] 
   /. {{x1_, y1_}, {x2_, y2_}} :> (x2 - x1) (y1 + (y2 - y1)/2)]

 (* 0.474513 *)

```

It is also implemented in [[2](https://github.com/antononcube/MathematicaForPrediction/blob/master/ROCFunctions.m)]:

```
N@ROCFunctions["AUROC"][aROCs]

(* 0.474513 *)

```

## References

[1] Anton Antonov, [MathematicaForPrediction utilities](https://github.com/antononcube/MathematicaForPrediction/blob/master/MathematicaForPredictionUtilities.m), (2014), source code [MathematicaForPrediction at GitHub](https://github.com/antononcube/MathematicaForPrediction), package [MathematicaForPredictionUtilities.m](https://raw.githubusercontent.com/antononcube/MathematicaForPrediction/master/MathematicaForPredictionUtilities.m).

[2] Anton Antonov, [Receiver operating characteristic functions Mathematica package](https://github.com/antononcube/MathematicaForPrediction/blob/master/ROCFunctions.m), (2016), source code [MathematicaForPrediction at GitHub](https://github.com/antononcube/MathematicaForPrediction), package [ROCFunctions.m](https://raw.githubusercontent.com/antononcube/MathematicaForPrediction/master/ROCFunctions.m) .

[3] Wikipedia entry, [Receiver operating characteristic](http://en.wikipedia.org/wiki/Receiver_operating_characteristic).

[4] Tom Fawcett, [An introduction to ROC analysis](https://ccrma.stanford.edu/workshops/mir2009/references/ROCintro.pdf), (2006), Pattern Recognition Letters, 27, 861-874.

---

<div class="post-metadata">

**Author:** ![wolframcommunity](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/wolframcommunity/32/8335_2.png) [@wolframcommunity](https://community.wolfram.com/u/wolframcommunity)\
**Post date:** [October 12, 2016, 1:54pm UTC](https://community.wolfram.com/t/basic-example-of-using-roc-with-linear-regression/9417/2 "2016-10-12T13:54:56Z")

</div>

![2015-11-02_10-07-11.png](https://global.discourse-cdn.com/wolfram/original/3X/5/0/50e59c9ead62f729e7130d3ea1482555a75602b6.png)

- another post of yours has been selected for the [Staff Picks](http://community.wolfram.com/content?curTag=staff+picks) group, congratulations! We are happy to see you at the top of the [“Featured Contributor” board](http://wolfr.am/featured). Thank you for your wonderful contributions, and please keep them coming!

---

<div class="post-metadata">

**Author:** ![antononcube](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/antononcube/32/7348_2.png) [@antononcube](https://community.wolfram.com/u/antononcube)\
**Post date:** [October 12, 2016, 3:17pm UTC](https://community.wolfram.com/t/basic-example-of-using-roc-with-linear-regression/9417/3 "2016-10-12T15:17:49Z")

</div>

Two years ago submitted more than a few answers to this Community question

[“Regression frustration”](https://wolfram.discourse.group/t/3663/1)

one of them with a notebook that had/has ROC implementations. While preparing for WTC-2016, I decided that it is good idea to make a package with ROC functionalities. (Making an `Association`-centric implementation.)

For a more elaborated example of Linear regression with ROC see this

[“Regression with ROC”](https://github.com/antononcube/MathematicaVsR/tree/master/Projects/RegressionWithROC)

project which is part of

[MathematicaVsR at GitHub](https://github.com/antononcube/MathematicaVsR).

---

<div class="post-metadata">

**Author:** ![jbaldwin](https://avatars.discourse-cdn.com/v4/letter/j/91b2a8/32.png) [@jbaldwin](https://community.wolfram.com/u/jbaldwin)\
**Post date:** [October 12, 2016, 3:23pm UTC](https://community.wolfram.com/t/basic-example-of-using-roc-with-linear-regression/9417/4 "2016-10-12T15:23:18Z")

</div>

Very impressive. I have to ask: Why did you use `LinearModelFit` when the binary nature of the dependent variable calls for something like `LogitModelFit`, `ProbitFit`, or `GeneralizedLinearModelFit`?

---

<div class="post-metadata">

**Author:** ![antononcube](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/antononcube/32/7348_2.png) [@antononcube](https://community.wolfram.com/u/antononcube)\
**Post date:** [October 12, 2016, 3:34pm UTC](https://community.wolfram.com/t/basic-example-of-using-roc-with-linear-regression/9417/5 "2016-10-12T15:34:14Z")

</div>

Good question!

1. I was trying to do a minimal and quick to execute example – the code of the post is included in the package [ROCFunctions.m](https://github.com/antononcube/MathematicaForPrediction/blob/master/ROCFunctions.m).

2. I am aware that there are better alternatives of `LinearModelFit`, but I plan to discuss those in the [MathematicaVsR](https://github.com/antononcube/MathematicaVsR) project: [“Regression with ROC”](https://github.com/antononcube/MathematicaVsR/tree/master/Projects/RegressionWithROC). (As the name hints, it is not just about Linear regression.)

3. Another point is that although the Linear regression is not a good method for this classification, nevertheless using ROC it can be made to give better results than, say, the built-in “NeuralNetwork” method. See the last section of [“Linear regression with ROC.md”](https://github.com/antononcube/MathematicaVsR/blob/master/Projects/RegressionWithROC/Mathematica/Linear-regression-with-ROC.md).

---

<div class="post-metadata">

**Author:** ![rubengarcia](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/rubengarcia/32/19286_2.png) [@rubengarcia](https://community.wolfram.com/u/rubengarcia)\
**Post date:** [October 15, 2016, 4:12am UTC](https://community.wolfram.com/t/basic-example-of-using-roc-with-linear-regression/9417/6 "2016-10-15T04:12:11Z")

</div>

May I know where to find more information about the construct:

```
Flatten@*List

```

I have tried to search in the documentation but there’s nothing about it.

---

<div class="post-metadata">

**Author:** ![antononcube](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/antononcube/32/7348_2.png) [@antononcube](https://community.wolfram.com/u/antononcube)\
**Post date:** [October 15, 2016, 5:41pm UTC](https://community.wolfram.com/t/basic-example-of-using-roc-with-linear-regression/9417/7 "2016-10-15T17:41:56Z")

</div>

Look into the built-in function [`Composition`](https://reference.wolfram.com/language/ref/Composition.html).

---

<div class="post-metadata">

**Author:** ![antononcube](https://yyz1.discourse-cdn.com/wolfram/user_avatar/community.wolfram.com/antononcube/32/7348_2.png) [@antononcube](https://community.wolfram.com/u/antononcube)\
**Post date:** [October 17, 2016, 3:41pm UTC](https://community.wolfram.com/t/basic-example-of-using-roc-with-linear-regression/9417/8 "2016-10-17T15:41:20Z")

</div>

An extensive exposition of applying ROC in classifiers ensembles and for classifier interpolation is done in this Community discussion:

[“ROC for classifier ensembles, bootstrapping, damaging, and interpolation”](http://community.wolfram.com/groups/-/m/t/944004) .
