|
| 1 | +''' |
| 2 | + @file dtc.py |
| 3 | + Class to benchmark the R Decision Tree method. |
| 4 | +''' |
| 5 | + |
| 6 | +import os |
| 7 | +import sys |
| 8 | +import inspect |
| 9 | + |
| 10 | +# Import the util path, this method even works if the path contains symlinks to |
| 11 | +# modules. |
| 12 | +cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join( |
| 13 | + os.path.split(inspect.getfile(inspect.currentframe()))[0], "../../util"))) |
| 14 | +if cmd_subfolder not in sys.path: |
| 15 | + sys.path.insert(0, cmd_subfolder) |
| 16 | + |
| 17 | +#Import the metrics definitions path. |
| 18 | +metrics_folder = os.path.realpath(os.path.abspath(os.path.join( |
| 19 | + os.path.split(inspect.getfile(inspect.currentframe()))[0], "../metrics"))) |
| 20 | +if metrics_folder not in sys.path: |
| 21 | + sys.path.insert(0, metrics_folder) |
| 22 | + |
| 23 | +from log import * |
| 24 | +from profiler import * |
| 25 | +from definitions import * |
| 26 | +from misc import * |
| 27 | + |
| 28 | +import shlex |
| 29 | +import subprocess |
| 30 | +import re |
| 31 | +import collections |
| 32 | +import numpy as np |
| 33 | + |
| 34 | +''' |
| 35 | +This class implements the Decision Tree benchmark. |
| 36 | +''' |
| 37 | +class DTC(object): |
| 38 | + |
| 39 | + ''' |
| 40 | + Create the Decision Tree benchmark instance. |
| 41 | + @param dataset - Input dataset to perform DTC on. |
| 42 | + @param timeout - The time until the timeout. Default no timeout. |
| 43 | + @param path - Path to the R executable. |
| 44 | + @param verbose - Display informational messages. |
| 45 | + ''' |
| 46 | + def __init__(self, dataset, timeout=0, path=os.environ["R_PATH"], |
| 47 | + verbose=True): |
| 48 | + self.verbose = verbose |
| 49 | + self.dataset = dataset |
| 50 | + self.path = path |
| 51 | + self.timeout = timeout |
| 52 | + self.build_opts = {} |
| 53 | + |
| 54 | + def __del__(self): |
| 55 | + Log.Info("Clean up.", self.verbose) |
| 56 | + filelist = ["predictions.csv", "log.txt"] |
| 57 | + for f in filelist: |
| 58 | + if os.path.isfile(f): |
| 59 | + os.remove(f) |
| 60 | + |
| 61 | + ''' |
| 62 | + DTC. If the method has been successfully completed return |
| 63 | + the elapsed time in seconds. |
| 64 | + @param options - Extra options for the method. |
| 65 | + @return - Elapsed time in seconds or a negative value if the method was not |
| 66 | + successful. |
| 67 | + ''' |
| 68 | + def RunMetrics(self, options): |
| 69 | + Log.Info("Perform DTC.", self.verbose) |
| 70 | + |
| 71 | + # Get all the parameters. |
| 72 | + self.build_opts = {} |
| 73 | + if "max_depth" in options: |
| 74 | + self.build_opts["max_depth"] = int(options.pop("max_depth")) |
| 75 | + else: |
| 76 | + self.build_opts["max_depth"] = 30 |
| 77 | + |
| 78 | + if "minimum_samples_split" in options: |
| 79 | + self.build_opts["min_samples_split"] = \ |
| 80 | + int(options.pop("minimum_samples_split")) |
| 81 | + else: |
| 82 | + self.build_opts["min_samples_split"] = 20 |
| 83 | + |
| 84 | + |
| 85 | + if len(options) > 0: |
| 86 | + Log.Fatal("Unknown parameters: " + str(options)) |
| 87 | + raise Exception("unknown parameters") |
| 88 | + |
| 89 | + if len(self.dataset) < 2: |
| 90 | + Log.Fatal("This method requires two or more datasets.") |
| 91 | + return -1 |
| 92 | + |
| 93 | + # Split the command using shell-like syntax. |
| 94 | + cmd = shlex.split("libraries/bin/Rscript " + self.path + "dtc.r" + |
| 95 | + " -t " + self.dataset[0] + " -T " + |
| 96 | + self.dataset[1] + " -md " + str(self.build_opts["max_depth"]) + |
| 97 | + " -ms " + str(self.build_opts["min_samples_split"]) ) |
| 98 | + |
| 99 | + # Run command with the nessecary arguments and return its output as a byte |
| 100 | + # string. We have untrusted input so we disable all shell based features. |
| 101 | + try: |
| 102 | + s = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=False, |
| 103 | + timeout=self.timeout) |
| 104 | + except subprocess.TimeoutExpired as e: |
| 105 | + Log.Warn(str(e)) |
| 106 | + return -2 |
| 107 | + except Exception as e: |
| 108 | + Log.Fatal("Could not execute command: " + str(cmd)) |
| 109 | + return -1 |
| 110 | + |
| 111 | + # Datastructure to store the results. |
| 112 | + metrics = {} |
| 113 | + # Parse data: runtime. |
| 114 | + timer = self.parseTimer(str(s)) |
| 115 | + if timer != -1: |
| 116 | + metrics['Runtime'] = timer |
| 117 | + predictions = np.genfromtxt("predictions.csv", delimiter = ',') |
| 118 | + predictions = predictions[1:] |
| 119 | + truelabels = np.genfromtxt(self.dataset[2], delimiter = ',') |
| 120 | + confusionMatrix = Metrics.ConfusionMatrix(truelabels, predictions) |
| 121 | + metrics['ACC'] = Metrics.AverageAccuracy(confusionMatrix) |
| 122 | + metrics['MCC'] = Metrics.MCCMultiClass(confusionMatrix) |
| 123 | + metrics['Precision'] = Metrics.AvgPrecision(confusionMatrix) |
| 124 | + metrics['Recall'] = Metrics.AvgRecall(confusionMatrix) |
| 125 | + metrics['MSE'] = Metrics.SimpleMeanSquaredError(truelabels, predictions) |
| 126 | + |
| 127 | + Log.Info(("total time: %fs" % (metrics['Runtime'])), self.verbose) |
| 128 | + |
| 129 | + return metrics |
| 130 | + |
| 131 | + ''' |
| 132 | + Parse the timer data form a given string. |
| 133 | + @param data - String to parse timer data from. |
| 134 | + @return - Namedtuple that contains the timer data or -1 in case of an error. |
| 135 | + ''' |
| 136 | + def parseTimer(self, data): |
| 137 | + # Compile the regular expression pattern into a regular expression object to |
| 138 | + # parse the timer data. |
| 139 | + pattern = re.findall("(\d+\.\d+). *sec elapsed", data) |
| 140 | + return float(pattern[0]) |
0 commit comments