Tensorflow.js 不接受 SymbolicTensor 作为输入

Tensorflow.js SymbolicTensor not accepted as an input

我正在尝试重现 Tensorflow.js 中的 A2C 算法,我想我已经成功地重现了演员和评论家的模型。

但是,我使用单一热编码来提供我的当前状态作为我模型的输入,在此之前,我使用 tf.input() 函数设置输入, returns 一个 SymbolicTensor(对我来说,它的作用与 Python API 中的 tf.placeholder 相同)。

tf.oneHot 函数只接受 tf.Tensor 对象作为第一个参数,我在文档中看不到解决方法。我还以为tf.SymbolicTensor是继承自tf.Tensor,但好像不是这样的

class A2CAgent {
    constructor(state_size, action_size) {
        this.render = false;
        this.state_size = state_size;
        this.action_size = action_size;
        this.value_size = 1;

        this.discount_factor = 0.99;
        this.actor_learningr = 0.001;
        this.critic_learningr = 0.005;

        this.actor = this.build_actor();
        #this.critic = this.build_critic();

    }

    build_actor() {
        const model = tf.sequential();

        this.state = tf.input({name:"state", dtype:'int32', shape:[]});
        let one_hot = tf.oneHot(this.state, this.state_size); //Pb ne prend pas de placeholder
        model.add(tf.layers.dense({
            units: 24,
            activation: 'relu',
            kernelInitializer:'glorotUniform',
            inputDim:tf.expandDims(one_hot, 0),
        }));

        model.add(tf.layers.dense({
            units: this.action_size,
            activation:'softmax',
            kernelInitializer:'glorotUniform',
        }));

        model.summary();

        model.compile({
            optimizer: tf.train.adam(this.actor_learningr),
            loss:tf.losses.softmaxCrossEntropy
        });

        return model;
    }
}

我希望这段代码执行得很好,但我却收到了这个错误:

Error: Argument 'indices' passed to 'oneHot' must be a Tensor or TensorLike, but got 'SymbolicTensor'

知道如何解决这个问题吗?

这里有几个问题:

tf.oneHot 接受多个参数,但所需的 2 个 indicesdepth 分别是 tensor1dnumber 类型。 要创建密集层,您不必传入 onehot 编码张量,尤其是在使用顺序模型时。您可能必须为模型提供一个单热张量,但只有当您在训练期间使用特征和标签数据拟合模型时才会发生这种情况。

tf.js 没有类似占位符的 tensorflow 方法,它先构建一个图,然后再在会话中执行它。您可以参考此 ,它强调了两种实现之间的这种差异

此外,请注意 inputDim 应该是一个数字而不是张量