Skip to content

Commit

Permalink
Merge pull request #6 from javidahmed64592/add-matrix-mutation-method
Browse files Browse the repository at this point in the history
Add method to mutate matrix
  • Loading branch information
javidahmed64592 authored Apr 16, 2024
2 parents 6ac9253 + 1048f50 commit ec35745
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
19 changes: 19 additions & 0 deletions neural_network/math/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,3 +201,22 @@ def average_matrix(matrix: Matrix, other_matrix: Matrix) -> Matrix:
"""
new_matrix = np.average([matrix.data, other_matrix.data], axis=0)
return Matrix.from_array(new_matrix)

@staticmethod
def mutated_matrix(matrix: Matrix, mutation_rate: float, random_range: List[float]) -> Matrix:
"""
Mutate Matrix with a mutation rate.
Parameters:
matrix (Matrix): Matrix to use for average
mutation_rate (float): Probability for mutation
random_range (List[float]): Range for random number
Returns:
new_matrix (Matrix): Mutated Matrix
"""
_mutation_matrix = np.random.uniform(low=0, high=1, size=matrix.shape)
new_matrix = np.where(
_mutation_matrix < mutation_rate, np.random.uniform(low=random_range[0], high=random_range[1]), matrix.data
)
return Matrix.from_array(new_matrix)
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from setuptools import find_packages, setup # type: ignore

__version__ = "1.1.0"
__version__ = "1.2.0"

setup(
name="neural_network",
Expand Down
13 changes: 13 additions & 0 deletions tests/math/test_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,16 @@ def test_given_two_matrices_when_calculating_average_matrix_then_check_new_matri
expected_vals = np.array([[0, 1.5], [3, -1], [2.5, 3]])
actual_vals = new_matrix.data
assert np.all(actual_vals == expected_vals)

def test_given_matrix_when_mutating_then_check_new_matrix_with_same_shape_returned(self):
array_1 = np.array([[1, 2], [4, 3], [2, 4]])
mutation_rate = 0.5
random_range = [1.0, 4.0]

matrix_1 = Matrix.from_array(array_1)
new_matrix = Matrix.mutated_matrix(matrix_1, mutation_rate, random_range)

expected_shape = matrix_1.shape
actual_shape = new_matrix.shape
assert np.all(actual_shape == expected_shape)
assert not np.all(matrix_1.data == new_matrix.data)

0 comments on commit ec35745

Please sign in to comment.