Пример #1
0
def predict(X, theta, house_dico):
    result_all = Matrix(X.dot(theta))
    result = Matrix([[1/float(1+math.exp(-z)) for z in row] for row in result_all]) # We need to apply dot by dot in the matrix

    # Selecting the best house
    col_result = Matrix([[0] for i in range(X.nrow)])
    for i in range(result.nrow):
        col_result[i][0] = house_dico[index_max(result[i])]
    return col_result
Пример #2
0
def gradient_descent(X, Y, num_iter, learning_rate):
    theta = Matrix([[0] for i in range(X.ncol)])
    for i in range(num_iter):
        grad = gradient(X, Y, theta)
        theta = theta.sub(grad.product(learning_rate))
        if i % 10 == 0:
            print('Loss Function after ' + str(i) + ' iterations : ',
                  loss_function(X, Y, theta))
    print('Final Loss function : ', loss_function(X, Y, theta))
    return theta
Пример #3
0
 def __init__(self, col, num, array=None):
     Matrix.__init__(self, 1, col, num)
     self.__row = 1
     self.__num = num
     self.__col = col
     if array is not None:
         self.__m = array
     else:
         self.__m = [
             random.randint(0, self.__num) for n in range(self.__col)
         ]
 def __init__(self, row, num, array=None):
     Matrix.__init__(self, row, 1, num)
     self.__row = row
     self.__num = num
     self.__col = 1
     if array is not None:
         self.__m = array
     else:
         self.__m = [[
             random.randint(0, self.__num) for n in range(self.__col)
         ] for n in range(self.__row)]
Пример #5
0
def assess_result(Y, res, house_dico):
    true_pred = 0
    Y_true_col = Matrix([[0] for i in range(Y.nrow)])
    for i in range(Y.nrow):
        Y_true_col[i][0] = house_dico[index_max(Y[i])]
        if res[i][0] == Y_true_col[i][0]:
            true_pred += 1
    Y_train_res = Y_true_col.append_col(res.to_list())
    accuracy = float(true_pred) / float(Y.nrow)
    write_csv(Matrix(Y_train_res), ['Y_true', 'Y_pred'], 'result_train')
    return accuracy
Пример #6
0
    def create_matrix(self):
        """
        Create a new matrix and add it to class list of matrices.
        Values are loaded from a file if not inserted.
        """

        rows = self.get_int("Počet řádků: ")[0]
        columns = self.get_int("Počet sloupců: ")[0]
        own_values = self.get_input("Vlastní hodnoty? (Ano) ")[0]

        matrix_values = None
        if own_values == "ano":
            prompt_txt = "Zadejte prosím hodnoty matice oddělené mezerou:\n"
            matrix_values = []
            while True:
                numbers = self.get_int(prompt_txt)
                if len(numbers) == (rows * columns):
                    for row in range(rows):
                        matrix_values.append(numbers[row * columns:(row + 1) *
                                                     columns])
                    break
                prompt_txt = "Chybně zadané hodnoty. Zkuste to prosím znovu:\n"

        # Save the matrix in class list and print info about the matrix
        self.matrices.append(Matrix(rows, columns, matrix_values))
        self.show_matrix_info(len(self.matrices) - 1)
Пример #7
0
    def run(self):
        """
        Run the program in a loop. Exit when "exit" is called.
        """

        first = True
        while not self.exit:
            # Check if program runs the first time
            if first:
                print("Program matice")
                first = False

            command = self.get_input("Příkaz: ")

            if command[0] == "exit":
                if self.get_input("Opravdu si přejete ukončit program? (Ano) "
                                  )[0] == "ano":
                    self.exit = True
            elif command[-1] == "create matrix":
                self.create_matrix()
            elif command[0] == "list":
                self.show_matrices()
            elif command[0] == "execute":
                self.execute_operation(command[1:-1])
            elif command[0] == "transpose":
                self.matrices.append(
                    Matrix(own=self.matrices[int(command[1][-1])].transpose()))
                self.show_matrix_info(len(self.matrices) - 1)
            elif command[0] == "show":
                self.show_matrix_info(int(command[1][-1]))
            elif command[0] == "save":
                self.save_to_file(int(command[1][-1]))
            elif command[0] == "help":
                self.help_funtion()
        print("Naviděnou! :)")
Пример #8
0
    def execute_operation(self, operation):
        """
        Execute given operation
        """

        matrix_1 = self.matrices[int(operation[0][-1])]
        # Check whether operation is scalar multiplication
        if operation[2][0] != 'm':
            self.matrices.append(
                Matrix(
                    own=matrix_1.scalar_multiplication(int(operation[2][0]))))

        # Operations between two matrices
        else:
            matrix_2 = self.matrices[int(operation[2][-1])]
            if operation[1] == "+":
                self.matrices.append(Matrix(own=matrix_1 + matrix_2))
            elif operation[1] == "-":
                self.matrices.append(Matrix(own=matrix_1 - matrix_2))
            elif operation[1] == "*":
                self.matrices.append(Matrix(own=matrix_1 * matrix_2))
            elif operation[1] == "/":
                self.matrices.append(Matrix(own=matrix_1 / matrix_2))
        self.show_matrix_info(len(self.matrices) - 1)
Пример #9
0
def gradient(X, Y, theta):
    return Matrix([[delta(X, Y, theta, j)] for j in range(X.ncol)])
Пример #10
0
def h(X, theta
      ):  # X is here an individual transformed into a lign / theta une colonne
    return g(Matrix(X.dot(theta)))
Пример #11
0
def impute_na(X):  # pour l'instant mean imputation
    return Matrix([[
        Mean([row[i] for row in X]) if row[i] == '' else row[i]
        for i in range(X.ncol)
    ] for row in X])
Пример #12
0
import random
import time
from matrix_class import Matrix, solve_linear_equation
import matplotlib.pyplot as plt
import numpy as np

times = []
for n in range(1, 500):
    a = Matrix(n, n + 1)
    a.randomise()
    start = time.time()
    x = solve_linear_equation(a)
    stop = time.time()
    time_taken = stop - start
    times.append(time_taken)
    print(n)

with open("../clock_times/python_clock_times.csv", "w") as outfile:
    for time_point in times:
        outfile.write(str(time_point))
        outfile.write(",")

print("Some stuff")
Пример #13
0
        Y_true_col[i][0] = house_dico[index_max(Y[i])]
        if res[i][0] == Y_true_col[i][0]:
            true_pred += 1
    Y_train_res = Y_true_col.append_col(res.to_list())
    accuracy = float(true_pred) / float(Y.nrow)
    write_csv(Matrix(Y_train_res), ['Y_true', 'Y_pred'], 'result_train')
    return accuracy

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'Dataset you want to describe')
    parser.add_argument('set', type = str, help = 'Name of the file to read')
    parser.add_argument('theta', type = str, help = 'Weights of the features')
    parser.add_argument('count', type = str, nargs = '?', help = 'If you want to assess your prediction of train set', default =  'False')
    args = parser.parse_args()

    X, Y, features, y_name = preprocess(args.set)
    all_theta = read_data3(args.theta)

    houses = all_theta[0]
    houses = [h.split('_')[1] for h in houses]
    house_dico = dict((i, houses[i]) for i in range(len(houses)))
    all_theta = Matrix(all_theta[1:]).to_float()

    res = predict(X, all_theta, house_dico)
    if args.count == 'True':
        accuracy = assess_result(Y, res, house_dico)
        print (accuracy)
    else:
        X_test = return_predict(args.set, res)
        write_csv(Matrix(X_test[1:]), X_test[0], 'result_test')