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

时间:2018-11-08 07:39:13

标签: python tensorflow machine-learning keras deep-learning

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

错误:

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

自定义损失功能:

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

2 个答案:

答案 0 :(得分:3)

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

如何修复:

  • 首先,您应该研究y_truey_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])

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

a = tf.placeholder(tf.float32, (None, 32))

答案 1 :(得分:0)

我修复了它:

def custom_loss(y_true, y_pred):

        y_pred = K.reshape(y_pred, (K.shape(y_pred)[0], -1))
        y_true = K.reshape(y_true, (K.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

问题在于找到y_true和y_predict的第一维。在编译期间,它将不会得到真实的形状,因此将返回None值。因此,我得到的是tf.Tensor形状,而不是得到形状的整数值。我将K.get_variable_shape(y_true)更改为仅K.shape(y_true)并解决了。

相关问题