Git Product home page Git Product logo

cpo's People

Contributors

dobro12 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cpo's Issues

Running Inference on a trained model

How can I inference a trained model?

I tried the code below, but it did not work. I cannot find what is the issue.

import torch
import argparse
from env import Env
from agent import Agent

def inference(saved_model_path, num_episodes):
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    seed = 10
    max_ep_len = 1000
    max_steps = 4000
    
    # Load the trained agent and its checkpoint
    loaded_checkpoint = torch.load(saved_model_path, map_location=device)
    
    env_name = "Safexp-PointGoal1-v0"
    env = Env(env_name, seed, max_ep_len)

    args = {
        'agent_name':'CPO',
        'save_name':'',
        'discount_factor':0.99,
        'hidden1':512,
        'hidden2':512,
        'v_lr':2e-4,
        'cost_v_lr':2e-4,
        'value_epochs':200,
        'batch_size':10000,
        'num_conjugate':10,
        'max_decay_num':10,
        'line_decay':0.8,
        'max_kl':0.001,
        'damping_coeff':0.01,
        'gae_coeff':0.97,
        'cost_d':25.0/1000.0,
    }
    
    # Initialize the agent with the necessary arguments
    agent = Agent(env, device, args)
    
    agent.policy.load_state_dict(loaded_checkpoint['policy'])
    agent.value.load_state_dict(loaded_checkpoint['value'])
    agent.cost_value.load_state_dict(loaded_checkpoint['cost_value'])
    
    for _ in range(num_episodes):
        state = env.reset()
        total_reward = 0
        
        for step in range(max_steps):
            state_tensor = torch.tensor(state, device=device, dtype=torch.float)
            action_tensor, _ = agent.getAction(state_tensor, is_train=False)
            action = action_tensor.detach().cpu().numpy()
            
            next_state, reward, done, _ = env.step(action)
            total_reward += reward
            
            state = next_state
            
            if done:
                print(f"Episode reward: {total_reward}")
                break

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Inference using a saved model')
    parser.add_argument('saved_model_path', type=str, help='Path to the saved model checkpoint')
    parser.add_argument('--num_episodes', type=int, default=10, help='Number of episodes for inference')
    args = parser.parse_args()
    
    inference(args.saved_model_path, args.num_episodes)


Error:

Traceback (most recent call last):
  File "inference.py", line 69, in <module>
    inference(args.saved_model_path, args.num_episodes)
  File "inference.py", line 39, in inference
    agent = Agent(env, device, args)
  File ".../CPO/torch/agent.py", line 84, in __init__
    self.load()
  File ".../CPO/torch/agent.py", line 367, in load
    os.makedirs(self.checkpoint_dir)
  File ".../anaconda3/envs/cpo-only-env/lib/python3.6/os.py", line 220, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/checkpoint'

TIA

how to run this code

I've been trying to run this for weeks, and found it hard to build a envrionment to run this.
can anyone provide a requirement.txt or a environment.yml to implement this code ?

Thanks!

"train. Py"

Hello, I encountered this error when running "train. Py":
Traceback (most recent call last):
File "D:/Users/zhangsunan/Desktop/CPO-master (3)/tf1/train.py", line 205, in
train()
File "D:/Users/zhangsunan/Desktop/CPO-master (3)/tf1/train.py", line 67, in train
env = gym.make(env_name)
File "D:\Anaconda3\envs\cpo2\lib\site-packages\gym\envs\registration.py", line 235, in make
return registry.make(id, kwargs)
File "D:\Anaconda3\envs\cpo2\lib\site-packages\gym\envs\registration.py", line 129, in make
env = spec.make(kwargs)
File "D:\Anaconda3\envs\cpo2\lib\site-packages\gym\envs\registration.py", line 90, in make
env = cls(_kwargs)
File "D:\Anaconda3\envs\cpo2\lib\site-packages\safety_gym\envs\engine.py", line 316, in init
self.seed(self._seed)
File "D:\Anaconda3\envs\cpo2\lib\site-packages\safety_gym\envs\engine.py", line 551, in seed
self._seed = np.random.randint(2
32) if seed is None else seed
File "mtrand.pyx", line 746, in numpy.random.mtrand.RandomState.randint
File "_bounded_integers.pyx", line 1336, in numpy.random._bounded_integers._rand_int32
ValueError: high is out of bounds for int32

I don't have a solution at the moment. How can I solve it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.