-
Notifications
You must be signed in to change notification settings - Fork 0
Tutorial 4: Car Neural Network
Important
This tutorial starts at the workshop-tutorial-3 branch and the complete solution can be found at workshop-tutorial-4 branch.
This tutorial focuses on the implementation of the CarNN class, which contains the main logics for the neural network.
Note
This tutorial will implement/update the following modules:
The CarNN class is already partially implemented as we see in the file, particularlly:
-
serialize: turns the neural network's weights into string so that it can be saved to files. -
deserialize: create the neural network from the given activation function, weights string, and the initial mutation noise to be passed tomutatefunction which we will implement later.
But we also need to implement the __init__ function before actually implementing other functions of the neural network.
The prev_fitness and prev_weights members, and the activation function are rather obvious to what they should be initialized to. However, the weights, the layer_sizes, and the hiddens members need a bit more design.
When weights is provided, we can actually find out the layer_sizes from it (by checking its len and shape). On the other hand, if weights is not provided, then the user must provide the layer_sizes so that we can initialize the weights to some specific sizes.
To find out what should the size of weights be, we need to understand how neural network works, but in essense weights are the linkage between each node in the previous layer to each node in the next layer. Due to mathematicaly reasons, the previous layer node will have an additional node than the actual number of hidden node. See below for a pseudocode presenting the use of weights.
for j, prev_node in [prev[0], prev[1], ..., prev[layer_sizes[i - 1]], additional]:
for k, curr_node in [curr[0], curr[1], ..., curr[layer_sizes[i]]]:
weights[i][j][k] is the link of prev_node and curr_nodeNote
The exact mathematical reason is explained in the Feedforward Neural Network section.
Then after finding layer_sizes, the hiddens are just the layer_sizes except the input and the output layer (i.e. the middle layers).
def __init__(
self,
activation: ActivationFunc,
weights: Optional[List[np.ndarray]] = None,
layer_sizes: Optional[List[int]] = None,
):
"""
Initialize the neural network.
Either `weights` or `layer_sizes` must be provided.
:param activation: The activation function
:param weights: The weights of the neural network
:param layer_sizes: The sizes of the layers
"""
# Check if either weights or layer_sizes is provided
if not weights and not layer_sizes:
raise ValueError("Either weights or layer_sizes must be provided")
# There is no previous fitness and weights, so they are None
self.prev_fitness = None
self.prev_weights = None
# Initialize the either with the given weight, or using a normal
# distribution
#
# The width should be the previous size + 1 for (x_0, x_1, ..., x_n, b)
# and the height should be the current layer size
self.weights = weights or [
np.random.normal(size=(_____, _____))
for prev_size, curr_size in zip(layer_sizes, layer_sizes[1:])
]
# Initialize the layer sizes by using the given layer sizes, or
# calculating from the weights
self.layer_sizes = layer_sizes or (
[
weights[0].shape[0] - 1,
*(weight.shape[1] for weight in weights),
]
)
# Initialize the hidden layers
#
# Since the initial values are not important, we can just use zeros
self.hiddens = [
np.array([0] * size, dtype=np.float32)
for size in self.layer_sizes[_____:_____]
]
# Assign the activation function
self.activation = activationSolution Code
def __init__(
self,
activation: ActivationFunc,
weights: Optional[List[np.ndarray]] = None,
layer_sizes: Optional[List[int]] = None,
):
"""
Initialize the neural network.
Either `weights` or `layer_sizes` must be provided.
:param activation: The activation function
:param weights: The weights of the neural network
:param layer_sizes: The sizes of the layers
"""
# Check if either weights or layer_sizes is provided
if not weights and not layer_sizes:
raise ValueError("Either weights or layer_sizes must be provided")
# There is no previous fitness and weights, so they are None
self.prev_fitness = None
self.prev_weights = None
# Initialize the either with the given weight, or using a normal
# distribution
#
# The width should be the previous size + 1 for (x_0, x_1, ..., x_n, b)
# and the height should be the current layer size
self.weights = weights or [
np.random.normal(size=(prev_size + 1, curr_size))
for prev_size, curr_size in zip(layer_sizes, layer_sizes[1:])
]
# Initialize the layer sizes by using the given layer sizes, or
# calculating from the weights
self.layer_sizes = layer_sizes or (
[
weights[0].shape[0] - 1,
*(weight.shape[1] for weight in weights),
]
)
# Initialize the hidden layers
#
# Since the initial values are not important, we can just use zeros
self.hiddens = [
np.array([0] * size, dtype=np.float32)
for size in self.layer_sizes[1:-1]
]
# Assign the activation function
self.activation = activationFeedforward neural network refers to neural networks which obtains the value of the next layer's nodes based on the previous nodes value multiplied by some weights.
More specifically, to find the value of the node in the current layer (
And in reality, we also add a bias (
The most simple form of a feedforward neural network is a linear function in the form of:
Or commonly written as:
Where the
Note
The reason why we only use a linear function (as compared to for example a quadratic function) between nodes is mainly because it is the most simple expression of relationship between values, and that more complicated relationships are instead modelled by having multiple layers.
As we multiply more and more hidden layers in between, the relationship between the input layer and the output layer becomes more and more complicated.
But when there are more
But when there are also multiple
We can then make the formula more simple by adding a
In pseudocode, the above formula will be expressed to:
for j in [0, m]
for i in [0, n + 1]
y[j] += w[i][j] * x[i]Now that we know
If we represent
It seems to be all good now, except one thing - we only have 2 layers (
Let
Then the previous formula will be further generlized.
Note
The previous layer is not really the
So we also need to
We are almost there! There is a final step, we need to apply an activation function on the result before really assigning it to the next layer.
Note
While in some scenario, activation functions may not be needed, but the reason why activation functions are often used in between layers is because it provides nonlinearity to the model and clip the values to a certain range, while still preserving differentiability so that the model can still learn.
Intuitively, it is like asking the neural network to think step by step instead of doing everything in one go by keeping the value in a certain range, e.g. "Am I in danger?" -> "Can I outrun the danger?"/"Can I win against the danger?" -> "Should I run or fight?".
After figuring out the math, here is a summary of what we need to do in the activate function:
- We need to find the first hidden layer's value
self.hiddens[0]from theinputparameter by doing the computation$h_0 = \text{activate}\left(w_0 \text{concat}(\dots h_{-1}, [1])\right)$ , except we don't have$h_{-1}$ so we replace it with theinput. - Then we loop over each adjacent layers
$h_k$ and$h_{k-1}$ and apply the same computation$h_k = \text{activate}\left(w_k \text{concat}(\dots h_{k-1}, [1])\right)$ . - The output layer will be obtained in the same way.
- Remember to clip the final output to [-1, 1] because it is what
AICar._get_inputexpects.
Here are some useful numpy functions: numpy.concatenate, numpy.dot, numpy.clip.
def activate(
self, inputs: npt.NDArray[np.float32]
) -> npt.NDArray[np.float32]:
"""
Activate the neural network.
:param inputs: The input vector
:return: The output vector
"""
# Check if the input size is correct
if len(inputs) != self.layer_sizes[0]:
raise ValueError(
f"Expected {self.layer_sizes[0]} inputs, got {len(inputs)}"
)
# Calculate the first hidden layer
self.hiddens[0] = _____(
np._____(np._____((_____, [1.0])), _____)
)
# Calculate the remaining hidden layers in a loop
for i in range(1, len(self.hiddens)):
self.hiddens[i] = _____(
np._____(
np._____((_____, [1.0])),
_____,
)
)
# Calculate the output layer, and also clip the values to [-1, 1]
# because it is what is required by the car
return np.clip(
np._____(
np._____((_____, [1.0])),
_____,
),
-1.0,
1.0,
)Solution Code
def activate(
self, inputs: npt.NDArray[np.float32]
) -> npt.NDArray[np.float32]:
"""
Activate the neural network.
:param inputs: The input vector
:return: The output vector
"""
# Check if the input size is correct
if len(inputs) != self.layer_sizes[0]:
raise ValueError(
f"Expected {self.layer_sizes[0]} inputs, got {len(inputs)}"
)
# Calculate the first hidden layer
self.hiddens[0] = self.activation(
np.dot(np.concatenate((inputs, [1.0])), self.weights[0])
)
# Calculate the remaining hidden layers in a loop
for i in range(1, len(self.hiddens)):
self.hiddens[i] = self.activation(
np.dot(
np.concatenate((self.hiddens[i - 1], [1.0])),
self.weights[i],
)
)
# Calculate the output layer, and also clip the values to [-1, 1]
# because it is what is required by the car
return np.clip(
np.dot(
np.concatenate((self.hiddens[-1], [1.0])),
self.weights[-1],
),
-1.0,
1.0,
)