SessionRunHook returning empty SessionRunValues after run









up vote
1
down vote

favorite












I'm trying to write a hook that will allow me to compute some global metrics (rather than batch-wise metrics). To prototype, I thought I'd get a simple hook up and running that would capture and remember true positives. It looks like this:



class TPHook(tf.train.SessionRunHook):

def after_create_session(self, session, coord):
print("Starting Hook")

tp_name = 'metrics/f1_macro/TP'
self.tp =
self.args = session.graph.get_operation_by_name(tp_name)
print(f"Got Args: self.args")

def before_run(self, run_context):
print("Starting Before Run")
return tf.train.SessionRunArgs(self.args)

def after_run(self, run_context, run_values):
print("After Run")
print(f"Got Values: run_values.results")


However, the values returned in the "after_run" part of the hook are always None. I tested this in both the train and evaluation phase. Am I misunderstanding something about how the SessionRunHooks are supposed to work?




Maybe relevant information:
The model was build in keras and converted to an estimator with the keras.estimator.model_to_estimator() function. The model has been tested and works fine, and the op that I'm trying to retrieve in the hook is defined in this code block:



def _f1_macro_vector(y_true, y_pred):
"""Computes the F1-score with Macro averaging.

Arguments:
y_true tf.Tensor -- Ground-truth labels
y_pred tf.Tensor -- Predicted labels

Returns:
tf.Tensor -- The computed F1-Score
"""
y_true = K.cast(y_true, tf.float64)
y_pred = K.cast(y_pred, tf.float64)

TP = tf.reduce_sum(y_true * K.round(y_pred), axis=0, name='TP')
FN = tf.reduce_sum(y_true * (1 - K.round(y_pred)), axis=0, name='FN')
FP = tf.reduce_sum((1 - y_true) * K.round(y_pred), axis=0, name='FP')

prec = TP / (TP + FP)
rec = TP / (TP + FN)

# Convert NaNs to Zero
prec = tf.where(tf.is_nan(prec), tf.zeros_like(prec), prec)
rec = tf.where(tf.is_nan(rec), tf.zeros_like(rec), rec)

f1 = 2 * (prec * rec) / (prec + rec)

# Convert NaN to Zero
f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)

return f1









share|improve this question

























    up vote
    1
    down vote

    favorite












    I'm trying to write a hook that will allow me to compute some global metrics (rather than batch-wise metrics). To prototype, I thought I'd get a simple hook up and running that would capture and remember true positives. It looks like this:



    class TPHook(tf.train.SessionRunHook):

    def after_create_session(self, session, coord):
    print("Starting Hook")

    tp_name = 'metrics/f1_macro/TP'
    self.tp =
    self.args = session.graph.get_operation_by_name(tp_name)
    print(f"Got Args: self.args")

    def before_run(self, run_context):
    print("Starting Before Run")
    return tf.train.SessionRunArgs(self.args)

    def after_run(self, run_context, run_values):
    print("After Run")
    print(f"Got Values: run_values.results")


    However, the values returned in the "after_run" part of the hook are always None. I tested this in both the train and evaluation phase. Am I misunderstanding something about how the SessionRunHooks are supposed to work?




    Maybe relevant information:
    The model was build in keras and converted to an estimator with the keras.estimator.model_to_estimator() function. The model has been tested and works fine, and the op that I'm trying to retrieve in the hook is defined in this code block:



    def _f1_macro_vector(y_true, y_pred):
    """Computes the F1-score with Macro averaging.

    Arguments:
    y_true tf.Tensor -- Ground-truth labels
    y_pred tf.Tensor -- Predicted labels

    Returns:
    tf.Tensor -- The computed F1-Score
    """
    y_true = K.cast(y_true, tf.float64)
    y_pred = K.cast(y_pred, tf.float64)

    TP = tf.reduce_sum(y_true * K.round(y_pred), axis=0, name='TP')
    FN = tf.reduce_sum(y_true * (1 - K.round(y_pred)), axis=0, name='FN')
    FP = tf.reduce_sum((1 - y_true) * K.round(y_pred), axis=0, name='FP')

    prec = TP / (TP + FP)
    rec = TP / (TP + FN)

    # Convert NaNs to Zero
    prec = tf.where(tf.is_nan(prec), tf.zeros_like(prec), prec)
    rec = tf.where(tf.is_nan(rec), tf.zeros_like(rec), rec)

    f1 = 2 * (prec * rec) / (prec + rec)

    # Convert NaN to Zero
    f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)

    return f1









    share|improve this question























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I'm trying to write a hook that will allow me to compute some global metrics (rather than batch-wise metrics). To prototype, I thought I'd get a simple hook up and running that would capture and remember true positives. It looks like this:



      class TPHook(tf.train.SessionRunHook):

      def after_create_session(self, session, coord):
      print("Starting Hook")

      tp_name = 'metrics/f1_macro/TP'
      self.tp =
      self.args = session.graph.get_operation_by_name(tp_name)
      print(f"Got Args: self.args")

      def before_run(self, run_context):
      print("Starting Before Run")
      return tf.train.SessionRunArgs(self.args)

      def after_run(self, run_context, run_values):
      print("After Run")
      print(f"Got Values: run_values.results")


      However, the values returned in the "after_run" part of the hook are always None. I tested this in both the train and evaluation phase. Am I misunderstanding something about how the SessionRunHooks are supposed to work?




      Maybe relevant information:
      The model was build in keras and converted to an estimator with the keras.estimator.model_to_estimator() function. The model has been tested and works fine, and the op that I'm trying to retrieve in the hook is defined in this code block:



      def _f1_macro_vector(y_true, y_pred):
      """Computes the F1-score with Macro averaging.

      Arguments:
      y_true tf.Tensor -- Ground-truth labels
      y_pred tf.Tensor -- Predicted labels

      Returns:
      tf.Tensor -- The computed F1-Score
      """
      y_true = K.cast(y_true, tf.float64)
      y_pred = K.cast(y_pred, tf.float64)

      TP = tf.reduce_sum(y_true * K.round(y_pred), axis=0, name='TP')
      FN = tf.reduce_sum(y_true * (1 - K.round(y_pred)), axis=0, name='FN')
      FP = tf.reduce_sum((1 - y_true) * K.round(y_pred), axis=0, name='FP')

      prec = TP / (TP + FP)
      rec = TP / (TP + FN)

      # Convert NaNs to Zero
      prec = tf.where(tf.is_nan(prec), tf.zeros_like(prec), prec)
      rec = tf.where(tf.is_nan(rec), tf.zeros_like(rec), rec)

      f1 = 2 * (prec * rec) / (prec + rec)

      # Convert NaN to Zero
      f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)

      return f1









      share|improve this question













      I'm trying to write a hook that will allow me to compute some global metrics (rather than batch-wise metrics). To prototype, I thought I'd get a simple hook up and running that would capture and remember true positives. It looks like this:



      class TPHook(tf.train.SessionRunHook):

      def after_create_session(self, session, coord):
      print("Starting Hook")

      tp_name = 'metrics/f1_macro/TP'
      self.tp =
      self.args = session.graph.get_operation_by_name(tp_name)
      print(f"Got Args: self.args")

      def before_run(self, run_context):
      print("Starting Before Run")
      return tf.train.SessionRunArgs(self.args)

      def after_run(self, run_context, run_values):
      print("After Run")
      print(f"Got Values: run_values.results")


      However, the values returned in the "after_run" part of the hook are always None. I tested this in both the train and evaluation phase. Am I misunderstanding something about how the SessionRunHooks are supposed to work?




      Maybe relevant information:
      The model was build in keras and converted to an estimator with the keras.estimator.model_to_estimator() function. The model has been tested and works fine, and the op that I'm trying to retrieve in the hook is defined in this code block:



      def _f1_macro_vector(y_true, y_pred):
      """Computes the F1-score with Macro averaging.

      Arguments:
      y_true tf.Tensor -- Ground-truth labels
      y_pred tf.Tensor -- Predicted labels

      Returns:
      tf.Tensor -- The computed F1-Score
      """
      y_true = K.cast(y_true, tf.float64)
      y_pred = K.cast(y_pred, tf.float64)

      TP = tf.reduce_sum(y_true * K.round(y_pred), axis=0, name='TP')
      FN = tf.reduce_sum(y_true * (1 - K.round(y_pred)), axis=0, name='FN')
      FP = tf.reduce_sum((1 - y_true) * K.round(y_pred), axis=0, name='FP')

      prec = TP / (TP + FP)
      rec = TP / (TP + FN)

      # Convert NaNs to Zero
      prec = tf.where(tf.is_nan(prec), tf.zeros_like(prec), prec)
      rec = tf.where(tf.is_nan(rec), tf.zeros_like(rec), rec)

      f1 = 2 * (prec * rec) / (prec + rec)

      # Convert NaN to Zero
      f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)

      return f1






      python-3.x tensorflow keras tensorflow-estimator






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 8 at 23:12









      mattdeak

      13810




      13810






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          In case anyone runs into the same problem, I found out how to restructure the program so that it worked. Although the documentation makes it sound like I can pass raw ops into the SessionRunArgs, it seems like it requires actual tensors (maybe this is a misreading on my part).
          This is pretty easy to accomplish - I just changed the after_create_session code to what's shown below.



          def after_create_session(self, session, coord):

          tp_name = 'metrics/f1_macro/TP'
          self.tp =
          tp_tensor = session.graph.get_tensor_by_name(tp_name+':0')

          self.args = [tp_tensor]


          And this successfully runs.






          share|improve this answer




















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53217564%2fsessionrunhook-returning-empty-sessionrunvalues-after-run%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote



            accepted










            In case anyone runs into the same problem, I found out how to restructure the program so that it worked. Although the documentation makes it sound like I can pass raw ops into the SessionRunArgs, it seems like it requires actual tensors (maybe this is a misreading on my part).
            This is pretty easy to accomplish - I just changed the after_create_session code to what's shown below.



            def after_create_session(self, session, coord):

            tp_name = 'metrics/f1_macro/TP'
            self.tp =
            tp_tensor = session.graph.get_tensor_by_name(tp_name+':0')

            self.args = [tp_tensor]


            And this successfully runs.






            share|improve this answer
























              up vote
              0
              down vote



              accepted










              In case anyone runs into the same problem, I found out how to restructure the program so that it worked. Although the documentation makes it sound like I can pass raw ops into the SessionRunArgs, it seems like it requires actual tensors (maybe this is a misreading on my part).
              This is pretty easy to accomplish - I just changed the after_create_session code to what's shown below.



              def after_create_session(self, session, coord):

              tp_name = 'metrics/f1_macro/TP'
              self.tp =
              tp_tensor = session.graph.get_tensor_by_name(tp_name+':0')

              self.args = [tp_tensor]


              And this successfully runs.






              share|improve this answer






















                up vote
                0
                down vote



                accepted







                up vote
                0
                down vote



                accepted






                In case anyone runs into the same problem, I found out how to restructure the program so that it worked. Although the documentation makes it sound like I can pass raw ops into the SessionRunArgs, it seems like it requires actual tensors (maybe this is a misreading on my part).
                This is pretty easy to accomplish - I just changed the after_create_session code to what's shown below.



                def after_create_session(self, session, coord):

                tp_name = 'metrics/f1_macro/TP'
                self.tp =
                tp_tensor = session.graph.get_tensor_by_name(tp_name+':0')

                self.args = [tp_tensor]


                And this successfully runs.






                share|improve this answer












                In case anyone runs into the same problem, I found out how to restructure the program so that it worked. Although the documentation makes it sound like I can pass raw ops into the SessionRunArgs, it seems like it requires actual tensors (maybe this is a misreading on my part).
                This is pretty easy to accomplish - I just changed the after_create_session code to what's shown below.



                def after_create_session(self, session, coord):

                tp_name = 'metrics/f1_macro/TP'
                self.tp =
                tp_tensor = session.graph.get_tensor_by_name(tp_name+':0')

                self.args = [tp_tensor]


                And this successfully runs.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 13 at 20:40









                mattdeak

                13810




                13810



























                     

                    draft saved


                    draft discarded















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53217564%2fsessionrunhook-returning-empty-sessionrunvalues-after-run%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

                    Edmonton

                    Crossroads (UK TV series)