Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- class Matrix:
- def __init__(self, n, m):
- self.rows = n
- self.columns = m
- self.size = n*m
- self.data = [[0] * m for i in range(n)]
- # Fill every slot in the matrix with the value of n.
- def fill_matrix(self, n):
- for i in range(self.rows):
- for j in range(self.columns):
- self.data[i][j] = n
- # Fill every slot in the matrix with a radnom value in a given range, between a and b.
- def fill_matrix_random(self,a,b):
- for i in range(self.rows):
- for j in range(self.columns):
- self.data[i][j] = random.randint(a,b)
- # Fill vector with array
- def fill_vector(self, array):
- for i in range(self.rows):
- self.data[i][0] = array[i]
- # Print the matrix in a neat way in the console.
- def print(self):
- for i in range(self.rows):
- for j in range(self.columns):
- print(self.data[i][j], end=' ')
- print()
- # add or subtract. input is 1 or -1 for additon or subtraction.
- def sum(self, a_s, M):
- o = Matrix(self.rows, self.columns)
- for i in range(self.rows):
- for j in range(self.columns):
- o.data[i][j] = self.data[i][j] + (M.data[i][j]*a_s)
- return o
- # Right multiplyes the Matrix M with the object the method is used with.
- def multiply(self, M):
- o = Matrix(self.rows, M.columns)
- for i in range(self.rows):
- for j in range(M.columns):
- sum = 0
- for k in range(M.rows):
- sum = sum + self.data[i][k] * M.data[k][j]
- o.data[i][j] = sum
- return o
- def square(self):
- o = Matrix(self.rows, self.columns)
- for i in range(self.rows):
- for j in range(self.columns):
- o.data[i][j] = (self.data[i][j])**2
- return o
- # Transpose matrix; mirror all values about the leading diagonal
- def transpose(self):
- o = Matrix(self.rows, self.columns)
- for i in range(self.rows):
- for j in range(self.columns):
- o.data[i][j] = self.data[j][i]
- return o
- import Matrix
- class Data:
- def __init__(self):
- self.number_inputs = 0
- self.input_vector = None
- def set_input(self, array):
- self.number_inputs = len(array)
- self.input_vector = Matrix.Matrix(len(array), 1)
- self.input_vector.fill_vector(array)
- class TrainingData(Data):
- def set_output(self, array):
- self.number_outputs = len(array)
- self.output_vector = Matrix.Matrix(len(array), 1)
- self.output_vector.fill_vector(array)
- def calculate_cost(self, prediction):
- m = Matrix.Matrix(1,1)
- m = self.output_vector.sum(-1, prediction).square
- return m
- p = TrainingData()
- p.set_input([1,1,1])
- p.set_output([2,2,2])
- pred = Matrix.Matrix(3,1)
- pred.fill_vector([1.5,1.5,1.5])
- p.calculate_cost(pred).print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement