在 Keras 中自定义损失函数中重塑张量

jee*_*a_v 3 python machine-learning deep-learning keras tensorflow

重塑张量时我得到 None 类型。当使用损失函数和优化器编译模型时(开始训练之前)会发生这种情况。我该怎么办?

错误:

TypeError: Failed to convert object of type <class 'tuple'> to Tensor. Contents: (None, -1). Consider casting elements to a supported type.  
Run Code Online (Sandbox Code Playgroud)

自定义损失函数:

def custom_loss(y_true, y_pred):

        y_pred = K.reshape(y_pred, (K.get_variable_shape(y_pred)[0], -1))
        y_true = K.reshape(y_true, (K.get_variable_shape(y_true)[0], -1))
        y_pred = K.std(y_pred, axis=0)
        y_true = K.std(y_true, axis=0)
        loss = (1/2) * (y_pred - y_true) ** 2
        loss = K.mean(loss)

        return loss
Run Code Online (Sandbox Code Playgroud)

Gab*_*abe 5

发生这种情况是因为您的y_truey_pred张量的形状未正确定义。None这里意味着张量的形状没有严格设置,但它可以根据我们看不到的先前操作而变化。或者你只是像这样初始化了你的张量。

如何修复它:

  • 首先,您应该研究 or 如何y_true获取y_pred其形状并避免获得 None 形状,因此张量将具有确定的行数和列数

例子:

您的损失函数适用于正确的输入:

import tensorflow as tf
from keras import backend as K


def custom_loss(y_true, y_pred):
    y_pred = K.reshape(y_pred, (K.get_variable_shape(y_pred)[0], -1))
    y_true = K.reshape(y_true, (K.get_variable_shape(y_true)[0], -1))
    y_pred = K.std(y_pred, axis=0)
    y_true = K.std(y_true, axis=0)
    loss = (1 / 2) * (y_pred - y_true) ** 2

    return loss


a = tf.constant([[1.0, 2., 3.]])
b = tf.constant([[1., 2., 3.]])
loss = custom_loss(a, b)
loss = tf.Print(loss, [loss], "loss")

with tf.Session() as sess:
    _ = sess.run([loss])
Run Code Online (Sandbox Code Playgroud)

但是当使用我没有定义形状的占位符时,会抛出相同的异常

a = tf.placeholder(tf.float32, (None, 32))
Run Code Online (Sandbox Code Playgroud)