且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

渴望执行功能的输入不能是Keras符号张量

更新时间:2023-12-03 11:00:10

另一种解决方案是将权重作为附加的输出特征而不是输入特征。

One alternative solution is to pass weights as additional output features rather than input features.

完全没有权重相关的任何权重,权重仅出现在损失函数和 .fit()调用中:

This keeps the model completely free of anything weights related, and the weights appear only in the loss function and the .fit() call:

import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, losses, models

data_x = 2 * np.ones((7, 11, 15, 3), dtype=float)
data_y = 5 * np.ones((7, 9, 13, 5), dtype=float)

x = layers.Input(data_x.shape[1:])
y = layers.Conv2D(5, kernel_size=3)(x)
model = models.Model(inputs=x, outputs=y)


def loss(y_true, y_pred):
    (y_true, w) = tf.split(y_true, num_or_size_splits=[-1, 1], axis=-1)
    loss = tf.squeeze(w, axis=-1) * losses.mse(y_true, y_pred)

    tf.print(tf.math.reduce_mean(y_true), "== 5")
    tf.print(tf.math.reduce_mean(w), "== 3")

    return loss


model.compile(loss=loss)

data_w = 3 * np.ones((7, 9, 13, 1), dtype=float)
data_yw = np.concatenate((data_y, data_w), axis=-1)
model.fit(data_x, data_yw)

一个缺点仍然是,合并 y numpy.stack()中> w ,因此将进一步欣赏类似于TensorFlow的东西。

One drawback still is that you need to manipulate (potentially) large arrays when merging y and w in numpy.stack(), so anymore more TensorFlow-like will be appreciated.