tensorflow中的 tf.argmax() 和 tf.argmin() 函数使用

一、首先来看官方文档的解释:(https://tensorflow.google.cn/api_docs/python/tf/arg_max   官方文档地址)

(注意:在不同的版本中,有两种形式 arg_max 和 argmax,官方说明在以后会舍弃前者)

函数原型:

tf.arg_max(
    input,
    dimension,
    output_type=tf.int64,
    name=None
)

Returns the index with the largest value across dimensions of a tensor.  返回结果是该张量在某个维度上的最大值的索引号。

Args:      (各个参数的解释)

  • input: A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import tensorflow as tf import numpy as np import gym # 创建 CartPole 游戏环境 env = gym.make('CartPole-v1') # 定义神经网络模型 model = tf.keras.models.Sequential([ tf.keras.layers.Dense(24, activation='relu', input_shape=(4,)), tf.keras.layers.Dense(24, activation='relu'), tf.keras.layers.Dense(2, activation='linear') ]) # 定义优化器和损失函数 optimizer = tf.keras.optimizers.Adam() loss_fn = tf.keras.losses.MeanSquaredError() # 定义超参数 gamma = 0.99 # 折扣因子 epsilon = 1.0 # ε-贪心策略的初始 ε 值 epsilon_min = 0.01 # ε-贪心策略的最小 ε 值 epsilon_decay = 0.995 # ε-贪心策略的衰减值 batch_size = 32 # 每个批次的样本数量 memory = [] # 记忆池 # 定义动作选择函数 def choose_action(state): if np.random.rand() < epsilon: return env.action_space.sample() else: Q_values = model.predict(state[np.newaxis]) return np.argmax(Q_values[0]) # 定义经验回放函数 def replay(batch_size): batch = np.random.choice(len(memory), batch_size, replace=False) for index in batch: state, action, reward, next_state, done = memory[index] target = model.predict(state[np.newaxis]) if done: target[0][action] = reward else: Q_future = np.max(model.predict(next_state[np.newaxis])[0]) target[0][action] = reward + Q_future * gamma model.fit(state[np.newaxis], target, epochs=1, verbose=0) # 训练模型 for episode in range(1000): state = env.reset() done = False total_reward = 0 while not done: action = choose_action(state) next_state, reward, done, _ = env.step(action) memory.append((state, action, reward, next_state, done)) state = next_state total_reward += reward if len(memory) > batch_size: replay(batch_size) epsilon = max(epsilon_min, epsilon * epsilon_decay) print("Episode {}: Score = {}, ε = {:.2f}".format(episode, total_reward, epsilon))next_state, reward, done, _ = env.step(action) ValueError: too many values to unpack (expected 4)优化代码
最新发布
05-24
问题出现在最后一个环节。根据 OpenAI Gym 的文档,CartPole-v1 环境的 step() 函数返回的是四个值,分别是下一个状态、本次动作的奖励、游戏是否结束和一些额外信息。而在原始代码使用了一个 _ 变量来占位,但实际上返回的值个数超过了 4,导致程序报错。解决这个问题的方法是将 _ 变量改成一个列表变量,如下所示: ```python next_state, reward, done, info = env.step(action) ``` 同时,建议将神经网络模型的优化器改成 RMSprop,这是一个更加适合强化学习问题的优化器。最后,为了更好地观察训练效果,可以将每个回合的得分输出到日志,而不是只输出最后一个回合的得分。下面是修改后的代码: ```python import tensorflow as tf import numpy as np import gym # 创建 CartPole 游戏环境 env = gym.make('CartPole-v1') # 定义神经网络模型 model = tf.keras.models.Sequential([ tf.keras.layers.Dense(24, activation='relu', input_shape=(4,)), tf.keras.layers.Dense(24, activation='relu'), tf.keras.layers.Dense(2, activation='linear') ]) # 定义优化器和损失函数 optimizer = tf.keras.optimizers.RMSprop(learning_rate=0.001) loss_fn = tf.keras.losses.MeanSquaredError() # 定义超参数 gamma = 0.99 # 折扣因子 epsilon = 1.0 # ε-贪心策略的初始 ε 值 epsilon_min = 0.01 # ε-贪心策略的最小 ε 值 epsilon_decay = 0.995 # ε-贪心策略的衰减值 batch_size = 32 # 每个批次的样本数量 memory = [] # 记忆池 # 定义动作选择函数 def choose_action(state): if np.random.rand() < epsilon: return env.action_space.sample() else: Q_values = model.predict(state[np.newaxis]) return np.argmax(Q_values[0]) # 定义经验回放函数 def replay(batch_size): batch = np.random.choice(len(memory), batch_size, replace=False) for index in batch: state, action, reward, next_state, done = memory[index] target = model.predict(state[np.newaxis]) if done: target[0][action] = reward else: Q_future = np.max(model.predict(next_state[np.newaxis])[0]) target[0][action] = reward + Q_future * gamma model.fit(state[np.newaxis], target, epochs=1, verbose=0, optimizer=optimizer, loss=loss_fn) # 训练模型 for episode in range(1000): state = env.reset() done = False total_reward = 0 while not done: action = choose_action(state) next_state, reward, done, info = env.step(action) memory.append((state, action, reward, next_state, done)) state = next_state total_reward += reward if len(memory) > batch_size: replay(batch_size) epsilon = max(epsilon_min, epsilon * epsilon_decay) print("Episode {}: Score = {:.2f}, ε = {:.2f}".format(episode, total_reward, epsilon)) ``` 注意,由于 RMSprop 的学习率比 Adam 更小,因此需要将其设为 0.001。如果学习率太高,会导致训练不稳定或不收敛。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值