def learn_and_predict_INERTIAL(data, K): model = GaussianHMM(K, data, rgzn_modes.INERTIAL) final_param = REG_PARAM model.learn(data, zeta=final_param, init=True) return np.array(model.decode(data), dtype="int8")
from __future__ import division import numpy as np from GaussianHMM import GaussianHMM from evaluation import * import os DATA_DIR = "./Dataset/" ACC_DIR = "./Dataset/" REG_PARAM = 3 # Controls the strength of regularization. (Lambda parameter) rgzn_modes = GaussianHMM.RgznModes() def learn_and_predict_MAP(data, K): model = GaussianHMM(K, data, rgzn_modes.MAP_SCALE_FREE) final_param = REG_PARAM model.learn(data, zeta=final_param, init=True) return np.array(model.decode(data), dtype="int8") def learn_and_predict_INERTIAL(data, K): model = GaussianHMM(K, data, rgzn_modes.INERTIAL) final_param = REG_PARAM model.learn(data, zeta=final_param, init=True) return np.array(model.decode(data), dtype="int8") def do_quantitative(mode=rgzn_modes.MAP_SCALE_FREE, results_dir="./Results/"): evaluation_dir = results_dir + "/evaluation/" if not os.path.exists(evaluation_dir): os.makedirs(evaluation_dir) results = []
from __future__ import division from itertools import permutations import numpy as np from GaussianHMM import GaussianHMM segment_func = GaussianHMM(1,np.random.random(size=(2,2))).get_segments def compute_cost_matrix(predicted_states, true_states): predicted_states -= predicted_states.min() N = len(true_states) num_states = max(true_states) + 1 cost = np.zeros((num_states, num_states)) for i in range(num_states): for j in range(num_states): ps = np.array(predicted_states) ps[ps == j] = j + num_states ps[ps == i] = j ps[ps == j + num_states] = i cost[i][j] = N - np.equal(ps, true_states).sum() return cost def segment_measurements(predicted_states, true_states): predicted_states -= predicted_states.min() s1 = segment_func(predicted_states) s2 = segment_func(true_states) l1 = len(s1) l2 = len(s2) return l1/l2, max(l1, l2)/min(l1, l2), abs(l1-l2) def max_correct(predicted_states, true_states): predicted_states -= predicted_states.min()
# num_states = [4, 8, 16, 32] # for n in num_states: # prob = [] # for i in range(num_iters): # hmm = GaussianHMM(n_state=n, x_size=1, iter=i) # hmm.train(data.reshape(-1, 1)) # prob.append(hmm.X_prob(data.reshape(-1, 1))) # plt.plot(range(num_iters), prob, label="states number: {}".format(n)) # plt.legend() # plt.xlabel("number of iterations") # plt.ylabel("loglikelihood") # plt.show() num_states = [4, 5, 6, 7] for n in num_states: hmm = GaussianHMM(n_state=n, x_size=1, iter=100) hmm.train(train_data.reshape(-1, 1)) predictions, _ = hmm.generate_seq(len(test_data)) plt.figure() plt.plot(predictions, label="predictions") plt.plot(test_data, label="actual values") plt.legend() plt.ylim((2000, 8000)) plt.title("{} hidden states".format(n)) plt.xlabel("t") plt.ylabel("price") plt.savefig("{}_hidden_states_predictions".format(n)) # print("means:", hmm.emit_means) # print("covs:", hmm.emit_covars)
import numpy as np from get_mfc_data import get_mfc_data from GaussianHMM import GaussianHMM if __name__ == "__main__": datas = get_mfc_data('C:/Users/18341/Desktop/book/听觉/实验3-语音识别/语料/features/') # 每个类别创建一个hmm, 并用kmeans初始化hmm hmms = dict() for category in datas: Qs = datas[category] n_hidden = 5 n_dim = Qs[0].shape[1] hmm = GaussianHMM(n_hidden,n_dim) #hmm.viterbi_init(Qs, iter_max=5) # TODO:维特比算法没测试 hmm.kmeans_init(Qs[:-3]) hmms[category] = hmm # 训练每个hmm print('start fit') for category in hmms: hmm = hmms[category] #print(hmm.covs) Qs = datas[category] hmm.fit(Qs[:-3], iter_max = 5) hmms[category] = hmm print(category, ':fit success') # 测试, 打印得分和最终正确率 correct_num = 0
#transition_prob = np.random.randn(n_hidden, n_hidden) initial_prob = np.ones((n_hidden)) initial_prob /= n_hidden transition_prob = np.ones((n_hidden, n_hidden)) transition_prob /= n_hidden n_dim = len(Qs[0][0]) means = np.random.randn(n_hidden, n_dim) * 10 covs = list() for _ in range(n_hidden): cov = np.eye(n_dim) for i in range(n_dim): cov[i,i] *= (np.random.randn() * 10) covs.append(cov) covs = np.asarray(covs) hmm = GaussianHMM(initial_prob, transition_prob, means, covs) #hmm.viterbi_init(Qs, iter_max=5) # TODO: hmm.kmeans_init(Qs) hmms[category] = hmm evaluate_num = 5 for evaluate_cnt in range(evaluate_num): print(evaluate_cnt, 'start fit') for category in hmms: hmm = hmms[category] #print(hmm.covs) Qs = datas[category] hmm.fit(Qs[:-3], iter_max = 10) hmms[category] = hmm print('fit success')
##main if __name__ == '__main__': order_text = ['开门', '关门', '打开', '关闭', '安静'] #训练 #datas = get_mfc_data('C:/Users/18341/Desktop/book/听觉/实验3-语音识别/语料/features/') datas = get_mfc_data('F:/HIT/大三上/视听觉/lab3/组/gzx_sound_mfcc/') # 每个类别创建一个hmm, 并用kmeans,viterbi初始化hmm hmms = dict() for category in datas: Qs = datas[category] n_hidden = 5 n_dim = Qs[0].shape[1] hmm = GaussianHMM(n_hidden, n_dim) hmm.kmeans_init(Qs[:-3]) hmm.viterbi_init(Qs) # hmms[category] = hmm # 训练每个hmm print('start fit') for category in hmms: hmm = hmms[category] #print(hmm.covs) Qs = datas[category] hmm.fit(Qs[:-3], iter_max=5) hmms[category] = hmm print(category, ':fit success') while (True):