def init_theta(X, Y): """ Initialization theta vector :param X: :param Y: :return: Theta vector + Matrix for any class """ # Split X: X1 = Matrix.from_list([X[i] for i in range(X.numrows) if Y[i][0] == 1]) X2 = Matrix.from_list([X[i] for i in range(X.numrows) if Y[i][0] == 0]) # A and B are avg data point of X1 and X2: A = [sum([X1[i][1] for i in range(X1.numrows)])/X1.numrows, sum([X1[i][2] for i in range(X1.numrows)])/X1.numrows] B = [sum([X2[i][1] for i in range(X2.numrows)])/X2.numrows, sum([X2[i][2] for i in range(X2.numrows)])/X2.numrows] # Vector AB: AB = [B[0] - A[0], B[1] - A[1]] # I is midpoint between A and B: I = [(A[0] + B[0])/2, (A[1] + B[1])/2] # Get equation of AB's bisection: theta1 = np.array([[-(AB[0]*I[0] + AB[1]*I[1])], [AB[0]], [AB[1]]]) # Scale theta: div = theta1[0][0] for i in range(len(theta1)): if abs(theta1[i][0]) > abs(div): div = theta1[i][0] for i in range(len(theta1)): theta1[i][0] /= div # Return theta and matrix of any class return [Matrix.from_list(theta1), X1, X2]
def test(self, m, size): one = Matrix(size) one.one() e_lu = (m * m.invertLU() - one).frobeniusNorm() e_qr_simple = (m * m.invertQRSimple() - one).frobeniusNorm() e_qr_house = (m * m.invertQRHouseholder() - one).frobeniusNorm() self.putMany([size, e_lu, e_qr_simple, e_qr_house])
def testKnown(self): m = Matrix([[1,2,3,4], [1,4,9,16], [1,8,27,64], [1,16,81,256]]) l = Matrix([[1,0,0,0], [1,1,0,0], [1,3,1,0], [1,7,6,1]]) u = Matrix([[1,2,3,4], [0,2,6,12], [0,0,6,24], [0 ,0,0,24]]) (x,y) = m.lu() self.assertTrue(x.isAlmostEqual(l)) self.assertTrue(y.isAlmostEqual(u)) self.assertTrue(m.isAlmostEqual(x*y))
def creat_matrix(self, de, boomnum): m = Matrix() temp = [] for i in range(de**2): temp.append(0) for i in range(boomnum): index = random.randint(0, de**2 - 1) temp[index] = 1 m.square(de, temp) self.checkerboard = m.copy
def __init__(self, N): self.shadow = None self.checkerboard = None self.boomlist = [] m = Matrix() if N == 'easy': m.full(8, 8, u'■') self.print = m.copy self.creat_matrix(8, 10) self.run()
def get_shadow(self, board): self.shadow = Matrix() self.shadow.square(len(board) + 2, full=0) for i in range(len(board)): for j in range(len(board)): if board.matrix[i][j] != 0: for k in range(3): self.shadow.matrix[i][j + k] += 1 self.shadow.matrix[i + 1][j + k] += 1 self.shadow.matrix[i + 2][j + k] += 1
def testRandom(self): l = Matrix(self.size) u = Matrix(self.size) l.randomLowerTriangular(5) u.randomUpperTriangular(5) m = l * u one = Matrix(self.size) one.one() self.assertTrue(one.isAlmostEqual(m * m.invertLU()))
def open_csv(path, header=None): matrix = Matrix() if header is None: pds = read_csv(path, header=None) else: pds = read_csv(path, header=header) temp = [] for i in range(len(pds)): temp.append(pds.loc[i]) matrix.get_matrix(temp) return matrix
def get_theta(m, x1, x2, y): t = Matrix(m, 3, fill=1) for i in range(0, m): t[i][1] = x1[i] t[i][2] = x2[i] k = Matrix(m, 1, fill=0) for i in range(0, m): k[i][0] = y[i] return ((t.trans() * t).inv()) * t.trans() * k
def __init__(self, key: list = None): if not key: key = Matrix.identity(3) self.key_matrix = Matrix.from_list(key) try: determinant_modulus_inverse = pow(round(self.key_matrix.det()), -1, 26) self.key_matrix_inverse = (determinant_modulus_inverse * self.key_matrix.adjoint()) % 26 except: raise Exception("Key matrix have to be modular inversible")
def test(self, m, size): one = Matrix(size) one.one() m.random(int(time())) q, r = m.QRSimple() a_simple = (q*q.transpose() - one).frobeniusNorm() b_simple = (m - q*r).frobeniusNorm() q, r = m.QRHouseholder() a_house = (q*q.transpose() - one).frobeniusNorm() b_house = (m - q*r).frobeniusNorm() self.putMany([size, a_simple, b_simple, a_house, b_house])
def testRandom(self): m = Matrix(self.size) m.random(3) q, r = m.QRHouseholder() one = Matrix(self.size) one.one() self.assertTrue(m.isAlmostEqual(q*r)) self.assertTrue(one.isAlmostEqual(q*q.transpose()))
def testRandom(self): m = Matrix(5) m.random(3) q, r = m.QRSimple() one = Matrix(5) one.one() self.assertTrue(m.isAlmostEqual(q*r)) self.assertTrue(one.isAlmostEqual(q*q.transpose()))
def get_matrix(data_input): """ Init X and Y matrix :param data_input: input file path :return: Matrix X and Y """ # Read data to dataframe df: df = (pd.read_csv(data_input)).values # Get X and Y: X = Matrix.from_list([df[i][0:2] for i in range(len(df))]) Y = Matrix.from_list([df[i][2:] for i in range(len(df))]) # Append 1 into any row of X: X = Matrix.from_list([np.insert(X[i], 0, (1,)) for i in range(len(df))]) # Return: return [X, Y]
def instanMatriz(): global matrices, matrizActual, nombreActual #print(matrizActual) print(matrizActual) matriz = Matrix(matrizActual) #print(matriz) matrices[nombreActual] = matriz
def sigmoid_function(theta, X): """ Cacl sigmoid value :param theta: :param X: :return: """ z = Matrix.from_list(X) * (-theta) return 1.0 / (1 + np.exp(z[0][0]))
def get_matrix(var): """ Lay ma tran theta, X va Y :param var: Ma tran tham so dau vao :return: list 3 ma tran: theta, X va Y """ # Y la cot cuoi cung cua var, con lai thuoc X X = [var[i] for i in range(len(var) - 1)] Y = var[len(var) - 1] # Them value 1 vao dau moi dong cua X X.insert(0, [1 for i in range(len(var[0]))]) # Tao ma tran X va Y: mX = Matrix.from_list(X) mY = Matrix.from_list([Y]) # Tra ve theta, X va Y: return [((mX * mX.trans()).inv()) * mX * mY.trans(), mX, mY]
def testUpperTriangularInversion(self): a = Matrix(15) a.randomUpperTriangular(87) b = a.invertUpperTriangular() c = Matrix(15) c.one() print (c - a * b).frobeniusNorm() self.assertTrue(c.isAlmostEqual(a * b)) self.assertTrue(c.isAlmostEqual(b * a))
def update_equation(X, Y, theta, alpha): """ Update Decision Boundary :param X: :param Y: :param theta: :param alpha: :return: New theta vector """ return theta - Matrix.from_list([[alpha * cost_function(X, Y, theta)] for i in range(theta.numrows)])
def one(self): res = NumMatrix() one = Matrix() empty = Matrix() res.full(12, 4, 0) one.full(12, 2, 1) empty.full(12, 1, 0) res.__putr(one) res.__putr(empty) for i in range(len(res.matrix)): for j in range(len(res.matrix[0])): if res.matrix[i][j] == 0: res.matrix[i][j] = ' ' self.matrix = res.matrix
def encrypt(self, plaintext: str) -> str: """ Encrypt a given string, returning an encrypted string. Overrides StringCipher.encrypt() """ no_space_plaintext = plaintext.replace(" ", "") if not no_space_plaintext.isalpha(): raise Exception( "Hill cipher only accept alphabets with or without spaces as plaintext" ) lowercase_plaintext = no_space_plaintext.lower() plaintext_mod_26_list = [ ord(char) - ord('a') for char in lowercase_plaintext ] ciphertext_mod_26_list = [] block = self.key_matrix.numcols offset = 0 while offset < len(plaintext_mod_26_list): plaintext_slice = None if len(plaintext_mod_26_list) - offset < block: padding = [ 0 for x in range(len(plaintext_mod_26_list), offset + block) ] plaintext_slice = plaintext_mod_26_list[ offset:len(plaintext_mod_26_list)] + padding else: plaintext_slice = plaintext_mod_26_list[offset:offset + block] plaintext_matrix_block = Matrix.from_list([[x] for x in plaintext_slice ]) ciphertext_matrix_block = self.key_matrix * plaintext_matrix_block for x in ciphertext_matrix_block.elements(): ciphertext_mod_26_list.append(x % 26) offset += block ciphertext = ''.join( [chr(x + ord('a')) for x in ciphertext_mod_26_list]).upper() return ciphertext
def testRandom(self): l = Matrix(5) l.randomLowerTriangular(5) u = Matrix(5) u.randomUpperTriangular(5) m = l*u (x,y) = m.lu() self.assertTrue(m.isAlmostEqual(x*y))
def infer(self, data_in): """Push data_in through network and give results.""" l3 = Matrix.from_list([data_in]) * self.l1 + self.b1 # l3 = NeuralNetwork._logistic(l3) l3 = l3 * self.l2 + self.b2 # l3 = NeuralNetwork._logistic(l3) e = [math.exp(elem) for elem in l3[0]] s = sum(e) odds = [elem / s for elem in e] return self.argmax(odds)
def seven(self): res = NumMatrix() res.full(2, 6, 7) one = NumMatrix() one.full(10, 4, 0) two = Matrix() two.full(10, 2, 7) one.__putr(two) empty = Matrix() empty.full(12, 1, 0) res.__putd(one) res.__putr(empty) for i in range(len(res.matrix)): for j in range(len(res.matrix[0])): if res.matrix[i][j] == 0: res.matrix[i][j] = ' ' self.matrix = res.matrix
def cost_function(X, Y, theta): """ Cacl avg cost value :param X: :param Y: :param theta: :return: Cost value """ m = X.numrows # Data length # Cacl total cost: cost = ([(-Y[i][0] * np.log(sigmoid_function(theta, [X[i]])) - (1 - Y[i][0]) * np.log(1 - sigmoid_function(theta, [X[i]]))) * Matrix.from_list([[X[i][0]]]) for i in range(m)]) # Return avg cost: return -sum([cost[i][0][0] for i in range(len(cost))])/m
def decrypt(self, ciphertext: str) -> str: """ Decrypt a given string, returning a plaintext string. Overrides StringCipher.decrypt() """ if not ciphertext.isalpha(): raise Exception("Hill cipher only accept alphabets as ciphertext") lowercase_ciphertext = ciphertext.lower() ciphertext_mod_26_list = [ ord(char) - ord('a') for char in lowercase_ciphertext ] plaintext_mod_26_list = [] block = self.key_matrix.numcols offset = 0 while offset < len(ciphertext_mod_26_list): ciphertext_slice = None if len(ciphertext_mod_26_list) - offset < block: padding = [ 0 for x in range(len(ciphertext_mod_26_list), offset + block) ] ciphertext_slice = ciphertext_mod_26_list[ offset:len(ciphertext_mod_26_list)] + padding else: ciphertext_slice = ciphertext_mod_26_list[offset:offset + block] ciphertext_matrix_block = Matrix.from_list( [[x] for x in ciphertext_slice]) plaintext_matrix_block = self.key_matrix_inverse * ciphertext_matrix_block for x in plaintext_matrix_block.elements(): plaintext_mod_26_list.append(round(x) % 26) offset += block plaintext = ''.join([chr(x + ord('a')) for x in plaintext_mod_26_list]) return plaintext
def love(num, printer=None): lover = MagicMatrix() op = assistfuction.Functions() one = Spmatrix() one.uper_ting(3, model=3) two = Matrix([[1], [1], [1]]) three = Matrix([[0, 0, 0], [1, 0, 1], [1, 1, 1]]) five = Spmatrix() five.uper_ting(3, model=2) five.T lover.get_matrix(op.split_matrix(one)) lover.__putr(two) lover.__putr(three) lover.__putr(two) lover.__putr(five) add = Matrix() add.full(num, 11, 1) lover.__putd(add) six = Spmatrix() six.uper_ting(5, model=2) seven = Matrix([[1], [1], [1], [1], [1]]) eight = Spmatrix() eight.uper_ting(5, model=1) eight.T temp2 = MagicMatrix() temp2.get_matrix(op.split_matrix(six)) temp2.__putr(seven) temp2.__putr(eight) lover.__putd(temp2) end = Matrix([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]) lover.__putd(end) for i in range(len(lover.matrix)): for j in range(len(lover.matrix[0])): if lover.matrix[i][j] == 0: lover.matrix[i][j] = ' ' else: lover.matrix[i][j] = u'♥' if printer is not None: print('\033[31m', lover, '\033[0m') return lover.copy
def update_equation(X, Y, theta, alpha, _lambda): """ Update Decision Boundary :param X: :param Y: :param theta: :param alpha: :return: New theta vector """ temp = theta[0][0] # Save theta0 value # Update theta(included theta0): theta = theta - Matrix.from_list( [[alpha * cost_function(X, Y, theta, _lambda)] for i in range(theta.numrows)]) # Update theta0 by special way: theta[0][0] = temp - alpha * cost_function(X, Y, theta, 0) return theta
def zero(self): res = NumMatrix() res.full(2, 6, 1) one = NumMatrix() one.full(8, 2, 1) two = Matrix() two.full(8, 2, 0) three = one.copy one.__putr(two) one.__putr(three) four = res.copy res.__putd(one) res.__putd(four) empty = Matrix() empty.full(12, 1, 0) res.__putr(empty) for i in range(len(res.matrix)): for j in range(len(res.matrix[0])): if res.matrix[i][j] == 0: res.matrix[i][j] = ' ' else: res.matrix[i][j] = 0 self.matrix = res.matrix
def genMatrix(size, kind): m = Matrix(size) if kind == "random": m.random(seed()) elif kind == "triangular": m.randomUpperTriangular(seed()) elif kind == "hilbert": m.hilbert() elif kind == "diagonal_dominant": m.randomDiagonalDominant(seed()) elif kind == "almost_singular": m.randomAlmostSingular(seed()) elif kind == "zero_minor": m.randomZeroMinor(seed()) elif kind == "tridiagonal": m.randomTridiagonal(seed()) else: return None return m
def testManipulators(self): a = Matrix(44) a.zero() a.one() a.hilbert()
from pymatrix import Matrix import pandas as pd import numpy as np from Regularization import Hx, get_matrix if __name__ == '__main__': df1 = pd.read_csv("result.txt").values df2 = (pd.read_csv("ex2data2.txt")).values temp = get_matrix("ex2data2.txt") X = temp[0] Y = temp[1] theta = Matrix.from_list(df1) for i in range(len(df1)): np.append(df1[i], 1 - Hx(theta, X, 6)) print df1
def testRandom(self): m = Matrix(self.size) m.random(3); one = Matrix(self.size) one.one() self.assertTrue(one.isAlmostEqual(m * m.invertQRHouseholder()))
def testClone(self): m = Matrix(7) a = m.copy() self.assertTrue(m.isAlmostEqual(a))
def _logistic(x): r = Matrix(1, 2) for row, col, elem in x.elements(): r[row][col] = 1.0 / (1 + math.exp(-elem)) return r
from pymatrix import Matrix from time import time minsize = 10 maxsize = 200 step = 5 print "# time test" print "# size LU QR-Gram QR-Householder" for size in range(minsize, maxsize + 1, step): m = Matrix(size) m.random(int(time())) m, lu_time = m.invertLUTimed() m, qr_gram_time = m.invertQRSimpleTimed() m, qr_house_time = m.invertQRHouseholderTimed() print size, lu_time, qr_gram_time, qr_house_time
import numpy as np from pymatrix import Matrix from pymatrix import Spmatrix from pymatrix import Operation import random class FeatureMatrix(Matrix): @staticmethod def create_rotation_matrix(dimension, p, q, theta, rou=3): matrix_origin = Spmatrix.diagonal(Spmatrix(), dimension, 1) matrix_origin.matrix[p][p] = round(np.cos(theta), rou) matrix_origin.matrix[p][q] = round(-np.sin(theta), rou) matrix_origin.matrix[q][p] = round(np.sin(theta), rou) matrix_origin.matrix[q][q] = round(np.cos(theta), rou) return matrix_origin if __name__ == '__main__': l = [] for i in range(5): l.append([]) for j in range(5): l[i].append(random.randint(1, 10)) m = Matrix(l) f = FeatureMatrix.create_rotation_matrix(5, 2, 1, 1.047) print(m) print(f) print(Operation.mul(m, f))
class Game: def __init__(self, N): self.shadow = None self.checkerboard = None self.boomlist = [] m = Matrix() if N == 'easy': m.full(8, 8, u'■') self.print = m.copy self.creat_matrix(8, 10) self.run() def init(self): print(self.print) def limit(self, x, y): if x < 0 or x > 7 or y < 0 or y > 7: return False else: return True def check(self): index = [] for i in range(8): for j in range(8): if self.print.matrix[i][j] == ' ': index.append([i, j]) for x, y in index: if x + 1 < 7: if self.shadow.matrix[x + 2][y + 1] != 0: self.print.matrix[x + 1][y] = self.shadow.matrix[x + 2][y + 1] if x - 1 > 0: if self.shadow.matrix[x][y + 1] != 0: self.print.matrix[x - 1][y] = self.shadow.matrix[x][y + 1] if y - 1 > 0: if self.shadow.matrix[x + 1][y] != 0: self.print.matrix[x][y - 1] = self.shadow.matrix[x + 1][y] if y + 1 < 7: if self.shadow.matrix[x + 1][y + 2] != 0: self.print.matrix[x][y + 1] = self.shadow.matrix[x + 1][y + 2] def get_shadow(self, board): self.shadow = Matrix() self.shadow.square(len(board) + 2, full=0) for i in range(len(board)): for j in range(len(board)): if board.matrix[i][j] != 0: for k in range(3): self.shadow.matrix[i][j + k] += 1 self.shadow.matrix[i + 1][j + k] += 1 self.shadow.matrix[i + 2][j + k] += 1 def reflash(self, point, MODEL=None): x, y = point queue = [point] if self.checkerboard.matrix[x][ y] == 0 and MODEL is None and self.shadow.matrix[x + 1][y + 1] == 0: self.print.matrix[x][y] = ' ' self.init() while queue: x, y = queue.pop(0) if self.limit(x + 1, y) and self.print.matrix[ x + 1][y] == u'■' and self.shadow.matrix[x + 2][y + 1] == 0: queue.append((x + 1, y)) self.print.matrix[x + 1][y] = ' ' if self.shadow.matrix[ x + 2][y + 1] == 0 else self.shadow.matrix[x + 2][y + 1] if self.limit(x - 1, y) and self.print.matrix[ x - 1][y] == u'■' and self.shadow.matrix[x][y + 1] == 0: queue.append((x - 1, y)) self.print.matrix[x - 1][y] = ' ' if self.shadow.matrix[x][ y + 1] == 0 else self.shadow.matrix[x][y + 1] if self.limit(x, y + 1) and self.print.matrix[x][ y + 1] == u'■' and self.shadow.matrix[x + 1][y + 2] == 0: queue.append((x, y + 1)) self.print.matrix[x][y + 1] = ' ' if self.shadow.matrix[ x + 1][y + 2] == 0 else self.shadow.matrix[x + 1][y + 2] if self.limit(x, y - 1) and self.print.matrix[x][ y - 1] == u'■' and self.shadow.matrix[x + 1][y] == 0: queue.append((x, y - 1)) self.print.matrix[x][y - 1] = ' ' if self.shadow.matrix[ x + 1][y] == 0 else self.shadow.matrix[x + 1][y] self.check() self.init() elif MODEL == 'over': self.print.matrix[x][y] = u'♂' self.init() else: self.print.matrix[x][y] = self.shadow.matrix[x + 1][y + 1] self.init() def draw(self, point, MODEL=None): return self.reflash(point, MODEL=MODEL) def judge(self, point): if point in self.boomlist: print('Game over!') self.draw(point, 'over') return False else: return True def win(self): num = 0 for i in self.checkerboard: if i != 0: num += 1 for i in self.print: if i == u'■': num -= 1 if num == 0: return True else: return False def creat_matrix(self, de, boomnum): m = Matrix() temp = [] for i in range(de**2): temp.append(0) for i in range(boomnum): index = random.randint(0, de**2 - 1) temp[index] = 1 m.square(de, temp) self.checkerboard = m.copy def run(self): self.init() get_piont_r, get_piont_l = input().split(',') get_piont_r, get_piont_l = int(get_piont_r), int(get_piont_l) point = (get_piont_r, get_piont_l) if self.checkerboard.matrix[get_piont_r][get_piont_l] != 0: self.checkerboard.matrix[get_piont_r][get_piont_l] = 0 self.get_shadow(self.checkerboard) for i in range(len(self.checkerboard.matrix)): for j in range(len(self.checkerboard.matrix[0])): if self.checkerboard.matrix[i][j] != 0: self.boomlist.append((i, j)) while self.judge((get_piont_r, get_piont_l)): if self.win(): print('YOU WIN!') break self.reflash(point) get_piont_r, get_piont_l = input().split(',') get_piont_r, get_piont_l = int(get_piont_r), int(get_piont_l) point = (get_piont_r, get_piont_l)
def testUnit(self): one = Matrix(self.size) one.one() self.assertTrue(one.isAlmostEqual(one.invertLU()))
def testHilbert(self): m = Matrix(50) m.hilbert() (l,u) = m.lu() self.assertTrue(m.isAlmostEqual(l*u))
def test_from_matrix(self): assert P(Matrix.from_list([[0.4], [0.2], [0.1]])) == P([0.4, 0.2, 0.1])
def testTransposition(self): m = Matrix([[1,2],[3,4]]) tr = Matrix([[1,3], [2,4]]) self.assertTrue(tr.isAlmostEqual(m.transpose()))
def testNorms(self): a = Matrix(44) a.frobeniusNorm() a.scaledFrobeniusNorm() a.firstNorm() a.infNorm()
num += 1 class Body(tk.Frame): def __init__(self, master): super().__init__(master) self.master = master self.master.place(relx=0.45, rely=0.05) background_image = tk.PhotoImage( file=r'C:\Python3\Lib\site-packages\pymatrix\head.gif') self.widget = tk.Label(master, image=background_image) self.widget.pack() if __name__ == '__main__': m = Matrix([[98 * 5, 98 * (-2), 0], [-2 * 98, 3 * 98, -98], [0, -98, 98]]) oper = Operation() mr = Spmatrix().diagonal(3, 0.27) a = oper.mul(oper.inverse(mr), m) for i in range(len(a)): for j in range(len(a)): a.matrix[i][j] = round(a.matrix[i][j], 2) print('原始矩阵为:', a) find = oper.feature_matrix(a, 3, e=0.1) # print(oper.feature_matrix(m, 3, e=0.1)) # print('特征矩阵:', find['eigenvector']) print('特征值', find['eigenvalues']) # vector = [[3, 4, 5]] # s = Spmatrix() # print(isinstance(s, Matrix))
def colvec(l): return Matrix.from_list([l]).trans()
def __init__(self): self.l1 = Matrix(16, 16) self.b1 = Matrix(1, 16) self.l2 = Matrix(16, 4) self.b2 = Matrix(1, 4)
comando = StringVar() E = Entry( root, relief=FLAT, highlightbackground="black", textvariable=comando, width=79, bd=0, bg="black", fg="white", insertbackground="white", ) E.place(x=75, y=415) matrices = { "a": Matrix([[3, 2, 1], [1, 1, 3], [0, 2, 1]]), "b": Matrix([[2, 1], [1, 0], [3, 2]]) } state = "idle" contMat = 2 nombreActual = "" matrizActual = [] def insertarTexto(texto, start="\n"): global text text.config(state=NORMAL) text.insert(END, "{0}{1}".format(start, texto)) text.see(END) text.config(state=DISABLED)
def testColumnNormalization(self): m = Matrix([[3,3],[4,4]]) norm = Matrix([[0.6, 0.6],[0.8,0.8]]) m.normalizeColumn(0) m.normalizeColumn(1) self.assertTrue(norm.isAlmostEqual(m))