【问题标题】:How to convert a keras tensor to a numpy array如何将 keras 张量转换为 numpy 数组
【发布时间】:2021-08-25 02:22:05
【问题描述】:

我正在尝试创建一个 q-learning 国际象棋引擎,其中神经网络最后一层的输出(密度等于合法移动的数量)通过 argmax() 函数运行,该函数返回一个整数我用作存储合法移动的数组的索引。这是我的代码的一部分:

#imports

env = gym.make('ChessAlphaZero-v0')   #builds environment
obs = env.reset()
type(obs)

done = False   #game is not won

num_actions = len(env.legal_moves)   #array where legal moves are stored

obs = chess.Board() 

model = models.Sequential()

def dqn(board):
    
    #dense layers
    
    action = layers.Dense(num_actions)(layer5)
    
    i = np.argmax(action)
    move = env.legal_moves[i]

    return keras.Model(inputs=inputs, outputs=move)

但是当我运行代码时出现以下错误:

TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.

任何代码示例都将不胜感激,谢谢。

【问题讨论】:

  • 您不能在 Dense 对象上调用 np.argmax()。尝试将argmax 操作包装在Lambda 层中。参考this

标签: python arrays numpy keras deep-learning


【解决方案1】:

在 keras 中构建模型和转发输入的正确方法是这样的:

1.构建模型

model = models.Sequential()
model.add(layers.Input(observation_shape))
model.add(layers.Dense(units=128, activation='relu'))
model.add(layers.Dense(units=num_actions, activation='softmax'))
return model

inputs = layers.Input(observation_shape)
x = layers.Dense(units=128, activation='relu')(inputs)
outputs = layers.Dense(units=num_actions, activation='softmax')(x)

model = keras.Model(inputs, output)

两种方式都是平等的。

2。转发观察并采取最佳行动

action_values = model.predict(observation)
best_action_index = tf.argmax(action_values)
best_action = action_values[best_action_index]

在 keras 中自己实现 DQN 可能会非常令人沮丧。您可能想使用一个 DRL 框架,例如 tf_agents,它实现了许多代理: https://www.tensorflow.org/agents

此存储库包含用于 openai 健身房环境的干净且易于理解的 DQN 实现。此外,它还包含使用 tf_agents 库以及更复杂的代理的示例: https://github.com/kochlisGit/Tensorflow-DQN

【讨论】:

    猜你喜欢
    • 2019-03-19
    • 2020-01-23
    • 2021-05-31
    • 2021-01-08
    • 1970-01-01
    • 2020-08-17
    • 2021-10-17
    • 2018-11-28
    • 2019-06-13
    相关资源
    最近更新 更多