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

如何从np.random.RandomState(0)中提取随机种子?训练测试集拆分问题

解决方法

首先,你不需要从np.random.RandomState(0)里提取种子——直接使用这个RandomState实例处理随机操作就好,这才是正确的做法。你的代码问题在于把RandomState对象传给了np.random.seed(),但这个函数只接受整数/种子类参数,不接受RandomState实例,所以无法正常运行。

修正后的函数代码可以这样写:

import numpy as np

def split_into_train_and_test(x_all_LF, frac_test=0.5, random_state=None):
    # 统一随机状态:传入实例则用它,否则用全局np.random
    rng = random_state if random_state is not None else np.random
    
    # 基于选定的随机状态生成打乱的索引
    shuffled_indices = rng.permutation(len(x_all_LF))
    test_size = int(len(x_all_LF) * frac_test)
    test_indices = shuffled_indices[:test_size]
    train_indices = shuffled_indices[test_size:]
    
    train_data = x_all_LF[train_indices]
    test_data = x_all_LF[test_indices]
    
    return train_data, test_data

关键说明:

  • 当你传入np.random.RandomState(0)时,rng就是这个实例,所有随机操作(比如permutation)都会基于它的内部状态执行,保证结果可复现。
  • RandomState并没有直接暴露可提取的单一种子属性(它的内部状态是一个数组),而且完全不需要提取种子——直接用实例的方法就足够完成需求。
  • 用permutation生成索引的方式不会直接修改输入的x_all_LF,比原代码里的np.shuffle更安全。

调用方式保持不变即可:

split_into_train_and_test(x_LF, frac_test=0.3, random_state=np.random.RandomState(0))

内容的提问来源于stack exchange,提问作者Airwrecka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:40:31