refactor(network.py): annotate Neuron constructor (comments other functions)

This commit is contained in:
2026-01-18 18:26:06 +01:00
parent 17be224d25
commit 4cca66db99

View File

@@ -1,6 +1,7 @@
import math import math
import random import random
def sigmoid(x: float) -> float: def sigmoid(x: float) -> float:
return 1 / (1 + math.exp(-x)) return 1 / (1 + math.exp(-x))
@@ -9,123 +10,154 @@ def sigmoid_deriv(x: float) -> float:
y: float = sigmoid(x) y: float = sigmoid(x)
return y * (1 - y) return y * (1 - y)
# neuron class
class Neuron: class Neuron:
def __init__(self, input_size: int) -> None:
""" """
z : linear combination of inputs and weights plus bias (pre-activation) Set up the neuron's parameters (weights, and bias)
y : output of the activation function (sigmoid(z))
w : list of weights, one for each input :param input_size: Number of incomming inputs (must be > 0)
""" """
def __init__(self, isize): # Store input dimensions for structural consistency
# number of inputs to this neuron self._input_size: int = input_size
self.isize = isize
# importance to each input
self.weight = [random.uniform(-1, 1) for _ in range(self.isize)]
# importance of the neuron
self.bias = random.uniform(-1, 1)
def forward(self, x, activate=True): # Scale each input influence using random weights.
""" self._weight: list[float] = [
x : list of input values to the neuron random.uniform(-1., 1.) for _ in range(input_size)
""" ]
# computes the weighted sum of inputs and add the bias
self.z = sum(w * xi for w, xi in zip(self.weight, x)) + self.bias
# normalize the output between 0 and 1 if activate
last_output = sigmoid(self.z) if activate else self.z
return last_output # Initialize a shift to the activation threshold with a random bias
self._bias: float = random.uniform(-1., 1.)
# adjust weight and bias of neuron def __repr__(self) -> str:
def backward(self, x, dcost_dy, learning_rate): jmp: int = int(math.sqrt(self._input_size))
""" text: list[str] = []
x : list of input values to the neuron
dcost_dy : derivate of the cost function `(2 * (output - target))`
learning_rate : learning factor (adjust the speed of weight/bias change during training)
weight -= learning_rate * dC/dy * dy/dz * dz/dw for i in range(0, self._input_size, jmp):
bias -= learning_rate * dC/dy * dy/dz * dz/db line: str = str.join("", str(self._weight[i: (i + jmp)]))
""" text.append(line)
# dy/dz: derivate of the sigmoid activation
dy_dz = sigmoid_deriv(self.z)
# dz/dw = x
dz_dw = x
assert len(dz_dw) >= self.isize, "too many value for input size" return f"weight:\n{str.join("\n", text)}\nbias: {self._bias}"
# dz/db = 1 # # neuron class
dz_db = 1 # class Neuron:
# """
# z : linear combination of inputs and weights plus bias (pre-activation)
# y : output of the activation function (sigmoid(z))
# w : list of weights, one for each input
# """
# def __init__(self, input_size):
# # number of inputs to this neuron
# self._input_size = input_size
# # importance to each input
# self._weight = [random.uniform(-1, 1) for _ in range(self._input_size)]
# # importance of the neuron
# self._bias = random.uniform(-1, 1)
for i in range(self.isize): # def forward(self, x, activate=True):
# update each weight `weight -= learning_rate * dC/dy * dy/dz * x_i` # """
self.weight[i] -= learning_rate * dcost_dy * dy_dz * dz_dw[i] # x : list of input values to the neuron
# """
# # computes the weighted sum of inputs and add the bias
# self._z = sum(w * xi for w, xi in zip(self.weight, x)) + self.bias
# # normalize the output between 0 and 1 if activate
# last_output = sigmoid(self.z) if activate else self.z
# update bias: bias -= learning_rate * dC/dy * dy/dz * dz/db # return last_output
self.bias -= learning_rate * dcost_dy * dy_dz * dz_db
# return gradient vector len(input) dimension # # adjust weight and bias of neuron
return [dcost_dy * dy_dz * w for w in self.weight] # def backward(self, x, dcost_dy, learning_rate):
# """
# x : list of input values to the neuron
# dcost_dy : derivate of the cost function `(2 * (output - target))`
# learning_rate : learning factor (adjust the speed of weight/bias change during training)
# weight -= learning_rate * dC/dy * dy/dz * dz/dw
# bias -= learning_rate * dC/dy * dy/dz * dz/db
# """
# # dy/dz: derivate of the sigmoid activation
# dy_dz = sigmoid_deriv(self.z)
# # dz/dw = x
# dz_dw = x
class Layer: # assert len(dz_dw) >= self.isize, "too many value for input size"
def __init__(self, input_size, output_size):
"""
input_size : size of each neuron input
output_size : size of neurons
"""
self.size = output_size
# list of neurons
self.neurons = [Neuron(input_size) for _ in range(output_size)]
def forward(self, inputs, activate=True): # # dz/db = 1
self.inputs = inputs # dz_db = 1
# give the same inputs to each neuron in the layer
return [neuron.forward(inputs, activate) for neuron in self.neurons]
# adjust weight and bias of the layer (all neurons) # for i in range(self.isize):
def backward(self, dcost_dy_list, learning_rate=0.1): # # update each weight `weight -= learning_rate * dC/dy * dy/dz * x_i`
# init layer gradient vector len(input) dimention # self.weight[i] -= learning_rate * dcost_dy * dy_dz * dz_dw[i]
input_gradients = [0.0] * len(self.inputs)
for i, neuron in enumerate(self.neurons): # # update bias: bias -= learning_rate * dC/dy * dy/dz * dz/db
dcost_dy = dcost_dy_list[i] # self.bias -= learning_rate * dcost_dy * dy_dz * dz_db
grad_to_input = neuron.backward(self.inputs, dcost_dy, learning_rate)
# accumulate the input gradients from all neurons # # return gradient vector len(weight) dimension
for j in range(len(grad_to_input)): # return [dcost_dy * dy_dz * w for w in self.weight]
input_gradients[j] += grad_to_input[j]
# return layer gradient # def __repr__(self):
return input_gradients # pass
class NeuralNetwork: # class Layer:
def __init__(self, layer_size): # def __init__(self, input_size, output_size):
self.layers = [Layer(layer_size[i], layer_size[i+1]) for i in range(len(layer_size) - 1)] # """
# input_size : size of each neuron input
# output_size : size of neurons
# """
# self.size = output_size
# # list of neurons
# self.neurons = [Neuron(input_size) for _ in range(output_size)]
def forward(self, inputs): # def forward(self, inputs, activate=True):
output = inputs # self.inputs = inputs
for i, layer in enumerate(self.layers): # # give the same inputs to each neuron in the layer
activate = (i != len(self.layers) - 1) # deactivate sigmoid latest neuron # return [neuron.forward(inputs, activate) for neuron in self.neurons]
output = layer.forward(output, activate=activate)
return output
def backward(self, inputs, targets, learning_rate=0.1): # # adjust weight and bias of the layer (all neurons)
""" # def backward(self, dcost_dy_list, learning_rate=0.1):
target must be a list with the same length that the final layer # # init layer gradient vector len(input) dimention
input # input_gradients = [0.0] * len(self.inputs)
"""
output = self.forward(inputs)
# computes the initial gradient of the cost function for each neuron # for i, neuron in enumerate(self.neurons):
# by using Mean Squared Error's derivate: dC/dy = 2 * (output - target) # dcost_dy = dcost_dy_list[i]
dcost_dy_list = [2 * (o - t) for o, t in zip(output, targets)] # grad_to_input = neuron.backward(self.inputs, dcost_dy, learning_rate)
grad = dcost_dy_list # # accumulate the input gradients from all neurons
for layer in reversed(self.layers): # for j in range(len(grad_to_input)):
# backpropagate the gradient of the layer to update weights and biases # input_gradients[j] += grad_to_input[j]
grad = layer.backward(grad, learning_rate)
# return final gradient # # return layer gradient
return grad # return input_gradients
if __name__ == "__main__": # class NeuralNetwork:
print("you might want to run main.py instead of network.py") # def __init__(self, layer_size):
# self.layers = [Layer(layer_size[i], layer_size[i+1]) for i in range(len(layer_size) - 1)]
# def forward(self, inputs):
# output = inputs
# for i, layer in enumerate(self.layers):
# activate = (i != len(self.layers) - 1) # deactivate sigmoid latest neuron
# output = layer.forward(output, activate=activate)
# return output
# def backward(self, inputs, targets, learning_rate=0.1):
# """
# target must be a list with the same length that the final layer
# input
# """
# output = self.forward(inputs)
# # computes the initial gradient of the cost function for each neuron
# # by using Mean Squared Error's derivate: dC/dy = 2 * (output - target)
# dcost_dy_list = [2 * (o - t) for o, t in zip(output, targets)]
# grad = dcost_dy_list
# for layer in reversed(self.layers):
# # backpropagate the gradient of the layer to update weights and biases
# grad = layer.backward(grad, learning_rate)
# # return final gradient
# return grad
# if __name__ == "__main__":
# print("you might want to run main.py instead of network.py")