diff --git a/neural_network/math/matrix.py b/neural_network/math/matrix.py index abeb88f..d0abe41 100644 --- a/neural_network/math/matrix.py +++ b/neural_network/math/matrix.py @@ -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) diff --git a/setup.py b/setup.py index 3a7cb62..72c5848 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,6 @@ from setuptools import find_packages, setup # type: ignore -__version__ = "1.1.0" +__version__ = "1.2.0" setup( name="neural_network", diff --git a/tests/math/test_matrix.py b/tests/math/test_matrix.py index 8b0d790..1de0e62 100644 --- a/tests/math/test_matrix.py +++ b/tests/math/test_matrix.py @@ -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)