在损失函数中将浮点张量转换为张量fo整数

时间:2020-09-22 20:08:20

标签: python numpy tensorflow keras

我正在构建损失函数,我需要使用y_true和y_pred作为用于计算损失的矩阵的索引。问题是,这两个都是浮点张量,而cast()和round()之类的函数不可微,因此我无法在损失函数中使用它们。

import numpy as np
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
from sklearn.utils import shuffle
from keras.utils import to_categorical

K = tf.keras.backend
A = np.random.randint(12, size=(12,12))


def score_loss(y_true, y_pred):
    y_pred = tf.nn.softmax(y_pred)
    y_true = tf.nn.softmax(y_true)
    y_pred = K.cast(y_pred,"int32")
    y_true = K.cast(y_true,"int32")
    loss = -K.sum(tf.gather_nd(A, tf.stack((y_true, y_pred), axis=-1)))
    return loss

data = np.random.rand(1000,10)
data_y = np.array(range(0,10))
X = data[:, 0:8]
y = data[:, 9]
for i in range(0, len(y)):
  y[i] = data_y[i%9]
y = shuffle(y)
y = to_categorical(y, 9)
model = Sequential()
model.add(Dense(200, input_shape = (8,), activation = "relu"))
model.add(Dense(9, activation = "softmax"))
model.compile(loss = score_loss, optimizer= Adam())

在训练过程中出现以下错误:

ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.

我需要另一种将其转换为整数的方法,或者另一种完成整件事的方法。

0 个答案:

没有答案