| 1 | """ |
| 2 | A script for testing / benchmarking HMM Implementations |
| 3 | """ |
| 4 | |
| 5 | import argparse |
| 6 | import collections |
| 7 | import logging |
| 8 | import time |
| 9 | |
| 10 | import hmmlearn.hmm |
| 11 | |
| 12 | import numpy as np |
| 13 | |
| 14 | import sklearn.base |
| 15 | |
| 16 | LOG = logging.getLogger(__file__) |
| 17 | |
| 18 | |
| 19 | class Benchmark: |
| 20 | def __init__(self, repeat, n_iter, verbose): |
| 21 | self.repeat = repeat |
| 22 | self.n_iter = n_iter |
| 23 | self.verbose = verbose |
| 24 | |
| 25 | def benchmark(self, sequences, lengths, model, tag): |
| 26 | elapsed = [] |
| 27 | for i in range(self.repeat): |
| 28 | start = time.time() |
| 29 | cloned = sklearn.base.clone(model) |
| 30 | cloned.fit(sequences, lengths) |
| 31 | end = time.time() |
| 32 | elapsed.append(end-start) |
| 33 | self.log_one_run(start, end, cloned, tag) |
| 34 | return np.asarray(elapsed) |
| 35 | |
| 36 | def generate_training_sequences(self): |
| 37 | pass |
| 38 | |
| 39 | def new_model(self, implementation): |
| 40 | pass |
| 41 | |
| 42 | def run(self, results_file): |
| 43 | runtimes = collections.defaultdict(dict) |
| 44 | |
| 45 | sequences, lengths = self.generate_training_sequences() |
| 46 | |
| 47 | for implementation in ["scaling", "log"]: |
| 48 | model = self.new_model(implementation) |
| 49 | LOG.info(f"{model.__class__.__name__}: testing {implementation}") |
| 50 | key = f"{model.__class__.__name__}|EM|hmmlearn-{implementation}" |
| 51 | elapsed = self.benchmark(sequences, lengths, model, key) |
| 52 | runtimes[key]["mean"] = elapsed.mean() |
| 53 | runtimes[key]["std"] = elapsed.std() |
| 54 | |
| 55 | with open(results_file, mode="w") as fd: |
| 56 | fd.write("configuration,mean,std,n_iterations,repeat\n") |
| 57 | for key, value in runtimes.items(): |
| 58 | fd.write(f"{key},{value['mean']},{value['std']}," |
| 59 | f"{self.n_iter},{self.repeat}\n") |
| 60 | |
| 61 | def log_one_run(self, start, end, model, tag): |
| 62 | LOG.info(f"Training Took {end-start} seconds {tag}") |
| 63 | LOG.info(f"startprob={model.startprob_}") |
| 64 | LOG.info(f"transmat={model.transmat_}") |
| 65 | |
| 66 | |
| 67 | class GaussianBenchmark(Benchmark): |
| 68 | |
| 69 | def new_model(self, implementation): |
| 70 | return hmmlearn.hmm.GaussianHMM( |
| 71 | n_components=4, |
| 72 | n_iter=self.n_iter, |
| 73 | covariance_type="full", |
| 74 | implementation=implementation, |
| 75 | verbose=self.verbose |
| 76 | ) |
| 77 | |
| 78 | def generate_training_sequences(self): |
| 79 | sampler = hmmlearn.hmm.GaussianHMM( |
| 80 | n_components=4, |
| 81 | covariance_type="full", |
| 82 | init_params="", |
| 83 | verbose=self.verbose |
| 84 | ) |
| 85 | |
| 86 | sampler.startprob_ = np.asarray([0, 0, 0, 1]) |
| 87 | sampler.transmat_ = np.asarray([ |
| 88 | [.2, .2, .3, .3], |
| 89 | [.3, .2, .2, .3], |
| 90 | [.2, .3, .3, .2], |
| 91 | [.3, .3, .2, .2], |
| 92 | ]) |
| 93 | sampler.means_ = np.asarray([ |
| 94 | -1.5, |
| 95 | 0, |
| 96 | 1.5, |
| 97 | 3 |
| 98 | ]).reshape(4, 1) |
| 99 | sampler.covars_ = np.asarray([ |
| 100 | .5, |
| 101 | .5, |
| 102 | .5, |
| 103 | .5 |
| 104 | ]).reshape(4, 1, 1,) |
| 105 | |
| 106 | sequences, states = sampler.sample(50000) |
| 107 | lengths = [len(sequences)] |
| 108 | return sequences, lengths |
| 109 | |
| 110 | def log_one_run(self, start, end, model, tag): |
| 111 | super().log_one_run(start, end, model, tag) |
| 112 | LOG.info(f"means={model.means_}") |
| 113 | LOG.info(f"covars={model.covars_}") |
| 114 | |
| 115 | |
| 116 | class MultinomialBenchmark(Benchmark): |
| 117 | |
| 118 | def new_model(self, implementation): |
| 119 | return hmmlearn.hmm.MultinomialHMM( |
| 120 | n_components=3, |
| 121 | n_iter=self.n_iter, |
| 122 | verbose=self.verbose, |
| 123 | implementation=implementation |
| 124 | ) |
| 125 | |
| 126 | def generate_training_sequences(self): |
| 127 | |
| 128 | sampler = hmmlearn.hmm.MultinomialHMM(n_components=3) |
| 129 | sampler.startprob_ = np.array([0.6, 0.3, 0.1]) |
| 130 | sampler.transmat_ = np.array([[0.6, 0.2, 0.2], |
| 131 | [0.3, 0.5, 0.2], |
| 132 | [0.4, 0.3, 0.3]]) |
| 133 | |
| 134 | sampler.emissionprob_ = np.array([ |
| 135 | [.1, .5, .1, .3], |
| 136 | [.1, .2, .4, .3], |
| 137 | [0, .5, .5, .0], |
| 138 | ]) |
| 139 | |
| 140 | sequences, states = sampler.sample(50000) |
| 141 | lengths = [len(sequences)] |
| 142 | return sequences, lengths |
| 143 | |
| 144 | def log_one_run(self, start, end, model, tag): |
| 145 | super().log_one_run(start, end, model, tag) |
| 146 | LOG.info(f"emissions={model.emissionprob_}") |
| 147 | |
| 148 | |
| 149 | class MultivariateGaussianBenchmark(GaussianBenchmark): |
| 150 | def generate_training_sequences(self): |
| 151 | sampler = hmmlearn.hmm.GaussianHMM( |
| 152 | n_components=4, |
| 153 | covariance_type="full", |
| 154 | init_params="" |
| 155 | ) |
| 156 | |
| 157 | sampler.startprob_ = np.asarray([0, 0, 0, 1]) |
| 158 | sampler.transmat_ = np.asarray([ |
| 159 | [.2, .2, .3, .3], |
| 160 | [.3, .2, .2, .3], |
| 161 | [.2, .3, .3, .2], |
| 162 | [.3, .3, .2, .2], |
| 163 | ]) |
| 164 | sampler.means_ = np.asarray([ |
| 165 | [-1.5, 0], |
| 166 | [0, 0], |
| 167 | [1.5, 0], |
| 168 | [3, 0] |
| 169 | ]) |
| 170 | sampler.covars_ = np.asarray([ |
| 171 | [[.5, 0], |
| 172 | [0, .5]], |
| 173 | [[.5, 0], |
| 174 | [0, 0.5]], |
| 175 | |
| 176 | [[.5, 0], |
| 177 | [0, .5]], |
| 178 | [[0.5, 0], |
| 179 | [0, 0.5]], |
| 180 | ]) |
| 181 | |
| 182 | observed, hidden = sampler.sample(50000) |
| 183 | lengths = [len(observed)] |
| 184 | return observed, lengths |
| 185 | |
| 186 | |
| 187 | class GMMBenchmark(GaussianBenchmark): |
| 188 | def generate_training_sequences(self): |
| 189 | sampler = hmmlearn.hmm.GMMHMM( |
| 190 | n_components=4, |
| 191 | n_mix=3, |
| 192 | covariance_type="full", |
| 193 | init_params="" |
| 194 | ) |
| 195 | |
| 196 | sampler.startprob_ = [.25, .25, .25, .25] |
| 197 | sampler.transmat_ = [ |
| 198 | [.1, .3, .3, .3], |
| 199 | [.3, .1, .3, .3], |
| 200 | [.3, .3, .1, .3], |
| 201 | [.3, .3, .3, .1], |
| 202 | ] |
| 203 | sampler.weights_ = [ |
| 204 | [.2, .2, .6], |
| 205 | [.6, .2, .2], |
| 206 | [.2, .6, .2], |
| 207 | [.1, .1, .8], |
| 208 | ] |
| 209 | sampler.means_ = np.asarray([ |
| 210 | [[-10], [-12], [-9]], |
| 211 | [[-5], [-4], [-3]], |
| 212 | [[-1.5], [0], [1.5]], |
| 213 | [[5], [7], [9]], |
| 214 | ]) |
| 215 | |
| 216 | sampler.covars_ = np.asarray([ |
| 217 | [[[.125]], [[.125]], [[.125]]], |
| 218 | [[[.125]], [[.125]], [[.125]]], |
| 219 | [[[.125]], [[.125]], [[.125]]], |
| 220 | [[[.125]], [[.125]], [[.125]]], |
| 221 | ]) |
| 222 | |
| 223 | n_sequences = 10 |
| 224 | length = 5_000 |
| 225 | sequences = [] |
| 226 | for i in range(n_sequences): |
| 227 | sequences.append(sampler.sample(5000)[0]) |
| 228 | return np.concatenate(sequences), [length] * n_sequences |
| 229 | |
| 230 | def new_model(self, implementation): |
| 231 | return hmmlearn.hmm.GMMHMM( |
| 232 | n_components=4, |
| 233 | n_mix=3, |
| 234 | n_iter=self.n_iter, |
| 235 | covariance_type="full", |
| 236 | verbose=self.verbose, |
| 237 | implementation=implementation |
| 238 | ) |
| 239 | |
| 240 | def log_one_run(self, start, end, model, tag): |
| 241 | super().log_one_run(start, end, model, tag) |
| 242 | LOG.info(f"weights_={model.weights_}") |
| 243 | |
| 244 | |
| 245 | def main(): |
| 246 | parser = argparse.ArgumentParser() |
| 247 | parser.add_argument("--all", action="store_true") |
| 248 | parser.add_argument("--categorical", action="store_true") |
| 249 | parser.add_argument("--gaussian", action="store_true") |
| 250 | parser.add_argument("--multivariate-gaussian", action="store_true") |
| 251 | parser.add_argument("--gaussian-mixture", action="store_true") |
| 252 | parser.add_argument("--repeat", type=int, default=10) |
| 253 | parser.add_argument("--verbose", action="store_true") |
| 254 | parser.add_argument("--n-iter", type=int, default=100) |
| 255 | |
| 256 | args = parser.parse_args() |
| 257 | if args.all: |
| 258 | args.categorical = True |
| 259 | args.gaussian = True |
| 260 | args.multivariate_gaussian = True |
| 261 | args.gaussian_mixture = True |
| 262 | |
| 263 | if args.categorical: |
| 264 | bench = MultinomialBenchmark( |
| 265 | repeat=args.repeat, |
| 266 | n_iter=args.n_iter, |
| 267 | verbose=args.verbose, |
| 268 | ) |
| 269 | bench.run("categorical.benchmark.csv") |
| 270 | if args.gaussian: |
| 271 | bench = GaussianBenchmark( |
| 272 | repeat=args.repeat, |
| 273 | n_iter=args.n_iter, |
| 274 | verbose=args.verbose, |
| 275 | ) |
| 276 | bench.run("gaussian.benchmark.csv") |
| 277 | if args.multivariate_gaussian: |
| 278 | bench = MultivariateGaussianBenchmark( |
| 279 | repeat=args.repeat, |
| 280 | n_iter=args.n_iter, |
| 281 | verbose=args.verbose, |
| 282 | ) |
| 283 | bench.run("multivariate_gaussian.benchmark.csv") |
| 284 | if args.gaussian_mixture: |
| 285 | bench = GMMBenchmark( |
| 286 | repeat=args.repeat, |
| 287 | n_iter=args.n_iter, |
| 288 | verbose=args.verbose, |
| 289 | ) |
| 290 | bench.run("gmm.benchmark.csv") |
| 291 | |
| 292 | |
| 293 | if __name__ == "__main__": |
| 294 | logging.basicConfig( |
| 295 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', |
| 296 | level=logging.DEBUG |
| 297 | ) |
| 298 | main() |