Convert Pytorch DDPG to Tensorflow










0














I found this DDPG implementation and I would like to convert it in Tensorflow:
https://github.com/higgsfield/RL-Adventure-2/blob/master/5.ddpg.ipynb



I am using Eager Execution and I have some problems in implementing the ddpg update function. I might have made some mistakes but I cannot find them



--- PYTORCH ---



def ddpg_update(batch_size, 
gamma = 0.99,
min_value=-np.inf,
max_value=np.inf,
soft_tau=1e-2):

state, action, reward, next_state, done = replay_buffer.sample(batch_size)

state = torch.FloatTensor(state).to(device)
next_state = torch.FloatTensor(next_state).to(device)
action = torch.FloatTensor(action).to(device)
reward = torch.FloatTensor(reward).unsqueeze(1).to(device)
done = torch.FloatTensor(np.float32(done)).unsqueeze(1).to(device)

policy_loss = value_net(state, policy_net(state))
policy_loss = -policy_loss.mean()

next_action = target_policy_net(next_state)
target_value = target_value_net(next_state, next_action.detach())
expected_value = reward + (1.0 - done) * gamma * target_value
expected_value = torch.clamp(expected_value, min_value, max_value)

value = value_net(state, action)
value_loss = value_criterion(value, expected_value.detach())


policy_optimizer.zero_grad()
policy_loss.backward()
policy_optimizer.step()

value_optimizer.zero_grad()
value_loss.backward()
value_optimizer.step()

for target_param, param in zip(target_value_net.parameters(), value_net.parameters()):
target_param.data.copy_(
target_param.data * (1.0 - soft_tau) + param.data * soft_tau
)

for target_param, param in zip(target_policy_net.parameters(), policy_net.parameters()):
target_param.data.copy_(
target_param.data * (1.0 - soft_tau) + param.data * soft_tau
)


--- TENSORFLOW ---



def ddpg_update(batch_size, 
gamma = 0.99,
min_value=-np.inf,
max_value=np.inf,
soft_tau=1e-2):

state, action, reward, next_state, done = replay_buffer.sample(batch_size)

state = np.reshape(state, (batch_size, state_dim))
next_state = np.reshape(next_state, (batch_size, state_dim))
action = np.reshape(action, (batch_size, action_dim))
done = np.reshape(done, (batch_size, 1))


t_state = tf.convert_to_tensor(state, dtype=tf.float32)
t_action = tf.convert_to_tensor(action, dtype=tf.float32)
t_reward = tf.convert_to_tensor(reward, dtype=tf.float32)
t_next_state = tf.convert_to_tensor(next_state, dtype=tf.float32)
t_done = tf.convert_to_tensor(done, dtype=tf.float32)

with tf.GradientTape(persistent=True) as tape:
policy_loss = tf.reduce_mean(value_net.predict(t_state, policy_net.predict(t_state)))

t_next_action = target_policy_net.predict(t_next_state)
t_target_value = target_value_net.predict(t_next_state, t_next_action)
expected_value = t_reward + (1.0 - t_done) * gamma * t_target_value
expected_value = tf.clip_by_value(expected_value, tf.constant(min_value), tf.constant(max_value))

value = value_net.predict(t_state, t_action)
value_loss = value_criterion(value, expected_value)

policy_grads = tape.gradient(policy_loss, policy_net.variables)
value_grads = tape.gradient(value_loss, value_net.variables)
policy_optimizer.apply_gradients(zip(policy_grads, policy_net.variables))
value_optimizer.apply_gradients(zip(value_grads, value_net.variables))

#update value target
for x in range(len(value_net.variables)):
#targe = (1-tau)*target + tau*source
#target = target - tau*(target-source)
target_value_net.variables[x].assign_sub(soft_tau * (target_value_net.variables[x] - value_net.variables[x]))


#update policy target
for x in range(len(policy_net.variables)):
target_policy_net.variables[x].assign_sub(soft_tau * (target_policy_net.variables[x] - policy_net.variables[x]))









share|improve this question























  • I set negative learning rate to the function to maximize the variable I called policy_loss
    – Alessio Ragno
    Nov 12 '18 at 19:49















0














I found this DDPG implementation and I would like to convert it in Tensorflow:
https://github.com/higgsfield/RL-Adventure-2/blob/master/5.ddpg.ipynb



I am using Eager Execution and I have some problems in implementing the ddpg update function. I might have made some mistakes but I cannot find them



--- PYTORCH ---



def ddpg_update(batch_size, 
gamma = 0.99,
min_value=-np.inf,
max_value=np.inf,
soft_tau=1e-2):

state, action, reward, next_state, done = replay_buffer.sample(batch_size)

state = torch.FloatTensor(state).to(device)
next_state = torch.FloatTensor(next_state).to(device)
action = torch.FloatTensor(action).to(device)
reward = torch.FloatTensor(reward).unsqueeze(1).to(device)
done = torch.FloatTensor(np.float32(done)).unsqueeze(1).to(device)

policy_loss = value_net(state, policy_net(state))
policy_loss = -policy_loss.mean()

next_action = target_policy_net(next_state)
target_value = target_value_net(next_state, next_action.detach())
expected_value = reward + (1.0 - done) * gamma * target_value
expected_value = torch.clamp(expected_value, min_value, max_value)

value = value_net(state, action)
value_loss = value_criterion(value, expected_value.detach())


policy_optimizer.zero_grad()
policy_loss.backward()
policy_optimizer.step()

value_optimizer.zero_grad()
value_loss.backward()
value_optimizer.step()

for target_param, param in zip(target_value_net.parameters(), value_net.parameters()):
target_param.data.copy_(
target_param.data * (1.0 - soft_tau) + param.data * soft_tau
)

for target_param, param in zip(target_policy_net.parameters(), policy_net.parameters()):
target_param.data.copy_(
target_param.data * (1.0 - soft_tau) + param.data * soft_tau
)


--- TENSORFLOW ---



def ddpg_update(batch_size, 
gamma = 0.99,
min_value=-np.inf,
max_value=np.inf,
soft_tau=1e-2):

state, action, reward, next_state, done = replay_buffer.sample(batch_size)

state = np.reshape(state, (batch_size, state_dim))
next_state = np.reshape(next_state, (batch_size, state_dim))
action = np.reshape(action, (batch_size, action_dim))
done = np.reshape(done, (batch_size, 1))


t_state = tf.convert_to_tensor(state, dtype=tf.float32)
t_action = tf.convert_to_tensor(action, dtype=tf.float32)
t_reward = tf.convert_to_tensor(reward, dtype=tf.float32)
t_next_state = tf.convert_to_tensor(next_state, dtype=tf.float32)
t_done = tf.convert_to_tensor(done, dtype=tf.float32)

with tf.GradientTape(persistent=True) as tape:
policy_loss = tf.reduce_mean(value_net.predict(t_state, policy_net.predict(t_state)))

t_next_action = target_policy_net.predict(t_next_state)
t_target_value = target_value_net.predict(t_next_state, t_next_action)
expected_value = t_reward + (1.0 - t_done) * gamma * t_target_value
expected_value = tf.clip_by_value(expected_value, tf.constant(min_value), tf.constant(max_value))

value = value_net.predict(t_state, t_action)
value_loss = value_criterion(value, expected_value)

policy_grads = tape.gradient(policy_loss, policy_net.variables)
value_grads = tape.gradient(value_loss, value_net.variables)
policy_optimizer.apply_gradients(zip(policy_grads, policy_net.variables))
value_optimizer.apply_gradients(zip(value_grads, value_net.variables))

#update value target
for x in range(len(value_net.variables)):
#targe = (1-tau)*target + tau*source
#target = target - tau*(target-source)
target_value_net.variables[x].assign_sub(soft_tau * (target_value_net.variables[x] - value_net.variables[x]))


#update policy target
for x in range(len(policy_net.variables)):
target_policy_net.variables[x].assign_sub(soft_tau * (target_policy_net.variables[x] - policy_net.variables[x]))









share|improve this question























  • I set negative learning rate to the function to maximize the variable I called policy_loss
    – Alessio Ragno
    Nov 12 '18 at 19:49













0












0








0







I found this DDPG implementation and I would like to convert it in Tensorflow:
https://github.com/higgsfield/RL-Adventure-2/blob/master/5.ddpg.ipynb



I am using Eager Execution and I have some problems in implementing the ddpg update function. I might have made some mistakes but I cannot find them



--- PYTORCH ---



def ddpg_update(batch_size, 
gamma = 0.99,
min_value=-np.inf,
max_value=np.inf,
soft_tau=1e-2):

state, action, reward, next_state, done = replay_buffer.sample(batch_size)

state = torch.FloatTensor(state).to(device)
next_state = torch.FloatTensor(next_state).to(device)
action = torch.FloatTensor(action).to(device)
reward = torch.FloatTensor(reward).unsqueeze(1).to(device)
done = torch.FloatTensor(np.float32(done)).unsqueeze(1).to(device)

policy_loss = value_net(state, policy_net(state))
policy_loss = -policy_loss.mean()

next_action = target_policy_net(next_state)
target_value = target_value_net(next_state, next_action.detach())
expected_value = reward + (1.0 - done) * gamma * target_value
expected_value = torch.clamp(expected_value, min_value, max_value)

value = value_net(state, action)
value_loss = value_criterion(value, expected_value.detach())


policy_optimizer.zero_grad()
policy_loss.backward()
policy_optimizer.step()

value_optimizer.zero_grad()
value_loss.backward()
value_optimizer.step()

for target_param, param in zip(target_value_net.parameters(), value_net.parameters()):
target_param.data.copy_(
target_param.data * (1.0 - soft_tau) + param.data * soft_tau
)

for target_param, param in zip(target_policy_net.parameters(), policy_net.parameters()):
target_param.data.copy_(
target_param.data * (1.0 - soft_tau) + param.data * soft_tau
)


--- TENSORFLOW ---



def ddpg_update(batch_size, 
gamma = 0.99,
min_value=-np.inf,
max_value=np.inf,
soft_tau=1e-2):

state, action, reward, next_state, done = replay_buffer.sample(batch_size)

state = np.reshape(state, (batch_size, state_dim))
next_state = np.reshape(next_state, (batch_size, state_dim))
action = np.reshape(action, (batch_size, action_dim))
done = np.reshape(done, (batch_size, 1))


t_state = tf.convert_to_tensor(state, dtype=tf.float32)
t_action = tf.convert_to_tensor(action, dtype=tf.float32)
t_reward = tf.convert_to_tensor(reward, dtype=tf.float32)
t_next_state = tf.convert_to_tensor(next_state, dtype=tf.float32)
t_done = tf.convert_to_tensor(done, dtype=tf.float32)

with tf.GradientTape(persistent=True) as tape:
policy_loss = tf.reduce_mean(value_net.predict(t_state, policy_net.predict(t_state)))

t_next_action = target_policy_net.predict(t_next_state)
t_target_value = target_value_net.predict(t_next_state, t_next_action)
expected_value = t_reward + (1.0 - t_done) * gamma * t_target_value
expected_value = tf.clip_by_value(expected_value, tf.constant(min_value), tf.constant(max_value))

value = value_net.predict(t_state, t_action)
value_loss = value_criterion(value, expected_value)

policy_grads = tape.gradient(policy_loss, policy_net.variables)
value_grads = tape.gradient(value_loss, value_net.variables)
policy_optimizer.apply_gradients(zip(policy_grads, policy_net.variables))
value_optimizer.apply_gradients(zip(value_grads, value_net.variables))

#update value target
for x in range(len(value_net.variables)):
#targe = (1-tau)*target + tau*source
#target = target - tau*(target-source)
target_value_net.variables[x].assign_sub(soft_tau * (target_value_net.variables[x] - value_net.variables[x]))


#update policy target
for x in range(len(policy_net.variables)):
target_policy_net.variables[x].assign_sub(soft_tau * (target_policy_net.variables[x] - policy_net.variables[x]))









share|improve this question















I found this DDPG implementation and I would like to convert it in Tensorflow:
https://github.com/higgsfield/RL-Adventure-2/blob/master/5.ddpg.ipynb



I am using Eager Execution and I have some problems in implementing the ddpg update function. I might have made some mistakes but I cannot find them



--- PYTORCH ---



def ddpg_update(batch_size, 
gamma = 0.99,
min_value=-np.inf,
max_value=np.inf,
soft_tau=1e-2):

state, action, reward, next_state, done = replay_buffer.sample(batch_size)

state = torch.FloatTensor(state).to(device)
next_state = torch.FloatTensor(next_state).to(device)
action = torch.FloatTensor(action).to(device)
reward = torch.FloatTensor(reward).unsqueeze(1).to(device)
done = torch.FloatTensor(np.float32(done)).unsqueeze(1).to(device)

policy_loss = value_net(state, policy_net(state))
policy_loss = -policy_loss.mean()

next_action = target_policy_net(next_state)
target_value = target_value_net(next_state, next_action.detach())
expected_value = reward + (1.0 - done) * gamma * target_value
expected_value = torch.clamp(expected_value, min_value, max_value)

value = value_net(state, action)
value_loss = value_criterion(value, expected_value.detach())


policy_optimizer.zero_grad()
policy_loss.backward()
policy_optimizer.step()

value_optimizer.zero_grad()
value_loss.backward()
value_optimizer.step()

for target_param, param in zip(target_value_net.parameters(), value_net.parameters()):
target_param.data.copy_(
target_param.data * (1.0 - soft_tau) + param.data * soft_tau
)

for target_param, param in zip(target_policy_net.parameters(), policy_net.parameters()):
target_param.data.copy_(
target_param.data * (1.0 - soft_tau) + param.data * soft_tau
)


--- TENSORFLOW ---



def ddpg_update(batch_size, 
gamma = 0.99,
min_value=-np.inf,
max_value=np.inf,
soft_tau=1e-2):

state, action, reward, next_state, done = replay_buffer.sample(batch_size)

state = np.reshape(state, (batch_size, state_dim))
next_state = np.reshape(next_state, (batch_size, state_dim))
action = np.reshape(action, (batch_size, action_dim))
done = np.reshape(done, (batch_size, 1))


t_state = tf.convert_to_tensor(state, dtype=tf.float32)
t_action = tf.convert_to_tensor(action, dtype=tf.float32)
t_reward = tf.convert_to_tensor(reward, dtype=tf.float32)
t_next_state = tf.convert_to_tensor(next_state, dtype=tf.float32)
t_done = tf.convert_to_tensor(done, dtype=tf.float32)

with tf.GradientTape(persistent=True) as tape:
policy_loss = tf.reduce_mean(value_net.predict(t_state, policy_net.predict(t_state)))

t_next_action = target_policy_net.predict(t_next_state)
t_target_value = target_value_net.predict(t_next_state, t_next_action)
expected_value = t_reward + (1.0 - t_done) * gamma * t_target_value
expected_value = tf.clip_by_value(expected_value, tf.constant(min_value), tf.constant(max_value))

value = value_net.predict(t_state, t_action)
value_loss = value_criterion(value, expected_value)

policy_grads = tape.gradient(policy_loss, policy_net.variables)
value_grads = tape.gradient(value_loss, value_net.variables)
policy_optimizer.apply_gradients(zip(policy_grads, policy_net.variables))
value_optimizer.apply_gradients(zip(value_grads, value_net.variables))

#update value target
for x in range(len(value_net.variables)):
#targe = (1-tau)*target + tau*source
#target = target - tau*(target-source)
target_value_net.variables[x].assign_sub(soft_tau * (target_value_net.variables[x] - value_net.variables[x]))


#update policy target
for x in range(len(policy_net.variables)):
target_policy_net.variables[x].assign_sub(soft_tau * (target_policy_net.variables[x] - policy_net.variables[x]))






tensorflow pytorch reinforcement-learning openai-gym q-learning






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 '18 at 19:46

























asked Nov 12 '18 at 17:02









Alessio Ragno

165116




165116











  • I set negative learning rate to the function to maximize the variable I called policy_loss
    – Alessio Ragno
    Nov 12 '18 at 19:49
















  • I set negative learning rate to the function to maximize the variable I called policy_loss
    – Alessio Ragno
    Nov 12 '18 at 19:49















I set negative learning rate to the function to maximize the variable I called policy_loss
– Alessio Ragno
Nov 12 '18 at 19:49




I set negative learning rate to the function to maximize the variable I called policy_loss
– Alessio Ragno
Nov 12 '18 at 19:49

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53266861%2fconvert-pytorch-ddpg-to-tensorflow%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53266861%2fconvert-pytorch-ddpg-to-tensorflow%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Barbados

How to read a connectionString WITH PROVIDER in .NET Core?

Node.js Script on GitHub Pages or Amazon S3