1
0
Fork 0
neural-network/Matrix.py

84 lines
2.3 KiB
Python

import random
class Matrix:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.data = []
for i in range(0, rows):
self.data.append([0 for _ in range(0, cols)])
@staticmethod
def from_list(lst):
m = Matrix(len(lst), 1)
m.map(lambda x, i, j: lst[i])
return m
@staticmethod
def product(a, b):
"""Matrix product"""
if a.cols != b.rows:
return None
result = Matrix(a.rows, b.cols)
result.map(lambda x, i, j: sum([a.data[i][k] * b.data[k][j] for k in range(0, a.cols)]))
return result
@staticmethod
def transpose(m):
"""Transpose a matrix"""
result = Matrix(m.cols, m.rows)
result.map(lambda x, i, j: m.data[j][i])
return result
@staticmethod
def subtract(a, b):
result = Matrix(a.rows, a.cols)
result.map(lambda x, i, j: a.data[i][j] - b.data[i][j])
return result
@staticmethod
def clone(m):
result = Matrix(m.rows, m.cols)
result.map(lambda x, i, j: m.data[i][j])
return result
def map(self, fun):
"""Execute a function on every element of the list, use the return value as the new value of the element"""
for i in range(0, self.rows):
for j in range(0, self.cols):
self.data[i][j] = fun(self.data[i][j], i, j)
def randomize(self):
"""Fill the matrix with random integers"""
self.map(lambda x, i, j: random.randint(-1, 1))
def multiply(self, n):
"""Hadamard or scalar product"""
if type(n) is Matrix:
self.map(lambda x, i, j: x * n.data[i][j])
else:
self.map(lambda x, i, j: x * n)
def add(self, n):
"""Entrywise or scalar addition"""
if type(n) is Matrix:
self.map(lambda x, i, j: x + n.data[i][j])
else:
self.map(lambda x, i, j: x + n)
def print(self):
"""Pretty print the matrix"""
for row in self.data:
for elem in row:
print(elem, end='\t')
print()
def to_list(self):
"""Returns the internal matrix as a list"""
lst = []
self.map(lambda x, i, j: lst.append(x))
return lst