Debian Codegraph @

scripts/heri-eval

raw
1 #!/usr/bin/env bash
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 # variables settable by user
26 : ${SVM_TRAIN_CMD:=svm-train}
27 : ${SVM_PREDICT_CMD:=svm-predict}
28
29 : ${SVM_HERI_STAT_CMD:=heri-stat}
30 : ${SVM_HERI_STAT_ADDONS_CMD:=heri-stat-addons}
31 : ${SVM_HERI_SPLIT_CMD:=heri-split}
32
33 : ${TMPDIR:=/tmp}
34
35 ############################################################
36 set -e
37 export LC_ALL=C
38
39 indent2 (){
40 sed '/./ s/^/ /' "$@"
41 }
42
43 sig_handler (){
44 on_exit
45 trap - "$1"
46 kill -"$1" $$
47 }
48
49 on_exit(){
50 show_stderr
51 if test -z "$keep_tmp"; then
52 if test -n "$tmp_dir"; then
53 rm -rf "$tmp_dir"
54 fi
55 else
56 echo "Temporary files are here $tmp_dir" 1>&2
57 fi
58 }
59
60 calculate_feature_count (){
61 awk '{
62 for (i=2; i <= NF; ++i) {
63 if ($i + 0 > m)
64 m = $i + 0
65 }
66 }
67 END {
68 print m+1
69 }' "$@"
70 }
71
72 calculate_feature_count (){
73 awk '{
74 for (i=2; i <= NF; ++i) {
75 if ($i + 0 > m)
76 m = $i + 0
77 }
78 }
79 END {
80 print m+1
81 }' "$@"
82 }
83
84 predictions_from_testing_sets (){
85 if ! test -s "$tmp_dir/testing_fold.txt"; then
86 cat "$tmp_dir/outcome_and_prediction1.txt"
87 return
88 fi
89
90 awk '
91 FNR == NR {
92 # reading testing_fold.txt
93 ++obj_num[$1]
94 testobj[$1,obj_num[$1]] = NR
95 next
96 }
97
98 # reading predictions on testing folds
99 FNR == 1 {
100 ++fold_num
101 }
102
103 {
104 idx = testobj[fold_num, FNR]
105 prediction [idx] = $0
106 }
107
108 END {
109 if ((NR % 2) != 0){
110 print "internal error!" > "/dev/stderr"
111 exit 12
112 }
113 count = NR/2
114 for (i=1; i <= count; ++i){
115 print prediction [i]
116 }
117 }' "$tmp_dir/testing_fold.txt" $prediction_all
118 }
119
120 show_stderr (){
121 if test -z "$last"; then
122 return
123 fi
124 for i in `seq $last`; do
125 #
126 fn="$tmp_dir/train_stderr${i}.txt"
127 if test -s "$fn"; then
128 echo "---- train stderr $i ----" 1>&2
129 cat -- "$fn" 1>&2
130 fi
131 #
132 fn="$tmp_dir/predict_stderr${i}.txt"
133 if test -s "$fn"; then
134 echo "---- predict stderr $i ----" 1>&2
135 cat -- "$fn" 1>&2
136 fi
137 done
138 }
139
140 wait_all (){
141 local i
142 local ex
143 ex=0
144 for i in `seq $last`; do
145 if wait ${pid[$i]}; then
146 :
147 else
148 ex=$?
149 fi
150 done
151 return "$ex"
152 }
153
154 # heri-eval -t10 -n 5 dataset.libsvm # 10*5-fold cross-validation
155 usage(){
156 cat 1>&2 <<'EOF'
157 usage: heri-eval [OPTIONS] training_set [-- SVM_TRAIN_OPTIONS]
158
159 OPTIONS:
160 -h Help message
161
162 -n <N> The number of folds for T*N-fold cross-validation
163 -r <ratio> The ratio (in percents) for training set for hold-out
164 -e testing_set Testing set for hold-out
165
166 -t <T> The number of runs for T*N-fold cross-validation
167 or holdouts
168
169 -T <threshold> Threshold for score
170
171 -o <filename> Save predictions from testing sets
172 to the specified file
173 (outcome_tag prediction_tag [score])
174 -O <filename> Save incorrectly classified objects
175 to the specified file
176 (#object_number: outcome_tag prediction_tag [score])
177 -m <filename> Save confusion matrix to the specified file
178 (frequency : outcome_tag prediction_tag)
179
180 -f Enable output of per-fold statistics (see -Mf)
181 -M <chars> Output mode:
182 t -- output total statistics,
183 f -- output per-fold statistics,
184 c -- output cross-fold statistics.
185 -s <split_opts> Options passed to heri-split(1)
186 -p <stat_opts> Options passed to heri-stat(1)
187 -S <seed> Seed value passed to heri-split(1).
188 If it is not specified, the dataset is splitted
189 into training and testing datasets randomly.
190 -K Keep temporary directory after exiting
191 -D Debugging mode, implies -K
192
193 SVM_TRAIN_OPTIONS: options passed to svm-train(1) and alike
194
195 Environment variables:
196 SVM_TRAIN_CMD -- training utility, e.g., liblinear-train
197 (the default is svm-train)
198 SVM_PREDICT_CMD -- predicting utility, e.g., liblinear-predict
199 (the default is svm-predict)
200 TMPDIR -- temporary directory (the default is /tmp)
201
202 Examples:
203 Ex1: heri-eval -e testing_set.libsvm training_set.libsvm -- -s 0 -t 0
204 Ex2: export SVM_TRAIN_CMD='liblinear-train'
205 export SVM_PREDICT_CMD='liblinear-predict'
206 heri-eval -p '-mr' -n 5 training_set.libsvm -- -s 4 -q
207 heri-eval -p '-mr' -n 5 training_set.libsvm -- -s 4 -q
208
209 Ex3: export SVM_TRAIN_CMD='scikit_rf-train --estimators=400'
210 export SVM_PREDICT_CMD='scikit_rf-predict'
211 heri-eval -p '-c' -Mt -t 50 -r 70 dataset.libsvm
212 EOF
213 }
214
215 seed=$RANDOM
216 runs=1
217 output_mode=tc
218 times=1
219 while getopts De:fhKm:M:n:o:O:p:r:s:S:t:T: f; do
220 case "$f" in
221 '?')
222 usage
223 exit 1;;
224 h)
225 usage
226 exit 0;;
227 n)
228 number_of_folds="$OPTARG";;
229 e)
230 testing_set="$OPTARG";;
231 t)
232 times="$OPTARG";;
233 T)
234 heristat_args="$heristat_args -t$OPTARG";;
235 r)
236 ratio="$OPTARG";;
237 m)
238 confusion_matrix="$OPTARG";;
239 o)
240 predictions="$OPTARG";;
241 O)
242 incorrect_predictions="$OPTARG";;
243 s)
244 herisplit_args="$herisplit_args $OPTARG";;
245 p)
246 heristat_args="$heristat_args $OPTARG";;
247 f)
248 output_mode="f$output_mode";;
249 M)
250 output_mode="$OPTARG";;
251 S)
252 seed="$OPTARG";;
253 K)
254 keep_tmp=1;;
255 D)
256 keep_tmp=1
257 debug=1;;
258 esac
259 done
260 shift `expr $OPTIND - 1`
261
262 while test "$#" -gt 0; do
263 case "$1" in
264 --)
265 shift
266 break;;
267 *)
268 print_sh=`printf '%q' "$1"`
269 files="$files $print_sh"
270 shift;;
271 esac
272 done
273
274 trap "sig_handler INT" INT
275 trap "on_exit" 0
276
277 if test -z "$number_of_folds" -a -z "$testing_set" -a -z "$ratio"; then
278 echo 'Either -n or -r or -e must be specified, run heri-eval -h for details' 1>&2
279 exit 1
280 fi
281
282 if test -z "$files"; then
283 echo 'Training set is mandatory, run heri-eval -h for details' 1>&2
284 exit 1
285 fi
286
287 tmp_dir=`mktemp -d "$TMPDIR"/svm.XXXXXX`
288
289 training_testing (){
290 if test -n "$number_of_folds"; then
291 ${SVM_HERI_SPLIT_CMD} $herisplit_args -c "$number_of_folds" -d "$tmp_dir" -s "$seed" $files
292 seed="$((seed+1))"
293 last="$number_of_folds"
294 for i in `seq $number_of_folds`; do
295 mv "$tmp_dir/test$i.txt" "$tmp_dir/test$i.libsvm"
296 mv "$tmp_dir/train$i.txt" "$tmp_dir/train$i.libsvm"
297 done
298 elif test -n "$ratio"; then
299 ${SVM_HERI_SPLIT_CMD} $herisplit_args -R "$ratio" -d "$tmp_dir" -s "$seed" $files
300 mv "$tmp_dir/test.txt" "$tmp_dir/test1.libsvm"
301 mv "$tmp_dir/train.txt" "$tmp_dir/train1.libsvm"
302 rm "$tmp_dir/testing_fold.txt"
303 seed="$((seed+1))"
304 last=1
305 else
306 eval "cat -- $files" > "$tmp_dir/train1.libsvm"
307 cp "$testing_set" "$tmp_dir/test1.libsvm"
308 last=1
309 fi
310
311 for i in `seq $last`; do
312 ${SVM_TRAIN_CMD} "$@" "$tmp_dir/train$i.libsvm" "$tmp_dir/model$i.bin" \
313 2> "$tmp_dir/train_stderr${i}.txt" \
314 > "$tmp_dir/train_stdout${i}.txt" &
315 pid[$i]=$!
316 done
317
318 wait_all
319
320 for i in `seq $last`; do
321 ${SVM_PREDICT_CMD} "$tmp_dir/test$i.libsvm" "$tmp_dir/model$i.bin" \
322 "$tmp_dir/prediction${i}.txt" \
323 2> "$tmp_dir/predict_stderr${i}.txt" \
324 > "$tmp_dir/predict_stdout${i}.txt" &
325 pid[$i]=$!
326 done
327
328 wait_all
329
330 rm -f "$tmp_dir/outcome.txt" "$tmp_dir/prediction.txt"
331 }
332
333 show_stat (){
334 for t in `seq $times`; do
335 prediction_all=''
336 for i in `seq $last`; do
337 awk '{print $1}' "$tmp_dir/test${t}_$i.libsvm" > "$tmp_dir/outcome${t}_${i}.txt"
338 paste "$tmp_dir/outcome${t}_${i}.txt" "$tmp_dir/prediction${t}_${i}.txt" | \
339 tr ' ' ' ' > "$tmp_dir/outcome_and_prediction${t}_${i}.txt"
340 ${SVM_HERI_STAT_CMD} -1R $heristat_args \
341 "$tmp_dir/outcome_and_prediction${t}_${i}.txt" > "$tmp_dir/stats${t}_${i}.txt"
342 if [[ "_$output_mode" =~ f ]]; then
343 echo "Fold ${t}x$i statistics"
344 ${SVM_HERI_STAT_CMD} -1 $heristat_args "$tmp_dir/outcome_and_prediction${t}_${i}.txt" |
345 indent2
346 echo ''
347 fi
348
349 ln -f "$tmp_dir/outcome_and_prediction${t}_${i}.txt" "$tmp_dir/outcome_and_prediction${i}.txt"
350 prediction_all="$prediction_all $tmp_dir/outcome_and_prediction${t}_${i}.txt"
351 done
352 done
353 }
354
355 export HERISVM_FC=`calculate_feature_count $files $testing_set`
356
357 for t in `seq $times`; do
358 training_testing "$@"
359 # ls -l "$tmp_dir/"
360 for i in `seq $last`; do
361 mv "$tmp_dir/train${i}.libsvm" "$tmp_dir/train${t}_$i.libsvm"
362 mv "$tmp_dir/test${i}.libsvm" "$tmp_dir/test${t}_$i.libsvm"
363 mv "$tmp_dir/prediction${i}.txt" "$tmp_dir/prediction${t}_${i}.txt"
364 mv "$tmp_dir/train_stderr${i}.txt" "$tmp_dir/train_stderr${t}_$i.txt"
365 mv "$tmp_dir/train_stdout${i}.txt" "$tmp_dir/train_stdout${t}_$i.txt"
366 mv "$tmp_dir/predict_stderr${i}.txt" "$tmp_dir/predict_stderr${t}_$i.txt"
367 mv "$tmp_dir/predict_stdout${i}.txt" "$tmp_dir/predict_stdout${t}_$i.txt"
368 if test -f "$tmp_dir/model${i}.bin"; then
369 mv "$tmp_dir/model${i}.bin" "$tmp_dir/model${t}_$i.bin"
370 fi
371 done
372 # rm "$tmp_dir/test${i}.txt" "$tmp_dir/prediction${i}.txt"
373 done
374
375 #echo before test
376 #ls -l "$tmp_dir"
377 show_stat
378 #echo after test
379
380 predictions_from_testing_sets > "$tmp_dir/prediction.txt"
381
382 # -o
383 if test -n "$predictions"; then
384 cp "$tmp_dir/prediction.txt" "$predictions"
385 fi
386
387 # -O
388 if test -n "$incorrect_predictions"; then
389 awk '$1 != $2 {print "#" NR, $0}' "$tmp_dir/prediction.txt" \
390 > "$incorrect_predictions"
391 fi
392
393 # -m
394 if test -n "$confusion_matrix"; then
395 awk '$1 != $2 {print $1, $2}' "$tmp_dir/prediction.txt" |
396 sort | uniq -c | sort -rn |
397 awk '{print $1, ":", $2, $3}' > "$confusion_matrix"
398 fi
399
400 rm "$tmp_dir/prediction.txt"
401
402 #
403 if [[ "_$output_mode" =~ t ]]; then
404 echo 'Total statistics'
405 ${SVM_HERI_STAT_CMD} -1 $heristat_args "$tmp_dir"/outcome_and_prediction*_*.txt | indent2
406 echo ''
407 fi
408
409 if test -n "$number_of_folds" && [[ "_$output_mode" =~ c ]]; then
410 echo 'Total cross-folds statistics'
411 ${SVM_HERI_STAT_ADDONS_CMD} "$tmp_dir"/stats*.txt | indent2
412 fi