def test_GaussHMM_posterior(cases: str) -> None: np.random.seed(12346) cases = int(cases) i = 1 N_decimal = 4 max_iter = 100 tol=1e-3 while i < cases: n_samples = np.random.randint(10, 50) hidden_states = np.random.randint(3, 6) n_features = np.random.randint(4, 9) X = [] lengths = [] for _ in range(n_samples): seq_length = np.random.randint(4, 9) this_x = np.random.rand(seq_length,n_features) X.append(this_x) lengths.append(seq_length) hmm_gold = GaussianHMM(n_components=hidden_states, covariance_type='full', n_iter=max_iter, tol=tol) X_gold = np.concatenate(X) hmm_gold.fit(X_gold, lengths) gold_means = hmm_gold.means_ gold_pi = hmm_gold.startprob_ gold_n_features = hmm_gold.n_features gold_transmat = hmm_gold.transmat_ gold_means = hmm_gold.means_ gold_covars = hmm_gold.covars_ hmm_mine = GaussHMM(hidden_states=hidden_states, A=gold_transmat, n_features=gold_n_features, means=gold_means, covar=gold_covars, pi=gold_pi, tol=tol, max_iter=max_iter) _,gold_posteriors = hmm_gold.score_samples(X_gold, lengths) mine_posterior_list = [hmm_mine.posterior(this_x) for this_x in X] mine_posterior_list = np.concatenate(mine_posterior_list) assert_almost_equal(mine_posterior_list, gold_posteriors, decimal=N_decimal) i+=1 print('Successfully testing the function of computing posteriors in Gaussian HMM!')
new_x = np.asarray(train_set) n_comps = 6 model = GaussianHMM(n_comps) model.fit([new_x]) hidden_states = model.predict(new_x) new_test = np.asarray(test_set) predictions = [] chunk = train_set[2500:] '''find prob for each test point, compare to expected, then re-fit HMM with it''' for idx, x in enumerate(chunk): _, pst_prob = model.score_samples([x]) max_ind = pst_prob.argmax() trn = model._get_transmat()[max_ind] '''Get the max one for now. Maybe use some other method later one''' max_trn = trn.argmax() cov = model._get_covars()[max_trn] mns = model._get_means()[max_trn] rd = np.random.multivariate_normal(mns, cov) int_rd = [int(x) for x in rd] predictions += [int_rd] # retrain HMM with new data point moving_idx = 30-idx