Sure! Below is a comprehensive guide to creating a Unity ML-Agents setup where a cube (CubeAgent) learns to navigate to a target food (TargetFood). The cube can turn left, turn right, move forward, and move backward. It receives observations from its environment (e.g., relative position to the food) and is trained using the PPO (Proximal Policy Optimization) algorithm. The agent is penalized the longer it takes to reach the food and is reset after 5 seconds if it fails to do so.
1. Setting Up the Unity Scene
Before diving into the script, ensure your Unity project has ML-Agents installed. If not, follow the ML-Agents installation guide.
Scene Setup:
-
Environment:
- Create a Plane to serve as the ground.
- Add walls or boundaries if needed to limit the agent's movement area.
-
Agent (Cube):
- Create a Cube (
CubeAgent) and add a Rigidbody component.
- Tag it appropriately (e.g., "Agent").
-
Target Food:
- Create another Cube or a different object to serve as the
TargetFood.
- Tag it as "Food".
-
Environment Controller:
- Create an empty GameObject named
EnvironmentController and attach the EnvironmentController.cs script (provided below) to manage spawning and resetting.
-
Camera:
- Add a Camera to visualize the environment from a suitable angle.
-
Add Behavior Parameters:
- On the
CubeAgent, add the Behavior Parameters component.
- Configure the observation space and action space as needed (the script below will handle actions and observations).
2. The CubeAgent.cs Script
This script handles the agent's behavior, observations, actions, rewards, and episode management.
using System.Collections;
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Sensors;
using Unity.MLAgents.Actuators;
public class CubeAgent : Agent
{
public float moveSpeed = 5f;
public float turnSpeed = 200f;
public float maxEpisodeTime = 5f;
private Rigidbody rb;
private EnvironmentController environment;
private float episodeStartTime;
public override void Initialize()
{
rb = GetComponent<Rigidbody>();
environment = GetComponentInParent<EnvironmentController>();
}
public override void OnEpisodeBegin()
{
// Reset velocity
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
// Reset position and rotation
transform.position = environment.GetRandomPosition();
transform.rotation = environment.GetRandomRotation();
// Reset the food position and rotation
environment.ResetFood();
// Reset the timer
episodeStartTime = Time.time;
}
public override void CollectObservations(VectorSensor sensor)
{
// Relative position of the food
Vector3 foodRelativePos = environment.food.transform.position - transform.position;
sensor.AddObservation(foodRelativePos.normalized); // 3 observations
// Agent's velocity
sensor.AddObservation(rb.velocity.x);
sensor.AddObservation(rb.velocity.z);
// Optional: Add distance to the food
sensor.AddObservation(foodRelativePos.magnitude);
}
public override void OnActionReceived(ActionBuffers actions)
{
// Actions: [0] Turn Left, [1] Turn Right, [2] Move Forward, [3] Move Backward
float turn = 0f;
float move = 0f;
if (actions.DiscreteActions[0] == 1)
{
turn = -1f;
}
if (actions.DiscreteActions[1] == 1)
{
turn = 1f;
}
if (actions.DiscreteActions[2] == 1)
{
move = 1f;
}
if (actions.DiscreteActions[3] == 1)
{
move = -1f;
}
// Apply turning
transform.Rotate(Vector3.up, turn * turnSpeed * Time.deltaTime);
// Apply movement
Vector3 forward = transform.forward * move * moveSpeed * Time.deltaTime;
rb.MovePosition(transform.position + forward);
// Time penalty
float timeElapsed = Time.time - episodeStartTime;
AddReward(-0.01f * Time.deltaTime); // Small negative reward each step
// Check for timeout
if (timeElapsed > maxEpisodeTime)
{
EndEpisode();
}
}
public override void Heuristic(in ActionBuffers actionsOut)
{
var discreteActions = actionsOut.DiscreteActions;
discreteActions.Array = new int[4];
// Simple keyboard controls for manual testing
if (Input.GetKey(KeyCode.LeftArrow))
{
discreteActions[0] = 1;
}
if (Input.GetKey(KeyCode.RightArrow))
{
discreteActions[1] = 1;
}
if (Input.GetKey(KeyCode.UpArrow))
{
discreteActions[2] = 1;
}
if (Input.GetKey(KeyCode.DownArrow))
{
discreteActions[3] = 1;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Food"))
{
// Reward for reaching the food
SetReward(1.0f);
EndEpisode();
}
}
}
3. The EnvironmentController.cs Script
This script manages the spawning and resetting of both the agent and the food at random positions and rotations.
using UnityEngine;
public class EnvironmentController : MonoBehaviour
{
public GameObject foodPrefab;
public GameObject food;
public Vector3 spawnAreaMin;
public Vector3 spawnAreaMax;
private void Start()
{
ResetFood();
}
public void ResetFood()
{
if (food != null)
{
Destroy(food);
}
Vector3 foodPos = GetRandomPosition();
Quaternion foodRot = GetRandomRotation();
food = Instantiate(foodPrefab, foodPos, foodRot, this.transform);
}
public Vector3 GetRandomPosition()
{
float x = Random.Range(spawnAreaMin.x, spawnAreaMax.x);
float y = 0.5f; // Assuming ground is at y=0
float z = Random.Range(spawnAreaMin.z, spawnAreaMax.z);
return new Vector3(x, y, z);
}
public Quaternion GetRandomRotation()
{
return Quaternion.Euler(0, Random.Range(0f, 360f), 0);
}
}
Setup Instructions for EnvironmentController:
- Attach
EnvironmentController.cs to EnvironmentController GameObject.
- Assign the
foodPrefab:
- Drag your
TargetFood prefab into the foodPrefab field in the Inspector.
- Define Spawn Area:
- Set
spawnAreaMin and spawnAreaMax to define the rectangular area where both the agent and food can spawn.
4. Configuring the Training (Hyperparameters)
Create a YAML configuration file (e.g., cube_agent.yaml) to define the PPO hyperparameters. Below is a recommended configuration, but feel free to tweak based on training performance.
behaviors:
CubeAgentBehavior:
trainer_type: ppo
hyperparameters:
batch_size: 1024
buffer_size: 10240
learning_rate: 3.0e-4
beta: 5.0e-3
epsilon: 0.2
lambd: 0.95
num_epoch: 3
learning_rate_schedule: linear
network_settings:
normalize: true
hidden_units: 128
num_layers: 2
reward_signals:
extrinsic:
gamma: 0.99
strength: 1.0
keep_checkpoints: 5
max_steps: 5e5
time_horizon: 64
summary_freq: 5000
Explanation of Hyperparameters:
- batch_size: Number of experiences sampled from the buffer for each training step.
- buffer_size: The number of experiences the agent collects before performing an update.
- learning_rate: The step size for the optimizer.
- beta: Coefficient for the entropy regularization (promotes exploration).
- epsilon: Clipping parameter for PPO.
- lambd: GAE (Generalized Advantage Estimation) parameter.
- num_epoch: Number of epochs to run when updating the network.
- learning_rate_schedule: Schedule for the learning rate (linear decay recommended).
- network_settings: Defines the neural network architecture.
- normalize: Whether to normalize observations.
- hidden_units: Number of neurons in each hidden layer.
- num_layers: Number of hidden layers.
- reward_signals: Defines how rewards are processed.
- gamma: Discount factor.
- strength: Weight of the extrinsic reward.
- keep_checkpoints: Number of checkpoints to keep.
- max_steps: Total number of training steps.
- time_horizon: Number of steps to collect before updating (related to buffer size).
- summary_freq: How often to record summaries.
5. Additional Configuration
Agent's Collider:
Ensure that both the agent and the food have appropriate colliders and that "Food" has a trigger collider to detect when the agent reaches it.
Physics Settings:
- Set the
Rigidbody of the agent to is Kinematic if you want to control movement entirely via script.
- Alternatively, use physics-based movement by applying forces.
6. Training the Agent
-
Create the Training Configuration:
- Save the YAML configuration (e.g.,
cube_agent.yaml) in the config directory of your ML-Agents project.
-
Start Training:
Open a terminal and navigate to your project directory. Run the following command:
mlagents-learn config/cube_agent.yaml --run-id=cube_run_001 --train
-
Play and Observe:
- Click the Play button in Unity to start the training process.
- Monitor the training progress in the terminal and TensorBoard (if set up).
7. Tips for Effective Training
- Reward Shaping: Ensure that the rewards are well-balanced. The small negative reward each step encourages the agent to find the food quickly.
- Observation Space: Providing normalized relative positions helps the agent generalize better.
- Action Space: Discrete actions are straightforward for simple movement. For more complex navigation, consider continuous actions.
- Environment Variability: Randomizing the spawn positions and rotations prevents the agent from memorizing specific patterns and encourages generalization.
8. Troubleshooting
- Agent Not Learning: Ensure that the observations provide sufficient information. You might need to include more environmental cues or adjust rewards.
- Sparse Rewards: If the agent rarely finds the food, consider adding intermediate rewards or increasing the episode length temporarily.
- Overfitting: Regularly randomize the environment to prevent the agent from overfitting to specific scenarios.
Conclusion
This setup provides a foundational framework for training a cube agent to navigate towards a target using Unity ML-Agents and PPO. By following the script and configuration guidelines, you can further expand the environment's complexity or tweak hyperparameters to achieve optimal training results.