Upload README.md with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236---language: entags:- evolutionary-strategy- cma-es- gymnasium- cartpole- optimizationlibrary_name: customdatasets:- gymnasium/CartPole-v1metrics:- mean_episode_lengthmodel-index:- name: CartPoleresults:- task:type: optimizationname: CartPole-v1dataset:name: gymnasium/CartPole-v1type: gymnasiummetrics:- type: mean_episode_lengthvalue: 500name: Mean Episode Lengthlicense: mitpipeline_tag: reinforcement-learning---> **Renamed:** previously `harpertoken/harpertoken-cartpole`. The old ID still redirects.# CartPole SolutionThis model solves CartPole-v1 using CMA-ES with a linear policy.### Training Convergence*Figure: Training convergence showing the mean fitness (episode length) across generations. The model achieves optimal performance (500 steps) within 3 generations.*## Model Details### Model DescriptionThis is a linear policy model for the CartPole-v1 environment that:- Uses a simple weight matrix to map 4D state inputs to 2D action outputs- Achieves optimal performance (500/500 steps) consistently- Was optimized using CMA-ES, requiring only 3 generations for convergence- Demonstrates sample-efficient learning for the CartPole balancing task```pythondef get_action(self, observation):observation = np.array(observation, dtype=np.float32)action_scores = np.dot(observation, self.weights)return int(np.argmax(action_scores))```- **Developed by:** Niladri Das- **Model type:** Linear Policy- **Language:** Python- **License:** MIT- **Finetuned from model:** No (trained from scratch)### Model Sources- **Hugging Face:** https://huggingface.co/harpertoken/harpertoken-cartpole## Uses### Direct UseThe model is designed for:1. Solving the CartPole-v1 environment from Gymnasium2. Demonstrating CMA-ES optimization for RL tasks3. Serving as a baseline for comparison with other algorithms4. Educational purposes in evolutionary strategies### Out-of-Scope UseThe model should not be used for:1. Complex control tasks beyond CartPole2. Real-world robotics applications3. Tasks requiring non-linear policies4. Environments with partial observability## Bias, Risks, and Limitations### Technical Limitations- Limited to CartPole-v1 environment- Requires full state observation- Linear policy architecture- No transfer learning capability- Environment-specific solution### Performance Limitations- May not handle significant environment variations- No adaptation to changing dynamics- Limited by linear policy capacity- Requires precise state information### RecommendationsUsers should:1. Only use for CartPole-v1 environment2. Ensure full state observability3. Understand the limitations of linear policies4. Consider more complex architectures for other tasks5. Validate performance in their specific setup## How to Get Started with the Model### Method 1: Using the CMAESAgent Class```pythonfrom model import CMAESAgent# Load the modelagent = CMAESAgent.from_pretrained("harpertoken/harpertoken-cartpole")# Evaluatemean_reward, std_reward = agent.evaluate(num_episodes=5)print(f"Mean reward: {mean_reward:.2f} ± {std_reward:.2f}")```### Method 2: Manual Implementation```pythonimport numpy as npfrom gymnasium import make# Load model weightsweights = np.load('model_weights.npy') # 4x2 matrix# Create environmentenv = make('CartPole-v1')# Run inferencedef get_action(observation):logits = observation @ weightsreturn int(np.argmax(logits))observation, _ = env.reset()while True:action = get_action(observation)observation, reward, done, truncated, info = env.step(action)if done or truncated:break```## Training Details### Training Data- **Environment:** Gymnasium CartPole-v1- **State Space:** 4D continuous (cart position, velocity, pole angle, angular velocity)- **Action Space:** 2D discrete (left, right)- **Reward:** +1 for each step, max 500 steps- **Episode Termination:** Pole angle > 15°, cart position > 2.4, or 500 steps reached- **Training Approach:** Direct environment interaction (no pre-collected dataset)### Training Procedure#### Training Hyperparameters- **Algorithm:** CMA-ES- **Population size:** 16- **Number of generations:** 100 (early convergence by generation 3)- **Initial step size:** 0.5- **Parameters:** 8 (4x2 weight matrix)- **Training regime:** Single precision (fp32)#### Hardware Requirements- **CPU:** Single core sufficient- **Memory:** <100MB RAM- **GPU:** Not required- **Training time:** ~5 minutes on standard CPU### Evaluation#### Testing Data & Metrics- **Environment:** Same as training (CartPole-v1)- **Episodes:** 100 test episodes- **Metrics:** Episode length, success rate#### Results- **Average Episode Length:** 500.0 ±0.0- **Success Rate:** 100%- **Convergence:** Achieved in 3 generations- **Final Population Mean:** 500.00- **Best Performance:** 500/500 consistently## Implementation DetailsThe implementation employs a straightforward linear policy:```pythonclass CMAESAgent:def __init__(self, env_name):self.env = gym.make(env_name)self.observation_space = self.env.observation_space.shape[0] # 4 for CartPoleself.action_space = self.env.action_space.n # 2 for CartPoleself.num_params = self.observation_space * self.action_space # 8 total parametersself.weights = Nonedef get_action(self, observation):observation = np.array(observation, dtype=np.float32)action_scores = np.dot(observation, self.weights)return int(np.argmax(action_scores))```The model's simplicity demonstrates that CartPole's optimal control policy is approximately linear in the state variables.## Environmental Impact- **Training time:** ~5 minutes- **Hardware:** Standard CPU- **Energy consumption:** Negligible (<0.001 kWh)- **CO2 emissions:** Minimal (<0.001 kg)## Citation**BibTeX:**```bibtex@misc{das2025cartpole,author = {Niladri Das},title = {CartPole Solution},year = {2025},publisher = {Hugging Face},journal = {Hugging Face Model Hub},howpublished = {https://huggingface.co/harpertoken/harpertoken-cartpole}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051---license: mitlanguage: enlibrary_name: custompipeline_tag: reinforcement-learningdatasets:- gymnasium/CartPole-v1tags:- cma-es- cartpole- evolutionary-strategy- gymnasium---> Previously published as `harpertoken/harpertoken-cartpole`. The old identifier still redirects here.# poleA linear policy for `CartPole-v1`, found by covariance matrix adaptation evolution strategy. The policy is a single 4-by-2 matrix of weights mapping the four-dimensional observation — cart position, cart velocity, pole angle, pole angular velocity — to a score for each of the two actions, with the larger score taken. Eight numbers in total.Evaluating `model.npy` over 100 episodes, resetting with seeds 0 through 99, the mean episode length is 500.00 with a standard deviation of 0.00; all 100 episodes reach the environment's 500-step ceiling. Since 500 is the maximum reward `CartPole-v1` permits, this is the ceiling rather than a measured score against a baseline, and there is nothing further to optimise.The repository contains three representations of a solution and they are not identical. `model.npy` is the one that achieves the result above and is the one to use. It is stored flat, as eight float64 values; the matrix form is `reshape(4, 2)`, which the previous version of this card did not say and which its example code got wrong by treating the file as a matrix directly. `cmaes_model.npy` and `cmaes_model.pth` hold the CMA-ES state — weights, a recorded fitness of 500.0, and the intended shape — but they describe a different weight vector. Measured over the same 100 episodes that vector averages 498.99 with a standard deviation of 5.93, touching 500 in 96 episodes and falling as low as 451. The recorded fitness of 500.0 is therefore slightly optimistic relative to what these weights actually do, and the two files should not be treated as interchangeable. Both `.npy` and `.pth` require `allow_pickle=True` / a permissive load to read.No Python code is included. The earlier card showed a `CMAESAgent` class and imported it `from model`, and referenced a `model_weights.npy`; neither the module nor that filename has existed in this repository. What is here is the weight arrays, a convergence figure under `assets/`, and a short video of the policy running.## Usage```pythonimport numpy as np, gymnasium as gymweights = np.load("model.npy").reshape(4, 2) # stored flat as 8 float64 valuesenv = gym.make("CartPole-v1")obs, _ = env.reset(seed=0)steps = 0while True:obs, reward, terminated, truncated, info = env.step(int(np.argmax(obs @ weights)))steps += 1if terminated or truncated:breakprint(steps)```## LimitationsThis solves one environment, from full state observation, with a policy class of eight parameters. It does not transfer: change the dynamics, the observation space or the action space and the weights are meaningless, and there is no mechanism to relearn them. It says nothing in particular about linear policies in control — the earlier card claimed this result demonstrated that CartPole's optimal policy is approximately linear, which is a much broader claim than one successful parameter vector supports, and has been removed. `assets/training_convergence.png` plots mean fitness per generation; the search reached the ceiling within roughly three generations from a population of sixteen, which is unremarkable for a problem of this size and not evidence about CMA-ES in general.## AttributionCartPole-v1 is the classic control task from Barto, Sutton and Anderson, and the Gymnasium implementation is described in Towers et al., *Gymnasium: A Standard Interface for Reinforcement Learning Environments* (2024). CMA-ES follows Hansen, *The CMA Evolution Strategy: A Tutorial* (2016).
README.md+27-212