Skip to content

Issue 12322 #12323

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 39 commits into from
Closed
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
b6e2f37
add rbfnn algorithm solving issue 12322
JeninaAngelin Oct 30, 2024
74212a6
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
5fbe96d
add rbfnn in directory solving issue 12322
JeninaAngelin Oct 30, 2024
f66b55f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
bb7ac35
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
aeb9015
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
2dadd7f
correcting errors in radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
ca15518
add doctests to radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
03eed71
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
90f0a5f
breaking long lines in radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
79239b5
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
4c7d0a2
add docstrings to radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
ae74131
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
c47d8e3
adjust sorting libraries radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
0831d48
resorting libraries radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
f7a69e3
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
d00b366
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
21dcb4d
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
30dc616
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
301d98f
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
d76d6bb
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
fe4a0c9
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
42826a1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
1140d30
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
64fc4a7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
0225212
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
42e34a1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
8767b57
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
e91f39f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
70f2b0c
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
ea1fcee
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
db59731
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
e7c58c9
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
352458d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
911ed3a
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
52e01d1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
49272c7
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
371f23a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Oct 30, 2024
aace140
Update radial_basis_function_neural_network.py
JeninaAngelin Oct 30, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -832,6 +832,7 @@
* [Input Data](neural_network/input_data.py)
* [Simple Neural Network](neural_network/simple_neural_network.py)
* [Two Hidden Layers Neural Network](neural_network/two_hidden_layers_neural_network.py)
* [Radial Basis Function Neural Network](neural_network/radial_basis_function_neural_network.py)

## Other
* [Activity Selection](other/activity_selection.py)
Expand Down
144 changes: 144 additions & 0 deletions neural_network/radial_basis_function_neural_network.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import numpy as np

class RadialBasisFunctionNeuralNetwork:

Check failure on line 3 in neural_network/radial_basis_function_neural_network.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

neural_network/radial_basis_function_neural_network.py:1:1: I001 Import block is un-sorted or un-formatted
"""
A simple implementation of a Radial Basis Function Neural Network (RBFNN).

Attributes:
num_centers (int): Number of centers for the radial basis functions.
spread (float): Spread of the radial basis functions.
centers (np.ndarray): Centers of the radial basis functions.
weights (np.ndarray): Weights for the output layer.
"""

def __init__(self, num_centers: int, spread: float):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: __init__. If the function does not return a value, please provide the type hint as: def function() -> None:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: __init__. If the function does not return a value, please provide the type hint as: def function() -> None:

"""
Initialize the RBFNN with the given number of centers and spread.

Args:
num_centers (int): Number of centers for the radial basis functions.
spread (float): Spread of the radial basis functions.

Examples:
>>> rbf_nn = RadialBasisFunctionNeuralNetwork(num_centers=3, spread=1.0)
>>> rbf_nn.num_centers
3
"""
self.num_centers = num_centers
self.spread = spread
self.centers: np.ndarray = None # To be initialized during training
self.weights: np.ndarray = None # To be initialized during training

def _gaussian_rbf(self, input_vector: np.ndarray, center: np.ndarray) -> float:
"""
Calculate the Gaussian radial basis function output for a given input vector and center.

Check failure on line 34 in neural_network/radial_basis_function_neural_network.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

neural_network/radial_basis_function_neural_network.py:34:89: E501 Line too long (96 > 88)

Args:
input_vector (np.ndarray): The input vector for which to calculate the RBF output.

Check failure on line 37 in neural_network/radial_basis_function_neural_network.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

neural_network/radial_basis_function_neural_network.py:37:89: E501 Line too long (94 > 88)
center (np.ndarray): The center of the radial basis function.

Returns:
float: The output of the radial basis function evaluated at the input vector.

Check failure on line 41 in neural_network/radial_basis_function_neural_network.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

neural_network/radial_basis_function_neural_network.py:41:89: E501 Line too long (89 > 88)

Examples:
>>> rbf_nn = RadialBasisFunctionNeuralNetwork(num_centers=2, spread=0.5)
>>> center = np.array([1, 1])
>>> rbf_nn._gaussian_rbf(np.array([0, 0]), center)
0.1353352832366127
"""
return np.exp(-(np.linalg.norm(input_vector - center) ** 2) / (2 * self.spread ** 2))

Check failure on line 49 in neural_network/radial_basis_function_neural_network.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

neural_network/radial_basis_function_neural_network.py:49:89: E501 Line too long (93 > 88)

def _compute_rbf_outputs(self, input_data: np.ndarray) -> np.ndarray:
"""
Compute the outputs of the radial basis functions for the input data.

Args:
input_data (np.ndarray): Input data matrix (num_samples x num_features).

Returns:
np.ndarray: A matrix of shape (num_samples x num_centers) containing the RBF outputs.

Check failure on line 59 in neural_network/radial_basis_function_neural_network.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

neural_network/radial_basis_function_neural_network.py:59:89: E501 Line too long (97 > 88)

Examples:
>>> rbf_nn = RadialBasisFunctionNeuralNetwork(num_centers=2, spread=1.0)
>>> rbf_nn.centers = np.array([[0, 0], [1, 1]])
>>> rbf_nn._compute_rbf_outputs(np.array([[0, 0], [1, 1]]))
array([[1. , 0.60653066],
[0.60653066, 1. ]])
"""
rbf_outputs = np.zeros((input_data.shape[0], self.num_centers))
for i, center in enumerate(self.centers):
for j in range(input_data.shape[0]):
rbf_outputs[j, i] = self._gaussian_rbf(input_data[j], center)
return rbf_outputs

def fit(self, input_data: np.ndarray, target_values: np.ndarray):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: fit. If the function does not return a value, please provide the type hint as: def function() -> None:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: fit. If the function does not return a value, please provide the type hint as: def function() -> None:

"""
Train the RBFNN using the provided input data and target values.

Args:
input_data (np.ndarray): Input data matrix (num_samples x num_features).
target_values (np.ndarray): Target values (num_samples x output_dim).

Raises:
ValueError: If the number of samples in input_data and target_values do not match.

Check failure on line 83 in neural_network/radial_basis_function_neural_network.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

neural_network/radial_basis_function_neural_network.py:83:89: E501 Line too long (94 > 88)

Examples:
>>> rbf_nn = RadialBasisFunctionNeuralNetwork(num_centers=2, spread=1.0)
>>> X = np.array([[0, 0], [1, 0], [0, 1], [1, 1]])
>>> y = np.array([[0], [1], [1], [0]])
>>> rbf_nn.fit(X, y)
>>> rbf_nn.weights is not None
True
"""
if input_data.shape[0] != target_values.shape[0]:
raise ValueError("Number of samples in input_data and target_values must match.")

Check failure on line 94 in neural_network/radial_basis_function_neural_network.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

neural_network/radial_basis_function_neural_network.py:94:89: E501 Line too long (93 > 88)

# Initialize centers using random samples from input_data
rng = np.random.default_rng() # Using new random number generator
random_indices = rng.choice(input_data.shape[0], self.num_centers, replace=False)

Check failure on line 98 in neural_network/radial_basis_function_neural_network.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

neural_network/radial_basis_function_neural_network.py:98:89: E501 Line too long (89 > 88)
self.centers = input_data[random_indices]

# Compute the RBF outputs for the training data
rbf_outputs = self._compute_rbf_outputs(input_data)

# Calculate weights using the pseudo-inverse
self.weights = np.linalg.pinv(rbf_outputs).dot(target_values)

def predict(self, input_data: np.ndarray) -> np.ndarray:
"""
Predict the output for the given input data using the trained RBFNN.

Args:
input_data (np.ndarray): Input data matrix (num_samples x num_features).

Returns:
np.ndarray: Predicted values (num_samples x output_dim).

Examples:
>>> rbf_nn = RadialBasisFunctionNeuralNetwork(num_centers=2, spread=1.0)
>>> rbf_nn.centers = np.array([[0, 0], [1, 1]])
>>> rbf_nn.weights = np.array([[0.5], [0.5]])
>>> rbf_nn.predict(np.array([[0, 0], [1, 1]]))
array([[0.5],
[0.5]])
"""
rbf_outputs = self._compute_rbf_outputs(input_data)
return rbf_outputs.dot(self.weights)


# Example Usage
if __name__ == "__main__":
import doctest
doctest.testmod()

# Sample dataset for XOR problem
X = np.array([[0, 0], [1, 0], [0, 1], [1, 1]]) # 2D input
y = np.array([[0], [1], [1], [0]]) # Target output for XOR

# Create and train the RBFNN
rbf_nn = RadialBasisFunctionNeuralNetwork(num_centers=2, spread=0.5)
rbf_nn.fit(X, y)

# Predict using the trained model
predictions = rbf_nn.predict(X)
print("Predictions:\n", predictions)
Loading