Tensorflow自定义损失函数-无法在损失函数中获取y_pred和y_true的样本

问题描述

我正在运行运行良好的LSTM网络(TF 2.0)。尝试修改损失函数时,我的问题开始了。 我计划对'y_true'和'y_pred'进行一些数据操作,但是由于TF强制将数据保持为张量(而不是将其转换为Pandas或NumPy),因此具有挑战性。 为了更好地控制损失函数中的数据,我模拟了tf.keras.losses.mae函数

我的目标是能够查看数据(“ y_true”和“ y_pred”),以便进行所需的调整。

原始功能

def mean_absolute_error(y_true,y_pred):
  y_pred = ops.convert_to_tensor(y_pred)
  y_true = math_ops.cast(y_true,y_pred.dtype)
  return K.mean(math_ops.abs(y_pred - y_true),axis=-1)

在进行调试调整后:

from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops
import tensorflow.keras.backend as K
def mean_absolute_error_test(y_true,y_pred):
     global temp_true
     temp_true=y_true
     print(y_true)
     y_pred = ops.convert_to_tensor(y_pred)
     y_true = math_ops.cast(y_true,y_pred.dtype)
     return K.mean(math_ops.abs(y_pred - y_true),axis=-1)

当我运行model.compile并打印y_true时,我得到: Tensor(“ dense_target:0”,shape =(None,None),dtype = float32)

type = tensorflow.python.framework.ops.Tensor

有人知道我如何看到“ y_pred”和“ y_true”,或者我想念什么? 好像我看不到y_true样本或数据为空。

主要代码部分:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dropout,Dense
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential,load_model
from tensorflow.python.keras.layers.recurrent import LSTM
from tensorflow.keras.callbacks import EarlyStopping
K.clear_session()

model = Sequential()
model.add(LSTM(20,activation='relu',input_shape=(look_back,len(training_columns)),recurrent_dropout=0.4))
model.add(Dropout(0.1))
model.add(Dense(1,activation='linear'))
model.compile(optimizer='adam',loss=test2,experimental_run_tf_function=False)# mse,mean_squared_logarithmic_error
num_epochs = 20
es = EarlyStopping(monitor='val_loss',mode='min',verbose=1,patience=3)
history=model.fit(X_train_lstm,y_train_lstm,epochs = num_epochs,batch_size = 128,shuffle=False,validation_data=[X_test_lstm,y_test_lstm],callbacks=[es])

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)