The NN class implements a modern, configurable neural network with advanced features for deep reinforcement learning.
NN(int inputs, int hiddens, int outputs)
Creates a neural network with default configuration.
Parameters:
inputs(int): Number of input neuronshiddens(int): Number of hidden neurons per layeroutputs(int): Number of output neurons
Example:
NN network = new NN(14, 64, 66);Creates a neural network with custom configuration.
Parameters:
config(NetworkConfig): Configuration object with all network parameters
Example:
NN.NetworkConfig config = new NN.NetworkConfig
{
numInputs = 14,
numHiddens = 64,
numOutputs = 66,
numHiddenLayers = 3,
learningRate = 0.001f,
useBatchNormalization = true,
activationType = NN.ActivationType.ReLU
};
NN network = new NN(config);Performs forward pass through the network.
Parameters:
input(float[]): Input vector
Returns:
List<float>: Network output (Q-values)
Throws:
ArgumentException: If input size doesn't match network input size
Example:
float[] state = {1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f, 11f, 12f, 13f, 14f};
List<float> qValues = network.calcNet(state);
int bestAction = qValues.IndexOf(qValues.Max());Trains the network on a single transition.
Parameters:
transition(Transition): State-action-reward transition
Example:
NN.Transition transition = new NN.Transition
{
state = currentState,
action = selectedAction,
reward = receivedReward
};
network.Train(transition);Gets the current training loss.
Returns:
float: Current loss value
Gets the moving average loss.
Returns:
float: Average loss over recent training steps
Gets the complete loss history.
Returns:
List<float>: List of all recorded loss values
Gets the number of training steps performed.
Returns:
int: Total training steps
Gets a summary of network information.
Returns:
string: Formatted network information
Saves the network to a stream.
Parameters:
writer(StreamWriter): Output stream
Example:
using (StreamWriter writer = new StreamWriter("model.txt"))
{
network.Save(writer);
}Loads the network from a stream.
Parameters:
reader(StreamReader): Input stream
Example:
using (StreamReader reader = new StreamReader("model.txt"))
{
network.Load(reader);
}The RL class implements advanced deep Q-learning with modern techniques like Double DQN, target networks, and prioritized experience replay.
Selects an action using epsilon-greedy policy.
Parameters:
state(float[]): Current state vector
Returns:
int: Selected action index
Example:
float[] state = GetCurrentState();
int action = agent.Act(state);
ExecuteAction(action);Learns from a state-action-reward transition.
Parameters:
transition(Transition): Complete transition with next state and terminal flag
Example:
RL.Transition transition = new RL.Transition
{
state = currentState,
action = selectedAction,
reward = receivedReward,
nextState = nextState,
isTerminal = isEpisodeOver
};
agent.Observe(transition);Begins a new episode, resetting episode-specific metrics.
Example:
agent.StartEpisode();
// ... perform actions ...
agent.EndEpisode();Ends the current episode, updating performance statistics.
Example:
if (isEpisodeOver)
{
agent.EndEpisode();
}Saves the complete agent state to a file.
Example:
agent.SaveModel(); // Saves to Application.persistentDataPath/rl_model.txtLoads the complete agent state from a file.
Example:
agent.LoadModel(); // Loads from Application.persistentDataPath/rl_model.txtResets the agent to initial state.
Example:
agent.ResetAgent();Gets the current exploration rate.
Returns:
float: Current epsilon value
Gets the total number of training steps.
Returns:
int: Total training steps
Gets the current episode reward.
Returns:
float: Current episode reward
Gets the average reward over recent episodes.
Returns:
float: Average reward
Gets the average episode length.
Returns:
float: Average episode length
Gets the current size of the experience replay buffer.
Returns:
int: Number of stored experiences
Gets a summary of agent information.
Returns:
string: Formatted agent information
numInputs(int): Number of input neuronsnumHiddens(int): Number of hidden neurons per layernumOutputs(int): Number of output neuronsnumHiddenLayers(int): Number of hidden layerslearningRate(float): Learning rate for trainingbatchSize(int): Batch size for trainingexperienceReplaySize(int): Size of experience replay bufferuseBatchNormalization(bool): Enable batch normalizationuseDropout(bool): Enable dropout regularizationdropoutRate(float): Dropout rate (0.0-1.0)activationType(ActivationType): Activation function typeweightInitType(WeightInitType): Weight initialization methodoptimizerType(OptimizerType): Optimizer type
epsilonStart(float): Initial exploration rateepsilonEnd(float): Final exploration rateepsilonDecay(float): Exploration decay rateepsilonDecaySteps(int): Steps for epsilon decaylearningRate(float): Learning rategamma(float): Discount factortargetUpdateFrequency(int): Target network update frequencyexperienceReplaySize(int): Experience replay buffer sizebatchSize(int): Training batch sizeuseDoubleDQN(bool): Enable Double DQNuseTargetNetwork(bool): Enable target networkusePrioritizedReplay(bool): Enable prioritized experience replayprioritizedReplayAlpha(float): Prioritized replay alpha parameterprioritizedReplayBeta(float): Prioritized replay beta parameterprioritizedReplayBetaIncrement(float): Beta increment ratenetworkConfig(NetworkConfig): Neural network configuration
Sigmoid: Sigmoid activation functionReLU: Rectified Linear UnitLeakyReLU: Leaky Rectified Linear UnitTanh: Hyperbolic tangent
Random: Random weight initializationXavier: Xavier/Glorot initializationHe: He initialization
SGD: Stochastic Gradient DescentAdam: Adam optimizerRMSprop: RMSprop optimizer
public struct Transition
{
public float[] state; // Current state
public int action; // Action taken
public float reward; // Reward received
}public struct Transition
{
public float[] state; // Current state
public int action; // Action taken
public float reward; // Reward received
public float[] nextState; // Next state
public bool isTerminal; // Episode termination flag
public float priority; // Priority for replay (internal)
public int index; // Buffer index (internal)
}ArgumentException: Invalid input parametersInvalidOperationException: Invalid operation stateFileNotFoundException: Save/load file not foundFormatException: Invalid file format
- Always validate input parameters
- Check for null references
- Handle file I/O exceptions
- Use try-catch blocks for critical operations
- Log errors for debugging
- Experience replay buffer: ~4MB for 10K transitions
- Neural network weights: ~1MB for 64x64x66 network
- Total memory footprint: ~10-20MB typical
- Forward pass: ~0.1ms per sample
- Backward pass: ~0.5ms per sample
- Batch training: ~10ms per batch of 32
- Target network update: ~1ms
- Use appropriate batch sizes (32-128)
- Enable batch normalization for stability
- Use Adam optimizer for faster convergence
- Monitor memory usage with large buffers
- Consider async training for large networks