You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何消除Kaggle Kernel中全局/操作级种子对后续单元格的影响?

Kaggle Kernel中种子设置的问题

问题背景

我在编写涉及全局/操作级种子设置的Kaggle Kernel时,将每个测试案例放在独立单元格中,但发现前序单元格的种子设置会影响后续单元格的输出。

比如下面这段代码,作为独立Python文件运行时,每次都会生成完全相同的序列:

"""
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'

但把这段代码放在Kaggle 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'

第二种方法

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'

提问

请问还有哪些方法可以尝试?或是我的操作中存在什么错误?


内容的提问来源于stack exchange,提问作者Deepak Tatyaji Ahire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:17:21