mercredi 10 mai 2023

How to nullify the effect of global/operation level seed in the subsequent cells of Kaggle kernel?

Context

I am trying to write a Kaggle kernel on a topic that involves setting global/operation level seeds. For this, I am writing each case separately in a different cell. But the issue I encountered is that the seeds which I set in my previous cells were impacting the output of my subsequent cells.

For example, have a look at the following snippet that describes one of the cases:

"""
Case:
    Setup: When only operation level seed is set -
           - Since operation level seed is set, the sequence will start from same number after restarts, 
            and sequence will be same

"""

import tensorflow as tf

print(tf.random.uniform([1], seed=1))  # generates 'A1'
print(tf.random.uniform([1], seed=1))  # generates 'A2'
print(tf.random.uniform([1], seed=1))  # generates 'A3'
print(tf.random.uniform([1], seed=1))  # generates 'A4'

If I re-run the above code (as part of separate python file), I get a same sequence (as expected).

But when I re-run the same code in a separate cell of my Kaggle kernel, I got a different sequence. This might be due to the global/operation level seeds that I must have set in my previous cells.

What did I try?

To nullify the effect of previous cells on the current cell, I used some already available techniques to restart the kernel:

import IPython.display as display
import time

# Restart the cell
display.Javascript('Jupyter.notebook.kernel.restart()')

# Wait for the kernel to restart
time.sleep(20)

"""
Case:
    Setup: When only operation level seed is set -
           - Since operation level seed is set, the sequence will start from same number after restarts, 
            and sequence will be same

"""

import tensorflow as tf

print(tf.random.uniform([1], seed=1))  # generates 'A1'
print(tf.random.uniform([1], seed=1))  # generates 'A2'
print(tf.random.uniform([1], seed=1))  # generates 'A3'
print(tf.random.uniform([1], seed=1))  # generates 'A4'

or this:

from IPython.core.display import HTML
HTML("<script>Jupyter.notebook.kernel.restart()</script>")

"""
Case:
    Setup: When only operation level seed is set -
           - Since operation level seed is set, the sequence will start from same number after restarts, 
            and sequence will be same

"""

import tensorflow as tf

print(tf.random.uniform([1], seed=1))  # generates 'A1'
print(tf.random.uniform([1], seed=1))  # generates 'A2'
print(tf.random.uniform([1], seed=1))  # generates 'A3'
print(tf.random.uniform([1], seed=1))  # generates 'A4'

But I still did not get the same sequence.

My question

What else should I try or am I doing something wrong here?




Aucun commentaire:

Enregistrer un commentaire