# Concise / idiomatic replacement for a For loop [closed]

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?

• Is data a List or an Association? Feb 19, 2017 at 1:33

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                         *)

• 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. Feb 19, 2017 at 5:00
• @Mr.Wizard I'm okay. Thank you for adding an extension. Feb 19, 2017 at 5:08
• I misunderstand someting maybe.Look here.
– yode
Feb 19, 2017 at 5:22
• @yode The for loop condition is i < Length[data] Feb 19, 2017 at 5:29

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}} *)