簡體   English   中英

How to implement a numpy equation in the call of a tensorflow layer for a tensorflow model(無法將符號 tf.Tensor 轉換為 numpy 數組)

[英]How to implement a numpy equation in the call of a tensorflow layer for a tensorflow model (Cannot convert a symbolic tf.Tensor to a numpy array)

我在 tensorflow 中有這個層 class,我想在 numpy 中實現一個特定的等式,以便在調用 function 中返回。我有以下自定義層:

class PhysicalLayer(keras.layers.Layer):
    def __init__(self, units=32):
        super(PhysicalLayer, self).__init__()
        self.units = units

    def build(self, input_shape):
        self.w = self.add_weight(
            shape=(input_shape[-1], self.units),
            initializer="random_normal",
            trainable=True,
        )
        self.b = self.add_weight(
            shape=(self.units,), initializer="random_normal", trainable=True
        )

    def call(self, inputs):
        rotationSpeedSquare = tf.math.square(rotationSpeed)
        maximumVibration = tf.convert_to_tensor(np.max(inputs))
        stiff = rotationSpeedSquare/maximumVibration
        stiff.astype('float32')
        return tf.matmul(stiff, self.w) + self.b

該層然后通過以下方式在 model 中實現:

class model(tf.keras.Model):

    def __init__(self, num_classes=50):
        super(model, self).__init__()
        self.dense1  = tf.keras.layers.Dense(num_classes, activation=tf.nn.relu)
        self.physical = PhysicalLayer()
        self.dense2  = tf.keras.layers.Dense(64, activation=tf.nn.relu)
        self.dense3  = tf.keras.layers.Dense(32, activation=tf.nn.relu)
        self.dense4  = tf.keras.layers.Dense(1, activation=tf.nn.relu)


    def call(self, inputs):
        x = self.dense1(inputs)
        x = self.physical(x)
        x = self.dense2(x)
        x = self.dense3(x)
        
        return self.dense4(x)

我首先關心的問題之一是我是否正確地執行了這個 model class 因為我剛剛學會了如何去做。 通過嘗試將這個 model 與訓練集相匹配(這是 numpy 數組,dtype = float32,大小為 (72367, 50))

model = model()
model.compile(optimizer='adam', loss='mae', metrics=[tf.keras.metrics.RootMeanSquaredError()])
model.fit(a, b, batch_size=32, epochs=2, verbose=2)

我收到以下錯誤:

NotImplementedError: Cannot convert a symbolic tf.Tensor (model_18/dense_72/Relu:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported.

謝謝

使用tf.math.reduce_max獲取張量的最大值:

    def call(self, inputs):
        rotationSpeedSquare = tf.math.square(rotationSpeed)
        maximumVibration = tf.math.reduce_max(inputs, axis=1, keepdims=True)

        stiff = rotationSpeedSquare / maximumVibration
        return tf.matmul(stiff, self.w) + self.b

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM