Exemplo n.º 1
0
 def aroBW(self,iter,func,pA,pB,ppi):
     inst = hmm()
     alpha=func(*[self.O, pA, pB, ppi])
     landa=[pA,pB,ppi,[]]
     probs=np.zeros((iter,1))
     P=alpha[-1]
     probs[0]=[alpha[-1]]
     for i in range(1,iter):
         landa=inst.baum_welch(self.O, landa[0], landa[1], landa[2],5)
         if (landa[-1].mean()<=P+1e-20):
             landa=self.aro(100,func,landa[0], landa[1], landa[2])
             P=landa[-1].mean()
         probs[i]=landa[-1].max()
         if (probs[i]>=1):
             print(str(i)+ "inja boodeh "+ str(probs[i]))
             return [landa[0], landa[1], landa[2],probs]
         
     return [landa[0], landa[1], landa[2],probs]       
               
def training_single(file_path, file_names):
    """
    training hmm models for all 6 gestures respectively, each using one observation sequence
    :param file_path: path
    :param file_names: list of 6 files, one for each gesture
    :return: models, a dictionary containing 6 hmm models
    """
    models = {}
    for i, gesture in enumerate(gesture_names):
        print("\nTraining model for gesture \"{}\"...".format(gesture))
        label = parse_label(gesture)
        model = hmm(N[i], M) # initialize model
        for file_name in file_names:
            if parse_label(file_name) == label:
                data = np.load(file_path+file_name)
                _ = model.baum_welch(data['Z'])
                models[gesture] = model
                break

    return models
def training_multi(file_path, file_names):
    """
    training hmm models for all 6 gestures respectively, each using multiple observation sequence
    :param file_path: path
    :param file_names: list of 6 files, one for each gesture
    :return: models, a dictionary containing 6 hmm models
    """
    models = {}
    for i, gesture in enumerate(gesture_names):
        print("Training model for gesture \"{}\"...".format(gesture))
        label = parse_label(gesture)
        file_names_of_gesture = [name for name in file_names if name.startswith(gesture)]
        obs_seq_set = []
        model = hmm(N[i], M, use_scaling=True)
        for file_name in file_names_of_gesture:
            # if file_name in train_name_bank:
            data = np.load(file_path + file_name)
            obs_seq_set.append(data['Z'])

        model.baum_welch_multi(obs_seq_set)
        models[gesture] = model

    return models
Exemplo n.º 4
0
import gc
gc.collect()

import numpy as np
import matplotlib.pyplot as plt
from HMM import HMM as hmm

#test sequence
test_sequence = [
    0, 1, 2, 1, 0, 3, 4, 4, 1, 3, 5, 5, 6, 2, 7, 8, 1, 0, 4, 7, 4, 4, 9, 5, 3,
    2, 7, 10, 0, 0, 9, 6, 8, 6
]
O = np.asarray(test_sequence).reshape(len(test_sequence), 1)

inst = hmm(6, 11)

A, B, pi = inst.initializer()

iter = 500

landa_BW = inst.baum_welch(O, A, B, pi, iter)
landa_ARO = inst.aro(O, A, B, pi, iter)
landa_AROBW = inst.aroBW(O, A, B, pi, iter)

# multiple line plot
plt.plot(range(iter),
         landa_BW[-1],
         marker='',
         markerfacecolor='blue',
         markersize=3,
Exemplo n.º 5
0
qlg_train_pred, post_train_pred = [], []
qlg_train_actual, post_train_actual = [], []
qlg_test_pred, post_test_pred = [], []
qlg_test_actual, post_test_actual = [], []

numkc = 10  # change number of kc for different data set

for train_index, test_index in kf.split(qlg_y):
    qlg_y_train, qlg_y_test = qlg_y[train_index], qlg_y[test_index]
    post_y_train, post_y_test = post_y[train_index], post_y[test_index]

    # symbols here refers to four differnt observations:
    # fast-correct, fast-incorrect, slow-correct, slow-incorrect
    symbols = [['0', '1', '2', '3']]
    h = hmm(2,
            Pi=np.array([0.8, 0.2]),
            T=np.array([[0.8, 0.2], [0.1, 0.9]]),
            obs_symbols=symbols)
    # change parameters here F= T=

    nlg_train = [[] for x in range(numkc)]
    nlg_test = [[] for x in range(numkc)]

    for i in range(numkc):
        X = np.load(folder + "new_bkt_pertime_kc" + str(i) + ".npy")
        X_train, X_test = X[train_index], X[test_index]

        train = [each for each in X_train if each]
        test = [each for each in X_test if each]
        if train and test:
            h.baum_welch(train, debug=False)  # training part
        nlg_train[i].extend(h.predict_nlg(X_train))
Exemplo n.º 6
0
    matrizIntermediate_train = matrizIntermediate[train_index]
    matrizIntermediate_test = matrizIntermediate[test_index]

    # Simbolos: 1 incorrecto, 2 correcto
    symbols = [['1', '2']]

    #Objeto HMM pasando como parámetro:
    # Probabilidad Inicial PI --> P(L0) 1-P(L0)
    # Calculada en base al número de aciertos de los puzzles de tutorial
    # Probabilidad de cambiar de un estado a otro T --> A
    # Probabilidad de Emission E --> B
    # Símbolos anteriores
    h = hmm(2,
            Pi=np.array([0.48, 0.52]),
            T=np.array([[1, 0], [0.4, 0.6]]),
            E=[np.array([[0.95, 0.05], [0.05, 0.95]])],
            obs_symbols=symbols)
    #h = hmm(2, Pi=np.array([0.8, 0.2]), T=np.array([[1, 0], [0.4, 0.6]]), obs_symbols=symbols)

    #Inicialización a vacío
    conjunto_train = [[] for x in range(numkc)]
    conjunto_test = [[] for x in range(numkc)]

    #Iteración para cada kc, en este caso 1 ya que no se ha hecho diferenciación de puzzles
    for i in range(numkc):

        #Matriz con lista de respuestas por alumno
        datosPuzzles = np.load(folder + "IntermediatePuzzlesResults.npy",
                               allow_pickle=True)
        print(datosPuzzles)