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

Python实现Sampling with replacement有放回采样代码补全问询

正确实现代码

首先确认你已经导入了numpy依赖:

import numpy as np

补全后的sample函数如下:

def sample(X, y):
    n_samples = len(X)
    # 均匀有放回采样,采样后训练集大小和输入数据集完全一致
    train_index = np.random.choice(n_samples, size=n_samples, replace=True)
    # 未被抽中的袋外样本作为验证集
    val_index = np.setdiff1d(np.arange(n_samples), np.unique(train_index))
    # 切分得到对应数据集
    x_trn, x_val = X[train_index], X[val_index]
    y_trn, y_val = y[train_index], y[val_index]
    return x_trn, x_val, y_trn, y_val

逻辑说明

  • 核心采样用np.random.choice实现,replace=True开启有放回采样,size=n_samples保证训练集大小符合要求,默认概率为均匀分布,完全匹配需求
  • 验证集采用Bootstrap采样的袋外样本(OOB)实现,和你原有代码拆分训练/验证集的意图一致
  • 修复了原有代码的问题:
    • 原np.random.permutation是无放回全量打乱,无法实现有放回采样逻辑
    • 修复了train_inex的变量名拼写错误
    • 移除了无意义的循环逻辑,修正了缩进错误

内容的提问来源于stack exchange,提问作者Java-NewBee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:15:03