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

我在重塑张量时得到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_truey_pred张量的形状没有正确定义。这里的None意味着张量的形状没有严格设置,而是可以根据我们看不到的之前的操作而变化。或者你只是这样初始化了你的张量。

如何修复:

  • 首先,你应该调查y_truey_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))

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注