Debian Codegraph @

scripts/heri-stat

raw
1 #!/usr/bin/env ruby
2
3 # Copyright (c) 2015 Alexandra Figlovskaya <[email protected]>
4 # Copyright (c) 2015-2019 Aleksey Cheusov <[email protected]>
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining
7 # a copy of this software and associated documentation files (the
8 # "Software"), to deal in the Software without restriction, including
9 # without limitation the rights to use, copy, modify, merge, publish,
10 # distribute, sublicense, and/or sell copies of the Software, and to
11 # permit persons to whom the Software is furnished to do so, subject to
12 # the following conditions:
13 #
14 # The above copyright notice and this permission notice shall be
15 # included in all copies or substantial portions of the Software.
16 #
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
25 require 'optparse'
26 require 'set'
27
28 @options = {}
29 @err = nil
30 @unspecified_class="__strelka_i_raketa__"
31
32 def print_pretty(class_name, p, p_comment, r, r_comment, f1, f1_comment)
33 puts "%13s P, R, F1: %-6.4g %-13s, %-6.4g %-13s, %-6.4g" \
34 % [class_name, p, p_comment, r, r_comment, f1, f1_comment]
35 end
36
37 def print_accuracy_pretty(a, a_comment)
38 puts "Accuracy : %-6.4g %-13s" % [a, a_comment]
39 end
40
41 def print_raw(class_name, p, p_comment, r, r_comment, f1, f1_comment)
42 puts "#{class_name}\tP\t#{p}\t#{p_comment.strip}"
43 puts "#{class_name}\tR\t#{r}\t#{r_comment.strip}"
44 puts "#{class_name}\tF1\t#{f1}\t#{f1_comment.strip}"
45 end
46
47 def print_accuracy_raw(a, a_comment)
48 puts "\tA\t#{a}\t#{a_comment.strip}"
49 end
50
51 def print_stat(class_name, p, p_comment, r, r_comment, f1, f1_comment)
52 if @options[:raw]
53 print_raw(class_name, p, p_comment, r, r_comment, f1, f1_comment)
54 else
55 print_pretty(class_name, p, p_comment, r, r_comment, f1, f1_comment)
56 end
57 end
58
59 def print_accuracy(a, a_comment)
60 if @options[:raw]
61 print_accuracy_raw(a, a_comment)
62 else
63 print_accuracy_pretty(a, a_comment)
64 end
65 end
66
67 def pretty_div(a, b)
68 "%5s/%-5s" % [a, b]
69 end
70
71 def normalize_tag(tag)
72 tag = tag.to_s.sub(/^[+]/, "") # +1 => 1
73 if tag =~ /^-?[0-9]+[.][0-9]+$/
74 tag = tag.sub(/[.]0+$/, "") # -1.0000 => -1
75 end
76 return tag
77 end
78
79 def split_into_3(line, fn)
80 line = line.gsub(/\s+/, " ").strip()
81
82 ret = ["", "", Float::MAX]
83
84 tokens = line.split(/ /)
85 case tokens.size
86 when 2
87 ret = [normalize_tag(tokens[0]), normalize_tag(tokens[1]), Float::MAX]
88 when 3
89 ret = [normalize_tag(tokens[0]), normalize_tag(tokens[1]), tokens[2].to_f]
90 else
91 ret = [normalize_tag(tokens[0]), normalize_tag(tokens[1]), Float::MAX]
92 line.sub!(/^fake ?/, "")
93 STDERR.puts("Bad line '#{line}' in file '#{fn}'")
94 @err = 1
95 end
96
97 if ret [2] < @options[:treshold]
98 ret [1] = @unspecified_class
99 end
100
101 return ret
102 end
103
104 def mse(outcomes, predictions)
105 sum = 0.0
106 outcomes.each_index do |idx|
107 sum += (outcomes[idx] - predictions[idx]) ** 2
108 end
109 return sum / outcomes.length.to_f
110 end
111
112 def rmse(outcomes, predictions)
113 return Math.sqrt(mse(outcomes, predictions))
114 end
115
116 def mae(outcomes, predictions)
117 sum = 0.0
118 outcomes.each_index do |idx|
119 sum += (outcomes[idx] - predictions[idx]).abs
120 end
121 return sum / outcomes.length.to_f
122 end
123
124 @options[:excluded] = Set.new()
125
126 OptionParser.new do |opts|
127 opts.banner = <<EOF
128 heri-stat calculates precision (P), recall (R), F1, accuracy (A),
129 mean absolute error (MAE), mean squared error (MSE) or
130 root mean squared error (RMSE) for given outcomes and predictions.
131 Unless -g is specified, predictions of classification is expected on input.
132 Usage:
133 heri-stat -h
134 heri-stat [-g mode] [-R] [OPTIONS] <outcomes> <predictions>
135 heri-stat -1 [-g mode] [-R] [OPTIONS] [files...]
136 OPTIONS:
137 EOF
138
139 opts.on('-h', '--help','display this message and exit') do
140 puts opts
141 exit 0
142 end
143
144 @options[:raw] = false
145 opts.on('-R', '--raw','raw tab-separated output') do
146 @options[:raw] = true
147 end
148
149 @options[:micro_avg] = false
150 opts.on('-m', '--micro-avg','disable micro averaged P/R/F1 output') do
151 @options[:micro_avg] = true
152 end
153
154 @options[:macro_avg] = false
155 opts.on('-r', '--macro-avg','disable macro averaged P/R/F1 output') do
156 @options[:macro_avg] = true
157 end
158
159 @options[:statistics] = false
160 opts.on('-c', '--per-class','disable output of per-class statistics') do
161 @options[:statistics] = true
162 end
163
164 @options[:accuracy] = false
165 opts.on('-a', '--accuracy','disable output of accuracy') do
166 @options[:accuracy] = true
167 end
168
169 @options[:single] = false
170 opts.on('-1', '--single','obtain both outcomes and
171 predicted classes from single source. If this option is specified,
172 the first token on input represents the outcome class
173 and second one -- predicted class') do
174 @options[:single] = true
175 end
176
177 @options[:unclassified] = false
178 opts.on("-u", "--unclassified=UNCLASSIFIED", 'set the label for "unclassified" object') do |u|
179 @options[:unclassified] = u.to_s
180 end
181
182 @options[:treshold] = -Float::MAX
183 opts.on("-t", "--treshold=TRESHOLD", 'Minimal treshold for score') do |u|
184 @options[:treshold] = u.to_f
185 @options[:unclassified] = @unspecified_class
186 end
187
188 @options[:excluded_labels] = false
189 opts.on("-x", "--exclude=LABELS", 'exclude the specified labels from statistics') do |x|
190 @options[:excluded] = Set.new(x.split(","))
191 end
192
193 opts.on("-g", "--regression=mode", 'Calculate MAE, MSE or RMSE') do |g|
194 @options[:regression] = true
195
196 @options[:mse] = g.include?("s")
197 @options[:rmse] = g.include?("r")
198 @options[:mae] = g.include?("a")
199
200 if /[^sra]/ =~ g
201 STDERR.puts "Invalid mode '#{g}' for option -g"
202 exit 1
203 end
204 end
205
206 opts.separator " "
207 end.parse!
208
209 if @options[:unclassified]
210 @options[:accuracy]=true
211 else
212 @options[:micro_avg]=true
213 end
214
215 def get_up_to_two_tokens(s)
216 s = s.strip
217 s = s.sub(/^([^\s]+\s([^\s]+))\s.*$/, "\\1")
218 return s
219 end
220
221 def get_up_to_three_tokens(s)
222 s = s.strip
223 s = s.sub(/^([^\s]+\s([^\s]+)\s([^\s]+))\s.*$/, "\\1")
224 return s
225 end
226
227 if @options[:single]
228 outcome_tags = []
229 prediction_tags = []
230 while line = gets do
231 gt, rt, fake = split_into_3(get_up_to_three_tokens(line), "")
232 outcome_tags << gt
233 prediction_tags << rt
234 end
235 else
236 outcome_tags = IO.read(ARGV[0]).split("\n").map! do |x| get_up_to_two_tokens(x) end
237 prediction_tags = IO.read(ARGV[1]).split("\n").map! do |x| get_up_to_two_tokens(x) end
238 if outcome_tags.length != prediction_tags.length
239 STDERR.puts("Dataset and prediction files should contain the same amount of lines");
240 exit 1
241 end
242
243 outcome_tags.each_index do |i|
244 fake1, outcome_tags[i], fake = split_into_3("fake " + outcome_tags[i], ARGV[0])
245 fake1, prediction_tags[i], fake = split_into_3("fake " + prediction_tags[i], ARGV[1])
246 end
247 end
248
249 exit 1 if @err
250
251 if @options[:regression]
252 outcome_tags.map! {|x| x.to_f}
253 prediction_tags.map! {|x| x.to_f}
254
255 mae_value = mae(outcome_tags, prediction_tags)
256 mse_value = mse(outcome_tags, prediction_tags)
257 rmse_value = rmse(outcome_tags, prediction_tags)
258
259 if @options[:mse]
260 if @options[:raw]
261 puts "\tMSE\t#{mse_value}"
262 else
263 puts "MSE: #{mse_value}"
264 end
265 end
266 if @options[:rmse]
267 if @options[:raw]
268 puts "\tRMSE\t#{rmse_value}"
269 else
270 puts "RMSE: #{rmse_value}"
271 end
272 end
273 if @options[:mae]
274 if @options[:raw]
275 puts "\tMAE\t#{mae_value}"
276 else
277 puts "MAE: #{mae_value}"
278 end
279 end
280
281 exit 0
282 end
283
284 tag2outcome_cnt = Hash.new(0)
285 tag2prediction_cnt = Hash.new(0)
286 tag2TP_cnt = Hash.new(0)
287 all_precision = 0
288 all_recall = 0
289
290 outcome_tags.each_index do |i|
291 gt = outcome_tags[i]
292 rt = prediction_tags[i]
293
294 # make sure hash cell exists
295 tag2TP_cnt[gt] += 0
296 tag2prediction_cnt[gt] += 0
297 tag2outcome_cnt[gt] += 1 if gt != @options[:unclassified]
298
299 if @options[:excluded].include?(rt)
300 next
301 end
302
303 if rt != @options[:unclassified]
304 tag2prediction_cnt[rt] += 1
305 tag2TP_cnt[rt] += (gt == rt ? 1 : 0)
306 end
307 end
308
309 @options[:excluded].each do |excluded|
310 tag2TP_cnt.delete(excluded)
311 tag2prediction_cnt.delete(excluded)
312 end
313
314 all_tp = 0
315 all_f1 = 0
316 res_tag2TP_cnt = tag2TP_cnt.sort_by { |key, value| key }
317 res_tag2TP_cnt.each do |t, tp|
318 if @options[:excluded].include?(t)
319 next
320 end
321
322 p = (tag2prediction_cnt[t] > 0.0 ? tp.to_f / tag2prediction_cnt[t] : 0.0)
323 r = (tag2outcome_cnt[t] > 0.0 ? tp.to_f / tag2outcome_cnt[t] : 0.0)
324 f1 = (p+r > 0.0 ? 2*p*r / (p+r) : 0.0)
325 if !@options[:statistics]
326 print_stat("Class %-6s" % [t],
327 p, pretty_div(tp, tag2prediction_cnt[t]),
328 r, pretty_div(tp, tag2outcome_cnt[t]),
329 f1, "")
330 end
331 all_precision += p
332 all_recall += r
333 all_tp += tp
334 all_f1 += f1
335 end
336
337 all_rt = 0
338 tag2prediction_cnt.each do |tag, rt|
339 all_rt += rt
340 end
341
342 all_gt = 0
343 tag2outcome_cnt.each do |tag, gt|
344 all_gt += gt
345 end
346
347 included_labels_count = res_tag2TP_cnt.size()
348 if included_labels_count == 1
349 @options[:accuracy] = true
350 @options[:micro_avg] = true
351 @options[:macro_avg] = true
352 end
353
354 if !@options[:accuracy]
355 accuracy = all_tp.to_f / all_rt.to_f
356 print_accuracy(accuracy, pretty_div(all_tp, all_rt))
357 end
358
359 if !@options[:micro_avg]
360 micro_avg_precision = all_tp.to_f / all_rt.to_f
361 micro_avg_recall = all_tp.to_f / all_gt.to_f
362 micro_avg_f1 = 2*micro_avg_precision*micro_avg_recall / (micro_avg_precision+micro_avg_recall)
363 print_stat("Micro average",
364 micro_avg_precision, pretty_div(all_tp, all_rt),
365 micro_avg_recall, pretty_div(all_tp, all_gt),
366 micro_avg_f1, "")
367 end
368
369 if !@options[:macro_avg] && tag2TP_cnt.size > 0
370 macro_avg_precision = all_precision / tag2TP_cnt.size
371 macro_avg_recall = all_recall / tag2TP_cnt.size
372 macro_avg_f1 = all_f1 / tag2TP_cnt.size
373 print_stat("Macro average",
374 macro_avg_precision, "",
375 macro_avg_recall, "",
376 macro_avg_f1, "")
377 end