TensorFlow自定义损失ValueError:没有为任何变量提供梯度: [英] TensorFlow custom loss ValueError: No gradients provided for any variable:

查看:63
本文介绍了TensorFlow自定义损失ValueError:没有为任何变量提供梯度:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现以下代码中的自定义损失函数,以进行简单分类.但是,当我运行代码时,出现错误ValueError:没有为任何变量提供渐变:

I am implementing a custom loss function as in the code below for a simple classification. However, when I run the code I get the error ValueError: No gradients provided for any variable:

import os 

os.environ['KERAS_BACKEND'] = "tensorflow"

import pandas as pd
import numpy as np 
import matplotlib.pyplot as plt 
from tensorflow import keras
from tensorflow.keras import layers
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
import statistics as st 
import tensorflow as tf
from keras.utils import np_utils

# if the probability is greater than 0.75 then set the value to 1 for buy or sell else set it to None
# convert the y_pred to 0 and 1 using argmax function
# add the two matrices y_pred and y_true
# if value is 2 then set that to 0
# multiply by misclassification matrix
# add the losses to give a unique number
def custom_loss(y_true, y_pred):
    y_pred = y_pred.numpy()
    y_pred_dummy = np.zeros_like(y_pred)
    y_pred_dummy[np.arange(len(y_pred)), y_pred.argmax(1)] = 1
    y_pred = y_pred_dummy
    y_true = y_true.numpy()
    y_final = y_pred + y_true
    y_final[y_final == 2] = 0
    w_array = [[1,1,5],[1,1,1],[5,1,1]]
    return tf.convert_to_tensor(np.sum(np.dot(y_final, w_array)))
     

model = keras.Sequential()
model.add(layers.Dense(32, input_dim=4, activation='relu'))
model.add(layers.Dense(16, input_dim=4, activation='relu'))
model.add(layers.Dense(8, input_dim=4, activation='relu'))
model.add(layers.Dense(3, activation='softmax'))

model.compile(loss=custom_loss, optimizer='adam', run_eagerly=True)

我不明白我在这里做错了什么.我通读了关于tensorflow的问题,原因之一是损失函数和输入变量之间的链接断开了.但是我在损失函数中使用y_true

I do not understand what I am doing incorrectly over here. I read through the issues on tensorflow and one of the reasons is that the link between the loss function and input variables is broken. But I am using y_true in the loss function

谢谢

推荐答案

自定义损失函数中不能使用numpy.此函数是图形的一部分,应处理张量,而不是数组.Numpy不支持渐变的反向传播.

You can not use numpy within custom loss function. this function is a part of graph and should deal with tensors, not arrays. Numpy doesn't support backpropagation of gradients.

这篇关于TensorFlow自定义损失ValueError:没有为任何变量提供梯度:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆