Ejemplo n.º 1
0
    def testmakeChange(self):
        rslt = HW2.makeChange(313, [7, 24, 42])
        rslt[1].sort()
        self.assertEqual(rslt, [10, [7, 24, 24, 24, 24, 42, 42, 42, 42, 42]])

        rslt = HW2.makeChange(13, [14, 1, 7, 6, 7, 13])
        self.assertEqual(rslt, [1, [13]])
Ejemplo n.º 2
0
def EM_GMM(XTrain, XTest, Lista_mu0, Lista_sigma0, v_pi0, N_States):
    LogLikelihood_1 = -9999999999
    iteration = 1
    Lista_mu = list(Lista_mu0)
    Lista_sigma = list(Lista_sigma0)
    v_pi = list(v_pi0)
    while (True):
        print "\n\tIteration GMM " + str(iteration)
        resultUpdate = hw2.updateParameters(v_pi, XTrain, Lista_mu,
                                            Lista_sigma, N_States)
        v_pi = resultUpdate[0]
        Lista_mu = resultUpdate[1]

        Lista_sigma = []
        for CVm in resultUpdate[2]:
            Lista_sigma.append(np.matrix(CVm))

        LogLikelihood = hw2.calculate_LogLikelihood(Lista_mu, Lista_sigma,
                                                    v_pi, XTest)

        iteration = iteration + 1

        if (LogLikelihood > LogLikelihood_1) and (iteration <= 30):
            LogLikelihood_1 = LogLikelihood
        else:
            break

    print "\nmus"
    print Lista_mu

    return (Lista_mu, Lista_sigma, v_pi)
Ejemplo n.º 3
0
def calculate_beta_HP(X, P, List_mu, List_CV):
    beta = []
    for ee in range(len(X)):
        beta.append([])
    dimX = P.shape[0]
    for n in range(len(X) - 1, -1, -1):
        if (n == len(X) - 1):
            temp = []
            for jj in range(dimX):
                temp.append(1.0 / dimX)
            beta[n] = temp
        else:
            vectorPsi = np.matrix(np.zeros((dimX, 1)))
            Beta_n_plus_1 = np.matrix(np.zeros((dimX, 1)))
            for ii in range(dimX):
                vectorPsi[ii, 0] = hw2.calculate_probability_MultiGaussian(
                    [X[n + 1]], List_mu[ii], List_CV[ii])
                Beta_n_plus_1[ii, 0] = beta[n + 1][ii]
            matrixTemp = HadamardProduct(vectorPsi, Beta_n_plus_1)
            Beta_n = P * matrixTemp
            Beta_n = Beta_n / np.sum(Beta_n)
            temp = Beta_n.tolist()
            ttemp = []
            for ii in range(dimX):
                ttemp.append(temp[ii][0])
            beta[n] = ttemp
    return beta
Ejemplo n.º 4
0
def calculate_alpha_HP(X, P, List_mu, List_CV):
    alpha = []
    dimX = P.shape[0]
    for n in range(len(X)):
        if (n == 0):
            temp = []
            for jj in range(dimX):
                temp.append(1.0 / dimX)
            alpha.append(temp)
        else:
            vectorPsi = np.matrix(np.zeros((dimX, 1)))
            Alpha_n_minus_1 = np.matrix(np.zeros((dimX, 1)))
            for ii in range(dimX):
                vectorPsi[ii, 0] = hw2.calculate_probability_MultiGaussian(
                    [X[n]], List_mu[ii], List_CV[ii])
                Alpha_n_minus_1[ii, 0] = alpha[n - 1][ii]
            matrixTemp = (P.T) * Alpha_n_minus_1
            Alpha_n = HadamardProduct(vectorPsi, matrixTemp)
            Alpha_n = Alpha_n / np.sum(Alpha_n)
            temp = Alpha_n.tolist()
            ttemp = []
            for ii in range(dimX):
                ttemp.append(temp[ii][0])
            alpha.append(ttemp)

    return alpha
 def test_read_from_file(self):
     """
     Test that the function can succesfully read from file and return a list
     :return:
     """
     self.assertEqual(HW2.myPowerList().readFromTextFile('file.txt'),
                      ['test'])
 def test_search_records(self):
     """
     Test that text can be successfully read from file
     :return:
     """
     self.assertEqual(
         HW2.Contacts().searchRecord('test', 'test_records.txt'), ['test'])
 def test_read_contacts_no_file(self):
     """
     Test that the function will return proper exception when file doesn't exist
    :return:
     """
     self.assertEqual(HW2.Contacts().getRecords('no_file.txt'),
                      'File Not Found')
 def test_read_contacts_from_file(self):
     """
     Test that the function can succesfully read from file and return a list
     :return:
     """
     self.assertEqual(HW2.Contacts().getRecords('test_records.txt'),
                      ['test'])
 def test_read_no_file(self):
     """
     Test that the function will return proper exception when file doesn't exist
     :return:
     """
     self.assertEqual(HW2.myPowerList().readFromTextFile('no_file.txt'),
                      'File Not Found')
Ejemplo n.º 10
0
def viterbi(jj, v_pi, List_mu, List_CV, X, P, N):
    #    print "jj " + str(kk) + ", n " + str(n) + "len X "+str(len(X))+"\n"
    result = []
    for n in range(N):
        if (n == 0):
            result.append(v_pi[jj] * hw2.calculate_probability_MultiGaussian(
                [X[n]], List_mu[jj], List_CV[jj]))
        else:
            LLista = []
            for ii in range(P.shape[0]):
                temp = hw2.calculate_probability_MultiGaussian([X[n]],
                                                               List_mu[jj],
                                                               List_CV[jj])
                LLista.append(P[ii, jj] * temp * result[n - 1])
            result.append(np.max(LLista))
    return result
Ejemplo n.º 11
0
def calculate_alpha(X, P, List_mu, List_CV):
    alpha = []
    dimX = P.shape[0]
    #I THINK I AM MISSING THE NORMALIZATION FOR n>0
    for n in range(len(X)):
        #        print "n " + str(n)
        if (n == 0):
            temp = []
            for jj in range(dimX):
                temp.append(1.0 / dimX)
            alpha.append(temp)
        else:
            auxalpha = []
            for jj in range(dimX):
                P_xt_zt_j = hw2.calculate_probability_MultiGaussian(
                    [X[n]], List_mu[jj], List_CV[jj])
                temp = 0
                for ii in range(dimX):
                    #We need to pass the scalar arguments as np.matrix
                    temp = temp + (P[ii, jj] * alpha[n - 1][ii])


#                 print "type " + str(type(auxalpha))
                auxalpha.append(temp * P_xt_zt_j)
                ttemp = []
                for ee in auxalpha:
                    ttemp.append(ee / np.sum(auxalpha))
            alpha.append(ttemp)

    return alpha
Ejemplo n.º 12
0
def calculate_beta(X, P, List_mu, List_CV):
    beta = []
    for ee in range(len(X)):
        beta.append([])
    dimX = P.shape[0]
    for n in range(len(X) - 1, -1, -1):
        if (n == len(X) - 1):
            temp = []
            for jj in range(dimX):
                temp.append(1.0)
            beta[n] = temp
        else:
            auxbeta = []
            for ii in range(dimX):
                temp = 0
                for jj in range(dimX):
                    P_xt_zt_j = hw2.calculate_probability_MultiGaussian(
                        [X[n]], List_mu[jj], List_CV[jj])
                    temp = temp + (
                        P_xt_zt_j * P[ii, jj] * beta[n + 1][jj]
                    )  #temp = temp + (P_xt_zt_j*P[ii,jj]*beta[n+1][ii])
                auxbeta.append(temp)
            beta[n] = auxbeta

    return beta
 def test_add_contact(self):
     """
     Test that a conctac can be added successfully
     :return:
     """
     self.assertEqual(
         HW2.Contacts().addContact('Name', 'Address', 'Phone', 'Email'),
         'Contact Added')
Ejemplo n.º 14
0
def main():

    car_make = input("Enter the car make: ")
    car_year = input("Enter the car year: ")
    # car_speed = 0
    car = HW2.Car(car_year, car_make)

    for iteration in range(5):
        car.accelerate()
        print("Accelerating... Your current speed is:", car.get_speed())
    for iteration in range(5):
        car.brake()
        print("Braking... Your current speed is:", car.get_speed())
Ejemplo n.º 15
0
def calculate_Matrix_xi_t(X, alpha, beta, P, List_mu, List_CV, n):
    dimX = P.shape[0]
    xi_t_tplus1 = np.matrix(np.zeros((dimX, dimX)))
    for i in range(dimX):
        for j in range(dimX):
            alpha_t_i = alpha[n][i]
            beta_tplus1_j = beta[n + 1][j]
            P_ij = P[i, j]
            P_xt_zt_j = hw2.calculate_probability_MultiGaussian([X[n + 1]],
                                                                List_mu[j],
                                                                List_CV[j])
            xi_t_tplus1[i, j] = alpha_t_i * beta_tplus1_j * P_ij * P_xt_zt_j
        xi_t_tplus1[i, :] = xi_t_tplus1[i, :] / np.sum(xi_t_tplus1[i, :])
    return xi_t_tplus1
Ejemplo n.º 16
0
def calculate_Matrix_xi_t_HP(X, alpha, beta, P, List_mu, List_CV, n):
    dimX = P.shape[0]
    xi_t_tplus1 = np.matrix(np.zeros((dimX, dimX)))
    alpha_n = np.matrix(alpha[n])
    beta_n_plus_1 = np.matrix(beta[n + 1])
    vectorPsi_nplus_1 = np.matrix(np.zeros((dimX, 1)))
    for ii in range(dimX):
        vectorPsi_nplus_1[ii, 0] = hw2.calculate_probability_MultiGaussian(
            [X[n + 1]], List_mu[ii], List_CV[ii])
    matrix1 = HadamardProduct(beta_n_plus_1.T, vectorPsi_nplus_1)
    matrix2 = alpha_n.T * matrix1.T
    matrix3 = HadamardProduct(P, matrix2)
    #    for ii in range(dimX):
    #        xi_t_tplus1[ii,:] = matrix3[ii,:]/np.sum(matrix3[ii,:])
    xi_t_tplus1 = matrix3
    return xi_t_tplus1
Ejemplo n.º 17
0
def main(targets):
    global test_flag
    if 'data' in targets:
        HW1.main()
    if 'test-data' in targets:
        test_flag = 1
        HW2.getTestData()
    if 'process' in targets:
        #cleans and prepares the data for analysis
        #smalis = getAllSmaliFiles("Apps")
        print(test_flag)
        smalis = HW2.prepare_data(test_flag)

        x, y = HW2.makeBaselineFeatures(smalis)
        HW2.baseline(x, y)

    return
Ejemplo n.º 18
0
def calculate_alpha(X, P, List_mu, List_CV):
    alpha = []
    dimX = P.shape[0]
    for n in range(len(X)):
        if (n == 0):
            temp = []
            for jj in range(dimX):
                temp.append(1.0 / dimX)
            alpha.append(temp)
        else:
            auxalpha = []
            for jj in range(dimX):
                P_xt_zt_j = hw2.calculate_probability_MultiGaussian(
                    [X[n]], List_mu[jj], List_CV[jj])
                temp = 0
                for ii in range(dimX):
                    temp = temp + (P[ii, jj] * alpha[n - 1][ii])
                auxalpha.append(temp * P_xt_zt_j)
                ttemp = []
                for ee in auxalpha:
                    ttemp.append(ee / np.sum(auxalpha))
            alpha.append(ttemp)

    return alpha
Ejemplo n.º 19
0
 def testLCS(self):
     self.assertEqual(HW2.LCS(self.a, self.c), "")
     self.assertEqual(HW2.LCS(self.a, self.s), "GCAGCA")
Ejemplo n.º 20
0
import HW2

if __name__ == '__main__':

    HW2.Run()




Ejemplo n.º 21
0
import HW2

boards = [
    "----x---x", "---o-o---", "x--------", "-x-------", "----x----",
    "-o--x----"
]
expected = ["7 win", "7 win", "0 tie", "0 tie", "-3 lose", "3 win"]
move = ["x in 0", "o in 4", "o in 1", "o in 3", "o in 1", "o in 7"]

for x in range(len(boards)):
    print("******************************************")
    print("testing " + boards[x])
    print("expecting " + expected[x])
    print("with " + move[x])

    print()
    print("They Say")
    result = HW2.search(boards[x])
    print("******************************************")

input()
Ejemplo n.º 22
0
#step 1 = import HW2 file
import HW2 as eq
#set score
print("Best possible health score: [1,1,1,1,1,1,1,1]")
print(
    eq.scoreHUI3(vision=1,
                 hearing=1,
                 speech=1,
                 ambulation=1,
                 dexterity=1,
                 emotion=1,
                 cognition=1,
                 pain=1))
print("Hypothetical patient: [3,1,5,2,3,3,5,1]"
      )  #add in potenital scores to get a potential paitent.
print(
    eq.scoreHUI3(vision=3,
                 hearing=1,
                 speech=5,
                 ambulation=2,
                 dexterity=3,
                 emotion=3,
                 cognition=5,
                 pain=1))  #and make it print
Ejemplo n.º 23
0
 def testPLCS(self):
     self.assertEqual(HW2.PLCS(self.a, self.c), [[-1], [-1]])
     self.assertEqual(HW2.PLCS(self.a, self.s),
                      [[0, 1, 2, 4, 5, 6], [0, 1, 3, 4, 5, 7]])
Ejemplo n.º 24
0
import HW2 as eq

#print perfect health score
print("Score for 'perfect' health: [1,1,1,1,1,1,1,1]")
print(
    eq.scoreHUI3(vision=1,
                 hearing=1,
                 speech=1,
                 ambulation=1,
                 dexterity=1,
                 emotion=1,
                 cognition=1,
                 pain=1))

#print health score with a variety of values
print("Score for potential patient: [4,2,1,2,1,2,3,1]")
print(
    eq.scoreHUI3(vision=4,
                 hearing=2,
                 speech=1,
                 ambulation=2,
                 dexterity=1,
                 emotion=2,
                 cognition=3,
                 pain=1))
Ejemplo n.º 25
0
import HW2 as eq

print("Score is")
print(
    eq.get_score(vision=1,
                 hearing=3,
                 speech=5,
                 ambulation=2,
                 dexterity=3,
                 emotion=2,
                 cognition=1,
                 pain=4))

print("Score is")
print(
    eq.get_score(vision=1,
                 hearing=8,
                 speech=5,
                 ambulation=2,
                 dexterity=3,
                 emotion=2,
                 cognition=1,
                 pain=4))
Ejemplo n.º 26
0
import HW2 as hui

print("score for", 1, 1, 1, 1, 2, 1, 1, 1)
print(hui.get_score(1, 1, 1, 1, 2, 1, 1, 1))

print("score for", 1, 1, 1, 1, 7, 1, 1, 1)
print(hui.get_score(1, 1, 1, 1, 7, 1, 1, 1))
Ejemplo n.º 27
0
def main(targets):
    global test_flag
    if 'data' in targets:
        HW1.main()
    if 'test-project' in targets:
        beg = time.time()
        test_flag = 1
        sample_size, categories = HW2.loadConfig("config/test-params.json")
        paths = HW2.loadEnv("config/env.json")
        HW2.getTestData(categories, sample_size)
        smalis = HW2.prepare_data(test_flag)
        df, xy = HW2.makeDF(smalis)
        train_df, train_y, test_df, test_y = HW2.splitTrain(df, xy)
        A_train = HW2.makeA(train_df, train_df["apps"].unique(), df.shape[0])
        P_train = HW2.makeP(train_df, df.shape[0])

        A_test = HW2.makeA(test_df, test_df["apps"].unique(), df.shape[0])
        P_test = HW2.makeP(test_df, df.shape[0])

        #y = [i[1] for i in xy]
        AAT_train = A_train.dot(
            A_train.T)  #HW2.matrixply([A_train, A_train.T])
        AATest = A_test.dot(A_train.T)
        clf = HW2.trainModel(AAT_train, train_y)
        preds = HW2.modelPredict(clf, AATest)
        HW2.getMetrics(preds, test_y, paths["AA^T"], "AA^T")

        APAT_train = A_train.dot(P_train).dot(A_train.T)
        APATest = A_test.dot(P_test).dot(A_train.T)
        clf = HW2.trainModel(APAT_train, train_y)
        preds = HW2.modelPredict(clf, APATest)
        HW2.getMetrics(preds, test_y, paths["APA^T"], "APA^T")

        B_train = HW2.makeB(train_df, df.shape[0])
        B_test = HW2.makeB(test_df, df.shape[0])

        ABAT_train = A_train.dot(B_train).dot(A_train.T)
        ABATest = A_test.dot(B_test).dot(A_train.T)
        clf = HW2.trainModel(ABAT_train, train_y)
        preds = HW2.modelPredict(clf, ABATest)
        HW2.getMetrics(preds, test_y, paths["ABA^T"], "ABA^T")

        APBPTAT_train = A_train.dot(P_train).dot(B_train).dot(P_train.T).dot(
            A_train.T)
        APBPTATest = A_test.dot(P_test).dot(B_test).dot(P_train.T).dot(
            A_train.T)
        clf = HW2.trainModel(APBPTAT_train, train_y)
        preds = HW2.modelPredict(clf, APBPTATest)
        HW2.getMetrics(preds, test_y, paths["APBP^TA^T"], "APBP^TA^T")

    if 'process' in targets:
        #cleans and prepares the data for analysis
        #smalis = getAllSmaliFiles("Apps")
        print(test_flag)
        smalis = HW2.prepare_data(test_flag)

        x, y = HW2.makeBaselineFeatures(smalis)
        HW2.baseline(x, y)

    return