首页 > 解决方案 > 为什么我的 tensorflow(keras) 模型会引发错误,ValueError: No gradients provided for any variable:?

问题描述

我一直在尝试让模型使用名为 Confusion_mat_loss 的自定义损失函数。但我有一个问题。我构建了模型,这是我的模型:

    def Generate_model(self, Batch_first=False, Batch_last=False):
        Input_layer = tf.keras.layers.Input( batch_shape=(None, 16, 24, 24, 24), name='Input_layer')

        # Make Mdoel -------------------------------------------------------------------------------------------------
        if Batch_first:
            Batch_normal = tf.keras.layers.BatchNormalization()(Input_layer)
            conv_layer1  = tf.keras.layers.Conv3D(filters=80, kernel_size=(3, 3, 3), activation='relu',
                                                  data_format='channels_first')(Batch_normal)
            # Max_pooling  = tf.keras.layers.MaxPooling3D( pool_size=(2, 2, 2), data_format='channels_first')(conv_layer1)

            conv_layer2  = tf.keras.layers.Conv3D(filters=100, kernel_size=(2, 2, 2), activation='relu',
                                                  data_format='channels_first')(conv_layer1)
            Max_pooling  = tf.keras.layers.MaxPooling3D( pool_size=(2, 2, 2), data_format='channels_first')(conv_layer2)

            GloMax_pool  = tf.keras.layers.GlobalMaxPool3D(data_format='channels_first')(Max_pooling)

        elif Batch_last:
            conv_layer1  = tf.keras.layers.Conv3D(filters=80, kernel_size=(2, 2, 2), activation='relu',
                                                 data_format='channels_first')(Input_layer)
            # Max_pooling  = tf.keras.layers.MaxPooling3D( pool_size=(2, 2, 2), data_format='channels_first')(conv_layer1)

            conv_layer2  = tf.keras.layers.Conv3D(filters=100, kernel_size=(2, 2, 2), activation='relu',
                                                 data_format='channels_first')(conv_layer1)
            Max_pooling  = tf.keras.layers.MaxPooling3D( pool_size=(2, 2, 2), data_format='channels_first')(conv_layer2)

            Batch_normal = tf.keras.layers.BatchNormalization()(Max_pooling)
            GloMax_pool  = tf.keras.layers.GlobalAvgPool3D(data_format='channels_first')(Batch_normal)

        Dense_layer  = tf.keras.layers.Dense(units=2 ** 7, activation='relu')(GloMax_pool)
        Output_layer = tf.keras.layers.LeakyReLU()(Dense_layer)
        Output_layer = tf.keras.layers.Dense(1, activation='sigmoid')(Output_layer)


        self.model = tf.keras.Model(inputs=Input_layer, outputs=Output_layer)
        self.model.summary()

对于我的模型,我想使用自定义损失函数,这是我的损失函数。

def Confusion_mat_loss(y_true, y_pred):
    y_true = K.cast(y_true, dtype='float32',)
    y_true = K.squeeze(y_true, axis=1)

    y_pred = K.cast(y_pred, dtype='float32',)
    y_pred = K.squeeze(y_pred, axis=1)
    Con_matrix = tf.math.confusion_matrix(labels=y_true, predictions=y_pred, num_classes=2)

    TP = Con_matrix[0, 0]; TN = Con_matrix[0, 1]; FP = Con_matrix[1, 0]; FN = Con_matrix[1, 1]
    fallout = FP / (FP + TN)
    print(fallout)

    return fallout

当我尝试使用此代码训练模型时:

self.model.compile(optimizer=optimizer, loss=Confusion_mat_loss, metrics=[Confusion_mat_loss,])
self.model.fit(x=x_train, y=y_train, epochs=1, batch_size=3, validation_split=0.2, verbose=False)

但是,我遇到了错误:

ValueError: No gradients provided for any variable: 
['batch_normalization/gamma:0', 'batch_normalization/beta:0', 'conv3d/kernel:0', 'conv3d/bias:0', 'conv3d_1/kernel:0', 'conv3d_1/bias:0', 'dense/kernel:0', 'dense/bias:0', 'dense_1/kernel:0', 'dense_1/bias:0'].

我不知道我错过了什么.. 知道是什么导致了这个问题吗?谢谢你。

标签: pythontensorflowkeras

解决方案


推荐阅读