def test_matrix_multiplication(): A = Matrix([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]]) B = Matrix([[0, 1, 2, 4], [1, 2, 4, 8], [2, 4, 8, 16], [4, 8, 16, 32]]) C = Matrix([[24, 49, 98, 196], [31, 64, 128, 256], [38, 79, 158, 316], [45, 94, 188, 376]]) assert A @ B == C
def test_matrix_determinant_3x3(): A = Matrix([[1, 2, 6], [-5, 8, -4], [2, 6, 4]]) assert A.cofactor(0, 0) == 56 assert A.cofactor(0, 1) == 12 assert A.cofactor(0, 2) == -46 assert A.determinant == -196
def test_matrix_determinant_4x4(): A = Matrix([[-2, -8, 3, 5], [-3, 1, 7, 3], [1, 2, -9, 6], [-6, 7, 7, -9]]) assert A.cofactor(0, 0) == 690 assert A.cofactor(0, 1) == 447 assert A.cofactor(0, 2) == 210 assert A.cofactor(0, 3) == 51 assert A.determinant == -4071
def train(self, input_list, target_list): """ Trains the neural network using the given input_list and target_array. Args: input_list: List of numbers containing the input values. target_list: List of numbers containing the target values. Returns: Returns the resulting neural network. """ inputs = Matrix.from_list(input_list) hidden = Matrix.dot_product(self.weights_ih, inputs) hidden.add_matrix(self.bias_h) hidden.map(self.activation_function.func) outputs = Matrix.dot_product(self.weights_ho, hidden) outputs.add_matrix(self.bias_o) outputs.map(self.activation_function.func) targets = Matrix.from_list(target_list) # Calculate the error output_errors = targets.sub_matrix(outputs, False) # Calculate gradient gradients = outputs.map(self.activation_function.dfunc, False) gradients.mul_matrix(output_errors) gradients.mul_scalar(self.learning_rate) # Calculate deltas hidden_t = Matrix.transpose(hidden) weights_ho_deltas = Matrix.dot_product(gradients, hidden_t) # Adjust the weights and the biases by the calculated deltas self.weights_ho.add_matrix(weights_ho_deltas) self.bias_o.add_matrix(gradients) # Calculate the hidden layer errors weights_ho_t = Matrix.transpose(self.weights_ho) hidden_errors = Matrix.dot_product(weights_ho_t, output_errors) # Calculate hidden gradient hidden_gradients = hidden.map(self.activation_function.dfunc, False) hidden_gradients.mul_matrix(hidden_errors) hidden_gradients.mul_scalar(self.learning_rate) # Calculate input -> hidden deltas inputs_t = Matrix.transpose(inputs) weights_ih_deltas = Matrix.dot_product(hidden_gradients, inputs_t) # Adjust the weights and the biases by the calculated deltas self.weights_ih.add_matrix(weights_ih_deltas) self.bias_h.add_matrix(hidden_gradients) return self
def qr(A): assert A.row_num() == A.col_num(), "A must be square" basis = [A.col_vector(i) for i in range(A.col_num())] P = gram_schmidt_process(basis) Q = Matrix([v / v.norm() for v in P]).T() R = Q.T().dot(A) return Q, R
def __init__(self, emule, mode): self.win = False self.running = True self.emule = emule self.c = True self.grill = Grill() self.matrix = Matrix() if not self.emule: self.machine = Machine() self.strategy = IA(self.matrix)
def inv(A): if A.row_num() != A.col_num(): return None n = A.row_num() ls = LinearSystem(A, Matrix.identity(n)) if not ls.gauss_jordan_elimination(): return None invA = [[row[i] for i in range(n, 2 * n)] for row in ls.Ab] return Matrix(invA)
def test_matrix_inverse_4x4(): A = Matrix([[-5, 2, 6, -8], [1, -5, 1, 8], [7, 7, -6, -7], [1, -3, 7, 4]]) B = A.inv assert A.determinant == 532 assert A.cofactor(2, 3) == -160 assert B[3, 2] == -160 / 532 assert A.cofactor(3, 2) == 105 assert B[2, 3] == 105 / 532 assert B == Matrix([[0.21805, 0.45113, 0.24060, -0.04511], [-0.80827, -1.45677, -0.44361, 0.52068], [-0.07895, -0.22368, -0.05263, 0.19737], [-0.52256, -0.81391, -0.30075, 0.30639]])
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate=0.1, activation_function=sigmoid): """ NeuralNetwork constructor: creates a neural network. Args: input_nodes: The number of input_nodes. hidden_nodes: The number of hidden_nodes. output_nodes: The number of output_nodes. learning_rate: The learning rate value (default 0.1). activation_function: The activation function (default sigmoid). Returns: Returns a new neural network object. """ self.input_nodes = input_nodes self.hidden_nodes = hidden_nodes self.output_nodes = output_nodes self.weights_ih = Matrix(self.hidden_nodes, self.input_nodes).randomize() self.weights_ho = Matrix(self.output_nodes, self.hidden_nodes).randomize() self.bias_h = Matrix(self.hidden_nodes, 1).randomize() self.bias_o = Matrix(self.output_nodes, 1).randomize() self.learning_rate = learning_rate self.activation_function = activation_function
class Game: def __init__(self, emule, mode): self.win = False self.running = True self.emule = emule self.c = True self.grill = Grill() self.matrix = Matrix() if not self.emule: self.machine = Machine() self.strategy = IA(self.matrix) def change_turn(self): self.turn = 3 - self.turn def get_choice(self): if self.turn == Refr.PLAYER: if self.emule: self.choice = self.grill.get_position() else: self.choice = self.machine.wait_player() elif self.turn == Refr.COMPUTER: self.choice = self.strategy.get_choice() def state(self): if self.choice == Refr.QUIT: self.running = False #if self.matrix.control_victory(): # self.win = True def go_turn(self): self.matrix.show() self.get_choice() y = self.matrix.add(self.turn, self.choice) self.grill.token(self.turn, self.choice, y) self.change_turn() self.state() def run(self, starter): self.turn = starter while not self.win and self.running: if self.c: self.go_turn() else: sleep(0.1) return self.turn
def build_emission_matrix(self): emission_probability_of_unk_word = 1 / len(self.training_data.get_unique_tags()) matrix = dict(self.training_data.matrix) for tag, word_count in self.training_data.items(): for word in word_count.keys(): matrix[tag][word] = self.training_data[tag][word] / self.__get_tag_count(tag) matrix[tag][unk_word] = emission_probability_of_unk_word return Matrix(matrix)
def test_matrix(): M = Matrix([[1, 2, 3, 4], [5.5, 6.5, 7.5, 8.5], [9, 10, 11, 12], [13.5, 14.5, 15.5, 16.5]]) assert M[0, 0] == 1 assert M[1, 0] == 5.5 assert M[2, 0] == 9 assert M[3, 3] == 16.5 assert M[3, 2] == 15.5
def lu(matrix): assert matrix.row_num() == matrix.col_num( ), "matrix must be a square matrix" n = matrix.row_num() A = [matrix.row_vector(i) for i in range(n)] L = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)] for i in range(n): # 看A[i][i]位置是否可以是主元 if is_zero(A[i][i]): return None, None else: for j in range(i + 1, n): p = A[j][i] / A[i][i] A[j] = A[j] - p * A[i] L[j][i] = p return Matrix(L), Matrix([A[i].underlying_list() for i in range(n)])
def main(sudoku): """ http://lanl.arxiv.org/pdf/cs/0011047 :param sudoku: :return: """ # m = Matrix("sudoku", 9, 3, sudoku) m = Matrix(sudoku) dlx = DLX(m) dlx.search(0)
def predict(self, input_list): """ Calculates the outputs using the given inputs. Args: input_list: List of numbers containing the input values. Returns: Returns a list of numbers containing the outputs. """ inputs = Matrix.from_list(input_list) hidden = Matrix.dot_product(self.weights_ih, inputs) hidden.add_matrix(self.bias_h) hidden.map(self.activation_function.func) outputs = Matrix.dot_product(self.weights_ho, hidden) outputs.add_matrix(self.bias_o) outputs.map(self.activation_function.func) return outputs.to_list()
def gram_schmidt_process(basis): matrix = Matrix(basis) assert rank(matrix) == len(basis) res = [basis[0]] for i in range(1, len(basis)): p = basis[i] for r in res: p = p - basis[i].dot(r) / r.dot(r) * r res.append(p) return res
def view_transform(from_position: Point, to: Point, up: Vector) -> Matrix: forward = normalize(to - from_position) left = cross(forward, normalize(up)) true_up = cross(left, forward) orientation = Matrix([ [left.x, left.y, left.z, 0], [true_up.x, true_up.y, true_up.z, 0], [-forward.x, -forward.y, -forward.z, 0], [0, 0, 0, 1], ]) return orientation * translation(-from_position.x, -from_position.y, -from_position.z)
def test_matrix_cofactor_3x3(): A = Matrix([[3, 5, 0], [2, -1, -7], [6, -1, 5]]) assert A.minor(0, 0) == -12 assert A.cofactor(0, 0) == -12 assert A.minor(1, 0) == 25 assert A.cofactor(1, 0) == -25
class MatrixTest(unittest.TestCase): # Tests def setUp(self): self.matrix = Matrix("9 8 7\n5 3 2\n6 6 7") # def test_extract_row_from_one_number_matrix(self): # matrix = Matrix("1") # self.assertEqual(matrix.row(1), [1]) def test_rows(self): self.assertEqual([[9, 8, 7], [5, 3, 2], [6, 6, 7]], self.matrix.row()) def test_columns__1(self): self.assertEqual([[9, 5, 6], [8, 3, 6], [7, 2, 7]], self.matrix.column()) def test_matrix(self): new_matrix = Matrix("9 8 7 3\n5 3 2 3\n6 6 7 3") self.assertEqual([[9, 8, 7, 3], [5, 3, 2, 3], [6, 6, 7, 3]], new_matrix.row()) self.assertEqual([[9, 5, 6], [8, 3, 6], [7, 2, 7], [3, 3, 3]], new_matrix.column())
def __init__(self): self.m1 = Matrix([[1, 123124142, 143, 46545], [5, 6, 7, 8], [10, 1211, 12, 1321, 146436]]) # mag=6 c=5 r=3 self.m2 = Matrix([[80, 8, 8, 8], [8, 8000, 80000, 8, 2], [8, 8, 8, 800000]]) # mag=1 c=4 r=3 self.m3 = Matrix([[8, 8, 8, 8], [8, 8, 8, 8], [8, 8, 8, 8]]) # mag=5 c=4 r=3 self.m4 = Matrix([[8, 8, 8, 8], [8, 8, 8, 8], [8, 8, 8, 8], [80, 800, 8000, 80000]]) self.m5 = Matrix([[1, 123124142, 143, 46545, 5, 1, 2], [5, 6, 7, 8], [10, 1211, 12, 1321, 146436]]) self.m = Matrix([['A', 'B', 'C', 'D', None], ['E', 'F', 'G', 'H', 'I'], ['J', 'K', 'L', 'M', None]])
def test_matrix_determinant_2x2(): A = Matrix([[1, 5], [-3, 2]]) assert A.determinant == 17
def test_init_0D(): bp.basic_test(res=Matrix("A"), expected="A", res_type=Matrix)
def test_init_2D(): bp.basic_test(res=Matrix([["A", "B"], ["C", "D"]]), expected=[["A", "B"], ["C", "D"]], res_type=Matrix)
def test_init_1D(): bp.basic_test(res=Matrix(["A", "B"]), expected=["A", "B"], res_type=Matrix)
def build_unigram_tag_probability(self): vector = dict((tag, 0) for tag in self.unique_tags) number_of_tags = len(self.tags_in_sequence) for tag in self.unique_tags: vector[tag] = self.tags_in_sequence.count(tag) / number_of_tags return Matrix(vector)
def test_matrix_identity(): A = Matrix([[1, 2, 3, 4], [2, 4, 4, 2], [8, 6, 4, 1], [0, 0, 0, 1]]) I = IdentityMatrix(4) assert A @ I == A and I @ A == A
def test_matrix_transpose(): A = Matrix([[1, 2, 3, 4], [2, 4, 4, 2], [8, 6, 4, 1], [0, 0, 0, 1]]) AT = Matrix([[1, 2, 8, 0], [2, 4, 6, 0], [3, 4, 4, 0], [4, 2, 1, 1]]) assert A.T == AT
def test_matrix_submatrix_3x3(): A = Matrix([[1, 5, 0], [-3, 2, 7], [0, 6, -3]]) a = A.submatrix(0, 2) assert a.n == 2 and a.m == 2 assert a == Matrix([[-3, 2], [0, 6]])
def test_matrix_minor_3x3(): A = Matrix([[3, 5, 0], [2, -1, -7], [6, -1, 5]]) b = A.submatrix(1, 0) assert b.determinant == 25 assert A.minor(1, 0) == 25
def test_matrix_submatrix_4x4(): A = Matrix([[-6, 1, 1, -6], [3, 2, 5, 1], [2, 1, -2, 3], [1, 5, 2, 7]]) a = A.submatrix(0, 3) assert a.n == 3 and a.m == 3 assert a == Matrix([[3, 2, 5], [2, 1, -2], [1, 5, 2]])