【问题标题】:How to save tensor to Numpy array in my customized loss function?如何在我的自定义损失函数中将张量保存到 Numpy 数组?
【发布时间】:2021-07-23 10:08:02
【问题描述】:

我想在训练模型时检查我的中间结果。所以,我需要将张量保存在我的自定义损失中。

这是我的代码:

from util import *
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow as tf
from gen_model import read_cache_data
from numpy import random
from ml_util import *
from catboost import CatBoostRegressor
import warnings
warnings.filterwarnings('ignore')

class myloss(keras.losses.Loss):
  def __init__(self, coef, name='myloss'):
    super().__init__(name=name)
    self.coef = coef

  def call(self, y, y_pred):
    # I want to save y_pred here, the following is the method i tried, none of them works!!!!!!!!!!
    #a = (tf.print(y_pred))
    #b = (tf.print(y))
    print(type(y_pred))
    #sess = tf.Session();
    sess = tf.compat.v1.Session()
    with sess.as_default(): print(y_pred.eval())
    #print(y_pred.eval())
    #print(y_pred.numpy())
    return tf.math.reduce_mean(tf.square(y - y_pred), axis=1)

def train_mlp(train_df, valid_df, test_df, fv_cols, res_col):
  callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=10)
  model = keras.Sequential([layers.Dense(50, input_shape=(len(fv_cols), ), activation='relu'), layers.Dense(30, activation='relu'), layers.Dense(1)])
  model.compile(optimizer=keras.optimizers.SGD(0.1), loss = myloss(0.1))
  model.summary()
  #sess.run(tf.compat.v1.global_variables_initializer())
  model.fit(train_df[fv_cols], np.reshape(train_df[res_col].tolist(), (-1, 1)), callbacks=[callback], validation_data=(valid_df[fv_cols], valid_df[res_col]), epochs=100, batch_size=65536)
  train_pred = (model.predict(train_df[fv_cols])).flatten()
  test_pred = (model.predict(test_df[fv_cols])).flatten()
  d = pd.DataFrame([train_pred, train_df[res_col], test_pred, test_df[res_col]]).T
  d.columns = ['train_pred', 'train_y', 'test_pred', 'test_y']
  print(d)
  print('MLP is R2 =', r2(y_pred = train_pred, y = train_df[res_col]))
  print('MLP os R2 =', r2(y_pred = test_pred, y = test_df[res_col]))


if __name__ == '__main__':
  df = read_cache_data('cache')
  df = df.replace(-np.inf, np.nan).replace(np.inf, np.nan).dropna()
  fv_cols = df.columns[21:-3]
  res_col = 'res_10'
  train, test_df = df.iloc[:int(0.5*len(df))], df.iloc[int(0.5*len(df)):]
  train = train.sample(frac=1, random_state=1).reset_index(drop=True)
  train_df, valid_df = train.iloc[:int(0.7*len(train))], train.iloc[int(0.7*len(train)):]
  train_mlp(train_df, valid_df, test_df, fv_cols, res_col)

我尝试了一些方法,包括eval()session.run(),但都没有奏效,
评估:错误是:

ValueError: Cannot evaluate tensor using `eval()`: No default session is registered. Use `with sess.as_default()` or pass an ex

对于会话,错误是:

InvalidArgumentError: You must feed a value for placeholder tensor 'sequential/dense/MatMul/ReadVariableOp/resource' with dtype reso
         [[node sequential/dense/MatMul/ReadVariableOp/resource (defined at lstm.py:58) ]]

有人可以帮忙吗?

【问题讨论】:

    标签: python tensorflow keras loss-function


    【解决方案1】:

    类似的东西

    # custom loss function 
    class myloss(tf.keras.losses.Loss):
      def __init__(self, coef=None, name='myloss'):
        super().__init__(name=name)
        self.coef = coef
      def call(self, y, y_pred):
        return tf.math.reduce_mean(tf.square(y - y_pred), axis=1)
    
    # some dummines 
    import numpy as np 
    y_true = np.array([[0., 1.], [0., 0.]])
    y_pred = np.array([[1., 1.], [1., 0.]])
    
    # calling function
    m = myloss()
    m(y_true, y_pred).numpy()
    0.5
    
    # saving loss value into numpy array and reloading 
    np.save('./loss', m(y_true, y_pred).numpy())
    rloss = np.load('loss.npy')
    rloss
    0.5
    

    我刚刚注意到您在 call 方法中的评论,其中您提到了保存 y_pred。不完全确定我是否正确地关注你,但这里有一些问题(请告诉我):

    def call(self, y, y_pred):
          np.save('./loss', y_pred)
          return tf.math.reduce_mean(tf.square(y - y_pred), axis=1)
    
    ...
    rloss = np.load('loss.npy')
    rloss
    array([[1., 1.],
           [1., 0.]])
    

    【讨论】:

      猜你喜欢
      • 2020-09-24
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2018-02-22
      相关资源
      最近更新 更多