2
$\begingroup$

I am using the following For loop to measure the misclassification errors in a Classifier.

errors = 0;
For[i = 1, i < Length[data], i++,
 actual = data[i][2];
 predicted = classifier[data[i]];
 If[actual != predicted, errors++]
 ]
Print[errors]

Is there a more concise / idiomatic replace instead of this For loop in Mathematica?

$\endgroup$
1
  • 2
    $\begingroup$ Is data a List or an Association? $\endgroup$ Feb 19, 2017 at 1:33

2 Answers 2

9
$\begingroup$

If the data is a list, you can map elements of data and compare using Map. Then, use Count to count errors.

classifier = Mod[#[[1]], 3] &;
data = {#, Mod[#, 2]} & /@ Range[20];

Count[(#[[2]] != classifier[#]) & /@ data, True]

  (*  13  *)

Or using CountsBy:

data // CountsBy[#[[2]] == classifier[#] &]

False /. %

  (*  <|True -> 7, False -> 13|>  *)

  (*   13                         *)
$\endgroup$
4
  • $\begingroup$ I made an extension to your answer and included a stand-alone example. If you do not like this please revert the edit, and I shall post separately. $\endgroup$
    – Mr.Wizard
    Feb 19, 2017 at 5:00
  • $\begingroup$ @Mr.Wizard I'm okay. Thank you for adding an extension. $\endgroup$ Feb 19, 2017 at 5:08
  • $\begingroup$ I misunderstand someting maybe.Look here. $\endgroup$
    – yode
    Feb 19, 2017 at 5:22
  • $\begingroup$ @yode The for loop condition is i < Length[data] $\endgroup$ Feb 19, 2017 at 5:29
1
$\begingroup$

If classifier was made with Classify we can use ClassifierMeasurements to find out the success rates.

Here is code following the example in the previous answer:

classifier = Mod[#[[1]], 3] &;
data = {#, Mod[#, 2]} & /@ Range[20];

cf = Classify[Rule @@@ data];

cm = ClassifierMeasurements[cf, Rule @@@ data]

cm["Recall"]

(* <|0 -> 0.3, 1 -> 0.1|> *)

cm["Precision"]

(* <|0 -> 0.25, 1 -> 0.125|> *)

cm["ConfusionMatrix"]

(* {{3, 7, 0}, {9, 1, 0}} *)
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.