我在重塑张量时得到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
回答:
出现这种情况是因为你的y_true
或y_pred
张量的形状没有正确定义。这里的None
意味着张量的形状没有严格设置,而是可以根据我们看不到的之前的操作而变化。或者你只是这样初始化了你的张量。
如何修复:
- 首先,你应该调查
y_true
或y_pred
是如何获得其形状的,并避免得到None形状,这样张量将具有确定性的行数和列数
示例:
你的损失函数适用于正确的输入:
import tensorflow as tffrom keras import backend as Kdef 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 lossa = 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))